[MIPS/GAS] Split Loongson EXT Instructions from loongson3a.
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2018 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define streq(a, b)           (strcmp (a, b) == 0)
46
47 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92 static char *mips_flags_frag;
93
94 #define ZERO 0
95 #define ATREG 1
96 #define S0  16
97 #define S7  23
98 #define TREG 24
99 #define PIC_CALL_REG 25
100 #define KT0 26
101 #define KT1 27
102 #define GP  28
103 #define SP  29
104 #define FP  30
105 #define RA  31
106
107 #define ILLEGAL_REG (32)
108
109 #define AT  mips_opts.at
110
111 extern int target_big_endian;
112
113 /* The name of the readonly data section.  */
114 #define RDATA_SECTION_NAME ".rodata"
115
116 /* Ways in which an instruction can be "appended" to the output.  */
117 enum append_method {
118   /* Just add it normally.  */
119   APPEND_ADD,
120
121   /* Add it normally and then add a nop.  */
122   APPEND_ADD_WITH_NOP,
123
124   /* Turn an instruction with a delay slot into a "compact" version.  */
125   APPEND_ADD_COMPACT,
126
127   /* Insert the instruction before the last one.  */
128   APPEND_SWAP
129 };
130
131 /* Information about an instruction, including its format, operands
132    and fixups.  */
133 struct mips_cl_insn
134 {
135   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
136   const struct mips_opcode *insn_mo;
137
138   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
139      a copy of INSN_MO->match with the operands filled in.  If we have
140      decided to use an extended MIPS16 instruction, this includes the
141      extension.  */
142   unsigned long insn_opcode;
143
144   /* The frag that contains the instruction.  */
145   struct frag *frag;
146
147   /* The offset into FRAG of the first instruction byte.  */
148   long where;
149
150   /* The relocs associated with the instruction, if any.  */
151   fixS *fixp[3];
152
153   /* True if this entry cannot be moved from its current position.  */
154   unsigned int fixed_p : 1;
155
156   /* True if this instruction occurred in a .set noreorder block.  */
157   unsigned int noreorder_p : 1;
158
159   /* True for mips16 instructions that jump to an absolute address.  */
160   unsigned int mips16_absolute_jump_p : 1;
161
162   /* True if this instruction is complete.  */
163   unsigned int complete_p : 1;
164
165   /* True if this instruction is cleared from history by unconditional
166      branch.  */
167   unsigned int cleared_p : 1;
168 };
169
170 /* The ABI to use.  */
171 enum mips_abi_level
172 {
173   NO_ABI = 0,
174   O32_ABI,
175   O64_ABI,
176   N32_ABI,
177   N64_ABI,
178   EABI_ABI
179 };
180
181 /* MIPS ABI we are using for this output file.  */
182 static enum mips_abi_level mips_abi = NO_ABI;
183
184 /* Whether or not we have code that can call pic code.  */
185 int mips_abicalls = FALSE;
186
187 /* Whether or not we have code which can be put into a shared
188    library.  */
189 static bfd_boolean mips_in_shared = TRUE;
190
191 /* This is the set of options which may be modified by the .set
192    pseudo-op.  We use a struct so that .set push and .set pop are more
193    reliable.  */
194
195 struct mips_set_options
196 {
197   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
198      if it has not been initialized.  Changed by `.set mipsN', and the
199      -mipsN command line option, and the default CPU.  */
200   int isa;
201   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
202      <asename>', by command line options, and based on the default
203      architecture.  */
204   int ase;
205   /* Whether we are assembling for the mips16 processor.  0 if we are
206      not, 1 if we are, and -1 if the value has not been initialized.
207      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
208      -nomips16 command line options, and the default CPU.  */
209   int mips16;
210   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
211      1 if we are, and -1 if the value has not been initialized.  Changed
212      by `.set micromips' and `.set nomicromips', and the -mmicromips
213      and -mno-micromips command line options, and the default CPU.  */
214   int micromips;
215   /* Non-zero if we should not reorder instructions.  Changed by `.set
216      reorder' and `.set noreorder'.  */
217   int noreorder;
218   /* Non-zero if we should not permit the register designated "assembler
219      temporary" to be used in instructions.  The value is the register
220      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
221      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
222   unsigned int at;
223   /* Non-zero if we should warn when a macro instruction expands into
224      more than one machine instruction.  Changed by `.set nomacro' and
225      `.set macro'.  */
226   int warn_about_macros;
227   /* Non-zero if we should not move instructions.  Changed by `.set
228      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
229   int nomove;
230   /* Non-zero if we should not optimize branches by moving the target
231      of the branch into the delay slot.  Actually, we don't perform
232      this optimization anyhow.  Changed by `.set bopt' and `.set
233      nobopt'.  */
234   int nobopt;
235   /* Non-zero if we should not autoextend mips16 instructions.
236      Changed by `.set autoextend' and `.set noautoextend'.  */
237   int noautoextend;
238   /* True if we should only emit 32-bit microMIPS instructions.
239      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
240      and -mno-insn32 command line options.  */
241   bfd_boolean insn32;
242   /* Restrict general purpose registers and floating point registers
243      to 32 bit.  This is initially determined when -mgp32 or -mfp32
244      is passed but can changed if the assembler code uses .set mipsN.  */
245   int gp;
246   int fp;
247   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
248      command line option, and the default CPU.  */
249   int arch;
250   /* True if ".set sym32" is in effect.  */
251   bfd_boolean sym32;
252   /* True if floating-point operations are not allowed.  Changed by .set
253      softfloat or .set hardfloat, by command line options -msoft-float or
254      -mhard-float.  The default is false.  */
255   bfd_boolean soft_float;
256
257   /* True if only single-precision floating-point operations are allowed.
258      Changed by .set singlefloat or .set doublefloat, command-line options
259      -msingle-float or -mdouble-float.  The default is false.  */
260   bfd_boolean single_float;
261
262   /* 1 if single-precision operations on odd-numbered registers are
263      allowed.  */
264   int oddspreg;
265 };
266
267 /* Specifies whether module level options have been checked yet.  */
268 static bfd_boolean file_mips_opts_checked = FALSE;
269
270 /* Do we support nan2008?  0 if we don't, 1 if we do, and -1 if the
271    value has not been initialized.  Changed by `.nan legacy' and
272    `.nan 2008', and the -mnan=legacy and -mnan=2008 command line
273    options, and the default CPU.  */
274 static int mips_nan2008 = -1;
275
276 /* This is the struct we use to hold the module level set of options.
277    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
278    fp fields to -1 to indicate that they have not been initialized.  */
279
280 static struct mips_set_options file_mips_opts =
281 {
282   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
283   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
284   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
285   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
286   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
287 };
288
289 /* This is similar to file_mips_opts, but for the current set of options.  */
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
294   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
295   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
296   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
297   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
298 };
299
300 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
301 static unsigned int file_ase_explicit;
302
303 /* These variables are filled in with the masks of registers used.
304    The object format code reads them and puts them in the appropriate
305    place.  */
306 unsigned long mips_gprmask;
307 unsigned long mips_cprmask[4];
308
309 /* True if any MIPS16 code was produced.  */
310 static int file_ase_mips16;
311
312 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
313                               || mips_opts.isa == ISA_MIPS32R2          \
314                               || mips_opts.isa == ISA_MIPS32R3          \
315                               || mips_opts.isa == ISA_MIPS32R5          \
316                               || mips_opts.isa == ISA_MIPS64            \
317                               || mips_opts.isa == ISA_MIPS64R2          \
318                               || mips_opts.isa == ISA_MIPS64R3          \
319                               || mips_opts.isa == ISA_MIPS64R5)
320
321 /* True if any microMIPS code was produced.  */
322 static int file_ase_micromips;
323
324 /* True if we want to create R_MIPS_JALR for jalr $25.  */
325 #ifdef TE_IRIX
326 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
327 #else
328 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
329    because there's no place for any addend, the only acceptable
330    expression is a bare symbol.  */
331 #define MIPS_JALR_HINT_P(EXPR) \
332   (!HAVE_IN_PLACE_ADDENDS \
333    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
334 #endif
335
336 /* The argument of the -march= flag.  The architecture we are assembling.  */
337 static const char *mips_arch_string;
338
339 /* The argument of the -mtune= flag.  The architecture for which we
340    are optimizing.  */
341 static int mips_tune = CPU_UNKNOWN;
342 static const char *mips_tune_string;
343
344 /* True when generating 32-bit code for a 64-bit processor.  */
345 static int mips_32bitmode = 0;
346
347 /* True if the given ABI requires 32-bit registers.  */
348 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
349
350 /* Likewise 64-bit registers.  */
351 #define ABI_NEEDS_64BIT_REGS(ABI)       \
352   ((ABI) == N32_ABI                     \
353    || (ABI) == N64_ABI                  \
354    || (ABI) == O64_ABI)
355
356 #define ISA_IS_R6(ISA)                  \
357   ((ISA) == ISA_MIPS32R6                \
358    || (ISA) == ISA_MIPS64R6)
359
360 /*  Return true if ISA supports 64 bit wide gp registers.  */
361 #define ISA_HAS_64BIT_REGS(ISA)         \
362   ((ISA) == ISA_MIPS3                   \
363    || (ISA) == ISA_MIPS4                \
364    || (ISA) == ISA_MIPS5                \
365    || (ISA) == ISA_MIPS64               \
366    || (ISA) == ISA_MIPS64R2             \
367    || (ISA) == ISA_MIPS64R3             \
368    || (ISA) == ISA_MIPS64R5             \
369    || (ISA) == ISA_MIPS64R6)
370
371 /*  Return true if ISA supports 64 bit wide float registers.  */
372 #define ISA_HAS_64BIT_FPRS(ISA)         \
373   ((ISA) == ISA_MIPS3                   \
374    || (ISA) == ISA_MIPS4                \
375    || (ISA) == ISA_MIPS5                \
376    || (ISA) == ISA_MIPS32R2             \
377    || (ISA) == ISA_MIPS32R3             \
378    || (ISA) == ISA_MIPS32R5             \
379    || (ISA) == ISA_MIPS32R6             \
380    || (ISA) == ISA_MIPS64               \
381    || (ISA) == ISA_MIPS64R2             \
382    || (ISA) == ISA_MIPS64R3             \
383    || (ISA) == ISA_MIPS64R5             \
384    || (ISA) == ISA_MIPS64R6)
385
386 /* Return true if ISA supports 64-bit right rotate (dror et al.)
387    instructions.  */
388 #define ISA_HAS_DROR(ISA)               \
389   ((ISA) == ISA_MIPS64R2                \
390    || (ISA) == ISA_MIPS64R3             \
391    || (ISA) == ISA_MIPS64R5             \
392    || (ISA) == ISA_MIPS64R6             \
393    || (mips_opts.micromips              \
394        && ISA_HAS_64BIT_REGS (ISA))     \
395    )
396
397 /* Return true if ISA supports 32-bit right rotate (ror et al.)
398    instructions.  */
399 #define ISA_HAS_ROR(ISA)                \
400   ((ISA) == ISA_MIPS32R2                \
401    || (ISA) == ISA_MIPS32R3             \
402    || (ISA) == ISA_MIPS32R5             \
403    || (ISA) == ISA_MIPS32R6             \
404    || (ISA) == ISA_MIPS64R2             \
405    || (ISA) == ISA_MIPS64R3             \
406    || (ISA) == ISA_MIPS64R5             \
407    || (ISA) == ISA_MIPS64R6             \
408    || (mips_opts.ase & ASE_SMARTMIPS)   \
409    || mips_opts.micromips               \
410    )
411
412 /* Return true if ISA supports single-precision floats in odd registers.  */
413 #define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
414   (((ISA) == ISA_MIPS32                 \
415     || (ISA) == ISA_MIPS32R2            \
416     || (ISA) == ISA_MIPS32R3            \
417     || (ISA) == ISA_MIPS32R5            \
418     || (ISA) == ISA_MIPS32R6            \
419     || (ISA) == ISA_MIPS64              \
420     || (ISA) == ISA_MIPS64R2            \
421     || (ISA) == ISA_MIPS64R3            \
422     || (ISA) == ISA_MIPS64R5            \
423     || (ISA) == ISA_MIPS64R6            \
424     || (CPU) == CPU_R5900)              \
425    && (CPU) != CPU_LOONGSON_3A)
426
427 /* Return true if ISA supports move to/from high part of a 64-bit
428    floating-point register. */
429 #define ISA_HAS_MXHC1(ISA)              \
430   ((ISA) == ISA_MIPS32R2                \
431    || (ISA) == ISA_MIPS32R3             \
432    || (ISA) == ISA_MIPS32R5             \
433    || (ISA) == ISA_MIPS32R6             \
434    || (ISA) == ISA_MIPS64R2             \
435    || (ISA) == ISA_MIPS64R3             \
436    || (ISA) == ISA_MIPS64R5             \
437    || (ISA) == ISA_MIPS64R6)
438
439 /*  Return true if ISA supports legacy NAN.  */
440 #define ISA_HAS_LEGACY_NAN(ISA)         \
441   ((ISA) == ISA_MIPS1                   \
442    || (ISA) == ISA_MIPS2                \
443    || (ISA) == ISA_MIPS3                \
444    || (ISA) == ISA_MIPS4                \
445    || (ISA) == ISA_MIPS5                \
446    || (ISA) == ISA_MIPS32               \
447    || (ISA) == ISA_MIPS32R2             \
448    || (ISA) == ISA_MIPS32R3             \
449    || (ISA) == ISA_MIPS32R5             \
450    || (ISA) == ISA_MIPS64               \
451    || (ISA) == ISA_MIPS64R2             \
452    || (ISA) == ISA_MIPS64R3             \
453    || (ISA) == ISA_MIPS64R5)
454
455 #define GPR_SIZE \
456     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
457      ? 32 \
458      : mips_opts.gp)
459
460 #define FPR_SIZE \
461     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
462      ? 32 \
463      : mips_opts.fp)
464
465 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
466
467 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
468
469 /* True if relocations are stored in-place.  */
470 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
471
472 /* The ABI-derived address size.  */
473 #define HAVE_64BIT_ADDRESSES \
474   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
475 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
476
477 /* The size of symbolic constants (i.e., expressions of the form
478    "SYMBOL" or "SYMBOL + OFFSET").  */
479 #define HAVE_32BIT_SYMBOLS \
480   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
481 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
482
483 /* Addresses are loaded in different ways, depending on the address size
484    in use.  The n32 ABI Documentation also mandates the use of additions
485    with overflow checking, but existing implementations don't follow it.  */
486 #define ADDRESS_ADD_INSN                                                \
487    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
488
489 #define ADDRESS_ADDI_INSN                                               \
490    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
491
492 #define ADDRESS_LOAD_INSN                                               \
493    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
494
495 #define ADDRESS_STORE_INSN                                              \
496    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
497
498 /* Return true if the given CPU supports the MIPS16 ASE.  */
499 #define CPU_HAS_MIPS16(cpu)                                             \
500    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
501     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
502
503 /* Return true if the given CPU supports the microMIPS ASE.  */
504 #define CPU_HAS_MICROMIPS(cpu)  0
505
506 /* True if CPU has a dror instruction.  */
507 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
508
509 /* True if CPU has a ror instruction.  */
510 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
511
512 /* True if CPU is in the Octeon family */
513 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
514                             || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
515
516 /* True if CPU has seq/sne and seqi/snei instructions.  */
517 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
518
519 /* True, if CPU has support for ldc1 and sdc1. */
520 #define CPU_HAS_LDC1_SDC1(CPU)  \
521    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
522
523 /* True if mflo and mfhi can be immediately followed by instructions
524    which write to the HI and LO registers.
525
526    According to MIPS specifications, MIPS ISAs I, II, and III need
527    (at least) two instructions between the reads of HI/LO and
528    instructions which write them, and later ISAs do not.  Contradicting
529    the MIPS specifications, some MIPS IV processor user manuals (e.g.
530    the UM for the NEC Vr5000) document needing the instructions between
531    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
532    MIPS64 and later ISAs to have the interlocks, plus any specific
533    earlier-ISA CPUs for which CPU documentation declares that the
534    instructions are really interlocked.  */
535 #define hilo_interlocks \
536   (mips_opts.isa == ISA_MIPS32                        \
537    || mips_opts.isa == ISA_MIPS32R2                   \
538    || mips_opts.isa == ISA_MIPS32R3                   \
539    || mips_opts.isa == ISA_MIPS32R5                   \
540    || mips_opts.isa == ISA_MIPS32R6                   \
541    || mips_opts.isa == ISA_MIPS64                     \
542    || mips_opts.isa == ISA_MIPS64R2                   \
543    || mips_opts.isa == ISA_MIPS64R3                   \
544    || mips_opts.isa == ISA_MIPS64R5                   \
545    || mips_opts.isa == ISA_MIPS64R6                   \
546    || mips_opts.arch == CPU_R4010                     \
547    || mips_opts.arch == CPU_R5900                     \
548    || mips_opts.arch == CPU_R10000                    \
549    || mips_opts.arch == CPU_R12000                    \
550    || mips_opts.arch == CPU_R14000                    \
551    || mips_opts.arch == CPU_R16000                    \
552    || mips_opts.arch == CPU_RM7000                    \
553    || mips_opts.arch == CPU_VR5500                    \
554    || mips_opts.micromips                             \
555    )
556
557 /* Whether the processor uses hardware interlocks to protect reads
558    from the GPRs after they are loaded from memory, and thus does not
559    require nops to be inserted.  This applies to instructions marked
560    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
561    level I and microMIPS mode instructions are always interlocked.  */
562 #define gpr_interlocks                                \
563   (mips_opts.isa != ISA_MIPS1                         \
564    || mips_opts.arch == CPU_R3900                     \
565    || mips_opts.arch == CPU_R5900                     \
566    || mips_opts.micromips                             \
567    )
568
569 /* Whether the processor uses hardware interlocks to avoid delays
570    required by coprocessor instructions, and thus does not require
571    nops to be inserted.  This applies to instructions marked
572    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
573    instructions marked INSN_WRITE_COND_CODE and ones marked
574    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
575    levels I, II, and III and microMIPS mode instructions are always
576    interlocked.  */
577 /* Itbl support may require additional care here.  */
578 #define cop_interlocks                                \
579   ((mips_opts.isa != ISA_MIPS1                        \
580     && mips_opts.isa != ISA_MIPS2                     \
581     && mips_opts.isa != ISA_MIPS3)                    \
582    || mips_opts.arch == CPU_R4300                     \
583    || mips_opts.micromips                             \
584    )
585
586 /* Whether the processor uses hardware interlocks to protect reads
587    from coprocessor registers after they are loaded from memory, and
588    thus does not require nops to be inserted.  This applies to
589    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
590    requires at MIPS ISA level I and microMIPS mode instructions are
591    always interlocked.  */
592 #define cop_mem_interlocks                            \
593   (mips_opts.isa != ISA_MIPS1                         \
594    || mips_opts.micromips                             \
595    )
596
597 /* Is this a mfhi or mflo instruction?  */
598 #define MF_HILO_INSN(PINFO) \
599   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
600
601 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
602    has been selected.  This implies, in particular, that addresses of text
603    labels have their LSB set.  */
604 #define HAVE_CODE_COMPRESSION                                           \
605   ((mips_opts.mips16 | mips_opts.micromips) != 0)
606
607 /* The minimum and maximum signed values that can be stored in a GPR.  */
608 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
609 #define GPR_SMIN (-GPR_SMAX - 1)
610
611 /* MIPS PIC level.  */
612
613 enum mips_pic_level mips_pic;
614
615 /* 1 if we should generate 32 bit offsets from the $gp register in
616    SVR4_PIC mode.  Currently has no meaning in other modes.  */
617 static int mips_big_got = 0;
618
619 /* 1 if trap instructions should used for overflow rather than break
620    instructions.  */
621 static int mips_trap = 0;
622
623 /* 1 if double width floating point constants should not be constructed
624    by assembling two single width halves into two single width floating
625    point registers which just happen to alias the double width destination
626    register.  On some architectures this aliasing can be disabled by a bit
627    in the status register, and the setting of this bit cannot be determined
628    automatically at assemble time.  */
629 static int mips_disable_float_construction;
630
631 /* Non-zero if any .set noreorder directives were used.  */
632
633 static int mips_any_noreorder;
634
635 /* Non-zero if nops should be inserted when the register referenced in
636    an mfhi/mflo instruction is read in the next two instructions.  */
637 static int mips_7000_hilo_fix;
638
639 /* The size of objects in the small data section.  */
640 static unsigned int g_switch_value = 8;
641 /* Whether the -G option was used.  */
642 static int g_switch_seen = 0;
643
644 #define N_RMASK 0xc4
645 #define N_VFP   0xd4
646
647 /* If we can determine in advance that GP optimization won't be
648    possible, we can skip the relaxation stuff that tries to produce
649    GP-relative references.  This makes delay slot optimization work
650    better.
651
652    This function can only provide a guess, but it seems to work for
653    gcc output.  It needs to guess right for gcc, otherwise gcc
654    will put what it thinks is a GP-relative instruction in a branch
655    delay slot.
656
657    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
658    fixed it for the non-PIC mode.  KR 95/04/07  */
659 static int nopic_need_relax (symbolS *, int);
660
661 /* handle of the OPCODE hash table */
662 static struct hash_control *op_hash = NULL;
663
664 /* The opcode hash table we use for the mips16.  */
665 static struct hash_control *mips16_op_hash = NULL;
666
667 /* The opcode hash table we use for the microMIPS ASE.  */
668 static struct hash_control *micromips_op_hash = NULL;
669
670 /* This array holds the chars that always start a comment.  If the
671     pre-processor is disabled, these aren't very useful */
672 const char comment_chars[] = "#";
673
674 /* This array holds the chars that only start a comment at the beginning of
675    a line.  If the line seems to have the form '# 123 filename'
676    .line and .file directives will appear in the pre-processed output */
677 /* Note that input_file.c hand checks for '#' at the beginning of the
678    first line of the input file.  This is because the compiler outputs
679    #NO_APP at the beginning of its output.  */
680 /* Also note that C style comments are always supported.  */
681 const char line_comment_chars[] = "#";
682
683 /* This array holds machine specific line separator characters.  */
684 const char line_separator_chars[] = ";";
685
686 /* Chars that can be used to separate mant from exp in floating point nums */
687 const char EXP_CHARS[] = "eE";
688
689 /* Chars that mean this number is a floating point constant */
690 /* As in 0f12.456 */
691 /* or    0d1.2345e12 */
692 const char FLT_CHARS[] = "rRsSfFdDxXpP";
693
694 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
695    changed in read.c .  Ideally it shouldn't have to know about it at all,
696    but nothing is ideal around here.
697  */
698
699 /* Types of printf format used for instruction-related error messages.
700    "I" means int ("%d") and "S" means string ("%s"). */
701 enum mips_insn_error_format {
702   ERR_FMT_PLAIN,
703   ERR_FMT_I,
704   ERR_FMT_SS,
705 };
706
707 /* Information about an error that was found while assembling the current
708    instruction.  */
709 struct mips_insn_error {
710   /* We sometimes need to match an instruction against more than one
711      opcode table entry.  Errors found during this matching are reported
712      against a particular syntactic argument rather than against the
713      instruction as a whole.  We grade these messages so that errors
714      against argument N have a greater priority than an error against
715      any argument < N, since the former implies that arguments up to N
716      were acceptable and that the opcode entry was therefore a closer match.
717      If several matches report an error against the same argument,
718      we only use that error if it is the same in all cases.
719
720      min_argnum is the minimum argument number for which an error message
721      should be accepted.  It is 0 if MSG is against the instruction as
722      a whole.  */
723   int min_argnum;
724
725   /* The printf()-style message, including its format and arguments.  */
726   enum mips_insn_error_format format;
727   const char *msg;
728   union {
729     int i;
730     const char *ss[2];
731   } u;
732 };
733
734 /* The error that should be reported for the current instruction.  */
735 static struct mips_insn_error insn_error;
736
737 static int auto_align = 1;
738
739 /* When outputting SVR4 PIC code, the assembler needs to know the
740    offset in the stack frame from which to restore the $gp register.
741    This is set by the .cprestore pseudo-op, and saved in this
742    variable.  */
743 static offsetT mips_cprestore_offset = -1;
744
745 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
746    more optimizations, it can use a register value instead of a memory-saved
747    offset and even an other register than $gp as global pointer.  */
748 static offsetT mips_cpreturn_offset = -1;
749 static int mips_cpreturn_register = -1;
750 static int mips_gp_register = GP;
751 static int mips_gprel_offset = 0;
752
753 /* Whether mips_cprestore_offset has been set in the current function
754    (or whether it has already been warned about, if not).  */
755 static int mips_cprestore_valid = 0;
756
757 /* This is the register which holds the stack frame, as set by the
758    .frame pseudo-op.  This is needed to implement .cprestore.  */
759 static int mips_frame_reg = SP;
760
761 /* Whether mips_frame_reg has been set in the current function
762    (or whether it has already been warned about, if not).  */
763 static int mips_frame_reg_valid = 0;
764
765 /* To output NOP instructions correctly, we need to keep information
766    about the previous two instructions.  */
767
768 /* Whether we are optimizing.  The default value of 2 means to remove
769    unneeded NOPs and swap branch instructions when possible.  A value
770    of 1 means to not swap branches.  A value of 0 means to always
771    insert NOPs.  */
772 static int mips_optimize = 2;
773
774 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
775    equivalent to seeing no -g option at all.  */
776 static int mips_debug = 0;
777
778 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
779 #define MAX_VR4130_NOPS 4
780
781 /* The maximum number of NOPs needed to fill delay slots.  */
782 #define MAX_DELAY_NOPS 2
783
784 /* The maximum number of NOPs needed for any purpose.  */
785 #define MAX_NOPS 4
786
787 /* A list of previous instructions, with index 0 being the most recent.
788    We need to look back MAX_NOPS instructions when filling delay slots
789    or working around processor errata.  We need to look back one
790    instruction further if we're thinking about using history[0] to
791    fill a branch delay slot.  */
792 static struct mips_cl_insn history[1 + MAX_NOPS];
793
794 /* Arrays of operands for each instruction.  */
795 #define MAX_OPERANDS 6
796 struct mips_operand_array {
797   const struct mips_operand *operand[MAX_OPERANDS];
798 };
799 static struct mips_operand_array *mips_operands;
800 static struct mips_operand_array *mips16_operands;
801 static struct mips_operand_array *micromips_operands;
802
803 /* Nop instructions used by emit_nop.  */
804 static struct mips_cl_insn nop_insn;
805 static struct mips_cl_insn mips16_nop_insn;
806 static struct mips_cl_insn micromips_nop16_insn;
807 static struct mips_cl_insn micromips_nop32_insn;
808
809 /* The appropriate nop for the current mode.  */
810 #define NOP_INSN (mips_opts.mips16                                      \
811                   ? &mips16_nop_insn                                    \
812                   : (mips_opts.micromips                                \
813                      ? (mips_opts.insn32                                \
814                         ? &micromips_nop32_insn                         \
815                         : &micromips_nop16_insn)                        \
816                      : &nop_insn))
817
818 /* The size of NOP_INSN in bytes.  */
819 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
820                         || (mips_opts.micromips && !mips_opts.insn32))  \
821                        ? 2 : 4)
822
823 /* If this is set, it points to a frag holding nop instructions which
824    were inserted before the start of a noreorder section.  If those
825    nops turn out to be unnecessary, the size of the frag can be
826    decreased.  */
827 static fragS *prev_nop_frag;
828
829 /* The number of nop instructions we created in prev_nop_frag.  */
830 static int prev_nop_frag_holds;
831
832 /* The number of nop instructions that we know we need in
833    prev_nop_frag.  */
834 static int prev_nop_frag_required;
835
836 /* The number of instructions we've seen since prev_nop_frag.  */
837 static int prev_nop_frag_since;
838
839 /* Relocations against symbols are sometimes done in two parts, with a HI
840    relocation and a LO relocation.  Each relocation has only 16 bits of
841    space to store an addend.  This means that in order for the linker to
842    handle carries correctly, it must be able to locate both the HI and
843    the LO relocation.  This means that the relocations must appear in
844    order in the relocation table.
845
846    In order to implement this, we keep track of each unmatched HI
847    relocation.  We then sort them so that they immediately precede the
848    corresponding LO relocation.  */
849
850 struct mips_hi_fixup
851 {
852   /* Next HI fixup.  */
853   struct mips_hi_fixup *next;
854   /* This fixup.  */
855   fixS *fixp;
856   /* The section this fixup is in.  */
857   segT seg;
858 };
859
860 /* The list of unmatched HI relocs.  */
861
862 static struct mips_hi_fixup *mips_hi_fixup_list;
863
864 /* The frag containing the last explicit relocation operator.
865    Null if explicit relocations have not been used.  */
866
867 static fragS *prev_reloc_op_frag;
868
869 /* Map mips16 register numbers to normal MIPS register numbers.  */
870
871 static const unsigned int mips16_to_32_reg_map[] =
872 {
873   16, 17, 2, 3, 4, 5, 6, 7
874 };
875
876 /* Map microMIPS register numbers to normal MIPS register numbers.  */
877
878 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
879
880 /* The microMIPS registers with type h.  */
881 static const unsigned int micromips_to_32_reg_h_map1[] =
882 {
883   5, 5, 6, 4, 4, 4, 4, 4
884 };
885 static const unsigned int micromips_to_32_reg_h_map2[] =
886 {
887   6, 7, 7, 21, 22, 5, 6, 7
888 };
889
890 /* The microMIPS registers with type m.  */
891 static const unsigned int micromips_to_32_reg_m_map[] =
892 {
893   0, 17, 2, 3, 16, 18, 19, 20
894 };
895
896 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
897
898 /* Classifies the kind of instructions we're interested in when
899    implementing -mfix-vr4120.  */
900 enum fix_vr4120_class
901 {
902   FIX_VR4120_MACC,
903   FIX_VR4120_DMACC,
904   FIX_VR4120_MULT,
905   FIX_VR4120_DMULT,
906   FIX_VR4120_DIV,
907   FIX_VR4120_MTHILO,
908   NUM_FIX_VR4120_CLASSES
909 };
910
911 /* ...likewise -mfix-loongson2f-jump.  */
912 static bfd_boolean mips_fix_loongson2f_jump;
913
914 /* ...likewise -mfix-loongson2f-nop.  */
915 static bfd_boolean mips_fix_loongson2f_nop;
916
917 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
918 static bfd_boolean mips_fix_loongson2f;
919
920 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
921    there must be at least one other instruction between an instruction
922    of type X and an instruction of type Y.  */
923 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
924
925 /* True if -mfix-vr4120 is in force.  */
926 static int mips_fix_vr4120;
927
928 /* ...likewise -mfix-vr4130.  */
929 static int mips_fix_vr4130;
930
931 /* ...likewise -mfix-24k.  */
932 static int mips_fix_24k;
933
934 /* ...likewise -mfix-rm7000  */
935 static int mips_fix_rm7000;
936
937 /* ...likewise -mfix-cn63xxp1 */
938 static bfd_boolean mips_fix_cn63xxp1;
939
940 /* We don't relax branches by default, since this causes us to expand
941    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
942    fail to compute the offset before expanding the macro to the most
943    efficient expansion.  */
944
945 static int mips_relax_branch;
946
947 /* TRUE if checks are suppressed for invalid branches between ISA modes.
948    Needed for broken assembly produced by some GCC versions and some
949    sloppy code out there, where branches to data labels are present.  */
950 static bfd_boolean mips_ignore_branch_isa;
951 \f
952 /* The expansion of many macros depends on the type of symbol that
953    they refer to.  For example, when generating position-dependent code,
954    a macro that refers to a symbol may have two different expansions,
955    one which uses GP-relative addresses and one which uses absolute
956    addresses.  When generating SVR4-style PIC, a macro may have
957    different expansions for local and global symbols.
958
959    We handle these situations by generating both sequences and putting
960    them in variant frags.  In position-dependent code, the first sequence
961    will be the GP-relative one and the second sequence will be the
962    absolute one.  In SVR4 PIC, the first sequence will be for global
963    symbols and the second will be for local symbols.
964
965    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
966    SECOND are the lengths of the two sequences in bytes.  These fields
967    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
968    the subtype has the following flags:
969
970    RELAX_PIC
971         Set if generating PIC code.
972
973    RELAX_USE_SECOND
974         Set if it has been decided that we should use the second
975         sequence instead of the first.
976
977    RELAX_SECOND_LONGER
978         Set in the first variant frag if the macro's second implementation
979         is longer than its first.  This refers to the macro as a whole,
980         not an individual relaxation.
981
982    RELAX_NOMACRO
983         Set in the first variant frag if the macro appeared in a .set nomacro
984         block and if one alternative requires a warning but the other does not.
985
986    RELAX_DELAY_SLOT
987         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
988         delay slot.
989
990    RELAX_DELAY_SLOT_16BIT
991         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
992         16-bit instruction.
993
994    RELAX_DELAY_SLOT_SIZE_FIRST
995         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
996         the macro is of the wrong size for the branch delay slot.
997
998    RELAX_DELAY_SLOT_SIZE_SECOND
999         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1000         the macro is of the wrong size for the branch delay slot.
1001
1002    The frag's "opcode" points to the first fixup for relaxable code.
1003
1004    Relaxable macros are generated using a sequence such as:
1005
1006       relax_start (SYMBOL);
1007       ... generate first expansion ...
1008       relax_switch ();
1009       ... generate second expansion ...
1010       relax_end ();
1011
1012    The code and fixups for the unwanted alternative are discarded
1013    by md_convert_frag.  */
1014 #define RELAX_ENCODE(FIRST, SECOND, PIC)                        \
1015   (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1016
1017 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1018 #define RELAX_SECOND(X) ((X) & 0xff)
1019 #define RELAX_PIC(X) (((X) & 0x10000) != 0)
1020 #define RELAX_USE_SECOND 0x20000
1021 #define RELAX_SECOND_LONGER 0x40000
1022 #define RELAX_NOMACRO 0x80000
1023 #define RELAX_DELAY_SLOT 0x100000
1024 #define RELAX_DELAY_SLOT_16BIT 0x200000
1025 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1026 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1027
1028 /* Branch without likely bit.  If label is out of range, we turn:
1029
1030         beq reg1, reg2, label
1031         delay slot
1032
1033    into
1034
1035         bne reg1, reg2, 0f
1036         nop
1037         j label
1038      0: delay slot
1039
1040    with the following opcode replacements:
1041
1042         beq <-> bne
1043         blez <-> bgtz
1044         bltz <-> bgez
1045         bc1f <-> bc1t
1046
1047         bltzal <-> bgezal  (with jal label instead of j label)
1048
1049    Even though keeping the delay slot instruction in the delay slot of
1050    the branch would be more efficient, it would be very tricky to do
1051    correctly, because we'd have to introduce a variable frag *after*
1052    the delay slot instruction, and expand that instead.  Let's do it
1053    the easy way for now, even if the branch-not-taken case now costs
1054    one additional instruction.  Out-of-range branches are not supposed
1055    to be common, anyway.
1056
1057    Branch likely.  If label is out of range, we turn:
1058
1059         beql reg1, reg2, label
1060         delay slot (annulled if branch not taken)
1061
1062    into
1063
1064         beql reg1, reg2, 1f
1065         nop
1066         beql $0, $0, 2f
1067         nop
1068      1: j[al] label
1069         delay slot (executed only if branch taken)
1070      2:
1071
1072    It would be possible to generate a shorter sequence by losing the
1073    likely bit, generating something like:
1074
1075         bne reg1, reg2, 0f
1076         nop
1077         j[al] label
1078         delay slot (executed only if branch taken)
1079      0:
1080
1081         beql -> bne
1082         bnel -> beq
1083         blezl -> bgtz
1084         bgtzl -> blez
1085         bltzl -> bgez
1086         bgezl -> bltz
1087         bc1fl -> bc1t
1088         bc1tl -> bc1f
1089
1090         bltzall -> bgezal  (with jal label instead of j label)
1091         bgezall -> bltzal  (ditto)
1092
1093
1094    but it's not clear that it would actually improve performance.  */
1095 #define RELAX_BRANCH_ENCODE(at, pic,                            \
1096                             uncond, likely, link, toofar)       \
1097   ((relax_substateT)                                            \
1098    (0xc0000000                                                  \
1099     | ((at) & 0x1f)                                             \
1100     | ((pic) ? 0x20 : 0)                                        \
1101     | ((toofar) ? 0x40 : 0)                                     \
1102     | ((link) ? 0x80 : 0)                                       \
1103     | ((likely) ? 0x100 : 0)                                    \
1104     | ((uncond) ? 0x200 : 0)))
1105 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1106 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1107 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1108 #define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1109 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1110 #define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1111 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1112
1113 /* For mips16 code, we use an entirely different form of relaxation.
1114    mips16 supports two versions of most instructions which take
1115    immediate values: a small one which takes some small value, and a
1116    larger one which takes a 16 bit value.  Since branches also follow
1117    this pattern, relaxing these values is required.
1118
1119    We can assemble both mips16 and normal MIPS code in a single
1120    object.  Therefore, we need to support this type of relaxation at
1121    the same time that we support the relaxation described above.  We
1122    use the high bit of the subtype field to distinguish these cases.
1123
1124    The information we store for this type of relaxation is the
1125    argument code found in the opcode file for this relocation, whether
1126    the user explicitly requested a small or extended form, and whether
1127    the relocation is in a jump or jal delay slot.  That tells us the
1128    size of the value, and how it should be stored.  We also store
1129    whether the fragment is considered to be extended or not.  We also
1130    store whether this is known to be a branch to a different section,
1131    whether we have tried to relax this frag yet, and whether we have
1132    ever extended a PC relative fragment because of a shift count.  */
1133 #define RELAX_MIPS16_ENCODE(type, e2, pic, sym32, nomacro,      \
1134                             small, ext,                         \
1135                             dslot, jal_dslot)                   \
1136   (0x80000000                                                   \
1137    | ((type) & 0xff)                                            \
1138    | ((e2) ? 0x100 : 0)                                         \
1139    | ((pic) ? 0x200 : 0)                                        \
1140    | ((sym32) ? 0x400 : 0)                                      \
1141    | ((nomacro) ? 0x800 : 0)                                    \
1142    | ((small) ? 0x1000 : 0)                                     \
1143    | ((ext) ? 0x2000 : 0)                                       \
1144    | ((dslot) ? 0x4000 : 0)                                     \
1145    | ((jal_dslot) ? 0x8000 : 0))
1146
1147 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1148 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1149 #define RELAX_MIPS16_E2(i) (((i) & 0x100) != 0)
1150 #define RELAX_MIPS16_PIC(i) (((i) & 0x200) != 0)
1151 #define RELAX_MIPS16_SYM32(i) (((i) & 0x400) != 0)
1152 #define RELAX_MIPS16_NOMACRO(i) (((i) & 0x800) != 0)
1153 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x1000) != 0)
1154 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x2000) != 0)
1155 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x4000) != 0)
1156 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x8000) != 0)
1157
1158 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x10000) != 0)
1159 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x10000)
1160 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x10000)
1161 #define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x20000) != 0)
1162 #define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x20000)
1163 #define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x20000)
1164 #define RELAX_MIPS16_MACRO(i) (((i) & 0x40000) != 0)
1165 #define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x40000)
1166 #define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x40000)
1167
1168 /* For microMIPS code, we use relaxation similar to one we use for
1169    MIPS16 code.  Some instructions that take immediate values support
1170    two encodings: a small one which takes some small value, and a
1171    larger one which takes a 16 bit value.  As some branches also follow
1172    this pattern, relaxing these values is required.
1173
1174    We can assemble both microMIPS and normal MIPS code in a single
1175    object.  Therefore, we need to support this type of relaxation at
1176    the same time that we support the relaxation described above.  We
1177    use one of the high bits of the subtype field to distinguish these
1178    cases.
1179
1180    The information we store for this type of relaxation is the argument
1181    code found in the opcode file for this relocation, the register
1182    selected as the assembler temporary, whether in the 32-bit
1183    instruction mode, whether the branch is unconditional, whether it is
1184    compact, whether there is no delay-slot instruction available to fill
1185    in, whether it stores the link address implicitly in $ra, whether
1186    relaxation of out-of-range 32-bit branches to a sequence of
1187    instructions is enabled, and whether the displacement of a branch is
1188    too large to fit as an immediate argument of a 16-bit and a 32-bit
1189    branch, respectively.  */
1190 #define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,           \
1191                                uncond, compact, link, nods,     \
1192                                relax32, toofar16, toofar32)     \
1193   (0x40000000                                                   \
1194    | ((type) & 0xff)                                            \
1195    | (((at) & 0x1f) << 8)                                       \
1196    | ((insn32) ? 0x2000 : 0)                                    \
1197    | ((pic) ? 0x4000 : 0)                                       \
1198    | ((uncond) ? 0x8000 : 0)                                    \
1199    | ((compact) ? 0x10000 : 0)                                  \
1200    | ((link) ? 0x20000 : 0)                                     \
1201    | ((nods) ? 0x40000 : 0)                                     \
1202    | ((relax32) ? 0x80000 : 0)                                  \
1203    | ((toofar16) ? 0x100000 : 0)                                \
1204    | ((toofar32) ? 0x200000 : 0))
1205 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1206 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1207 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1208 #define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1209 #define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1210 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1211 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1212 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1213 #define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1214 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1215
1216 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1217 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1218 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1219 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1220 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1221 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1222
1223 /* Sign-extend 16-bit value X.  */
1224 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1225
1226 /* Is the given value a sign-extended 32-bit value?  */
1227 #define IS_SEXT_32BIT_NUM(x)                                            \
1228   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1229    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1230
1231 /* Is the given value a sign-extended 16-bit value?  */
1232 #define IS_SEXT_16BIT_NUM(x)                                            \
1233   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1234    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1235
1236 /* Is the given value a sign-extended 12-bit value?  */
1237 #define IS_SEXT_12BIT_NUM(x)                                            \
1238   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1239
1240 /* Is the given value a sign-extended 9-bit value?  */
1241 #define IS_SEXT_9BIT_NUM(x)                                             \
1242   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1243
1244 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1245 #define IS_ZEXT_32BIT_NUM(x)                                            \
1246   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1247    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1248
1249 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1250    SHIFT places.  */
1251 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1252   (((STRUCT) >> (SHIFT)) & (MASK))
1253
1254 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1255 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1256   (!(MICROMIPS) \
1257    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1258    : EXTRACT_BITS ((INSN).insn_opcode, \
1259                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1260 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1261   EXTRACT_BITS ((INSN).insn_opcode, \
1262                 MIPS16OP_MASK_##FIELD, \
1263                 MIPS16OP_SH_##FIELD)
1264
1265 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1266 #define MIPS16_EXTEND (0xf000U << 16)
1267 \f
1268 /* Whether or not we are emitting a branch-likely macro.  */
1269 static bfd_boolean emit_branch_likely_macro = FALSE;
1270
1271 /* Global variables used when generating relaxable macros.  See the
1272    comment above RELAX_ENCODE for more details about how relaxation
1273    is used.  */
1274 static struct {
1275   /* 0 if we're not emitting a relaxable macro.
1276      1 if we're emitting the first of the two relaxation alternatives.
1277      2 if we're emitting the second alternative.  */
1278   int sequence;
1279
1280   /* The first relaxable fixup in the current frag.  (In other words,
1281      the first fixup that refers to relaxable code.)  */
1282   fixS *first_fixup;
1283
1284   /* sizes[0] says how many bytes of the first alternative are stored in
1285      the current frag.  Likewise sizes[1] for the second alternative.  */
1286   unsigned int sizes[2];
1287
1288   /* The symbol on which the choice of sequence depends.  */
1289   symbolS *symbol;
1290 } mips_relax;
1291 \f
1292 /* Global variables used to decide whether a macro needs a warning.  */
1293 static struct {
1294   /* True if the macro is in a branch delay slot.  */
1295   bfd_boolean delay_slot_p;
1296
1297   /* Set to the length in bytes required if the macro is in a delay slot
1298      that requires a specific length of instruction, otherwise zero.  */
1299   unsigned int delay_slot_length;
1300
1301   /* For relaxable macros, sizes[0] is the length of the first alternative
1302      in bytes and sizes[1] is the length of the second alternative.
1303      For non-relaxable macros, both elements give the length of the
1304      macro in bytes.  */
1305   unsigned int sizes[2];
1306
1307   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1308      instruction of the first alternative in bytes and first_insn_sizes[1]
1309      is the length of the first instruction of the second alternative.
1310      For non-relaxable macros, both elements give the length of the first
1311      instruction in bytes.
1312
1313      Set to zero if we haven't yet seen the first instruction.  */
1314   unsigned int first_insn_sizes[2];
1315
1316   /* For relaxable macros, insns[0] is the number of instructions for the
1317      first alternative and insns[1] is the number of instructions for the
1318      second alternative.
1319
1320      For non-relaxable macros, both elements give the number of
1321      instructions for the macro.  */
1322   unsigned int insns[2];
1323
1324   /* The first variant frag for this macro.  */
1325   fragS *first_frag;
1326 } mips_macro_warning;
1327 \f
1328 /* Prototypes for static functions.  */
1329
1330 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1331
1332 static void append_insn
1333   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1334    bfd_boolean expansionp);
1335 static void mips_no_prev_insn (void);
1336 static void macro_build (expressionS *, const char *, const char *, ...);
1337 static void mips16_macro_build
1338   (expressionS *, const char *, const char *, va_list *);
1339 static void load_register (int, expressionS *, int);
1340 static void macro_start (void);
1341 static void macro_end (void);
1342 static void macro (struct mips_cl_insn *ip, char *str);
1343 static void mips16_macro (struct mips_cl_insn * ip);
1344 static void mips_ip (char *str, struct mips_cl_insn * ip);
1345 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1346 static unsigned long mips16_immed_extend (offsetT, unsigned int);
1347 static void mips16_immed
1348   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1349    unsigned int, unsigned long *);
1350 static size_t my_getSmallExpression
1351   (expressionS *, bfd_reloc_code_real_type *, char *);
1352 static void my_getExpression (expressionS *, char *);
1353 static void s_align (int);
1354 static void s_change_sec (int);
1355 static void s_change_section (int);
1356 static void s_cons (int);
1357 static void s_float_cons (int);
1358 static void s_mips_globl (int);
1359 static void s_option (int);
1360 static void s_mipsset (int);
1361 static void s_abicalls (int);
1362 static void s_cpload (int);
1363 static void s_cpsetup (int);
1364 static void s_cplocal (int);
1365 static void s_cprestore (int);
1366 static void s_cpreturn (int);
1367 static void s_dtprelword (int);
1368 static void s_dtpreldword (int);
1369 static void s_tprelword (int);
1370 static void s_tpreldword (int);
1371 static void s_gpvalue (int);
1372 static void s_gpword (int);
1373 static void s_gpdword (int);
1374 static void s_ehword (int);
1375 static void s_cpadd (int);
1376 static void s_insn (int);
1377 static void s_nan (int);
1378 static void s_module (int);
1379 static void s_mips_ent (int);
1380 static void s_mips_end (int);
1381 static void s_mips_frame (int);
1382 static void s_mips_mask (int reg_type);
1383 static void s_mips_stab (int);
1384 static void s_mips_weakext (int);
1385 static void s_mips_file (int);
1386 static void s_mips_loc (int);
1387 static bfd_boolean pic_need_relax (symbolS *);
1388 static int relaxed_branch_length (fragS *, asection *, int);
1389 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1390 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1391 static void file_mips_check_options (void);
1392
1393 /* Table and functions used to map between CPU/ISA names, and
1394    ISA levels, and CPU numbers.  */
1395
1396 struct mips_cpu_info
1397 {
1398   const char *name;           /* CPU or ISA name.  */
1399   int flags;                  /* MIPS_CPU_* flags.  */
1400   int ase;                    /* Set of ASEs implemented by the CPU.  */
1401   int isa;                    /* ISA level.  */
1402   int cpu;                    /* CPU number (default CPU if ISA).  */
1403 };
1404
1405 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1406
1407 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1408 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1409 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1410 \f
1411 /* Command-line options.  */
1412 const char *md_shortopts = "O::g::G:";
1413
1414 enum options
1415   {
1416     OPTION_MARCH = OPTION_MD_BASE,
1417     OPTION_MTUNE,
1418     OPTION_MIPS1,
1419     OPTION_MIPS2,
1420     OPTION_MIPS3,
1421     OPTION_MIPS4,
1422     OPTION_MIPS5,
1423     OPTION_MIPS32,
1424     OPTION_MIPS64,
1425     OPTION_MIPS32R2,
1426     OPTION_MIPS32R3,
1427     OPTION_MIPS32R5,
1428     OPTION_MIPS32R6,
1429     OPTION_MIPS64R2,
1430     OPTION_MIPS64R3,
1431     OPTION_MIPS64R5,
1432     OPTION_MIPS64R6,
1433     OPTION_MIPS16,
1434     OPTION_NO_MIPS16,
1435     OPTION_MIPS3D,
1436     OPTION_NO_MIPS3D,
1437     OPTION_MDMX,
1438     OPTION_NO_MDMX,
1439     OPTION_DSP,
1440     OPTION_NO_DSP,
1441     OPTION_MT,
1442     OPTION_NO_MT,
1443     OPTION_VIRT,
1444     OPTION_NO_VIRT,
1445     OPTION_MSA,
1446     OPTION_NO_MSA,
1447     OPTION_SMARTMIPS,
1448     OPTION_NO_SMARTMIPS,
1449     OPTION_DSPR2,
1450     OPTION_NO_DSPR2,
1451     OPTION_DSPR3,
1452     OPTION_NO_DSPR3,
1453     OPTION_EVA,
1454     OPTION_NO_EVA,
1455     OPTION_XPA,
1456     OPTION_NO_XPA,
1457     OPTION_MICROMIPS,
1458     OPTION_NO_MICROMIPS,
1459     OPTION_MCU,
1460     OPTION_NO_MCU,
1461     OPTION_MIPS16E2,
1462     OPTION_NO_MIPS16E2,
1463     OPTION_CRC,
1464     OPTION_NO_CRC,
1465     OPTION_M4650,
1466     OPTION_NO_M4650,
1467     OPTION_M4010,
1468     OPTION_NO_M4010,
1469     OPTION_M4100,
1470     OPTION_NO_M4100,
1471     OPTION_M3900,
1472     OPTION_NO_M3900,
1473     OPTION_M7000_HILO_FIX,
1474     OPTION_MNO_7000_HILO_FIX,
1475     OPTION_FIX_24K,
1476     OPTION_NO_FIX_24K,
1477     OPTION_FIX_RM7000,
1478     OPTION_NO_FIX_RM7000,
1479     OPTION_FIX_LOONGSON2F_JUMP,
1480     OPTION_NO_FIX_LOONGSON2F_JUMP,
1481     OPTION_FIX_LOONGSON2F_NOP,
1482     OPTION_NO_FIX_LOONGSON2F_NOP,
1483     OPTION_FIX_VR4120,
1484     OPTION_NO_FIX_VR4120,
1485     OPTION_FIX_VR4130,
1486     OPTION_NO_FIX_VR4130,
1487     OPTION_FIX_CN63XXP1,
1488     OPTION_NO_FIX_CN63XXP1,
1489     OPTION_TRAP,
1490     OPTION_BREAK,
1491     OPTION_EB,
1492     OPTION_EL,
1493     OPTION_FP32,
1494     OPTION_GP32,
1495     OPTION_CONSTRUCT_FLOATS,
1496     OPTION_NO_CONSTRUCT_FLOATS,
1497     OPTION_FP64,
1498     OPTION_FPXX,
1499     OPTION_GP64,
1500     OPTION_RELAX_BRANCH,
1501     OPTION_NO_RELAX_BRANCH,
1502     OPTION_IGNORE_BRANCH_ISA,
1503     OPTION_NO_IGNORE_BRANCH_ISA,
1504     OPTION_INSN32,
1505     OPTION_NO_INSN32,
1506     OPTION_MSHARED,
1507     OPTION_MNO_SHARED,
1508     OPTION_MSYM32,
1509     OPTION_MNO_SYM32,
1510     OPTION_SOFT_FLOAT,
1511     OPTION_HARD_FLOAT,
1512     OPTION_SINGLE_FLOAT,
1513     OPTION_DOUBLE_FLOAT,
1514     OPTION_32,
1515     OPTION_CALL_SHARED,
1516     OPTION_CALL_NONPIC,
1517     OPTION_NON_SHARED,
1518     OPTION_XGOT,
1519     OPTION_MABI,
1520     OPTION_N32,
1521     OPTION_64,
1522     OPTION_MDEBUG,
1523     OPTION_NO_MDEBUG,
1524     OPTION_PDR,
1525     OPTION_NO_PDR,
1526     OPTION_MVXWORKS_PIC,
1527     OPTION_NAN,
1528     OPTION_ODD_SPREG,
1529     OPTION_NO_ODD_SPREG,
1530     OPTION_GINV,
1531     OPTION_NO_GINV,
1532     OPTION_LOONGSON_MMI,
1533     OPTION_NO_LOONGSON_MMI,
1534     OPTION_LOONGSON_CAM,
1535     OPTION_NO_LOONGSON_CAM,
1536     OPTION_LOONGSON_EXT,
1537     OPTION_NO_LOONGSON_EXT,
1538     OPTION_END_OF_ENUM
1539   };
1540
1541 struct option md_longopts[] =
1542 {
1543   /* Options which specify architecture.  */
1544   {"march", required_argument, NULL, OPTION_MARCH},
1545   {"mtune", required_argument, NULL, OPTION_MTUNE},
1546   {"mips0", no_argument, NULL, OPTION_MIPS1},
1547   {"mips1", no_argument, NULL, OPTION_MIPS1},
1548   {"mips2", no_argument, NULL, OPTION_MIPS2},
1549   {"mips3", no_argument, NULL, OPTION_MIPS3},
1550   {"mips4", no_argument, NULL, OPTION_MIPS4},
1551   {"mips5", no_argument, NULL, OPTION_MIPS5},
1552   {"mips32", no_argument, NULL, OPTION_MIPS32},
1553   {"mips64", no_argument, NULL, OPTION_MIPS64},
1554   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1555   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1556   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1557   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1558   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1559   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1560   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1561   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1562
1563   /* Options which specify Application Specific Extensions (ASEs).  */
1564   {"mips16", no_argument, NULL, OPTION_MIPS16},
1565   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1566   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1567   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1568   {"mdmx", no_argument, NULL, OPTION_MDMX},
1569   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1570   {"mdsp", no_argument, NULL, OPTION_DSP},
1571   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1572   {"mmt", no_argument, NULL, OPTION_MT},
1573   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1574   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1575   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1576   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1577   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1578   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1579   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1580   {"meva", no_argument, NULL, OPTION_EVA},
1581   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1582   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1583   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1584   {"mmcu", no_argument, NULL, OPTION_MCU},
1585   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1586   {"mvirt", no_argument, NULL, OPTION_VIRT},
1587   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1588   {"mmsa", no_argument, NULL, OPTION_MSA},
1589   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1590   {"mxpa", no_argument, NULL, OPTION_XPA},
1591   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1592   {"mmips16e2", no_argument, NULL, OPTION_MIPS16E2},
1593   {"mno-mips16e2", no_argument, NULL, OPTION_NO_MIPS16E2},
1594   {"mcrc", no_argument, NULL, OPTION_CRC},
1595   {"mno-crc", no_argument, NULL, OPTION_NO_CRC},
1596   {"mginv", no_argument, NULL, OPTION_GINV},
1597   {"mno-ginv", no_argument, NULL, OPTION_NO_GINV},
1598   {"mloongson-mmi", no_argument, NULL, OPTION_LOONGSON_MMI},
1599   {"mno-loongson-mmi", no_argument, NULL, OPTION_NO_LOONGSON_MMI},
1600   {"mloongson-cam", no_argument, NULL, OPTION_LOONGSON_CAM},
1601   {"mno-loongson-cam", no_argument, NULL, OPTION_NO_LOONGSON_CAM},
1602   {"mloongson-ext", no_argument, NULL, OPTION_LOONGSON_EXT},
1603   {"mno-loongson-ext", no_argument, NULL, OPTION_NO_LOONGSON_EXT},
1604
1605   /* Old-style architecture options.  Don't add more of these.  */
1606   {"m4650", no_argument, NULL, OPTION_M4650},
1607   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1608   {"m4010", no_argument, NULL, OPTION_M4010},
1609   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1610   {"m4100", no_argument, NULL, OPTION_M4100},
1611   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1612   {"m3900", no_argument, NULL, OPTION_M3900},
1613   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1614
1615   /* Options which enable bug fixes.  */
1616   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1617   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1618   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1619   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1620   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1621   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1622   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1623   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1624   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1625   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1626   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1627   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1628   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1629   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1630   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1631   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1632   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1633
1634   /* Miscellaneous options.  */
1635   {"trap", no_argument, NULL, OPTION_TRAP},
1636   {"no-break", no_argument, NULL, OPTION_TRAP},
1637   {"break", no_argument, NULL, OPTION_BREAK},
1638   {"no-trap", no_argument, NULL, OPTION_BREAK},
1639   {"EB", no_argument, NULL, OPTION_EB},
1640   {"EL", no_argument, NULL, OPTION_EL},
1641   {"mfp32", no_argument, NULL, OPTION_FP32},
1642   {"mgp32", no_argument, NULL, OPTION_GP32},
1643   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1644   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1645   {"mfp64", no_argument, NULL, OPTION_FP64},
1646   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1647   {"mgp64", no_argument, NULL, OPTION_GP64},
1648   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1649   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1650   {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1651   {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1652   {"minsn32", no_argument, NULL, OPTION_INSN32},
1653   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1654   {"mshared", no_argument, NULL, OPTION_MSHARED},
1655   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1656   {"msym32", no_argument, NULL, OPTION_MSYM32},
1657   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1658   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1659   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1660   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1661   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1662   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1663   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1664
1665   /* Strictly speaking this next option is ELF specific,
1666      but we allow it for other ports as well in order to
1667      make testing easier.  */
1668   {"32", no_argument, NULL, OPTION_32},
1669
1670   /* ELF-specific options.  */
1671   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1672   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1673   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1674   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1675   {"xgot", no_argument, NULL, OPTION_XGOT},
1676   {"mabi", required_argument, NULL, OPTION_MABI},
1677   {"n32", no_argument, NULL, OPTION_N32},
1678   {"64", no_argument, NULL, OPTION_64},
1679   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1680   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1681   {"mpdr", no_argument, NULL, OPTION_PDR},
1682   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1683   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1684   {"mnan", required_argument, NULL, OPTION_NAN},
1685
1686   {NULL, no_argument, NULL, 0}
1687 };
1688 size_t md_longopts_size = sizeof (md_longopts);
1689 \f
1690 /* Information about either an Application Specific Extension or an
1691    optional architecture feature that, for simplicity, we treat in the
1692    same way as an ASE.  */
1693 struct mips_ase
1694 {
1695   /* The name of the ASE, used in both the command-line and .set options.  */
1696   const char *name;
1697
1698   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1699      and 64-bit architectures, the flags here refer to the subset that
1700      is available on both.  */
1701   unsigned int flags;
1702
1703   /* The ASE_* flag used for instructions that are available on 64-bit
1704      architectures but that are not included in FLAGS.  */
1705   unsigned int flags64;
1706
1707   /* The command-line options that turn the ASE on and off.  */
1708   int option_on;
1709   int option_off;
1710
1711   /* The minimum required architecture revisions for MIPS32, MIPS64,
1712      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1713   int mips32_rev;
1714   int mips64_rev;
1715   int micromips32_rev;
1716   int micromips64_rev;
1717
1718   /* The architecture where the ASE was removed or -1 if the extension has not
1719      been removed.  */
1720   int rem_rev;
1721 };
1722
1723 /* A table of all supported ASEs.  */
1724 static const struct mips_ase mips_ases[] = {
1725   { "dsp", ASE_DSP, ASE_DSP64,
1726     OPTION_DSP, OPTION_NO_DSP,
1727     2, 2, 2, 2,
1728     -1 },
1729
1730   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1731     OPTION_DSPR2, OPTION_NO_DSPR2,
1732     2, 2, 2, 2,
1733     -1 },
1734
1735   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1736     OPTION_DSPR3, OPTION_NO_DSPR3,
1737     6, 6, -1, -1,
1738     -1 },
1739
1740   { "eva", ASE_EVA, 0,
1741     OPTION_EVA, OPTION_NO_EVA,
1742      2,  2,  2,  2,
1743     -1 },
1744
1745   { "mcu", ASE_MCU, 0,
1746     OPTION_MCU, OPTION_NO_MCU,
1747      2,  2,  2,  2,
1748     -1 },
1749
1750   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1751   { "mdmx", ASE_MDMX, 0,
1752     OPTION_MDMX, OPTION_NO_MDMX,
1753     -1, 1, -1, -1,
1754      6 },
1755
1756   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1757   { "mips3d", ASE_MIPS3D, 0,
1758     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1759     2, 1, -1, -1,
1760     6 },
1761
1762   { "mt", ASE_MT, 0,
1763     OPTION_MT, OPTION_NO_MT,
1764      2,  2, -1, -1,
1765     -1 },
1766
1767   { "smartmips", ASE_SMARTMIPS, 0,
1768     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1769     1, -1, -1, -1,
1770     6 },
1771
1772   { "virt", ASE_VIRT, ASE_VIRT64,
1773     OPTION_VIRT, OPTION_NO_VIRT,
1774      2,  2,  2,  2,
1775     -1 },
1776
1777   { "msa", ASE_MSA, ASE_MSA64,
1778     OPTION_MSA, OPTION_NO_MSA,
1779      2,  2,  2,  2,
1780     -1 },
1781
1782   { "xpa", ASE_XPA, 0,
1783     OPTION_XPA, OPTION_NO_XPA,
1784     2, 2, 2, 2,
1785     -1 },
1786
1787   { "mips16e2", ASE_MIPS16E2, 0,
1788     OPTION_MIPS16E2, OPTION_NO_MIPS16E2,
1789     2,  2, -1, -1,
1790     6 },
1791
1792   { "crc", ASE_CRC, ASE_CRC64,
1793     OPTION_CRC, OPTION_NO_CRC,
1794     6,  6, -1, -1,
1795     -1 },
1796
1797   { "ginv", ASE_GINV, 0,
1798     OPTION_GINV, OPTION_NO_GINV,
1799     6,  6, 6, 6,
1800     -1 },
1801
1802   { "loongson-mmi", ASE_LOONGSON_MMI, 0,
1803     OPTION_LOONGSON_MMI, OPTION_NO_LOONGSON_MMI,
1804     0, 0, -1, -1,
1805     -1 },
1806
1807   { "loongson-cam", ASE_LOONGSON_CAM, 0,
1808     OPTION_LOONGSON_CAM, OPTION_NO_LOONGSON_CAM,
1809     0, 0, -1, -1,
1810     -1 },
1811
1812   { "loongson-ext", ASE_LOONGSON_EXT, 0,
1813     OPTION_LOONGSON_EXT, OPTION_NO_LOONGSON_EXT,
1814     0, 0, -1, -1,
1815     -1 },
1816 };
1817
1818 /* The set of ASEs that require -mfp64.  */
1819 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1820
1821 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1822 static const unsigned int mips_ase_groups[] = {
1823   ASE_DSP | ASE_DSPR2 | ASE_DSPR3
1824 };
1825 \f
1826 /* Pseudo-op table.
1827
1828    The following pseudo-ops from the Kane and Heinrich MIPS book
1829    should be defined here, but are currently unsupported: .alias,
1830    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1831
1832    The following pseudo-ops from the Kane and Heinrich MIPS book are
1833    specific to the type of debugging information being generated, and
1834    should be defined by the object format: .aent, .begin, .bend,
1835    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1836    .vreg.
1837
1838    The following pseudo-ops from the Kane and Heinrich MIPS book are
1839    not MIPS CPU specific, but are also not specific to the object file
1840    format.  This file is probably the best place to define them, but
1841    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1842
1843 static const pseudo_typeS mips_pseudo_table[] =
1844 {
1845   /* MIPS specific pseudo-ops.  */
1846   {"option", s_option, 0},
1847   {"set", s_mipsset, 0},
1848   {"rdata", s_change_sec, 'r'},
1849   {"sdata", s_change_sec, 's'},
1850   {"livereg", s_ignore, 0},
1851   {"abicalls", s_abicalls, 0},
1852   {"cpload", s_cpload, 0},
1853   {"cpsetup", s_cpsetup, 0},
1854   {"cplocal", s_cplocal, 0},
1855   {"cprestore", s_cprestore, 0},
1856   {"cpreturn", s_cpreturn, 0},
1857   {"dtprelword", s_dtprelword, 0},
1858   {"dtpreldword", s_dtpreldword, 0},
1859   {"tprelword", s_tprelword, 0},
1860   {"tpreldword", s_tpreldword, 0},
1861   {"gpvalue", s_gpvalue, 0},
1862   {"gpword", s_gpword, 0},
1863   {"gpdword", s_gpdword, 0},
1864   {"ehword", s_ehword, 0},
1865   {"cpadd", s_cpadd, 0},
1866   {"insn", s_insn, 0},
1867   {"nan", s_nan, 0},
1868   {"module", s_module, 0},
1869
1870   /* Relatively generic pseudo-ops that happen to be used on MIPS
1871      chips.  */
1872   {"asciiz", stringer, 8 + 1},
1873   {"bss", s_change_sec, 'b'},
1874   {"err", s_err, 0},
1875   {"half", s_cons, 1},
1876   {"dword", s_cons, 3},
1877   {"weakext", s_mips_weakext, 0},
1878   {"origin", s_org, 0},
1879   {"repeat", s_rept, 0},
1880
1881   /* For MIPS this is non-standard, but we define it for consistency.  */
1882   {"sbss", s_change_sec, 'B'},
1883
1884   /* These pseudo-ops are defined in read.c, but must be overridden
1885      here for one reason or another.  */
1886   {"align", s_align, 0},
1887   {"byte", s_cons, 0},
1888   {"data", s_change_sec, 'd'},
1889   {"double", s_float_cons, 'd'},
1890   {"float", s_float_cons, 'f'},
1891   {"globl", s_mips_globl, 0},
1892   {"global", s_mips_globl, 0},
1893   {"hword", s_cons, 1},
1894   {"int", s_cons, 2},
1895   {"long", s_cons, 2},
1896   {"octa", s_cons, 4},
1897   {"quad", s_cons, 3},
1898   {"section", s_change_section, 0},
1899   {"short", s_cons, 1},
1900   {"single", s_float_cons, 'f'},
1901   {"stabd", s_mips_stab, 'd'},
1902   {"stabn", s_mips_stab, 'n'},
1903   {"stabs", s_mips_stab, 's'},
1904   {"text", s_change_sec, 't'},
1905   {"word", s_cons, 2},
1906
1907   { "extern", ecoff_directive_extern, 0},
1908
1909   { NULL, NULL, 0 },
1910 };
1911
1912 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1913 {
1914   /* These pseudo-ops should be defined by the object file format.
1915      However, a.out doesn't support them, so we have versions here.  */
1916   {"aent", s_mips_ent, 1},
1917   {"bgnb", s_ignore, 0},
1918   {"end", s_mips_end, 0},
1919   {"endb", s_ignore, 0},
1920   {"ent", s_mips_ent, 0},
1921   {"file", s_mips_file, 0},
1922   {"fmask", s_mips_mask, 'F'},
1923   {"frame", s_mips_frame, 0},
1924   {"loc", s_mips_loc, 0},
1925   {"mask", s_mips_mask, 'R'},
1926   {"verstamp", s_ignore, 0},
1927   { NULL, NULL, 0 },
1928 };
1929
1930 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1931    purpose of the `.dc.a' internal pseudo-op.  */
1932
1933 int
1934 mips_address_bytes (void)
1935 {
1936   file_mips_check_options ();
1937   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1938 }
1939
1940 extern void pop_insert (const pseudo_typeS *);
1941
1942 void
1943 mips_pop_insert (void)
1944 {
1945   pop_insert (mips_pseudo_table);
1946   if (! ECOFF_DEBUGGING)
1947     pop_insert (mips_nonecoff_pseudo_table);
1948 }
1949 \f
1950 /* Symbols labelling the current insn.  */
1951
1952 struct insn_label_list
1953 {
1954   struct insn_label_list *next;
1955   symbolS *label;
1956 };
1957
1958 static struct insn_label_list *free_insn_labels;
1959 #define label_list tc_segment_info_data.labels
1960
1961 static void mips_clear_insn_labels (void);
1962 static void mips_mark_labels (void);
1963 static void mips_compressed_mark_labels (void);
1964
1965 static inline void
1966 mips_clear_insn_labels (void)
1967 {
1968   struct insn_label_list **pl;
1969   segment_info_type *si;
1970
1971   if (now_seg)
1972     {
1973       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1974         ;
1975
1976       si = seg_info (now_seg);
1977       *pl = si->label_list;
1978       si->label_list = NULL;
1979     }
1980 }
1981
1982 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1983
1984 static inline void
1985 mips_mark_labels (void)
1986 {
1987   if (HAVE_CODE_COMPRESSION)
1988     mips_compressed_mark_labels ();
1989 }
1990 \f
1991 static char *expr_end;
1992
1993 /* An expression in a macro instruction.  This is set by mips_ip and
1994    mips16_ip and when populated is always an O_constant.  */
1995
1996 static expressionS imm_expr;
1997
1998 /* The relocatable field in an instruction and the relocs associated
1999    with it.  These variables are used for instructions like LUI and
2000    JAL as well as true offsets.  They are also used for address
2001    operands in macros.  */
2002
2003 static expressionS offset_expr;
2004 static bfd_reloc_code_real_type offset_reloc[3]
2005   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2006
2007 /* This is set to the resulting size of the instruction to be produced
2008    by mips16_ip if an explicit extension is used or by mips_ip if an
2009    explicit size is supplied.  */
2010
2011 static unsigned int forced_insn_length;
2012
2013 /* True if we are assembling an instruction.  All dot symbols defined during
2014    this time should be treated as code labels.  */
2015
2016 static bfd_boolean mips_assembling_insn;
2017
2018 /* The pdr segment for per procedure frame/regmask info.  Not used for
2019    ECOFF debugging.  */
2020
2021 static segT pdr_seg;
2022
2023 /* The default target format to use.  */
2024
2025 #if defined (TE_FreeBSD)
2026 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
2027 #elif defined (TE_TMIPS)
2028 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
2029 #else
2030 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
2031 #endif
2032
2033 const char *
2034 mips_target_format (void)
2035 {
2036   switch (OUTPUT_FLAVOR)
2037     {
2038     case bfd_target_elf_flavour:
2039 #ifdef TE_VXWORKS
2040       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
2041         return (target_big_endian
2042                 ? "elf32-bigmips-vxworks"
2043                 : "elf32-littlemips-vxworks");
2044 #endif
2045       return (target_big_endian
2046               ? (HAVE_64BIT_OBJECTS
2047                  ? ELF_TARGET ("elf64-", "big")
2048                  : (HAVE_NEWABI
2049                     ? ELF_TARGET ("elf32-n", "big")
2050                     : ELF_TARGET ("elf32-", "big")))
2051               : (HAVE_64BIT_OBJECTS
2052                  ? ELF_TARGET ("elf64-", "little")
2053                  : (HAVE_NEWABI
2054                     ? ELF_TARGET ("elf32-n", "little")
2055                     : ELF_TARGET ("elf32-", "little"))));
2056     default:
2057       abort ();
2058       return NULL;
2059     }
2060 }
2061
2062 /* Return the ISA revision that is currently in use, or 0 if we are
2063    generating code for MIPS V or below.  */
2064
2065 static int
2066 mips_isa_rev (void)
2067 {
2068   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2069     return 2;
2070
2071   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2072     return 3;
2073
2074   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2075     return 5;
2076
2077   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2078     return 6;
2079
2080   /* microMIPS implies revision 2 or above.  */
2081   if (mips_opts.micromips)
2082     return 2;
2083
2084   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2085     return 1;
2086
2087   return 0;
2088 }
2089
2090 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2091
2092 static unsigned int
2093 mips_ase_mask (unsigned int flags)
2094 {
2095   unsigned int i;
2096
2097   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2098     if (flags & mips_ase_groups[i])
2099       flags |= mips_ase_groups[i];
2100   return flags;
2101 }
2102
2103 /* Check whether the current ISA supports ASE.  Issue a warning if
2104    appropriate.  */
2105
2106 static void
2107 mips_check_isa_supports_ase (const struct mips_ase *ase)
2108 {
2109   const char *base;
2110   int min_rev, size;
2111   static unsigned int warned_isa;
2112   static unsigned int warned_fp32;
2113
2114   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2115     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2116   else
2117     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2118   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2119       && (warned_isa & ase->flags) != ase->flags)
2120     {
2121       warned_isa |= ase->flags;
2122       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2123       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2124       if (min_rev < 0)
2125         as_warn (_("the %d-bit %s architecture does not support the"
2126                    " `%s' extension"), size, base, ase->name);
2127       else
2128         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2129                  ase->name, base, size, min_rev);
2130     }
2131   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2132            && (warned_isa & ase->flags) != ase->flags)
2133     {
2134       warned_isa |= ase->flags;
2135       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2136       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2137       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2138                ase->name, base, size, ase->rem_rev);
2139     }
2140
2141   if ((ase->flags & FP64_ASES)
2142       && mips_opts.fp != 64
2143       && (warned_fp32 & ase->flags) != ase->flags)
2144     {
2145       warned_fp32 |= ase->flags;
2146       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2147     }
2148 }
2149
2150 /* Check all enabled ASEs to see whether they are supported by the
2151    chosen architecture.  */
2152
2153 static void
2154 mips_check_isa_supports_ases (void)
2155 {
2156   unsigned int i, mask;
2157
2158   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2159     {
2160       mask = mips_ase_mask (mips_ases[i].flags);
2161       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2162         mips_check_isa_supports_ase (&mips_ases[i]);
2163     }
2164 }
2165
2166 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2167    that were affected.  */
2168
2169 static unsigned int
2170 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2171               bfd_boolean enabled_p)
2172 {
2173   unsigned int mask;
2174
2175   mask = mips_ase_mask (ase->flags);
2176   opts->ase &= ~mask;
2177
2178   /* Clear combination ASE flags, which need to be recalculated based on
2179      updated regular ASE settings.  */
2180   opts->ase &= ~(ASE_MIPS16E2_MT | ASE_XPA_VIRT);
2181
2182   if (enabled_p)
2183     opts->ase |= ase->flags;
2184
2185   /* The Virtualization ASE has eXtended Physical Addressing (XPA)
2186      instructions which are only valid when both ASEs are enabled.
2187      This sets the ASE_XPA_VIRT flag when both ASEs are present.  */
2188   if ((opts->ase & (ASE_XPA | ASE_VIRT)) == (ASE_XPA | ASE_VIRT))
2189     {
2190       opts->ase |= ASE_XPA_VIRT;
2191       mask |= ASE_XPA_VIRT;
2192     }
2193   if ((opts->ase & (ASE_MIPS16E2 | ASE_MT)) == (ASE_MIPS16E2 | ASE_MT))
2194     {
2195       opts->ase |= ASE_MIPS16E2_MT;
2196       mask |= ASE_MIPS16E2_MT;
2197     }
2198
2199   return mask;
2200 }
2201
2202 /* Return the ASE called NAME, or null if none.  */
2203
2204 static const struct mips_ase *
2205 mips_lookup_ase (const char *name)
2206 {
2207   unsigned int i;
2208
2209   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2210     if (strcmp (name, mips_ases[i].name) == 0)
2211       return &mips_ases[i];
2212   return NULL;
2213 }
2214
2215 /* Return the length of a microMIPS instruction in bytes.  If bits of
2216    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2217    otherwise it is a 32-bit instruction.  */
2218
2219 static inline unsigned int
2220 micromips_insn_length (const struct mips_opcode *mo)
2221 {
2222   return mips_opcode_32bit_p (mo) ? 4 : 2;
2223 }
2224
2225 /* Return the length of MIPS16 instruction OPCODE.  */
2226
2227 static inline unsigned int
2228 mips16_opcode_length (unsigned long opcode)
2229 {
2230   return (opcode >> 16) == 0 ? 2 : 4;
2231 }
2232
2233 /* Return the length of instruction INSN.  */
2234
2235 static inline unsigned int
2236 insn_length (const struct mips_cl_insn *insn)
2237 {
2238   if (mips_opts.micromips)
2239     return micromips_insn_length (insn->insn_mo);
2240   else if (mips_opts.mips16)
2241     return mips16_opcode_length (insn->insn_opcode);
2242   else
2243     return 4;
2244 }
2245
2246 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2247
2248 static void
2249 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2250 {
2251   size_t i;
2252
2253   insn->insn_mo = mo;
2254   insn->insn_opcode = mo->match;
2255   insn->frag = NULL;
2256   insn->where = 0;
2257   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2258     insn->fixp[i] = NULL;
2259   insn->fixed_p = (mips_opts.noreorder > 0);
2260   insn->noreorder_p = (mips_opts.noreorder > 0);
2261   insn->mips16_absolute_jump_p = 0;
2262   insn->complete_p = 0;
2263   insn->cleared_p = 0;
2264 }
2265
2266 /* Get a list of all the operands in INSN.  */
2267
2268 static const struct mips_operand_array *
2269 insn_operands (const struct mips_cl_insn *insn)
2270 {
2271   if (insn->insn_mo >= &mips_opcodes[0]
2272       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2273     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2274
2275   if (insn->insn_mo >= &mips16_opcodes[0]
2276       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2277     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2278
2279   if (insn->insn_mo >= &micromips_opcodes[0]
2280       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2281     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2282
2283   abort ();
2284 }
2285
2286 /* Get a description of operand OPNO of INSN.  */
2287
2288 static const struct mips_operand *
2289 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2290 {
2291   const struct mips_operand_array *operands;
2292
2293   operands = insn_operands (insn);
2294   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2295     abort ();
2296   return operands->operand[opno];
2297 }
2298
2299 /* Install UVAL as the value of OPERAND in INSN.  */
2300
2301 static inline void
2302 insn_insert_operand (struct mips_cl_insn *insn,
2303                      const struct mips_operand *operand, unsigned int uval)
2304 {
2305   if (mips_opts.mips16
2306       && operand->type == OP_INT && operand->lsb == 0
2307       && mips_opcode_32bit_p (insn->insn_mo))
2308     insn->insn_opcode |= mips16_immed_extend (uval, operand->size);
2309   else
2310     insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2311 }
2312
2313 /* Extract the value of OPERAND from INSN.  */
2314
2315 static inline unsigned
2316 insn_extract_operand (const struct mips_cl_insn *insn,
2317                       const struct mips_operand *operand)
2318 {
2319   return mips_extract_operand (operand, insn->insn_opcode);
2320 }
2321
2322 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2323
2324 static void
2325 mips_record_compressed_mode (void)
2326 {
2327   segment_info_type *si;
2328
2329   si = seg_info (now_seg);
2330   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2331     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2332   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2333     si->tc_segment_info_data.micromips = mips_opts.micromips;
2334 }
2335
2336 /* Read a standard MIPS instruction from BUF.  */
2337
2338 static unsigned long
2339 read_insn (char *buf)
2340 {
2341   if (target_big_endian)
2342     return bfd_getb32 ((bfd_byte *) buf);
2343   else
2344     return bfd_getl32 ((bfd_byte *) buf);
2345 }
2346
2347 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2348    the next byte.  */
2349
2350 static char *
2351 write_insn (char *buf, unsigned int insn)
2352 {
2353   md_number_to_chars (buf, insn, 4);
2354   return buf + 4;
2355 }
2356
2357 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2358    has length LENGTH.  */
2359
2360 static unsigned long
2361 read_compressed_insn (char *buf, unsigned int length)
2362 {
2363   unsigned long insn;
2364   unsigned int i;
2365
2366   insn = 0;
2367   for (i = 0; i < length; i += 2)
2368     {
2369       insn <<= 16;
2370       if (target_big_endian)
2371         insn |= bfd_getb16 ((char *) buf);
2372       else
2373         insn |= bfd_getl16 ((char *) buf);
2374       buf += 2;
2375     }
2376   return insn;
2377 }
2378
2379 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2380    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2381
2382 static char *
2383 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2384 {
2385   unsigned int i;
2386
2387   for (i = 0; i < length; i += 2)
2388     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2389   return buf + length;
2390 }
2391
2392 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2393
2394 static void
2395 install_insn (const struct mips_cl_insn *insn)
2396 {
2397   char *f = insn->frag->fr_literal + insn->where;
2398   if (HAVE_CODE_COMPRESSION)
2399     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2400   else
2401     write_insn (f, insn->insn_opcode);
2402   mips_record_compressed_mode ();
2403 }
2404
2405 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2406    and install the opcode in the new location.  */
2407
2408 static void
2409 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2410 {
2411   size_t i;
2412
2413   insn->frag = frag;
2414   insn->where = where;
2415   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2416     if (insn->fixp[i] != NULL)
2417       {
2418         insn->fixp[i]->fx_frag = frag;
2419         insn->fixp[i]->fx_where = where;
2420       }
2421   install_insn (insn);
2422 }
2423
2424 /* Add INSN to the end of the output.  */
2425
2426 static void
2427 add_fixed_insn (struct mips_cl_insn *insn)
2428 {
2429   char *f = frag_more (insn_length (insn));
2430   move_insn (insn, frag_now, f - frag_now->fr_literal);
2431 }
2432
2433 /* Start a variant frag and move INSN to the start of the variant part,
2434    marking it as fixed.  The other arguments are as for frag_var.  */
2435
2436 static void
2437 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2438                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2439 {
2440   frag_grow (max_chars);
2441   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2442   insn->fixed_p = 1;
2443   frag_var (rs_machine_dependent, max_chars, var,
2444             subtype, symbol, offset, NULL);
2445 }
2446
2447 /* Insert N copies of INSN into the history buffer, starting at
2448    position FIRST.  Neither FIRST nor N need to be clipped.  */
2449
2450 static void
2451 insert_into_history (unsigned int first, unsigned int n,
2452                      const struct mips_cl_insn *insn)
2453 {
2454   if (mips_relax.sequence != 2)
2455     {
2456       unsigned int i;
2457
2458       for (i = ARRAY_SIZE (history); i-- > first;)
2459         if (i >= first + n)
2460           history[i] = history[i - n];
2461         else
2462           history[i] = *insn;
2463     }
2464 }
2465
2466 /* Clear the error in insn_error.  */
2467
2468 static void
2469 clear_insn_error (void)
2470 {
2471   memset (&insn_error, 0, sizeof (insn_error));
2472 }
2473
2474 /* Possibly record error message MSG for the current instruction.
2475    If the error is about a particular argument, ARGNUM is the 1-based
2476    number of that argument, otherwise it is 0.  FORMAT is the format
2477    of MSG.  Return true if MSG was used, false if the current message
2478    was kept.  */
2479
2480 static bfd_boolean
2481 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2482                        const char *msg)
2483 {
2484   if (argnum == 0)
2485     {
2486       /* Give priority to errors against specific arguments, and to
2487          the first whole-instruction message.  */
2488       if (insn_error.msg)
2489         return FALSE;
2490     }
2491   else
2492     {
2493       /* Keep insn_error if it is against a later argument.  */
2494       if (argnum < insn_error.min_argnum)
2495         return FALSE;
2496
2497       /* If both errors are against the same argument but are different,
2498          give up on reporting a specific error for this argument.
2499          See the comment about mips_insn_error for details.  */
2500       if (argnum == insn_error.min_argnum
2501           && insn_error.msg
2502           && strcmp (insn_error.msg, msg) != 0)
2503         {
2504           insn_error.msg = 0;
2505           insn_error.min_argnum += 1;
2506           return FALSE;
2507         }
2508     }
2509   insn_error.min_argnum = argnum;
2510   insn_error.format = format;
2511   insn_error.msg = msg;
2512   return TRUE;
2513 }
2514
2515 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2516    as for set_insn_error_format.  */
2517
2518 static void
2519 set_insn_error (int argnum, const char *msg)
2520 {
2521   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2522 }
2523
2524 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2525    as for set_insn_error_format.  */
2526
2527 static void
2528 set_insn_error_i (int argnum, const char *msg, int i)
2529 {
2530   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2531     insn_error.u.i = i;
2532 }
2533
2534 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2535    are as for set_insn_error_format.  */
2536
2537 static void
2538 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2539 {
2540   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2541     {
2542       insn_error.u.ss[0] = s1;
2543       insn_error.u.ss[1] = s2;
2544     }
2545 }
2546
2547 /* Report the error in insn_error, which is against assembly code STR.  */
2548
2549 static void
2550 report_insn_error (const char *str)
2551 {
2552   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2553
2554   switch (insn_error.format)
2555     {
2556     case ERR_FMT_PLAIN:
2557       as_bad (msg, str);
2558       break;
2559
2560     case ERR_FMT_I:
2561       as_bad (msg, insn_error.u.i, str);
2562       break;
2563
2564     case ERR_FMT_SS:
2565       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2566       break;
2567     }
2568
2569   free ((char *) msg);
2570 }
2571
2572 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2573    the idea is to make it obvious at a glance that each errata is
2574    included.  */
2575
2576 static void
2577 init_vr4120_conflicts (void)
2578 {
2579 #define CONFLICT(FIRST, SECOND) \
2580     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2581
2582   /* Errata 21 - [D]DIV[U] after [D]MACC */
2583   CONFLICT (MACC, DIV);
2584   CONFLICT (DMACC, DIV);
2585
2586   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2587   CONFLICT (DMULT, DMULT);
2588   CONFLICT (DMULT, DMACC);
2589   CONFLICT (DMACC, DMULT);
2590   CONFLICT (DMACC, DMACC);
2591
2592   /* Errata 24 - MT{LO,HI} after [D]MACC */
2593   CONFLICT (MACC, MTHILO);
2594   CONFLICT (DMACC, MTHILO);
2595
2596   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2597      instruction is executed immediately after a MACC or DMACC
2598      instruction, the result of [either instruction] is incorrect."  */
2599   CONFLICT (MACC, MULT);
2600   CONFLICT (MACC, DMULT);
2601   CONFLICT (DMACC, MULT);
2602   CONFLICT (DMACC, DMULT);
2603
2604   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2605      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2606      DDIV or DDIVU instruction, the result of the MACC or
2607      DMACC instruction is incorrect.".  */
2608   CONFLICT (DMULT, MACC);
2609   CONFLICT (DMULT, DMACC);
2610   CONFLICT (DIV, MACC);
2611   CONFLICT (DIV, DMACC);
2612
2613 #undef CONFLICT
2614 }
2615
2616 struct regname {
2617   const char *name;
2618   unsigned int num;
2619 };
2620
2621 #define RNUM_MASK       0x00000ff
2622 #define RTYPE_MASK      0x0ffff00
2623 #define RTYPE_NUM       0x0000100
2624 #define RTYPE_FPU       0x0000200
2625 #define RTYPE_FCC       0x0000400
2626 #define RTYPE_VEC       0x0000800
2627 #define RTYPE_GP        0x0001000
2628 #define RTYPE_CP0       0x0002000
2629 #define RTYPE_PC        0x0004000
2630 #define RTYPE_ACC       0x0008000
2631 #define RTYPE_CCC       0x0010000
2632 #define RTYPE_VI        0x0020000
2633 #define RTYPE_VF        0x0040000
2634 #define RTYPE_R5900_I   0x0080000
2635 #define RTYPE_R5900_Q   0x0100000
2636 #define RTYPE_R5900_R   0x0200000
2637 #define RTYPE_R5900_ACC 0x0400000
2638 #define RTYPE_MSA       0x0800000
2639 #define RWARN           0x8000000
2640
2641 #define GENERIC_REGISTER_NUMBERS \
2642     {"$0",      RTYPE_NUM | 0},  \
2643     {"$1",      RTYPE_NUM | 1},  \
2644     {"$2",      RTYPE_NUM | 2},  \
2645     {"$3",      RTYPE_NUM | 3},  \
2646     {"$4",      RTYPE_NUM | 4},  \
2647     {"$5",      RTYPE_NUM | 5},  \
2648     {"$6",      RTYPE_NUM | 6},  \
2649     {"$7",      RTYPE_NUM | 7},  \
2650     {"$8",      RTYPE_NUM | 8},  \
2651     {"$9",      RTYPE_NUM | 9},  \
2652     {"$10",     RTYPE_NUM | 10}, \
2653     {"$11",     RTYPE_NUM | 11}, \
2654     {"$12",     RTYPE_NUM | 12}, \
2655     {"$13",     RTYPE_NUM | 13}, \
2656     {"$14",     RTYPE_NUM | 14}, \
2657     {"$15",     RTYPE_NUM | 15}, \
2658     {"$16",     RTYPE_NUM | 16}, \
2659     {"$17",     RTYPE_NUM | 17}, \
2660     {"$18",     RTYPE_NUM | 18}, \
2661     {"$19",     RTYPE_NUM | 19}, \
2662     {"$20",     RTYPE_NUM | 20}, \
2663     {"$21",     RTYPE_NUM | 21}, \
2664     {"$22",     RTYPE_NUM | 22}, \
2665     {"$23",     RTYPE_NUM | 23}, \
2666     {"$24",     RTYPE_NUM | 24}, \
2667     {"$25",     RTYPE_NUM | 25}, \
2668     {"$26",     RTYPE_NUM | 26}, \
2669     {"$27",     RTYPE_NUM | 27}, \
2670     {"$28",     RTYPE_NUM | 28}, \
2671     {"$29",     RTYPE_NUM | 29}, \
2672     {"$30",     RTYPE_NUM | 30}, \
2673     {"$31",     RTYPE_NUM | 31}
2674
2675 #define FPU_REGISTER_NAMES       \
2676     {"$f0",     RTYPE_FPU | 0},  \
2677     {"$f1",     RTYPE_FPU | 1},  \
2678     {"$f2",     RTYPE_FPU | 2},  \
2679     {"$f3",     RTYPE_FPU | 3},  \
2680     {"$f4",     RTYPE_FPU | 4},  \
2681     {"$f5",     RTYPE_FPU | 5},  \
2682     {"$f6",     RTYPE_FPU | 6},  \
2683     {"$f7",     RTYPE_FPU | 7},  \
2684     {"$f8",     RTYPE_FPU | 8},  \
2685     {"$f9",     RTYPE_FPU | 9},  \
2686     {"$f10",    RTYPE_FPU | 10}, \
2687     {"$f11",    RTYPE_FPU | 11}, \
2688     {"$f12",    RTYPE_FPU | 12}, \
2689     {"$f13",    RTYPE_FPU | 13}, \
2690     {"$f14",    RTYPE_FPU | 14}, \
2691     {"$f15",    RTYPE_FPU | 15}, \
2692     {"$f16",    RTYPE_FPU | 16}, \
2693     {"$f17",    RTYPE_FPU | 17}, \
2694     {"$f18",    RTYPE_FPU | 18}, \
2695     {"$f19",    RTYPE_FPU | 19}, \
2696     {"$f20",    RTYPE_FPU | 20}, \
2697     {"$f21",    RTYPE_FPU | 21}, \
2698     {"$f22",    RTYPE_FPU | 22}, \
2699     {"$f23",    RTYPE_FPU | 23}, \
2700     {"$f24",    RTYPE_FPU | 24}, \
2701     {"$f25",    RTYPE_FPU | 25}, \
2702     {"$f26",    RTYPE_FPU | 26}, \
2703     {"$f27",    RTYPE_FPU | 27}, \
2704     {"$f28",    RTYPE_FPU | 28}, \
2705     {"$f29",    RTYPE_FPU | 29}, \
2706     {"$f30",    RTYPE_FPU | 30}, \
2707     {"$f31",    RTYPE_FPU | 31}
2708
2709 #define FPU_CONDITION_CODE_NAMES \
2710     {"$fcc0",   RTYPE_FCC | 0},  \
2711     {"$fcc1",   RTYPE_FCC | 1},  \
2712     {"$fcc2",   RTYPE_FCC | 2},  \
2713     {"$fcc3",   RTYPE_FCC | 3},  \
2714     {"$fcc4",   RTYPE_FCC | 4},  \
2715     {"$fcc5",   RTYPE_FCC | 5},  \
2716     {"$fcc6",   RTYPE_FCC | 6},  \
2717     {"$fcc7",   RTYPE_FCC | 7}
2718
2719 #define COPROC_CONDITION_CODE_NAMES         \
2720     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2721     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2722     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2723     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2724     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2725     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2726     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2727     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2728
2729 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2730     {"$a4",     RTYPE_GP | 8},  \
2731     {"$a5",     RTYPE_GP | 9},  \
2732     {"$a6",     RTYPE_GP | 10}, \
2733     {"$a7",     RTYPE_GP | 11}, \
2734     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2735     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2736     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2737     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2738     {"$t0",     RTYPE_GP | 12}, \
2739     {"$t1",     RTYPE_GP | 13}, \
2740     {"$t2",     RTYPE_GP | 14}, \
2741     {"$t3",     RTYPE_GP | 15}
2742
2743 #define O32_SYMBOLIC_REGISTER_NAMES \
2744     {"$t0",     RTYPE_GP | 8},  \
2745     {"$t1",     RTYPE_GP | 9},  \
2746     {"$t2",     RTYPE_GP | 10}, \
2747     {"$t3",     RTYPE_GP | 11}, \
2748     {"$t4",     RTYPE_GP | 12}, \
2749     {"$t5",     RTYPE_GP | 13}, \
2750     {"$t6",     RTYPE_GP | 14}, \
2751     {"$t7",     RTYPE_GP | 15}, \
2752     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2753     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2754     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2755     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2756
2757 /* Remaining symbolic register names */
2758 #define SYMBOLIC_REGISTER_NAMES \
2759     {"$zero",   RTYPE_GP | 0},  \
2760     {"$at",     RTYPE_GP | 1},  \
2761     {"$AT",     RTYPE_GP | 1},  \
2762     {"$v0",     RTYPE_GP | 2},  \
2763     {"$v1",     RTYPE_GP | 3},  \
2764     {"$a0",     RTYPE_GP | 4},  \
2765     {"$a1",     RTYPE_GP | 5},  \
2766     {"$a2",     RTYPE_GP | 6},  \
2767     {"$a3",     RTYPE_GP | 7},  \
2768     {"$s0",     RTYPE_GP | 16}, \
2769     {"$s1",     RTYPE_GP | 17}, \
2770     {"$s2",     RTYPE_GP | 18}, \
2771     {"$s3",     RTYPE_GP | 19}, \
2772     {"$s4",     RTYPE_GP | 20}, \
2773     {"$s5",     RTYPE_GP | 21}, \
2774     {"$s6",     RTYPE_GP | 22}, \
2775     {"$s7",     RTYPE_GP | 23}, \
2776     {"$t8",     RTYPE_GP | 24}, \
2777     {"$t9",     RTYPE_GP | 25}, \
2778     {"$k0",     RTYPE_GP | 26}, \
2779     {"$kt0",    RTYPE_GP | 26}, \
2780     {"$k1",     RTYPE_GP | 27}, \
2781     {"$kt1",    RTYPE_GP | 27}, \
2782     {"$gp",     RTYPE_GP | 28}, \
2783     {"$sp",     RTYPE_GP | 29}, \
2784     {"$s8",     RTYPE_GP | 30}, \
2785     {"$fp",     RTYPE_GP | 30}, \
2786     {"$ra",     RTYPE_GP | 31}
2787
2788 #define MIPS16_SPECIAL_REGISTER_NAMES \
2789     {"$pc",     RTYPE_PC | 0}
2790
2791 #define MDMX_VECTOR_REGISTER_NAMES \
2792     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2793     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2794     {"$v2",     RTYPE_VEC | 2},  \
2795     {"$v3",     RTYPE_VEC | 3},  \
2796     {"$v4",     RTYPE_VEC | 4},  \
2797     {"$v5",     RTYPE_VEC | 5},  \
2798     {"$v6",     RTYPE_VEC | 6},  \
2799     {"$v7",     RTYPE_VEC | 7},  \
2800     {"$v8",     RTYPE_VEC | 8},  \
2801     {"$v9",     RTYPE_VEC | 9},  \
2802     {"$v10",    RTYPE_VEC | 10}, \
2803     {"$v11",    RTYPE_VEC | 11}, \
2804     {"$v12",    RTYPE_VEC | 12}, \
2805     {"$v13",    RTYPE_VEC | 13}, \
2806     {"$v14",    RTYPE_VEC | 14}, \
2807     {"$v15",    RTYPE_VEC | 15}, \
2808     {"$v16",    RTYPE_VEC | 16}, \
2809     {"$v17",    RTYPE_VEC | 17}, \
2810     {"$v18",    RTYPE_VEC | 18}, \
2811     {"$v19",    RTYPE_VEC | 19}, \
2812     {"$v20",    RTYPE_VEC | 20}, \
2813     {"$v21",    RTYPE_VEC | 21}, \
2814     {"$v22",    RTYPE_VEC | 22}, \
2815     {"$v23",    RTYPE_VEC | 23}, \
2816     {"$v24",    RTYPE_VEC | 24}, \
2817     {"$v25",    RTYPE_VEC | 25}, \
2818     {"$v26",    RTYPE_VEC | 26}, \
2819     {"$v27",    RTYPE_VEC | 27}, \
2820     {"$v28",    RTYPE_VEC | 28}, \
2821     {"$v29",    RTYPE_VEC | 29}, \
2822     {"$v30",    RTYPE_VEC | 30}, \
2823     {"$v31",    RTYPE_VEC | 31}
2824
2825 #define R5900_I_NAMES \
2826     {"$I",      RTYPE_R5900_I | 0}
2827
2828 #define R5900_Q_NAMES \
2829     {"$Q",      RTYPE_R5900_Q | 0}
2830
2831 #define R5900_R_NAMES \
2832     {"$R",      RTYPE_R5900_R | 0}
2833
2834 #define R5900_ACC_NAMES \
2835     {"$ACC",    RTYPE_R5900_ACC | 0 }
2836
2837 #define MIPS_DSP_ACCUMULATOR_NAMES \
2838     {"$ac0",    RTYPE_ACC | 0}, \
2839     {"$ac1",    RTYPE_ACC | 1}, \
2840     {"$ac2",    RTYPE_ACC | 2}, \
2841     {"$ac3",    RTYPE_ACC | 3}
2842
2843 static const struct regname reg_names[] = {
2844   GENERIC_REGISTER_NUMBERS,
2845   FPU_REGISTER_NAMES,
2846   FPU_CONDITION_CODE_NAMES,
2847   COPROC_CONDITION_CODE_NAMES,
2848
2849   /* The $txx registers depends on the abi,
2850      these will be added later into the symbol table from
2851      one of the tables below once mips_abi is set after
2852      parsing of arguments from the command line. */
2853   SYMBOLIC_REGISTER_NAMES,
2854
2855   MIPS16_SPECIAL_REGISTER_NAMES,
2856   MDMX_VECTOR_REGISTER_NAMES,
2857   R5900_I_NAMES,
2858   R5900_Q_NAMES,
2859   R5900_R_NAMES,
2860   R5900_ACC_NAMES,
2861   MIPS_DSP_ACCUMULATOR_NAMES,
2862   {0, 0}
2863 };
2864
2865 static const struct regname reg_names_o32[] = {
2866   O32_SYMBOLIC_REGISTER_NAMES,
2867   {0, 0}
2868 };
2869
2870 static const struct regname reg_names_n32n64[] = {
2871   N32N64_SYMBOLIC_REGISTER_NAMES,
2872   {0, 0}
2873 };
2874
2875 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2876    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2877    of these register symbols, return the associated vector register,
2878    otherwise return SYMVAL itself.  */
2879
2880 static unsigned int
2881 mips_prefer_vec_regno (unsigned int symval)
2882 {
2883   if ((symval & -2) == (RTYPE_GP | 2))
2884     return RTYPE_VEC | (symval & 1);
2885   return symval;
2886 }
2887
2888 /* Return true if string [S, E) is a valid register name, storing its
2889    symbol value in *SYMVAL_PTR if so.  */
2890
2891 static bfd_boolean
2892 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2893 {
2894   char save_c;
2895   symbolS *symbol;
2896
2897   /* Terminate name.  */
2898   save_c = *e;
2899   *e = '\0';
2900
2901   /* Look up the name.  */
2902   symbol = symbol_find (s);
2903   *e = save_c;
2904
2905   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2906     return FALSE;
2907
2908   *symval_ptr = S_GET_VALUE (symbol);
2909   return TRUE;
2910 }
2911
2912 /* Return true if the string at *SPTR is a valid register name.  Allow it
2913    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2914    is nonnull.
2915
2916    When returning true, move *SPTR past the register, store the
2917    register's symbol value in *SYMVAL_PTR and the channel mask in
2918    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2919    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2920    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2921
2922 static bfd_boolean
2923 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2924                      unsigned int *channels_ptr)
2925 {
2926   char *s, *e, *m;
2927   const char *q;
2928   unsigned int channels, symval, bit;
2929
2930   /* Find end of name.  */
2931   s = e = *sptr;
2932   if (is_name_beginner (*e))
2933     ++e;
2934   while (is_part_of_name (*e))
2935     ++e;
2936
2937   channels = 0;
2938   if (!mips_parse_register_1 (s, e, &symval))
2939     {
2940       if (!channels_ptr)
2941         return FALSE;
2942
2943       /* Eat characters from the end of the string that are valid
2944          channel suffixes.  The preceding register must be $ACC or
2945          end with a digit, so there is no ambiguity.  */
2946       bit = 1;
2947       m = e;
2948       for (q = "wzyx"; *q; q++, bit <<= 1)
2949         if (m > s && m[-1] == *q)
2950           {
2951             --m;
2952             channels |= bit;
2953           }
2954
2955       if (channels == 0
2956           || !mips_parse_register_1 (s, m, &symval)
2957           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2958         return FALSE;
2959     }
2960
2961   *sptr = e;
2962   *symval_ptr = symval;
2963   if (channels_ptr)
2964     *channels_ptr = channels;
2965   return TRUE;
2966 }
2967
2968 /* Check if SPTR points at a valid register specifier according to TYPES.
2969    If so, then return 1, advance S to consume the specifier and store
2970    the register's number in REGNOP, otherwise return 0.  */
2971
2972 static int
2973 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2974 {
2975   unsigned int regno;
2976
2977   if (mips_parse_register (s, &regno, NULL))
2978     {
2979       if (types & RTYPE_VEC)
2980         regno = mips_prefer_vec_regno (regno);
2981       if (regno & types)
2982         regno &= RNUM_MASK;
2983       else
2984         regno = ~0;
2985     }
2986   else
2987     {
2988       if (types & RWARN)
2989         as_warn (_("unrecognized register name `%s'"), *s);
2990       regno = ~0;
2991     }
2992   if (regnop)
2993     *regnop = regno;
2994   return regno <= RNUM_MASK;
2995 }
2996
2997 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2998    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2999
3000 static char *
3001 mips_parse_vu0_channels (char *s, unsigned int *channels)
3002 {
3003   unsigned int i;
3004
3005   *channels = 0;
3006   for (i = 0; i < 4; i++)
3007     if (*s == "xyzw"[i])
3008       {
3009         *channels |= 1 << (3 - i);
3010         ++s;
3011       }
3012   return s;
3013 }
3014
3015 /* Token types for parsed operand lists.  */
3016 enum mips_operand_token_type {
3017   /* A plain register, e.g. $f2.  */
3018   OT_REG,
3019
3020   /* A 4-bit XYZW channel mask.  */
3021   OT_CHANNELS,
3022
3023   /* A constant vector index, e.g. [1].  */
3024   OT_INTEGER_INDEX,
3025
3026   /* A register vector index, e.g. [$2].  */
3027   OT_REG_INDEX,
3028
3029   /* A continuous range of registers, e.g. $s0-$s4.  */
3030   OT_REG_RANGE,
3031
3032   /* A (possibly relocated) expression.  */
3033   OT_INTEGER,
3034
3035   /* A floating-point value.  */
3036   OT_FLOAT,
3037
3038   /* A single character.  This can be '(', ')' or ',', but '(' only appears
3039      before OT_REGs.  */
3040   OT_CHAR,
3041
3042   /* A doubled character, either "--" or "++".  */
3043   OT_DOUBLE_CHAR,
3044
3045   /* The end of the operand list.  */
3046   OT_END
3047 };
3048
3049 /* A parsed operand token.  */
3050 struct mips_operand_token
3051 {
3052   /* The type of token.  */
3053   enum mips_operand_token_type type;
3054   union
3055   {
3056     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
3057     unsigned int regno;
3058
3059     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
3060     unsigned int channels;
3061
3062     /* The integer value of an OT_INTEGER_INDEX.  */
3063     addressT index;
3064
3065     /* The two register symbol values involved in an OT_REG_RANGE.  */
3066     struct {
3067       unsigned int regno1;
3068       unsigned int regno2;
3069     } reg_range;
3070
3071     /* The value of an OT_INTEGER.  The value is represented as an
3072        expression and the relocation operators that were applied to
3073        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
3074        relocation operators were used.  */
3075     struct {
3076       expressionS value;
3077       bfd_reloc_code_real_type relocs[3];
3078     } integer;
3079
3080     /* The binary data for an OT_FLOAT constant, and the number of bytes
3081        in the constant.  */
3082     struct {
3083       unsigned char data[8];
3084       int length;
3085     } flt;
3086
3087     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3088     char ch;
3089   } u;
3090 };
3091
3092 /* An obstack used to construct lists of mips_operand_tokens.  */
3093 static struct obstack mips_operand_tokens;
3094
3095 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3096
3097 static void
3098 mips_add_token (struct mips_operand_token *token,
3099                 enum mips_operand_token_type type)
3100 {
3101   token->type = type;
3102   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3103 }
3104
3105 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
3106    and OT_REG tokens for them if so, and return a pointer to the first
3107    unconsumed character.  Return null otherwise.  */
3108
3109 static char *
3110 mips_parse_base_start (char *s)
3111 {
3112   struct mips_operand_token token;
3113   unsigned int regno, channels;
3114   bfd_boolean decrement_p;
3115
3116   if (*s != '(')
3117     return 0;
3118
3119   ++s;
3120   SKIP_SPACE_TABS (s);
3121
3122   /* Only match "--" as part of a base expression.  In other contexts "--X"
3123      is a double negative.  */
3124   decrement_p = (s[0] == '-' && s[1] == '-');
3125   if (decrement_p)
3126     {
3127       s += 2;
3128       SKIP_SPACE_TABS (s);
3129     }
3130
3131   /* Allow a channel specifier because that leads to better error messages
3132      than treating something like "$vf0x++" as an expression.  */
3133   if (!mips_parse_register (&s, &regno, &channels))
3134     return 0;
3135
3136   token.u.ch = '(';
3137   mips_add_token (&token, OT_CHAR);
3138
3139   if (decrement_p)
3140     {
3141       token.u.ch = '-';
3142       mips_add_token (&token, OT_DOUBLE_CHAR);
3143     }
3144
3145   token.u.regno = regno;
3146   mips_add_token (&token, OT_REG);
3147
3148   if (channels)
3149     {
3150       token.u.channels = channels;
3151       mips_add_token (&token, OT_CHANNELS);
3152     }
3153
3154   /* For consistency, only match "++" as part of base expressions too.  */
3155   SKIP_SPACE_TABS (s);
3156   if (s[0] == '+' && s[1] == '+')
3157     {
3158       s += 2;
3159       token.u.ch = '+';
3160       mips_add_token (&token, OT_DOUBLE_CHAR);
3161     }
3162
3163   return s;
3164 }
3165
3166 /* Parse one or more tokens from S.  Return a pointer to the first
3167    unconsumed character on success.  Return null if an error was found
3168    and store the error text in insn_error.  FLOAT_FORMAT is as for
3169    mips_parse_arguments.  */
3170
3171 static char *
3172 mips_parse_argument_token (char *s, char float_format)
3173 {
3174   char *end, *save_in;
3175   const char *err;
3176   unsigned int regno1, regno2, channels;
3177   struct mips_operand_token token;
3178
3179   /* First look for "($reg", since we want to treat that as an
3180      OT_CHAR and OT_REG rather than an expression.  */
3181   end = mips_parse_base_start (s);
3182   if (end)
3183     return end;
3184
3185   /* Handle other characters that end up as OT_CHARs.  */
3186   if (*s == ')' || *s == ',')
3187     {
3188       token.u.ch = *s;
3189       mips_add_token (&token, OT_CHAR);
3190       ++s;
3191       return s;
3192     }
3193
3194   /* Handle tokens that start with a register.  */
3195   if (mips_parse_register (&s, &regno1, &channels))
3196     {
3197       if (channels)
3198         {
3199           /* A register and a VU0 channel suffix.  */
3200           token.u.regno = regno1;
3201           mips_add_token (&token, OT_REG);
3202
3203           token.u.channels = channels;
3204           mips_add_token (&token, OT_CHANNELS);
3205           return s;
3206         }
3207
3208       SKIP_SPACE_TABS (s);
3209       if (*s == '-')
3210         {
3211           /* A register range.  */
3212           ++s;
3213           SKIP_SPACE_TABS (s);
3214           if (!mips_parse_register (&s, &regno2, NULL))
3215             {
3216               set_insn_error (0, _("invalid register range"));
3217               return 0;
3218             }
3219
3220           token.u.reg_range.regno1 = regno1;
3221           token.u.reg_range.regno2 = regno2;
3222           mips_add_token (&token, OT_REG_RANGE);
3223           return s;
3224         }
3225
3226       /* Add the register itself.  */
3227       token.u.regno = regno1;
3228       mips_add_token (&token, OT_REG);
3229
3230       /* Check for a vector index.  */
3231       if (*s == '[')
3232         {
3233           ++s;
3234           SKIP_SPACE_TABS (s);
3235           if (mips_parse_register (&s, &token.u.regno, NULL))
3236             mips_add_token (&token, OT_REG_INDEX);
3237           else
3238             {
3239               expressionS element;
3240
3241               my_getExpression (&element, s);
3242               if (element.X_op != O_constant)
3243                 {
3244                   set_insn_error (0, _("vector element must be constant"));
3245                   return 0;
3246                 }
3247               s = expr_end;
3248               token.u.index = element.X_add_number;
3249               mips_add_token (&token, OT_INTEGER_INDEX);
3250             }
3251           SKIP_SPACE_TABS (s);
3252           if (*s != ']')
3253             {
3254               set_insn_error (0, _("missing `]'"));
3255               return 0;
3256             }
3257           ++s;
3258         }
3259       return s;
3260     }
3261
3262   if (float_format)
3263     {
3264       /* First try to treat expressions as floats.  */
3265       save_in = input_line_pointer;
3266       input_line_pointer = s;
3267       err = md_atof (float_format, (char *) token.u.flt.data,
3268                      &token.u.flt.length);
3269       end = input_line_pointer;
3270       input_line_pointer = save_in;
3271       if (err && *err)
3272         {
3273           set_insn_error (0, err);
3274           return 0;
3275         }
3276       if (s != end)
3277         {
3278           mips_add_token (&token, OT_FLOAT);
3279           return end;
3280         }
3281     }
3282
3283   /* Treat everything else as an integer expression.  */
3284   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3285   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3286   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3287   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3288   s = expr_end;
3289   mips_add_token (&token, OT_INTEGER);
3290   return s;
3291 }
3292
3293 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3294    if expressions should be treated as 32-bit floating-point constants,
3295    'd' if they should be treated as 64-bit floating-point constants,
3296    or 0 if they should be treated as integer expressions (the usual case).
3297
3298    Return a list of tokens on success, otherwise return 0.  The caller
3299    must obstack_free the list after use.  */
3300
3301 static struct mips_operand_token *
3302 mips_parse_arguments (char *s, char float_format)
3303 {
3304   struct mips_operand_token token;
3305
3306   SKIP_SPACE_TABS (s);
3307   while (*s)
3308     {
3309       s = mips_parse_argument_token (s, float_format);
3310       if (!s)
3311         {
3312           obstack_free (&mips_operand_tokens,
3313                         obstack_finish (&mips_operand_tokens));
3314           return 0;
3315         }
3316       SKIP_SPACE_TABS (s);
3317     }
3318   mips_add_token (&token, OT_END);
3319   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3320 }
3321
3322 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3323    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3324
3325 static bfd_boolean
3326 is_opcode_valid (const struct mips_opcode *mo)
3327 {
3328   int isa = mips_opts.isa;
3329   int ase = mips_opts.ase;
3330   int fp_s, fp_d;
3331   unsigned int i;
3332
3333   if (ISA_HAS_64BIT_REGS (isa))
3334     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3335       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3336         ase |= mips_ases[i].flags64;
3337
3338   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3339     return FALSE;
3340
3341   /* Check whether the instruction or macro requires single-precision or
3342      double-precision floating-point support.  Note that this information is
3343      stored differently in the opcode table for insns and macros.  */
3344   if (mo->pinfo == INSN_MACRO)
3345     {
3346       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3347       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3348     }
3349   else
3350     {
3351       fp_s = mo->pinfo & FP_S;
3352       fp_d = mo->pinfo & FP_D;
3353     }
3354
3355   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3356     return FALSE;
3357
3358   if (fp_s && mips_opts.soft_float)
3359     return FALSE;
3360
3361   return TRUE;
3362 }
3363
3364 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3365    selected ISA and architecture.  */
3366
3367 static bfd_boolean
3368 is_opcode_valid_16 (const struct mips_opcode *mo)
3369 {
3370   int isa = mips_opts.isa;
3371   int ase = mips_opts.ase;
3372   unsigned int i;
3373
3374   if (ISA_HAS_64BIT_REGS (isa))
3375     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3376       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3377         ase |= mips_ases[i].flags64;
3378
3379   return opcode_is_member (mo, isa, ase, mips_opts.arch);
3380 }
3381
3382 /* Return TRUE if the size of the microMIPS opcode MO matches one
3383    explicitly requested.  Always TRUE in the standard MIPS mode.
3384    Use is_size_valid_16 for MIPS16 opcodes.  */
3385
3386 static bfd_boolean
3387 is_size_valid (const struct mips_opcode *mo)
3388 {
3389   if (!mips_opts.micromips)
3390     return TRUE;
3391
3392   if (mips_opts.insn32)
3393     {
3394       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3395         return FALSE;
3396       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3397         return FALSE;
3398     }
3399   if (!forced_insn_length)
3400     return TRUE;
3401   if (mo->pinfo == INSN_MACRO)
3402     return FALSE;
3403   return forced_insn_length == micromips_insn_length (mo);
3404 }
3405
3406 /* Return TRUE if the size of the MIPS16 opcode MO matches one
3407    explicitly requested.  */
3408
3409 static bfd_boolean
3410 is_size_valid_16 (const struct mips_opcode *mo)
3411 {
3412   if (!forced_insn_length)
3413     return TRUE;
3414   if (mo->pinfo == INSN_MACRO)
3415     return FALSE;
3416   if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3417     return FALSE;
3418   if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3419     return FALSE;
3420   return TRUE;
3421 }
3422
3423 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3424    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3425
3426    We don't accept macros in 16-bit delay slots to avoid a case where
3427    a macro expansion fails because it relies on a preceding 32-bit real
3428    instruction to have matched and does not handle the operands correctly.
3429    The only macros that may expand to 16-bit instructions are JAL that
3430    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3431    and BGT (that likewise cannot be placed in a delay slot) that decay to
3432    a NOP.  In all these cases the macros precede any corresponding real
3433    instruction definitions in the opcode table, so they will match in the
3434    second pass where the size of the delay slot is ignored and therefore
3435    produce correct code.  */
3436
3437 static bfd_boolean
3438 is_delay_slot_valid (const struct mips_opcode *mo)
3439 {
3440   if (!mips_opts.micromips)
3441     return TRUE;
3442
3443   if (mo->pinfo == INSN_MACRO)
3444     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3445   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3446       && micromips_insn_length (mo) != 4)
3447     return FALSE;
3448   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3449       && micromips_insn_length (mo) != 2)
3450     return FALSE;
3451
3452   return TRUE;
3453 }
3454
3455 /* For consistency checking, verify that all bits of OPCODE are specified
3456    either by the match/mask part of the instruction definition, or by the
3457    operand list.  Also build up a list of operands in OPERANDS.
3458
3459    INSN_BITS says which bits of the instruction are significant.
3460    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3461    provides the mips_operand description of each operand.  DECODE_OPERAND
3462    is null for MIPS16 instructions.  */
3463
3464 static int
3465 validate_mips_insn (const struct mips_opcode *opcode,
3466                     unsigned long insn_bits,
3467                     const struct mips_operand *(*decode_operand) (const char *),
3468                     struct mips_operand_array *operands)
3469 {
3470   const char *s;
3471   unsigned long used_bits, doubled, undefined, opno, mask;
3472   const struct mips_operand *operand;
3473
3474   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3475   if ((mask & opcode->match) != opcode->match)
3476     {
3477       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3478               opcode->name, opcode->args);
3479       return 0;
3480     }
3481   used_bits = 0;
3482   opno = 0;
3483   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3484     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3485   for (s = opcode->args; *s; ++s)
3486     switch (*s)
3487       {
3488       case ',':
3489       case '(':
3490       case ')':
3491         break;
3492
3493       case '#':
3494         s++;
3495         break;
3496
3497       default:
3498         if (!decode_operand)
3499           operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3500         else
3501           operand = decode_operand (s);
3502         if (!operand && opcode->pinfo != INSN_MACRO)
3503           {
3504             as_bad (_("internal: unknown operand type: %s %s"),
3505                     opcode->name, opcode->args);
3506             return 0;
3507           }
3508         gas_assert (opno < MAX_OPERANDS);
3509         operands->operand[opno] = operand;
3510         if (!decode_operand && operand
3511             && operand->type == OP_INT && operand->lsb == 0
3512             && mips_opcode_32bit_p (opcode))
3513           used_bits |= mips16_immed_extend (-1, operand->size);
3514         else if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3515           {
3516             used_bits = mips_insert_operand (operand, used_bits, -1);
3517             if (operand->type == OP_MDMX_IMM_REG)
3518               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3519                  has separate entries for each format.  */
3520               used_bits &= ~(1 << (operand->lsb + 5));
3521             if (operand->type == OP_ENTRY_EXIT_LIST)
3522               used_bits &= ~(mask & 0x700);
3523             /* interAptiv MR2 SAVE/RESTORE instructions have a discontiguous
3524                operand field that cannot be fully described with LSB/SIZE.  */
3525             if (operand->type == OP_SAVE_RESTORE_LIST && operand->lsb == 6)
3526               used_bits &= ~0x6000;
3527           }
3528         /* Skip prefix characters.  */
3529         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3530           ++s;
3531         opno += 1;
3532         break;
3533       }
3534   doubled = used_bits & mask & insn_bits;
3535   if (doubled)
3536     {
3537       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3538                 " %s %s"), doubled, opcode->name, opcode->args);
3539       return 0;
3540     }
3541   used_bits |= mask;
3542   undefined = ~used_bits & insn_bits;
3543   if (opcode->pinfo != INSN_MACRO && undefined)
3544     {
3545       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3546               undefined, opcode->name, opcode->args);
3547       return 0;
3548     }
3549   used_bits &= ~insn_bits;
3550   if (used_bits)
3551     {
3552       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3553               used_bits, opcode->name, opcode->args);
3554       return 0;
3555     }
3556   return 1;
3557 }
3558
3559 /* The MIPS16 version of validate_mips_insn.  */
3560
3561 static int
3562 validate_mips16_insn (const struct mips_opcode *opcode,
3563                       struct mips_operand_array *operands)
3564 {
3565   unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3566
3567   return validate_mips_insn (opcode, insn_bits, 0, operands);
3568 }
3569
3570 /* The microMIPS version of validate_mips_insn.  */
3571
3572 static int
3573 validate_micromips_insn (const struct mips_opcode *opc,
3574                          struct mips_operand_array *operands)
3575 {
3576   unsigned long insn_bits;
3577   unsigned long major;
3578   unsigned int length;
3579
3580   if (opc->pinfo == INSN_MACRO)
3581     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3582                                operands);
3583
3584   length = micromips_insn_length (opc);
3585   if (length != 2 && length != 4)
3586     {
3587       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3588                 "%s %s"), length, opc->name, opc->args);
3589       return 0;
3590     }
3591   major = opc->match >> (10 + 8 * (length - 2));
3592   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3593       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3594     {
3595       as_bad (_("internal error: bad microMIPS opcode "
3596                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3597       return 0;
3598     }
3599
3600   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3601   insn_bits = 1 << 4 * length;
3602   insn_bits <<= 4 * length;
3603   insn_bits -= 1;
3604   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3605                              operands);
3606 }
3607
3608 /* This function is called once, at assembler startup time.  It should set up
3609    all the tables, etc. that the MD part of the assembler will need.  */
3610
3611 void
3612 md_begin (void)
3613 {
3614   const char *retval = NULL;
3615   int i = 0;
3616   int broken = 0;
3617
3618   if (mips_pic != NO_PIC)
3619     {
3620       if (g_switch_seen && g_switch_value != 0)
3621         as_bad (_("-G may not be used in position-independent code"));
3622       g_switch_value = 0;
3623     }
3624   else if (mips_abicalls)
3625     {
3626       if (g_switch_seen && g_switch_value != 0)
3627         as_bad (_("-G may not be used with abicalls"));
3628       g_switch_value = 0;
3629     }
3630
3631   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3632     as_warn (_("could not set architecture and machine"));
3633
3634   op_hash = hash_new ();
3635
3636   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3637   for (i = 0; i < NUMOPCODES;)
3638     {
3639       const char *name = mips_opcodes[i].name;
3640
3641       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3642       if (retval != NULL)
3643         {
3644           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3645                    mips_opcodes[i].name, retval);
3646           /* Probably a memory allocation problem?  Give up now.  */
3647           as_fatal (_("broken assembler, no assembly attempted"));
3648         }
3649       do
3650         {
3651           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3652                                    decode_mips_operand, &mips_operands[i]))
3653             broken = 1;
3654           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3655             {
3656               create_insn (&nop_insn, mips_opcodes + i);
3657               if (mips_fix_loongson2f_nop)
3658                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3659               nop_insn.fixed_p = 1;
3660             }
3661           ++i;
3662         }
3663       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3664     }
3665
3666   mips16_op_hash = hash_new ();
3667   mips16_operands = XCNEWVEC (struct mips_operand_array,
3668                               bfd_mips16_num_opcodes);
3669
3670   i = 0;
3671   while (i < bfd_mips16_num_opcodes)
3672     {
3673       const char *name = mips16_opcodes[i].name;
3674
3675       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3676       if (retval != NULL)
3677         as_fatal (_("internal: can't hash `%s': %s"),
3678                   mips16_opcodes[i].name, retval);
3679       do
3680         {
3681           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3682             broken = 1;
3683           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3684             {
3685               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3686               mips16_nop_insn.fixed_p = 1;
3687             }
3688           ++i;
3689         }
3690       while (i < bfd_mips16_num_opcodes
3691              && strcmp (mips16_opcodes[i].name, name) == 0);
3692     }
3693
3694   micromips_op_hash = hash_new ();
3695   micromips_operands = XCNEWVEC (struct mips_operand_array,
3696                                  bfd_micromips_num_opcodes);
3697
3698   i = 0;
3699   while (i < bfd_micromips_num_opcodes)
3700     {
3701       const char *name = micromips_opcodes[i].name;
3702
3703       retval = hash_insert (micromips_op_hash, name,
3704                             (void *) &micromips_opcodes[i]);
3705       if (retval != NULL)
3706         as_fatal (_("internal: can't hash `%s': %s"),
3707                   micromips_opcodes[i].name, retval);
3708       do
3709         {
3710           struct mips_cl_insn *micromips_nop_insn;
3711
3712           if (!validate_micromips_insn (&micromips_opcodes[i],
3713                                         &micromips_operands[i]))
3714             broken = 1;
3715
3716           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3717             {
3718               if (micromips_insn_length (micromips_opcodes + i) == 2)
3719                 micromips_nop_insn = &micromips_nop16_insn;
3720               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3721                 micromips_nop_insn = &micromips_nop32_insn;
3722               else
3723                 continue;
3724
3725               if (micromips_nop_insn->insn_mo == NULL
3726                   && strcmp (name, "nop") == 0)
3727                 {
3728                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3729                   micromips_nop_insn->fixed_p = 1;
3730                 }
3731             }
3732         }
3733       while (++i < bfd_micromips_num_opcodes
3734              && strcmp (micromips_opcodes[i].name, name) == 0);
3735     }
3736
3737   if (broken)
3738     as_fatal (_("broken assembler, no assembly attempted"));
3739
3740   /* We add all the general register names to the symbol table.  This
3741      helps us detect invalid uses of them.  */
3742   for (i = 0; reg_names[i].name; i++)
3743     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3744                                      reg_names[i].num, /* & RNUM_MASK, */
3745                                      &zero_address_frag));
3746   if (HAVE_NEWABI)
3747     for (i = 0; reg_names_n32n64[i].name; i++)
3748       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3749                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3750                                        &zero_address_frag));
3751   else
3752     for (i = 0; reg_names_o32[i].name; i++)
3753       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3754                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3755                                        &zero_address_frag));
3756
3757   for (i = 0; i < 32; i++)
3758     {
3759       char regname[6];
3760
3761       /* R5900 VU0 floating-point register.  */
3762       sprintf (regname, "$vf%d", i);
3763       symbol_table_insert (symbol_new (regname, reg_section,
3764                                        RTYPE_VF | i, &zero_address_frag));
3765
3766       /* R5900 VU0 integer register.  */
3767       sprintf (regname, "$vi%d", i);
3768       symbol_table_insert (symbol_new (regname, reg_section,
3769                                        RTYPE_VI | i, &zero_address_frag));
3770
3771       /* MSA register.  */
3772       sprintf (regname, "$w%d", i);
3773       symbol_table_insert (symbol_new (regname, reg_section,
3774                                        RTYPE_MSA | i, &zero_address_frag));
3775     }
3776
3777   obstack_init (&mips_operand_tokens);
3778
3779   mips_no_prev_insn ();
3780
3781   mips_gprmask = 0;
3782   mips_cprmask[0] = 0;
3783   mips_cprmask[1] = 0;
3784   mips_cprmask[2] = 0;
3785   mips_cprmask[3] = 0;
3786
3787   /* set the default alignment for the text section (2**2) */
3788   record_alignment (text_section, 2);
3789
3790   bfd_set_gp_size (stdoutput, g_switch_value);
3791
3792   /* On a native system other than VxWorks, sections must be aligned
3793      to 16 byte boundaries.  When configured for an embedded ELF
3794      target, we don't bother.  */
3795   if (strncmp (TARGET_OS, "elf", 3) != 0
3796       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3797     {
3798       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3799       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3800       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3801     }
3802
3803   /* Create a .reginfo section for register masks and a .mdebug
3804      section for debugging information.  */
3805   {
3806     segT seg;
3807     subsegT subseg;
3808     flagword flags;
3809     segT sec;
3810
3811     seg = now_seg;
3812     subseg = now_subseg;
3813
3814     /* The ABI says this section should be loaded so that the
3815        running program can access it.  However, we don't load it
3816        if we are configured for an embedded target */
3817     flags = SEC_READONLY | SEC_DATA;
3818     if (strncmp (TARGET_OS, "elf", 3) != 0)
3819       flags |= SEC_ALLOC | SEC_LOAD;
3820
3821     if (mips_abi != N64_ABI)
3822       {
3823         sec = subseg_new (".reginfo", (subsegT) 0);
3824
3825         bfd_set_section_flags (stdoutput, sec, flags);
3826         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3827
3828         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3829       }
3830     else
3831       {
3832         /* The 64-bit ABI uses a .MIPS.options section rather than
3833            .reginfo section.  */
3834         sec = subseg_new (".MIPS.options", (subsegT) 0);
3835         bfd_set_section_flags (stdoutput, sec, flags);
3836         bfd_set_section_alignment (stdoutput, sec, 3);
3837
3838         /* Set up the option header.  */
3839         {
3840           Elf_Internal_Options opthdr;
3841           char *f;
3842
3843           opthdr.kind = ODK_REGINFO;
3844           opthdr.size = (sizeof (Elf_External_Options)
3845                          + sizeof (Elf64_External_RegInfo));
3846           opthdr.section = 0;
3847           opthdr.info = 0;
3848           f = frag_more (sizeof (Elf_External_Options));
3849           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3850                                          (Elf_External_Options *) f);
3851
3852           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3853         }
3854       }
3855
3856     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3857     bfd_set_section_flags (stdoutput, sec,
3858                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3859     bfd_set_section_alignment (stdoutput, sec, 3);
3860     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3861
3862     if (ECOFF_DEBUGGING)
3863       {
3864         sec = subseg_new (".mdebug", (subsegT) 0);
3865         (void) bfd_set_section_flags (stdoutput, sec,
3866                                       SEC_HAS_CONTENTS | SEC_READONLY);
3867         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3868       }
3869     else if (mips_flag_pdr)
3870       {
3871         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3872         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3873                                       SEC_READONLY | SEC_RELOC
3874                                       | SEC_DEBUGGING);
3875         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3876       }
3877
3878     subseg_set (seg, subseg);
3879   }
3880
3881   if (mips_fix_vr4120)
3882     init_vr4120_conflicts ();
3883 }
3884
3885 static inline void
3886 fpabi_incompatible_with (int fpabi, const char *what)
3887 {
3888   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3889            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3890 }
3891
3892 static inline void
3893 fpabi_requires (int fpabi, const char *what)
3894 {
3895   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3896            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3897 }
3898
3899 /* Check -mabi and register sizes against the specified FP ABI.  */
3900 static void
3901 check_fpabi (int fpabi)
3902 {
3903   switch (fpabi)
3904     {
3905     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3906       if (file_mips_opts.soft_float)
3907         fpabi_incompatible_with (fpabi, "softfloat");
3908       else if (file_mips_opts.single_float)
3909         fpabi_incompatible_with (fpabi, "singlefloat");
3910       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3911         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3912       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3913         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3914       break;
3915
3916     case Val_GNU_MIPS_ABI_FP_XX:
3917       if (mips_abi != O32_ABI)
3918         fpabi_requires (fpabi, "-mabi=32");
3919       else if (file_mips_opts.soft_float)
3920         fpabi_incompatible_with (fpabi, "softfloat");
3921       else if (file_mips_opts.single_float)
3922         fpabi_incompatible_with (fpabi, "singlefloat");
3923       else if (file_mips_opts.fp != 0)
3924         fpabi_requires (fpabi, "fp=xx");
3925       break;
3926
3927     case Val_GNU_MIPS_ABI_FP_64A:
3928     case Val_GNU_MIPS_ABI_FP_64:
3929       if (mips_abi != O32_ABI)
3930         fpabi_requires (fpabi, "-mabi=32");
3931       else if (file_mips_opts.soft_float)
3932         fpabi_incompatible_with (fpabi, "softfloat");
3933       else if (file_mips_opts.single_float)
3934         fpabi_incompatible_with (fpabi, "singlefloat");
3935       else if (file_mips_opts.fp != 64)
3936         fpabi_requires (fpabi, "fp=64");
3937       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3938         fpabi_incompatible_with (fpabi, "nooddspreg");
3939       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3940         fpabi_requires (fpabi, "nooddspreg");
3941       break;
3942
3943     case Val_GNU_MIPS_ABI_FP_SINGLE:
3944       if (file_mips_opts.soft_float)
3945         fpabi_incompatible_with (fpabi, "softfloat");
3946       else if (!file_mips_opts.single_float)
3947         fpabi_requires (fpabi, "singlefloat");
3948       break;
3949
3950     case Val_GNU_MIPS_ABI_FP_SOFT:
3951       if (!file_mips_opts.soft_float)
3952         fpabi_requires (fpabi, "softfloat");
3953       break;
3954
3955     case Val_GNU_MIPS_ABI_FP_OLD_64:
3956       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3957                Tag_GNU_MIPS_ABI_FP, fpabi);
3958       break;
3959
3960     case Val_GNU_MIPS_ABI_FP_NAN2008:
3961       /* Silently ignore compatibility value.  */
3962       break;
3963
3964     default:
3965       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3966                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3967       break;
3968     }
3969 }
3970
3971 /* Perform consistency checks on the current options.  */
3972
3973 static void
3974 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3975 {
3976   /* Check the size of integer registers agrees with the ABI and ISA.  */
3977   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3978     as_bad (_("`gp=64' used with a 32-bit processor"));
3979   else if (abi_checks
3980            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3981     as_bad (_("`gp=32' used with a 64-bit ABI"));
3982   else if (abi_checks
3983            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3984     as_bad (_("`gp=64' used with a 32-bit ABI"));
3985
3986   /* Check the size of the float registers agrees with the ABI and ISA.  */
3987   switch (opts->fp)
3988     {
3989     case 0:
3990       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3991         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3992       else if (opts->single_float == 1)
3993         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3994       break;
3995     case 64:
3996       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3997         as_bad (_("`fp=64' used with a 32-bit fpu"));
3998       else if (abi_checks
3999                && ABI_NEEDS_32BIT_REGS (mips_abi)
4000                && !ISA_HAS_MXHC1 (opts->isa))
4001         as_warn (_("`fp=64' used with a 32-bit ABI"));
4002       break;
4003     case 32:
4004       if (abi_checks
4005           && ABI_NEEDS_64BIT_REGS (mips_abi))
4006         as_warn (_("`fp=32' used with a 64-bit ABI"));
4007       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
4008         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
4009       break;
4010     default:
4011       as_bad (_("Unknown size of floating point registers"));
4012       break;
4013     }
4014
4015   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
4016     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
4017
4018   if (opts->micromips == 1 && opts->mips16 == 1)
4019     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
4020   else if (ISA_IS_R6 (opts->isa)
4021            && (opts->micromips == 1
4022                || opts->mips16 == 1))
4023     as_fatal (_("`%s' cannot be used with `%s'"),
4024               opts->micromips ? "micromips" : "mips16",
4025               mips_cpu_info_from_isa (opts->isa)->name);
4026
4027   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
4028     as_fatal (_("branch relaxation is not supported in `%s'"),
4029               mips_cpu_info_from_isa (opts->isa)->name);
4030 }
4031
4032 /* Perform consistency checks on the module level options exactly once.
4033    This is a deferred check that happens:
4034      at the first .set directive
4035      or, at the first pseudo op that generates code (inc .dc.a)
4036      or, at the first instruction
4037      or, at the end.  */
4038
4039 static void
4040 file_mips_check_options (void)
4041 {
4042   const struct mips_cpu_info *arch_info = 0;
4043
4044   if (file_mips_opts_checked)
4045     return;
4046
4047   /* The following code determines the register size.
4048      Similar code was added to GCC 3.3 (see override_options() in
4049      config/mips/mips.c).  The GAS and GCC code should be kept in sync
4050      as much as possible.  */
4051
4052   if (file_mips_opts.gp < 0)
4053     {
4054       /* Infer the integer register size from the ABI and processor.
4055          Restrict ourselves to 32-bit registers if that's all the
4056          processor has, or if the ABI cannot handle 64-bit registers.  */
4057       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
4058                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
4059                           ? 32 : 64;
4060     }
4061
4062   if (file_mips_opts.fp < 0)
4063     {
4064       /* No user specified float register size.
4065          ??? GAS treats single-float processors as though they had 64-bit
4066          float registers (although it complains when double-precision
4067          instructions are used).  As things stand, saying they have 32-bit
4068          registers would lead to spurious "register must be even" messages.
4069          So here we assume float registers are never smaller than the
4070          integer ones.  */
4071       if (file_mips_opts.gp == 64)
4072         /* 64-bit integer registers implies 64-bit float registers.  */
4073         file_mips_opts.fp = 64;
4074       else if ((file_mips_opts.ase & FP64_ASES)
4075                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
4076         /* Handle ASEs that require 64-bit float registers, if possible.  */
4077         file_mips_opts.fp = 64;
4078       else if (ISA_IS_R6 (mips_opts.isa))
4079         /* R6 implies 64-bit float registers.  */
4080         file_mips_opts.fp = 64;
4081       else
4082         /* 32-bit float registers.  */
4083         file_mips_opts.fp = 32;
4084     }
4085
4086   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
4087
4088   /* Disable operations on odd-numbered floating-point registers by default
4089      when using the FPXX ABI.  */
4090   if (file_mips_opts.oddspreg < 0)
4091     {
4092       if (file_mips_opts.fp == 0)
4093         file_mips_opts.oddspreg = 0;
4094       else
4095         file_mips_opts.oddspreg = 1;
4096     }
4097
4098   /* End of GCC-shared inference code.  */
4099
4100   /* This flag is set when we have a 64-bit capable CPU but use only
4101      32-bit wide registers.  Note that EABI does not use it.  */
4102   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4103       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4104           || mips_abi == O32_ABI))
4105     mips_32bitmode = 1;
4106
4107   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4108     as_bad (_("trap exception not supported at ISA 1"));
4109
4110   /* If the selected architecture includes support for ASEs, enable
4111      generation of code for them.  */
4112   if (file_mips_opts.mips16 == -1)
4113     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4114   if (file_mips_opts.micromips == -1)
4115     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4116                                 ? 1 : 0;
4117
4118   if (mips_nan2008 == -1)
4119     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4120   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4121     as_fatal (_("`%s' does not support legacy NaN"),
4122               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4123
4124   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4125      being selected implicitly.  */
4126   if (file_mips_opts.fp != 64)
4127     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4128
4129   /* If the user didn't explicitly select or deselect a particular ASE,
4130      use the default setting for the CPU.  */
4131   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
4132
4133   /* Set up the current options.  These may change throughout assembly.  */
4134   mips_opts = file_mips_opts;
4135
4136   mips_check_isa_supports_ases ();
4137   mips_check_options (&file_mips_opts, TRUE);
4138   file_mips_opts_checked = TRUE;
4139
4140   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4141     as_warn (_("could not set architecture and machine"));
4142 }
4143
4144 void
4145 md_assemble (char *str)
4146 {
4147   struct mips_cl_insn insn;
4148   bfd_reloc_code_real_type unused_reloc[3]
4149     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4150
4151   file_mips_check_options ();
4152
4153   imm_expr.X_op = O_absent;
4154   offset_expr.X_op = O_absent;
4155   offset_reloc[0] = BFD_RELOC_UNUSED;
4156   offset_reloc[1] = BFD_RELOC_UNUSED;
4157   offset_reloc[2] = BFD_RELOC_UNUSED;
4158
4159   mips_mark_labels ();
4160   mips_assembling_insn = TRUE;
4161   clear_insn_error ();
4162
4163   if (mips_opts.mips16)
4164     mips16_ip (str, &insn);
4165   else
4166     {
4167       mips_ip (str, &insn);
4168       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4169             str, insn.insn_opcode));
4170     }
4171
4172   if (insn_error.msg)
4173     report_insn_error (str);
4174   else if (insn.insn_mo->pinfo == INSN_MACRO)
4175     {
4176       macro_start ();
4177       if (mips_opts.mips16)
4178         mips16_macro (&insn);
4179       else
4180         macro (&insn, str);
4181       macro_end ();
4182     }
4183   else
4184     {
4185       if (offset_expr.X_op != O_absent)
4186         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4187       else
4188         append_insn (&insn, NULL, unused_reloc, FALSE);
4189     }
4190
4191   mips_assembling_insn = FALSE;
4192 }
4193
4194 /* Convenience functions for abstracting away the differences between
4195    MIPS16 and non-MIPS16 relocations.  */
4196
4197 static inline bfd_boolean
4198 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4199 {
4200   switch (reloc)
4201     {
4202     case BFD_RELOC_MIPS16_JMP:
4203     case BFD_RELOC_MIPS16_GPREL:
4204     case BFD_RELOC_MIPS16_GOT16:
4205     case BFD_RELOC_MIPS16_CALL16:
4206     case BFD_RELOC_MIPS16_HI16_S:
4207     case BFD_RELOC_MIPS16_HI16:
4208     case BFD_RELOC_MIPS16_LO16:
4209     case BFD_RELOC_MIPS16_16_PCREL_S1:
4210       return TRUE;
4211
4212     default:
4213       return FALSE;
4214     }
4215 }
4216
4217 static inline bfd_boolean
4218 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4219 {
4220   switch (reloc)
4221     {
4222     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4223     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4224     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4225     case BFD_RELOC_MICROMIPS_GPREL16:
4226     case BFD_RELOC_MICROMIPS_JMP:
4227     case BFD_RELOC_MICROMIPS_HI16:
4228     case BFD_RELOC_MICROMIPS_HI16_S:
4229     case BFD_RELOC_MICROMIPS_LO16:
4230     case BFD_RELOC_MICROMIPS_LITERAL:
4231     case BFD_RELOC_MICROMIPS_GOT16:
4232     case BFD_RELOC_MICROMIPS_CALL16:
4233     case BFD_RELOC_MICROMIPS_GOT_HI16:
4234     case BFD_RELOC_MICROMIPS_GOT_LO16:
4235     case BFD_RELOC_MICROMIPS_CALL_HI16:
4236     case BFD_RELOC_MICROMIPS_CALL_LO16:
4237     case BFD_RELOC_MICROMIPS_SUB:
4238     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4239     case BFD_RELOC_MICROMIPS_GOT_OFST:
4240     case BFD_RELOC_MICROMIPS_GOT_DISP:
4241     case BFD_RELOC_MICROMIPS_HIGHEST:
4242     case BFD_RELOC_MICROMIPS_HIGHER:
4243     case BFD_RELOC_MICROMIPS_SCN_DISP:
4244     case BFD_RELOC_MICROMIPS_JALR:
4245       return TRUE;
4246
4247     default:
4248       return FALSE;
4249     }
4250 }
4251
4252 static inline bfd_boolean
4253 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4254 {
4255   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4256 }
4257
4258 static inline bfd_boolean
4259 b_reloc_p (bfd_reloc_code_real_type reloc)
4260 {
4261   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4262           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4263           || reloc == BFD_RELOC_16_PCREL_S2
4264           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4265           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4266           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4267           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4268 }
4269
4270 static inline bfd_boolean
4271 got16_reloc_p (bfd_reloc_code_real_type reloc)
4272 {
4273   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4274           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4275 }
4276
4277 static inline bfd_boolean
4278 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4279 {
4280   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4281           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4282 }
4283
4284 static inline bfd_boolean
4285 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4286 {
4287   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4288           || reloc == BFD_RELOC_MICROMIPS_LO16);
4289 }
4290
4291 static inline bfd_boolean
4292 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4293 {
4294   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4295 }
4296
4297 static inline bfd_boolean
4298 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4299 {
4300   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4301           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4302 }
4303
4304 /* Return true if RELOC is a PC-relative relocation that does not have
4305    full address range.  */
4306
4307 static inline bfd_boolean
4308 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4309 {
4310   switch (reloc)
4311     {
4312     case BFD_RELOC_16_PCREL_S2:
4313     case BFD_RELOC_MIPS16_16_PCREL_S1:
4314     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4315     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4316     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4317     case BFD_RELOC_MIPS_21_PCREL_S2:
4318     case BFD_RELOC_MIPS_26_PCREL_S2:
4319     case BFD_RELOC_MIPS_18_PCREL_S3:
4320     case BFD_RELOC_MIPS_19_PCREL_S2:
4321       return TRUE;
4322
4323     case BFD_RELOC_32_PCREL:
4324     case BFD_RELOC_HI16_S_PCREL:
4325     case BFD_RELOC_LO16_PCREL:
4326       return HAVE_64BIT_ADDRESSES;
4327
4328     default:
4329       return FALSE;
4330     }
4331 }
4332
4333 /* Return true if the given relocation might need a matching %lo().
4334    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4335    need a matching %lo() when applied to local symbols.  */
4336
4337 static inline bfd_boolean
4338 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4339 {
4340   return (HAVE_IN_PLACE_ADDENDS
4341           && (hi16_reloc_p (reloc)
4342               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4343                  all GOT16 relocations evaluate to "G".  */
4344               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4345 }
4346
4347 /* Return the type of %lo() reloc needed by RELOC, given that
4348    reloc_needs_lo_p.  */
4349
4350 static inline bfd_reloc_code_real_type
4351 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4352 {
4353   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4354           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4355              : BFD_RELOC_LO16));
4356 }
4357
4358 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4359    relocation.  */
4360
4361 static inline bfd_boolean
4362 fixup_has_matching_lo_p (fixS *fixp)
4363 {
4364   return (fixp->fx_next != NULL
4365           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4366           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4367           && fixp->fx_offset == fixp->fx_next->fx_offset);
4368 }
4369
4370 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4371    says whether the labels refer to text or data.  */
4372
4373 static void
4374 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4375 {
4376   struct insn_label_list *l;
4377   valueT val;
4378
4379   for (l = labels; l != NULL; l = l->next)
4380     {
4381       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4382       symbol_set_frag (l->label, frag_now);
4383       val = (valueT) frag_now_fix ();
4384       /* MIPS16/microMIPS text labels are stored as odd.  */
4385       if (text_p && HAVE_CODE_COMPRESSION)
4386         ++val;
4387       S_SET_VALUE (l->label, val);
4388     }
4389 }
4390
4391 /* Move all labels in insn_labels to the current insertion point
4392    and treat them as text labels.  */
4393
4394 static void
4395 mips_move_text_labels (void)
4396 {
4397   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4398 }
4399
4400 /* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4401
4402 static bfd_boolean
4403 s_is_linkonce (symbolS *sym, segT from_seg)
4404 {
4405   bfd_boolean linkonce = FALSE;
4406   segT symseg = S_GET_SEGMENT (sym);
4407
4408   if (symseg != from_seg && !S_IS_LOCAL (sym))
4409     {
4410       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4411         linkonce = TRUE;
4412       /* The GNU toolchain uses an extension for ELF: a section
4413          beginning with the magic string .gnu.linkonce is a
4414          linkonce section.  */
4415       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4416                    sizeof ".gnu.linkonce" - 1) == 0)
4417         linkonce = TRUE;
4418     }
4419   return linkonce;
4420 }
4421
4422 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4423    linker to handle them specially, such as generating jalx instructions
4424    when needed.  We also make them odd for the duration of the assembly,
4425    in order to generate the right sort of code.  We will make them even
4426    in the adjust_symtab routine, while leaving them marked.  This is
4427    convenient for the debugger and the disassembler.  The linker knows
4428    to make them odd again.  */
4429
4430 static void
4431 mips_compressed_mark_label (symbolS *label)
4432 {
4433   gas_assert (HAVE_CODE_COMPRESSION);
4434
4435   if (mips_opts.mips16)
4436     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4437   else
4438     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4439   if ((S_GET_VALUE (label) & 1) == 0
4440       /* Don't adjust the address if the label is global or weak, or
4441          in a link-once section, since we'll be emitting symbol reloc
4442          references to it which will be patched up by the linker, and
4443          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4444       && !S_IS_WEAK (label)
4445       && !S_IS_EXTERNAL (label)
4446       && !s_is_linkonce (label, now_seg))
4447     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4448 }
4449
4450 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4451
4452 static void
4453 mips_compressed_mark_labels (void)
4454 {
4455   struct insn_label_list *l;
4456
4457   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4458     mips_compressed_mark_label (l->label);
4459 }
4460
4461 /* End the current frag.  Make it a variant frag and record the
4462    relaxation info.  */
4463
4464 static void
4465 relax_close_frag (void)
4466 {
4467   mips_macro_warning.first_frag = frag_now;
4468   frag_var (rs_machine_dependent, 0, 0,
4469             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4470                           mips_pic != NO_PIC),
4471             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4472
4473   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4474   mips_relax.first_fixup = 0;
4475 }
4476
4477 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4478    See the comment above RELAX_ENCODE for more details.  */
4479
4480 static void
4481 relax_start (symbolS *symbol)
4482 {
4483   gas_assert (mips_relax.sequence == 0);
4484   mips_relax.sequence = 1;
4485   mips_relax.symbol = symbol;
4486 }
4487
4488 /* Start generating the second version of a relaxable sequence.
4489    See the comment above RELAX_ENCODE for more details.  */
4490
4491 static void
4492 relax_switch (void)
4493 {
4494   gas_assert (mips_relax.sequence == 1);
4495   mips_relax.sequence = 2;
4496 }
4497
4498 /* End the current relaxable sequence.  */
4499
4500 static void
4501 relax_end (void)
4502 {
4503   gas_assert (mips_relax.sequence == 2);
4504   relax_close_frag ();
4505   mips_relax.sequence = 0;
4506 }
4507
4508 /* Return true if IP is a delayed branch or jump.  */
4509
4510 static inline bfd_boolean
4511 delayed_branch_p (const struct mips_cl_insn *ip)
4512 {
4513   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4514                                 | INSN_COND_BRANCH_DELAY
4515                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4516 }
4517
4518 /* Return true if IP is a compact branch or jump.  */
4519
4520 static inline bfd_boolean
4521 compact_branch_p (const struct mips_cl_insn *ip)
4522 {
4523   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4524                                  | INSN2_COND_BRANCH)) != 0;
4525 }
4526
4527 /* Return true if IP is an unconditional branch or jump.  */
4528
4529 static inline bfd_boolean
4530 uncond_branch_p (const struct mips_cl_insn *ip)
4531 {
4532   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4533           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4534 }
4535
4536 /* Return true if IP is a branch-likely instruction.  */
4537
4538 static inline bfd_boolean
4539 branch_likely_p (const struct mips_cl_insn *ip)
4540 {
4541   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4542 }
4543
4544 /* Return the type of nop that should be used to fill the delay slot
4545    of delayed branch IP.  */
4546
4547 static struct mips_cl_insn *
4548 get_delay_slot_nop (const struct mips_cl_insn *ip)
4549 {
4550   if (mips_opts.micromips
4551       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4552     return &micromips_nop32_insn;
4553   return NOP_INSN;
4554 }
4555
4556 /* Return a mask that has bit N set if OPCODE reads the register(s)
4557    in operand N.  */
4558
4559 static unsigned int
4560 insn_read_mask (const struct mips_opcode *opcode)
4561 {
4562   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4563 }
4564
4565 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4566    in operand N.  */
4567
4568 static unsigned int
4569 insn_write_mask (const struct mips_opcode *opcode)
4570 {
4571   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4572 }
4573
4574 /* Return a mask of the registers specified by operand OPERAND of INSN.
4575    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4576    is set.  */
4577
4578 static unsigned int
4579 operand_reg_mask (const struct mips_cl_insn *insn,
4580                   const struct mips_operand *operand,
4581                   unsigned int type_mask)
4582 {
4583   unsigned int uval, vsel;
4584
4585   switch (operand->type)
4586     {
4587     case OP_INT:
4588     case OP_MAPPED_INT:
4589     case OP_MSB:
4590     case OP_PCREL:
4591     case OP_PERF_REG:
4592     case OP_ADDIUSP_INT:
4593     case OP_ENTRY_EXIT_LIST:
4594     case OP_REPEAT_DEST_REG:
4595     case OP_REPEAT_PREV_REG:
4596     case OP_PC:
4597     case OP_VU0_SUFFIX:
4598     case OP_VU0_MATCH_SUFFIX:
4599     case OP_IMM_INDEX:
4600       abort ();
4601
4602     case OP_REG28:
4603       return 1 << 28;
4604
4605     case OP_REG:
4606     case OP_OPTIONAL_REG:
4607       {
4608         const struct mips_reg_operand *reg_op;
4609
4610         reg_op = (const struct mips_reg_operand *) operand;
4611         if (!(type_mask & (1 << reg_op->reg_type)))
4612           return 0;
4613         uval = insn_extract_operand (insn, operand);
4614         return 1 << mips_decode_reg_operand (reg_op, uval);
4615       }
4616
4617     case OP_REG_PAIR:
4618       {
4619         const struct mips_reg_pair_operand *pair_op;
4620
4621         pair_op = (const struct mips_reg_pair_operand *) operand;
4622         if (!(type_mask & (1 << pair_op->reg_type)))
4623           return 0;
4624         uval = insn_extract_operand (insn, operand);
4625         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4626       }
4627
4628     case OP_CLO_CLZ_DEST:
4629       if (!(type_mask & (1 << OP_REG_GP)))
4630         return 0;
4631       uval = insn_extract_operand (insn, operand);
4632       return (1 << (uval & 31)) | (1 << (uval >> 5));
4633
4634     case OP_SAME_RS_RT:
4635       if (!(type_mask & (1 << OP_REG_GP)))
4636         return 0;
4637       uval = insn_extract_operand (insn, operand);
4638       gas_assert ((uval & 31) == (uval >> 5));
4639       return 1 << (uval & 31);
4640
4641     case OP_CHECK_PREV:
4642     case OP_NON_ZERO_REG:
4643       if (!(type_mask & (1 << OP_REG_GP)))
4644         return 0;
4645       uval = insn_extract_operand (insn, operand);
4646       return 1 << (uval & 31);
4647
4648     case OP_LWM_SWM_LIST:
4649       abort ();
4650
4651     case OP_SAVE_RESTORE_LIST:
4652       abort ();
4653
4654     case OP_MDMX_IMM_REG:
4655       if (!(type_mask & (1 << OP_REG_VEC)))
4656         return 0;
4657       uval = insn_extract_operand (insn, operand);
4658       vsel = uval >> 5;
4659       if ((vsel & 0x18) == 0x18)
4660         return 0;
4661       return 1 << (uval & 31);
4662
4663     case OP_REG_INDEX:
4664       if (!(type_mask & (1 << OP_REG_GP)))
4665         return 0;
4666       return 1 << insn_extract_operand (insn, operand);
4667     }
4668   abort ();
4669 }
4670
4671 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4672    where bit N of OPNO_MASK is set if operand N should be included.
4673    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4674    is set.  */
4675
4676 static unsigned int
4677 insn_reg_mask (const struct mips_cl_insn *insn,
4678                unsigned int type_mask, unsigned int opno_mask)
4679 {
4680   unsigned int opno, reg_mask;
4681
4682   opno = 0;
4683   reg_mask = 0;
4684   while (opno_mask != 0)
4685     {
4686       if (opno_mask & 1)
4687         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4688       opno_mask >>= 1;
4689       opno += 1;
4690     }
4691   return reg_mask;
4692 }
4693
4694 /* Return the mask of core registers that IP reads.  */
4695
4696 static unsigned int
4697 gpr_read_mask (const struct mips_cl_insn *ip)
4698 {
4699   unsigned long pinfo, pinfo2;
4700   unsigned int mask;
4701
4702   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4703   pinfo = ip->insn_mo->pinfo;
4704   pinfo2 = ip->insn_mo->pinfo2;
4705   if (pinfo & INSN_UDI)
4706     {
4707       /* UDI instructions have traditionally been assumed to read RS
4708          and RT.  */
4709       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4710       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4711     }
4712   if (pinfo & INSN_READ_GPR_24)
4713     mask |= 1 << 24;
4714   if (pinfo2 & INSN2_READ_GPR_16)
4715     mask |= 1 << 16;
4716   if (pinfo2 & INSN2_READ_SP)
4717     mask |= 1 << SP;
4718   if (pinfo2 & INSN2_READ_GPR_31)
4719     mask |= 1 << 31;
4720   /* Don't include register 0.  */
4721   return mask & ~1;
4722 }
4723
4724 /* Return the mask of core registers that IP writes.  */
4725
4726 static unsigned int
4727 gpr_write_mask (const struct mips_cl_insn *ip)
4728 {
4729   unsigned long pinfo, pinfo2;
4730   unsigned int mask;
4731
4732   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4733   pinfo = ip->insn_mo->pinfo;
4734   pinfo2 = ip->insn_mo->pinfo2;
4735   if (pinfo & INSN_WRITE_GPR_24)
4736     mask |= 1 << 24;
4737   if (pinfo & INSN_WRITE_GPR_31)
4738     mask |= 1 << 31;
4739   if (pinfo & INSN_UDI)
4740     /* UDI instructions have traditionally been assumed to write to RD.  */
4741     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4742   if (pinfo2 & INSN2_WRITE_SP)
4743     mask |= 1 << SP;
4744   /* Don't include register 0.  */
4745   return mask & ~1;
4746 }
4747
4748 /* Return the mask of floating-point registers that IP reads.  */
4749
4750 static unsigned int
4751 fpr_read_mask (const struct mips_cl_insn *ip)
4752 {
4753   unsigned long pinfo;
4754   unsigned int mask;
4755
4756   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4757                              | (1 << OP_REG_MSA)),
4758                         insn_read_mask (ip->insn_mo));
4759   pinfo = ip->insn_mo->pinfo;
4760   /* Conservatively treat all operands to an FP_D instruction are doubles.
4761      (This is overly pessimistic for things like cvt.d.s.)  */
4762   if (FPR_SIZE != 64 && (pinfo & FP_D))
4763     mask |= mask << 1;
4764   return mask;
4765 }
4766
4767 /* Return the mask of floating-point registers that IP writes.  */
4768
4769 static unsigned int
4770 fpr_write_mask (const struct mips_cl_insn *ip)
4771 {
4772   unsigned long pinfo;
4773   unsigned int mask;
4774
4775   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4776                              | (1 << OP_REG_MSA)),
4777                         insn_write_mask (ip->insn_mo));
4778   pinfo = ip->insn_mo->pinfo;
4779   /* Conservatively treat all operands to an FP_D instruction are doubles.
4780      (This is overly pessimistic for things like cvt.s.d.)  */
4781   if (FPR_SIZE != 64 && (pinfo & FP_D))
4782     mask |= mask << 1;
4783   return mask;
4784 }
4785
4786 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4787    Check whether that is allowed.  */
4788
4789 static bfd_boolean
4790 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4791 {
4792   const char *s = insn->name;
4793   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4794                           || FPR_SIZE == 64)
4795                          && mips_opts.oddspreg;
4796
4797   if (insn->pinfo == INSN_MACRO)
4798     /* Let a macro pass, we'll catch it later when it is expanded.  */
4799     return TRUE;
4800
4801   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4802      otherwise it depends on oddspreg.  */
4803   if ((insn->pinfo & FP_S)
4804       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4805                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4806     return FPR_SIZE == 32 || oddspreg;
4807
4808   /* Allow odd registers for single-precision ops and double-precision if the
4809      floating-point registers are 64-bit wide.  */
4810   switch (insn->pinfo & (FP_S | FP_D))
4811     {
4812     case FP_S:
4813     case 0:
4814       return oddspreg;
4815     case FP_D:
4816       return FPR_SIZE == 64;
4817     default:
4818       break;
4819     }
4820
4821   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4822   s = strchr (insn->name, '.');
4823   if (s != NULL && opnum == 2)
4824     s = strchr (s + 1, '.');
4825   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4826     return oddspreg;
4827
4828   return FPR_SIZE == 64;
4829 }
4830
4831 /* Information about an instruction argument that we're trying to match.  */
4832 struct mips_arg_info
4833 {
4834   /* The instruction so far.  */
4835   struct mips_cl_insn *insn;
4836
4837   /* The first unconsumed operand token.  */
4838   struct mips_operand_token *token;
4839
4840   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4841   int opnum;
4842
4843   /* The 1-based argument number, for error reporting.  This does not
4844      count elided optional registers, etc..  */
4845   int argnum;
4846
4847   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4848   unsigned int last_regno;
4849
4850   /* If the first operand was an OP_REG, this is the register that it
4851      specified, otherwise it is ILLEGAL_REG.  */
4852   unsigned int dest_regno;
4853
4854   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4855      where it gives the lsb position.  */
4856   unsigned int last_op_int;
4857
4858   /* If true, match routines should assume that no later instruction
4859      alternative matches and should therefore be as accommodating as
4860      possible.  Match routines should not report errors if something
4861      is only invalid for !LAX_MATCH.  */
4862   bfd_boolean lax_match;
4863
4864   /* True if a reference to the current AT register was seen.  */
4865   bfd_boolean seen_at;
4866 };
4867
4868 /* Record that the argument is out of range.  */
4869
4870 static void
4871 match_out_of_range (struct mips_arg_info *arg)
4872 {
4873   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4874 }
4875
4876 /* Record that the argument isn't constant but needs to be.  */
4877
4878 static void
4879 match_not_constant (struct mips_arg_info *arg)
4880 {
4881   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4882                     arg->argnum);
4883 }
4884
4885 /* Try to match an OT_CHAR token for character CH.  Consume the token
4886    and return true on success, otherwise return false.  */
4887
4888 static bfd_boolean
4889 match_char (struct mips_arg_info *arg, char ch)
4890 {
4891   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4892     {
4893       ++arg->token;
4894       if (ch == ',')
4895         arg->argnum += 1;
4896       return TRUE;
4897     }
4898   return FALSE;
4899 }
4900
4901 /* Try to get an expression from the next tokens in ARG.  Consume the
4902    tokens and return true on success, storing the expression value in
4903    VALUE and relocation types in R.  */
4904
4905 static bfd_boolean
4906 match_expression (struct mips_arg_info *arg, expressionS *value,
4907                   bfd_reloc_code_real_type *r)
4908 {
4909   /* If the next token is a '(' that was parsed as being part of a base
4910      expression, assume we have an elided offset.  The later match will fail
4911      if this turns out to be wrong.  */
4912   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4913     {
4914       value->X_op = O_constant;
4915       value->X_add_number = 0;
4916       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4917       return TRUE;
4918     }
4919
4920   /* Reject register-based expressions such as "0+$2" and "(($2))".
4921      For plain registers the default error seems more appropriate.  */
4922   if (arg->token->type == OT_INTEGER
4923       && arg->token->u.integer.value.X_op == O_register)
4924     {
4925       set_insn_error (arg->argnum, _("register value used as expression"));
4926       return FALSE;
4927     }
4928
4929   if (arg->token->type == OT_INTEGER)
4930     {
4931       *value = arg->token->u.integer.value;
4932       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4933       ++arg->token;
4934       return TRUE;
4935     }
4936
4937   set_insn_error_i
4938     (arg->argnum, _("operand %d must be an immediate expression"),
4939      arg->argnum);
4940   return FALSE;
4941 }
4942
4943 /* Try to get a constant expression from the next tokens in ARG.  Consume
4944    the tokens and return true on success, storing the constant value
4945    in *VALUE.  */
4946
4947 static bfd_boolean
4948 match_const_int (struct mips_arg_info *arg, offsetT *value)
4949 {
4950   expressionS ex;
4951   bfd_reloc_code_real_type r[3];
4952
4953   if (!match_expression (arg, &ex, r))
4954     return FALSE;
4955
4956   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4957     *value = ex.X_add_number;
4958   else
4959     {
4960       if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_big)
4961         match_out_of_range (arg);
4962       else
4963         match_not_constant (arg);
4964       return FALSE;
4965     }
4966   return TRUE;
4967 }
4968
4969 /* Return the RTYPE_* flags for a register operand of type TYPE that
4970    appears in instruction OPCODE.  */
4971
4972 static unsigned int
4973 convert_reg_type (const struct mips_opcode *opcode,
4974                   enum mips_reg_operand_type type)
4975 {
4976   switch (type)
4977     {
4978     case OP_REG_GP:
4979       return RTYPE_NUM | RTYPE_GP;
4980
4981     case OP_REG_FP:
4982       /* Allow vector register names for MDMX if the instruction is a 64-bit
4983          FPR load, store or move (including moves to and from GPRs).  */
4984       if ((mips_opts.ase & ASE_MDMX)
4985           && (opcode->pinfo & FP_D)
4986           && (opcode->pinfo & (INSN_COPROC_MOVE
4987                                | INSN_COPROC_MEMORY_DELAY
4988                                | INSN_LOAD_COPROC
4989                                | INSN_LOAD_MEMORY
4990                                | INSN_STORE_MEMORY)))
4991         return RTYPE_FPU | RTYPE_VEC;
4992       return RTYPE_FPU;
4993
4994     case OP_REG_CCC:
4995       if (opcode->pinfo & (FP_D | FP_S))
4996         return RTYPE_CCC | RTYPE_FCC;
4997       return RTYPE_CCC;
4998
4999     case OP_REG_VEC:
5000       if (opcode->membership & INSN_5400)
5001         return RTYPE_FPU;
5002       return RTYPE_FPU | RTYPE_VEC;
5003
5004     case OP_REG_ACC:
5005       return RTYPE_ACC;
5006
5007     case OP_REG_COPRO:
5008       if (opcode->name[strlen (opcode->name) - 1] == '0')
5009         return RTYPE_NUM | RTYPE_CP0;
5010       return RTYPE_NUM;
5011
5012     case OP_REG_HW:
5013       return RTYPE_NUM;
5014
5015     case OP_REG_VI:
5016       return RTYPE_NUM | RTYPE_VI;
5017
5018     case OP_REG_VF:
5019       return RTYPE_NUM | RTYPE_VF;
5020
5021     case OP_REG_R5900_I:
5022       return RTYPE_R5900_I;
5023
5024     case OP_REG_R5900_Q:
5025       return RTYPE_R5900_Q;
5026
5027     case OP_REG_R5900_R:
5028       return RTYPE_R5900_R;
5029
5030     case OP_REG_R5900_ACC:
5031       return RTYPE_R5900_ACC;
5032
5033     case OP_REG_MSA:
5034       return RTYPE_MSA;
5035
5036     case OP_REG_MSA_CTRL:
5037       return RTYPE_NUM;
5038     }
5039   abort ();
5040 }
5041
5042 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
5043
5044 static void
5045 check_regno (struct mips_arg_info *arg,
5046              enum mips_reg_operand_type type, unsigned int regno)
5047 {
5048   if (AT && type == OP_REG_GP && regno == AT)
5049     arg->seen_at = TRUE;
5050
5051   if (type == OP_REG_FP
5052       && (regno & 1) != 0
5053       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
5054     {
5055       /* This was a warning prior to introducing O32 FPXX and FP64 support
5056          so maintain a warning for FP32 but raise an error for the new
5057          cases.  */
5058       if (FPR_SIZE == 32)
5059         as_warn (_("float register should be even, was %d"), regno);
5060       else
5061         as_bad (_("float register should be even, was %d"), regno);
5062     }
5063
5064   if (type == OP_REG_CCC)
5065     {
5066       const char *name;
5067       size_t length;
5068
5069       name = arg->insn->insn_mo->name;
5070       length = strlen (name);
5071       if ((regno & 1) != 0
5072           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
5073               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
5074         as_warn (_("condition code register should be even for %s, was %d"),
5075                  name, regno);
5076
5077       if ((regno & 3) != 0
5078           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
5079         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
5080                  name, regno);
5081     }
5082 }
5083
5084 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
5085    a register of type TYPE.  Return true on success, storing the register
5086    number in *REGNO and warning about any dubious uses.  */
5087
5088 static bfd_boolean
5089 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5090              unsigned int symval, unsigned int *regno)
5091 {
5092   if (type == OP_REG_VEC)
5093     symval = mips_prefer_vec_regno (symval);
5094   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
5095     return FALSE;
5096
5097   *regno = symval & RNUM_MASK;
5098   check_regno (arg, type, *regno);
5099   return TRUE;
5100 }
5101
5102 /* Try to interpret the next token in ARG as a register of type TYPE.
5103    Consume the token and return true on success, storing the register
5104    number in *REGNO.  Return false on failure.  */
5105
5106 static bfd_boolean
5107 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5108            unsigned int *regno)
5109 {
5110   if (arg->token->type == OT_REG
5111       && match_regno (arg, type, arg->token->u.regno, regno))
5112     {
5113       ++arg->token;
5114       return TRUE;
5115     }
5116   return FALSE;
5117 }
5118
5119 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
5120    Consume the token and return true on success, storing the register numbers
5121    in *REGNO1 and *REGNO2.  Return false on failure.  */
5122
5123 static bfd_boolean
5124 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5125                  unsigned int *regno1, unsigned int *regno2)
5126 {
5127   if (match_reg (arg, type, regno1))
5128     {
5129       *regno2 = *regno1;
5130       return TRUE;
5131     }
5132   if (arg->token->type == OT_REG_RANGE
5133       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5134       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5135       && *regno1 <= *regno2)
5136     {
5137       ++arg->token;
5138       return TRUE;
5139     }
5140   return FALSE;
5141 }
5142
5143 /* OP_INT matcher.  */
5144
5145 static bfd_boolean
5146 match_int_operand (struct mips_arg_info *arg,
5147                    const struct mips_operand *operand_base)
5148 {
5149   const struct mips_int_operand *operand;
5150   unsigned int uval;
5151   int min_val, max_val, factor;
5152   offsetT sval;
5153
5154   operand = (const struct mips_int_operand *) operand_base;
5155   factor = 1 << operand->shift;
5156   min_val = mips_int_operand_min (operand);
5157   max_val = mips_int_operand_max (operand);
5158
5159   if (operand_base->lsb == 0
5160       && operand_base->size == 16
5161       && operand->shift == 0
5162       && operand->bias == 0
5163       && (operand->max_val == 32767 || operand->max_val == 65535))
5164     {
5165       /* The operand can be relocated.  */
5166       if (!match_expression (arg, &offset_expr, offset_reloc))
5167         return FALSE;
5168
5169       if (offset_expr.X_op == O_big)
5170         {
5171           match_out_of_range (arg);
5172           return FALSE;
5173         }
5174
5175       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5176         /* Relocation operators were used.  Accept the argument and
5177            leave the relocation value in offset_expr and offset_relocs
5178            for the caller to process.  */
5179         return TRUE;
5180
5181       if (offset_expr.X_op != O_constant)
5182         {
5183           /* Accept non-constant operands if no later alternative matches,
5184              leaving it for the caller to process.  */
5185           if (!arg->lax_match)
5186             {
5187               match_not_constant (arg);
5188               return FALSE;
5189             }
5190           offset_reloc[0] = BFD_RELOC_LO16;
5191           return TRUE;
5192         }
5193
5194       /* Clear the global state; we're going to install the operand
5195          ourselves.  */
5196       sval = offset_expr.X_add_number;
5197       offset_expr.X_op = O_absent;
5198
5199       /* For compatibility with older assemblers, we accept
5200          0x8000-0xffff as signed 16-bit numbers when only
5201          signed numbers are allowed.  */
5202       if (sval > max_val)
5203         {
5204           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5205           if (!arg->lax_match && sval <= max_val)
5206             {
5207               match_out_of_range (arg);
5208               return FALSE;
5209             }
5210         }
5211     }
5212   else
5213     {
5214       if (!match_const_int (arg, &sval))
5215         return FALSE;
5216     }
5217
5218   arg->last_op_int = sval;
5219
5220   if (sval < min_val || sval > max_val || sval % factor)
5221     {
5222       match_out_of_range (arg);
5223       return FALSE;
5224     }
5225
5226   uval = (unsigned int) sval >> operand->shift;
5227   uval -= operand->bias;
5228
5229   /* Handle -mfix-cn63xxp1.  */
5230   if (arg->opnum == 1
5231       && mips_fix_cn63xxp1
5232       && !mips_opts.micromips
5233       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5234     switch (uval)
5235       {
5236       case 5:
5237       case 25:
5238       case 26:
5239       case 27:
5240       case 28:
5241       case 29:
5242       case 30:
5243       case 31:
5244         /* These are ok.  */
5245         break;
5246
5247       default:
5248         /* The rest must be changed to 28.  */
5249         uval = 28;
5250         break;
5251       }
5252
5253   insn_insert_operand (arg->insn, operand_base, uval);
5254   return TRUE;
5255 }
5256
5257 /* OP_MAPPED_INT matcher.  */
5258
5259 static bfd_boolean
5260 match_mapped_int_operand (struct mips_arg_info *arg,
5261                           const struct mips_operand *operand_base)
5262 {
5263   const struct mips_mapped_int_operand *operand;
5264   unsigned int uval, num_vals;
5265   offsetT sval;
5266
5267   operand = (const struct mips_mapped_int_operand *) operand_base;
5268   if (!match_const_int (arg, &sval))
5269     return FALSE;
5270
5271   num_vals = 1 << operand_base->size;
5272   for (uval = 0; uval < num_vals; uval++)
5273     if (operand->int_map[uval] == sval)
5274       break;
5275   if (uval == num_vals)
5276     {
5277       match_out_of_range (arg);
5278       return FALSE;
5279     }
5280
5281   insn_insert_operand (arg->insn, operand_base, uval);
5282   return TRUE;
5283 }
5284
5285 /* OP_MSB matcher.  */
5286
5287 static bfd_boolean
5288 match_msb_operand (struct mips_arg_info *arg,
5289                    const struct mips_operand *operand_base)
5290 {
5291   const struct mips_msb_operand *operand;
5292   int min_val, max_val, max_high;
5293   offsetT size, sval, high;
5294
5295   operand = (const struct mips_msb_operand *) operand_base;
5296   min_val = operand->bias;
5297   max_val = min_val + (1 << operand_base->size) - 1;
5298   max_high = operand->opsize;
5299
5300   if (!match_const_int (arg, &size))
5301     return FALSE;
5302
5303   high = size + arg->last_op_int;
5304   sval = operand->add_lsb ? high : size;
5305
5306   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5307     {
5308       match_out_of_range (arg);
5309       return FALSE;
5310     }
5311   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5312   return TRUE;
5313 }
5314
5315 /* OP_REG matcher.  */
5316
5317 static bfd_boolean
5318 match_reg_operand (struct mips_arg_info *arg,
5319                    const struct mips_operand *operand_base)
5320 {
5321   const struct mips_reg_operand *operand;
5322   unsigned int regno, uval, num_vals;
5323
5324   operand = (const struct mips_reg_operand *) operand_base;
5325   if (!match_reg (arg, operand->reg_type, &regno))
5326     return FALSE;
5327
5328   if (operand->reg_map)
5329     {
5330       num_vals = 1 << operand->root.size;
5331       for (uval = 0; uval < num_vals; uval++)
5332         if (operand->reg_map[uval] == regno)
5333           break;
5334       if (num_vals == uval)
5335         return FALSE;
5336     }
5337   else
5338     uval = regno;
5339
5340   arg->last_regno = regno;
5341   if (arg->opnum == 1)
5342     arg->dest_regno = regno;
5343   insn_insert_operand (arg->insn, operand_base, uval);
5344   return TRUE;
5345 }
5346
5347 /* OP_REG_PAIR matcher.  */
5348
5349 static bfd_boolean
5350 match_reg_pair_operand (struct mips_arg_info *arg,
5351                         const struct mips_operand *operand_base)
5352 {
5353   const struct mips_reg_pair_operand *operand;
5354   unsigned int regno1, regno2, uval, num_vals;
5355
5356   operand = (const struct mips_reg_pair_operand *) operand_base;
5357   if (!match_reg (arg, operand->reg_type, &regno1)
5358       || !match_char (arg, ',')
5359       || !match_reg (arg, operand->reg_type, &regno2))
5360     return FALSE;
5361
5362   num_vals = 1 << operand_base->size;
5363   for (uval = 0; uval < num_vals; uval++)
5364     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5365       break;
5366   if (uval == num_vals)
5367     return FALSE;
5368
5369   insn_insert_operand (arg->insn, operand_base, uval);
5370   return TRUE;
5371 }
5372
5373 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5374
5375 static bfd_boolean
5376 match_pcrel_operand (struct mips_arg_info *arg)
5377 {
5378   bfd_reloc_code_real_type r[3];
5379
5380   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5381 }
5382
5383 /* OP_PERF_REG matcher.  */
5384
5385 static bfd_boolean
5386 match_perf_reg_operand (struct mips_arg_info *arg,
5387                         const struct mips_operand *operand)
5388 {
5389   offsetT sval;
5390
5391   if (!match_const_int (arg, &sval))
5392     return FALSE;
5393
5394   if (sval != 0
5395       && (sval != 1
5396           || (mips_opts.arch == CPU_R5900
5397               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5398                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5399     {
5400       set_insn_error (arg->argnum, _("invalid performance register"));
5401       return FALSE;
5402     }
5403
5404   insn_insert_operand (arg->insn, operand, sval);
5405   return TRUE;
5406 }
5407
5408 /* OP_ADDIUSP matcher.  */
5409
5410 static bfd_boolean
5411 match_addiusp_operand (struct mips_arg_info *arg,
5412                        const struct mips_operand *operand)
5413 {
5414   offsetT sval;
5415   unsigned int uval;
5416
5417   if (!match_const_int (arg, &sval))
5418     return FALSE;
5419
5420   if (sval % 4)
5421     {
5422       match_out_of_range (arg);
5423       return FALSE;
5424     }
5425
5426   sval /= 4;
5427   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5428     {
5429       match_out_of_range (arg);
5430       return FALSE;
5431     }
5432
5433   uval = (unsigned int) sval;
5434   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5435   insn_insert_operand (arg->insn, operand, uval);
5436   return TRUE;
5437 }
5438
5439 /* OP_CLO_CLZ_DEST matcher.  */
5440
5441 static bfd_boolean
5442 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5443                             const struct mips_operand *operand)
5444 {
5445   unsigned int regno;
5446
5447   if (!match_reg (arg, OP_REG_GP, &regno))
5448     return FALSE;
5449
5450   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5451   return TRUE;
5452 }
5453
5454 /* OP_CHECK_PREV matcher.  */
5455
5456 static bfd_boolean
5457 match_check_prev_operand (struct mips_arg_info *arg,
5458                           const struct mips_operand *operand_base)
5459 {
5460   const struct mips_check_prev_operand *operand;
5461   unsigned int regno;
5462
5463   operand = (const struct mips_check_prev_operand *) operand_base;
5464
5465   if (!match_reg (arg, OP_REG_GP, &regno))
5466     return FALSE;
5467
5468   if (!operand->zero_ok && regno == 0)
5469     return FALSE;
5470
5471   if ((operand->less_than_ok && regno < arg->last_regno)
5472       || (operand->greater_than_ok && regno > arg->last_regno)
5473       || (operand->equal_ok && regno == arg->last_regno))
5474     {
5475       arg->last_regno = regno;
5476       insn_insert_operand (arg->insn, operand_base, regno);
5477       return TRUE;
5478     }
5479
5480   return FALSE;
5481 }
5482
5483 /* OP_SAME_RS_RT matcher.  */
5484
5485 static bfd_boolean
5486 match_same_rs_rt_operand (struct mips_arg_info *arg,
5487                           const struct mips_operand *operand)
5488 {
5489   unsigned int regno;
5490
5491   if (!match_reg (arg, OP_REG_GP, &regno))
5492     return FALSE;
5493
5494   if (regno == 0)
5495     {
5496       set_insn_error (arg->argnum, _("the source register must not be $0"));
5497       return FALSE;
5498     }
5499
5500   arg->last_regno = regno;
5501
5502   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5503   return TRUE;
5504 }
5505
5506 /* OP_LWM_SWM_LIST matcher.  */
5507
5508 static bfd_boolean
5509 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5510                             const struct mips_operand *operand)
5511 {
5512   unsigned int reglist, sregs, ra, regno1, regno2;
5513   struct mips_arg_info reset;
5514
5515   reglist = 0;
5516   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5517     return FALSE;
5518   do
5519     {
5520       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5521         {
5522           reglist |= 1 << FP;
5523           regno2 = S7;
5524         }
5525       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5526       reset = *arg;
5527     }
5528   while (match_char (arg, ',')
5529          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5530   *arg = reset;
5531
5532   if (operand->size == 2)
5533     {
5534       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5535
5536          s0, ra
5537          s0, s1, ra, s2, s3
5538          s0-s2, ra
5539
5540          and any permutations of these.  */
5541       if ((reglist & 0xfff1ffff) != 0x80010000)
5542         return FALSE;
5543
5544       sregs = (reglist >> 17) & 7;
5545       ra = 0;
5546     }
5547   else
5548     {
5549       /* The list must include at least one of ra and s0-sN,
5550          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5551          which are $23 and $30 respectively.)  E.g.:
5552
5553          ra
5554          s0
5555          ra, s0, s1, s2
5556          s0-s8
5557          s0-s5, ra
5558
5559          and any permutations of these.  */
5560       if ((reglist & 0x3f00ffff) != 0)
5561         return FALSE;
5562
5563       ra = (reglist >> 27) & 0x10;
5564       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5565     }
5566   sregs += 1;
5567   if ((sregs & -sregs) != sregs)
5568     return FALSE;
5569
5570   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5571   return TRUE;
5572 }
5573
5574 /* OP_ENTRY_EXIT_LIST matcher.  */
5575
5576 static unsigned int
5577 match_entry_exit_operand (struct mips_arg_info *arg,
5578                           const struct mips_operand *operand)
5579 {
5580   unsigned int mask;
5581   bfd_boolean is_exit;
5582
5583   /* The format is the same for both ENTRY and EXIT, but the constraints
5584      are different.  */
5585   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5586   mask = (is_exit ? 7 << 3 : 0);
5587   do
5588     {
5589       unsigned int regno1, regno2;
5590       bfd_boolean is_freg;
5591
5592       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5593         is_freg = FALSE;
5594       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5595         is_freg = TRUE;
5596       else
5597         return FALSE;
5598
5599       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5600         {
5601           mask &= ~(7 << 3);
5602           mask |= (5 + regno2) << 3;
5603         }
5604       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5605         mask |= (regno2 - 3) << 3;
5606       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5607         mask |= (regno2 - 15) << 1;
5608       else if (regno1 == RA && regno2 == RA)
5609         mask |= 1;
5610       else
5611         return FALSE;
5612     }
5613   while (match_char (arg, ','));
5614
5615   insn_insert_operand (arg->insn, operand, mask);
5616   return TRUE;
5617 }
5618
5619 /* Encode regular MIPS SAVE/RESTORE instruction operands according to
5620    the argument register mask AMASK, the number of static registers
5621    saved NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5622    respectively, and the frame size FRAME_SIZE.  */
5623
5624 static unsigned int
5625 mips_encode_save_restore (unsigned int amask, unsigned int nsreg,
5626                           unsigned int ra, unsigned int s0, unsigned int s1,
5627                           unsigned int frame_size)
5628 {
5629   return ((nsreg << 23) | ((frame_size & 0xf0) << 15) | (amask << 15)
5630           | (ra << 12) | (s0 << 11) | (s1 << 10) | ((frame_size & 0xf) << 6));
5631 }
5632
5633 /* Encode MIPS16 SAVE/RESTORE instruction operands according to the
5634    argument register mask AMASK, the number of static registers saved
5635    NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5636    respectively, and the frame size FRAME_SIZE.  */
5637
5638 static unsigned int
5639 mips16_encode_save_restore (unsigned int amask, unsigned int nsreg,
5640                             unsigned int ra, unsigned int s0, unsigned int s1,
5641                             unsigned int frame_size)
5642 {
5643   unsigned int args;
5644
5645   args = (ra << 6) | (s0 << 5) | (s1 << 4) | (frame_size & 0xf);
5646   if (nsreg || amask || frame_size == 0 || frame_size > 16)
5647     args |= (MIPS16_EXTEND | (nsreg << 24) | (amask << 16)
5648              | ((frame_size & 0xf0) << 16));
5649   return args;
5650 }
5651
5652 /* OP_SAVE_RESTORE_LIST matcher.  */
5653
5654 static bfd_boolean
5655 match_save_restore_list_operand (struct mips_arg_info *arg)
5656 {
5657   unsigned int opcode, args, statics, sregs;
5658   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5659   unsigned int arg_mask, ra, s0, s1;
5660   offsetT frame_size;
5661
5662   opcode = arg->insn->insn_opcode;
5663   frame_size = 0;
5664   num_frame_sizes = 0;
5665   args = 0;
5666   statics = 0;
5667   sregs = 0;
5668   ra = 0;
5669   s0 = 0;
5670   s1 = 0;
5671   do
5672     {
5673       unsigned int regno1, regno2;
5674
5675       if (arg->token->type == OT_INTEGER)
5676         {
5677           /* Handle the frame size.  */
5678           if (!match_const_int (arg, &frame_size))
5679             return FALSE;
5680           num_frame_sizes += 1;
5681         }
5682       else
5683         {
5684           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5685             return FALSE;
5686
5687           while (regno1 <= regno2)
5688             {
5689               if (regno1 >= 4 && regno1 <= 7)
5690                 {
5691                   if (num_frame_sizes == 0)
5692                     /* args $a0-$a3 */
5693                     args |= 1 << (regno1 - 4);
5694                   else
5695                     /* statics $a0-$a3 */
5696                     statics |= 1 << (regno1 - 4);
5697                 }
5698               else if (regno1 >= 16 && regno1 <= 23)
5699                 /* $s0-$s7 */
5700                 sregs |= 1 << (regno1 - 16);
5701               else if (regno1 == 30)
5702                 /* $s8 */
5703                 sregs |= 1 << 8;
5704               else if (regno1 == 31)
5705                 /* Add $ra to insn.  */
5706                 ra = 1;
5707               else
5708                 return FALSE;
5709               regno1 += 1;
5710               if (regno1 == 24)
5711                 regno1 = 30;
5712             }
5713         }
5714     }
5715   while (match_char (arg, ','));
5716
5717   /* Encode args/statics combination.  */
5718   if (args & statics)
5719     return FALSE;
5720   else if (args == 0xf)
5721     /* All $a0-$a3 are args.  */
5722     arg_mask = MIPS_SVRS_ALL_ARGS;
5723   else if (statics == 0xf)
5724     /* All $a0-$a3 are statics.  */
5725     arg_mask = MIPS_SVRS_ALL_STATICS;
5726   else
5727     {
5728       /* Count arg registers.  */
5729       num_args = 0;
5730       while (args & 0x1)
5731         {
5732           args >>= 1;
5733           num_args += 1;
5734         }
5735       if (args != 0)
5736         return FALSE;
5737
5738       /* Count static registers.  */
5739       num_statics = 0;
5740       while (statics & 0x8)
5741         {
5742           statics = (statics << 1) & 0xf;
5743           num_statics += 1;
5744         }
5745       if (statics != 0)
5746         return FALSE;
5747
5748       /* Encode args/statics.  */
5749       arg_mask = (num_args << 2) | num_statics;
5750     }
5751
5752   /* Encode $s0/$s1.  */
5753   if (sregs & (1 << 0))         /* $s0 */
5754     s0 = 1;
5755   if (sregs & (1 << 1))         /* $s1 */
5756     s1 = 1;
5757   sregs >>= 2;
5758
5759   /* Encode $s2-$s8. */
5760   num_sregs = 0;
5761   while (sregs & 1)
5762     {
5763       sregs >>= 1;
5764       num_sregs += 1;
5765     }
5766   if (sregs != 0)
5767     return FALSE;
5768
5769   /* Encode frame size.  */
5770   if (num_frame_sizes == 0)
5771     {
5772       set_insn_error (arg->argnum, _("missing frame size"));
5773       return FALSE;
5774     }
5775   if (num_frame_sizes > 1)
5776     {
5777       set_insn_error (arg->argnum, _("frame size specified twice"));
5778       return FALSE;
5779     }
5780   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5781     {
5782       set_insn_error (arg->argnum, _("invalid frame size"));
5783       return FALSE;
5784     }
5785   frame_size /= 8;
5786
5787   /* Finally build the instruction.  */
5788   if (mips_opts.mips16)
5789     opcode |= mips16_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5790                                           frame_size);
5791   else if (!mips_opts.micromips)
5792     opcode |= mips_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5793                                         frame_size);
5794   else
5795     abort ();
5796
5797   arg->insn->insn_opcode = opcode;
5798   return TRUE;
5799 }
5800
5801 /* OP_MDMX_IMM_REG matcher.  */
5802
5803 static bfd_boolean
5804 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5805                             const struct mips_operand *operand)
5806 {
5807   unsigned int regno, uval;
5808   bfd_boolean is_qh;
5809   const struct mips_opcode *opcode;
5810
5811   /* The mips_opcode records whether this is an octobyte or quadhalf
5812      instruction.  Start out with that bit in place.  */
5813   opcode = arg->insn->insn_mo;
5814   uval = mips_extract_operand (operand, opcode->match);
5815   is_qh = (uval != 0);
5816
5817   if (arg->token->type == OT_REG)
5818     {
5819       if ((opcode->membership & INSN_5400)
5820           && strcmp (opcode->name, "rzu.ob") == 0)
5821         {
5822           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5823                             arg->argnum);
5824           return FALSE;
5825         }
5826
5827       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5828         return FALSE;
5829       ++arg->token;
5830
5831       /* Check whether this is a vector register or a broadcast of
5832          a single element.  */
5833       if (arg->token->type == OT_INTEGER_INDEX)
5834         {
5835           if (arg->token->u.index > (is_qh ? 3 : 7))
5836             {
5837               set_insn_error (arg->argnum, _("invalid element selector"));
5838               return FALSE;
5839             }
5840           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5841           ++arg->token;
5842         }
5843       else
5844         {
5845           /* A full vector.  */
5846           if ((opcode->membership & INSN_5400)
5847               && (strcmp (opcode->name, "sll.ob") == 0
5848                   || strcmp (opcode->name, "srl.ob") == 0))
5849             {
5850               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5851                                 arg->argnum);
5852               return FALSE;
5853             }
5854
5855           if (is_qh)
5856             uval |= MDMX_FMTSEL_VEC_QH << 5;
5857           else
5858             uval |= MDMX_FMTSEL_VEC_OB << 5;
5859         }
5860       uval |= regno;
5861     }
5862   else
5863     {
5864       offsetT sval;
5865
5866       if (!match_const_int (arg, &sval))
5867         return FALSE;
5868       if (sval < 0 || sval > 31)
5869         {
5870           match_out_of_range (arg);
5871           return FALSE;
5872         }
5873       uval |= (sval & 31);
5874       if (is_qh)
5875         uval |= MDMX_FMTSEL_IMM_QH << 5;
5876       else
5877         uval |= MDMX_FMTSEL_IMM_OB << 5;
5878     }
5879   insn_insert_operand (arg->insn, operand, uval);
5880   return TRUE;
5881 }
5882
5883 /* OP_IMM_INDEX matcher.  */
5884
5885 static bfd_boolean
5886 match_imm_index_operand (struct mips_arg_info *arg,
5887                          const struct mips_operand *operand)
5888 {
5889   unsigned int max_val;
5890
5891   if (arg->token->type != OT_INTEGER_INDEX)
5892     return FALSE;
5893
5894   max_val = (1 << operand->size) - 1;
5895   if (arg->token->u.index > max_val)
5896     {
5897       match_out_of_range (arg);
5898       return FALSE;
5899     }
5900   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5901   ++arg->token;
5902   return TRUE;
5903 }
5904
5905 /* OP_REG_INDEX matcher.  */
5906
5907 static bfd_boolean
5908 match_reg_index_operand (struct mips_arg_info *arg,
5909                          const struct mips_operand *operand)
5910 {
5911   unsigned int regno;
5912
5913   if (arg->token->type != OT_REG_INDEX)
5914     return FALSE;
5915
5916   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5917     return FALSE;
5918
5919   insn_insert_operand (arg->insn, operand, regno);
5920   ++arg->token;
5921   return TRUE;
5922 }
5923
5924 /* OP_PC matcher.  */
5925
5926 static bfd_boolean
5927 match_pc_operand (struct mips_arg_info *arg)
5928 {
5929   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5930     {
5931       ++arg->token;
5932       return TRUE;
5933     }
5934   return FALSE;
5935 }
5936
5937 /* OP_REG28 matcher.  */
5938
5939 static bfd_boolean
5940 match_reg28_operand (struct mips_arg_info *arg)
5941 {
5942   unsigned int regno;
5943
5944   if (arg->token->type == OT_REG
5945       && match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno)
5946       && regno == GP)
5947     {
5948       ++arg->token;
5949       return TRUE;
5950     }
5951   return FALSE;
5952 }
5953
5954 /* OP_NON_ZERO_REG matcher.  */
5955
5956 static bfd_boolean
5957 match_non_zero_reg_operand (struct mips_arg_info *arg,
5958                             const struct mips_operand *operand)
5959 {
5960   unsigned int regno;
5961
5962   if (!match_reg (arg, OP_REG_GP, &regno))
5963     return FALSE;
5964
5965   if (regno == 0)
5966     return FALSE;
5967
5968   arg->last_regno = regno;
5969   insn_insert_operand (arg->insn, operand, regno);
5970   return TRUE;
5971 }
5972
5973 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5974    register that we need to match.  */
5975
5976 static bfd_boolean
5977 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5978 {
5979   unsigned int regno;
5980
5981   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5982 }
5983
5984 /* Try to match a floating-point constant from ARG for LI.S or LI.D.
5985    LENGTH is the length of the value in bytes (4 for float, 8 for double)
5986    and USING_GPRS says whether the destination is a GPR rather than an FPR.
5987
5988    Return the constant in IMM and OFFSET as follows:
5989
5990    - If the constant should be loaded via memory, set IMM to O_absent and
5991      OFFSET to the memory address.
5992
5993    - Otherwise, if the constant should be loaded into two 32-bit registers,
5994      set IMM to the O_constant to load into the high register and OFFSET
5995      to the corresponding value for the low register.
5996
5997    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5998
5999    These constants only appear as the last operand in an instruction,
6000    and every instruction that accepts them in any variant accepts them
6001    in all variants.  This means we don't have to worry about backing out
6002    any changes if the instruction does not match.  We just match
6003    unconditionally and report an error if the constant is invalid.  */
6004
6005 static bfd_boolean
6006 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
6007                       expressionS *offset, int length, bfd_boolean using_gprs)
6008 {
6009   char *p;
6010   segT seg, new_seg;
6011   subsegT subseg;
6012   const char *newname;
6013   unsigned char *data;
6014
6015   /* Where the constant is placed is based on how the MIPS assembler
6016      does things:
6017
6018      length == 4 && using_gprs  -- immediate value only
6019      length == 8 && using_gprs  -- .rdata or immediate value
6020      length == 4 && !using_gprs -- .lit4 or immediate value
6021      length == 8 && !using_gprs -- .lit8 or immediate value
6022
6023      The .lit4 and .lit8 sections are only used if permitted by the
6024      -G argument.  */
6025   if (arg->token->type != OT_FLOAT)
6026     {
6027       set_insn_error (arg->argnum, _("floating-point expression required"));
6028       return FALSE;
6029     }
6030
6031   gas_assert (arg->token->u.flt.length == length);
6032   data = arg->token->u.flt.data;
6033   ++arg->token;
6034
6035   /* Handle 32-bit constants for which an immediate value is best.  */
6036   if (length == 4
6037       && (using_gprs
6038           || g_switch_value < 4
6039           || (data[0] == 0 && data[1] == 0)
6040           || (data[2] == 0 && data[3] == 0)))
6041     {
6042       imm->X_op = O_constant;
6043       if (!target_big_endian)
6044         imm->X_add_number = bfd_getl32 (data);
6045       else
6046         imm->X_add_number = bfd_getb32 (data);
6047       offset->X_op = O_absent;
6048       return TRUE;
6049     }
6050
6051   /* Handle 64-bit constants for which an immediate value is best.  */
6052   if (length == 8
6053       && !mips_disable_float_construction
6054       /* Constants can only be constructed in GPRs and copied to FPRs if the
6055          GPRs are at least as wide as the FPRs or MTHC1 is available.
6056          Unlike most tests for 32-bit floating-point registers this check
6057          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
6058          permit 64-bit moves without MXHC1.
6059          Force the constant into memory otherwise.  */
6060       && (using_gprs
6061           || GPR_SIZE == 64
6062           || ISA_HAS_MXHC1 (mips_opts.isa)
6063           || FPR_SIZE == 32)
6064       && ((data[0] == 0 && data[1] == 0)
6065           || (data[2] == 0 && data[3] == 0))
6066       && ((data[4] == 0 && data[5] == 0)
6067           || (data[6] == 0 && data[7] == 0)))
6068     {
6069       /* The value is simple enough to load with a couple of instructions.
6070          If using 32-bit registers, set IMM to the high order 32 bits and
6071          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
6072          64 bit constant.  */
6073       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
6074         {
6075           imm->X_op = O_constant;
6076           offset->X_op = O_constant;
6077           if (!target_big_endian)
6078             {
6079               imm->X_add_number = bfd_getl32 (data + 4);
6080               offset->X_add_number = bfd_getl32 (data);
6081             }
6082           else
6083             {
6084               imm->X_add_number = bfd_getb32 (data);
6085               offset->X_add_number = bfd_getb32 (data + 4);
6086             }
6087           if (offset->X_add_number == 0)
6088             offset->X_op = O_absent;
6089         }
6090       else
6091         {
6092           imm->X_op = O_constant;
6093           if (!target_big_endian)
6094             imm->X_add_number = bfd_getl64 (data);
6095           else
6096             imm->X_add_number = bfd_getb64 (data);
6097           offset->X_op = O_absent;
6098         }
6099       return TRUE;
6100     }
6101
6102   /* Switch to the right section.  */
6103   seg = now_seg;
6104   subseg = now_subseg;
6105   if (length == 4)
6106     {
6107       gas_assert (!using_gprs && g_switch_value >= 4);
6108       newname = ".lit4";
6109     }
6110   else
6111     {
6112       if (using_gprs || g_switch_value < 8)
6113         newname = RDATA_SECTION_NAME;
6114       else
6115         newname = ".lit8";
6116     }
6117
6118   new_seg = subseg_new (newname, (subsegT) 0);
6119   bfd_set_section_flags (stdoutput, new_seg,
6120                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
6121   frag_align (length == 4 ? 2 : 3, 0, 0);
6122   if (strncmp (TARGET_OS, "elf", 3) != 0)
6123     record_alignment (new_seg, 4);
6124   else
6125     record_alignment (new_seg, length == 4 ? 2 : 3);
6126   if (seg == now_seg)
6127     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
6128
6129   /* Set the argument to the current address in the section.  */
6130   imm->X_op = O_absent;
6131   offset->X_op = O_symbol;
6132   offset->X_add_symbol = symbol_temp_new_now ();
6133   offset->X_add_number = 0;
6134
6135   /* Put the floating point number into the section.  */
6136   p = frag_more (length);
6137   memcpy (p, data, length);
6138
6139   /* Switch back to the original section.  */
6140   subseg_set (seg, subseg);
6141   return TRUE;
6142 }
6143
6144 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
6145    them.  */
6146
6147 static bfd_boolean
6148 match_vu0_suffix_operand (struct mips_arg_info *arg,
6149                           const struct mips_operand *operand,
6150                           bfd_boolean match_p)
6151 {
6152   unsigned int uval;
6153
6154   /* The operand can be an XYZW mask or a single 2-bit channel index
6155      (with X being 0).  */
6156   gas_assert (operand->size == 2 || operand->size == 4);
6157
6158   /* The suffix can be omitted when it is already part of the opcode.  */
6159   if (arg->token->type != OT_CHANNELS)
6160     return match_p;
6161
6162   uval = arg->token->u.channels;
6163   if (operand->size == 2)
6164     {
6165       /* Check that a single bit is set and convert it into a 2-bit index.  */
6166       if ((uval & -uval) != uval)
6167         return FALSE;
6168       uval = 4 - ffs (uval);
6169     }
6170
6171   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6172     return FALSE;
6173
6174   ++arg->token;
6175   if (!match_p)
6176     insn_insert_operand (arg->insn, operand, uval);
6177   return TRUE;
6178 }
6179
6180 /* Try to match a token from ARG against OPERAND.  Consume the token
6181    and return true on success, otherwise return false.  */
6182
6183 static bfd_boolean
6184 match_operand (struct mips_arg_info *arg,
6185                const struct mips_operand *operand)
6186 {
6187   switch (operand->type)
6188     {
6189     case OP_INT:
6190       return match_int_operand (arg, operand);
6191
6192     case OP_MAPPED_INT:
6193       return match_mapped_int_operand (arg, operand);
6194
6195     case OP_MSB:
6196       return match_msb_operand (arg, operand);
6197
6198     case OP_REG:
6199     case OP_OPTIONAL_REG:
6200       return match_reg_operand (arg, operand);
6201
6202     case OP_REG_PAIR:
6203       return match_reg_pair_operand (arg, operand);
6204
6205     case OP_PCREL:
6206       return match_pcrel_operand (arg);
6207
6208     case OP_PERF_REG:
6209       return match_perf_reg_operand (arg, operand);
6210
6211     case OP_ADDIUSP_INT:
6212       return match_addiusp_operand (arg, operand);
6213
6214     case OP_CLO_CLZ_DEST:
6215       return match_clo_clz_dest_operand (arg, operand);
6216
6217     case OP_LWM_SWM_LIST:
6218       return match_lwm_swm_list_operand (arg, operand);
6219
6220     case OP_ENTRY_EXIT_LIST:
6221       return match_entry_exit_operand (arg, operand);
6222
6223     case OP_SAVE_RESTORE_LIST:
6224       return match_save_restore_list_operand (arg);
6225
6226     case OP_MDMX_IMM_REG:
6227       return match_mdmx_imm_reg_operand (arg, operand);
6228
6229     case OP_REPEAT_DEST_REG:
6230       return match_tied_reg_operand (arg, arg->dest_regno);
6231
6232     case OP_REPEAT_PREV_REG:
6233       return match_tied_reg_operand (arg, arg->last_regno);
6234
6235     case OP_PC:
6236       return match_pc_operand (arg);
6237
6238     case OP_REG28:
6239       return match_reg28_operand (arg);
6240
6241     case OP_VU0_SUFFIX:
6242       return match_vu0_suffix_operand (arg, operand, FALSE);
6243
6244     case OP_VU0_MATCH_SUFFIX:
6245       return match_vu0_suffix_operand (arg, operand, TRUE);
6246
6247     case OP_IMM_INDEX:
6248       return match_imm_index_operand (arg, operand);
6249
6250     case OP_REG_INDEX:
6251       return match_reg_index_operand (arg, operand);
6252
6253     case OP_SAME_RS_RT:
6254       return match_same_rs_rt_operand (arg, operand);
6255
6256     case OP_CHECK_PREV:
6257       return match_check_prev_operand (arg, operand);
6258
6259     case OP_NON_ZERO_REG:
6260       return match_non_zero_reg_operand (arg, operand);
6261     }
6262   abort ();
6263 }
6264
6265 /* ARG is the state after successfully matching an instruction.
6266    Issue any queued-up warnings.  */
6267
6268 static void
6269 check_completed_insn (struct mips_arg_info *arg)
6270 {
6271   if (arg->seen_at)
6272     {
6273       if (AT == ATREG)
6274         as_warn (_("used $at without \".set noat\""));
6275       else
6276         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6277     }
6278 }
6279
6280 /* Return true if modifying general-purpose register REG needs a delay.  */
6281
6282 static bfd_boolean
6283 reg_needs_delay (unsigned int reg)
6284 {
6285   unsigned long prev_pinfo;
6286
6287   prev_pinfo = history[0].insn_mo->pinfo;
6288   if (!mips_opts.noreorder
6289       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6290           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6291       && (gpr_write_mask (&history[0]) & (1 << reg)))
6292     return TRUE;
6293
6294   return FALSE;
6295 }
6296
6297 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6298    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6299    by VR4120 errata.  */
6300
6301 static unsigned int
6302 classify_vr4120_insn (const char *name)
6303 {
6304   if (strncmp (name, "macc", 4) == 0)
6305     return FIX_VR4120_MACC;
6306   if (strncmp (name, "dmacc", 5) == 0)
6307     return FIX_VR4120_DMACC;
6308   if (strncmp (name, "mult", 4) == 0)
6309     return FIX_VR4120_MULT;
6310   if (strncmp (name, "dmult", 5) == 0)
6311     return FIX_VR4120_DMULT;
6312   if (strstr (name, "div"))
6313     return FIX_VR4120_DIV;
6314   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6315     return FIX_VR4120_MTHILO;
6316   return NUM_FIX_VR4120_CLASSES;
6317 }
6318
6319 #define INSN_ERET       0x42000018
6320 #define INSN_DERET      0x4200001f
6321 #define INSN_DMULT      0x1c
6322 #define INSN_DMULTU     0x1d
6323
6324 /* Return the number of instructions that must separate INSN1 and INSN2,
6325    where INSN1 is the earlier instruction.  Return the worst-case value
6326    for any INSN2 if INSN2 is null.  */
6327
6328 static unsigned int
6329 insns_between (const struct mips_cl_insn *insn1,
6330                const struct mips_cl_insn *insn2)
6331 {
6332   unsigned long pinfo1, pinfo2;
6333   unsigned int mask;
6334
6335   /* If INFO2 is null, pessimistically assume that all flags are set for
6336      the second instruction.  */
6337   pinfo1 = insn1->insn_mo->pinfo;
6338   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6339
6340   /* For most targets, write-after-read dependencies on the HI and LO
6341      registers must be separated by at least two instructions.  */
6342   if (!hilo_interlocks)
6343     {
6344       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6345         return 2;
6346       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6347         return 2;
6348     }
6349
6350   /* If we're working around r7000 errata, there must be two instructions
6351      between an mfhi or mflo and any instruction that uses the result.  */
6352   if (mips_7000_hilo_fix
6353       && !mips_opts.micromips
6354       && MF_HILO_INSN (pinfo1)
6355       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6356     return 2;
6357
6358   /* If we're working around 24K errata, one instruction is required
6359      if an ERET or DERET is followed by a branch instruction.  */
6360   if (mips_fix_24k && !mips_opts.micromips)
6361     {
6362       if (insn1->insn_opcode == INSN_ERET
6363           || insn1->insn_opcode == INSN_DERET)
6364         {
6365           if (insn2 == NULL
6366               || insn2->insn_opcode == INSN_ERET
6367               || insn2->insn_opcode == INSN_DERET
6368               || delayed_branch_p (insn2))
6369             return 1;
6370         }
6371     }
6372
6373   /* If we're working around PMC RM7000 errata, there must be three
6374      nops between a dmult and a load instruction.  */
6375   if (mips_fix_rm7000 && !mips_opts.micromips)
6376     {
6377       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6378           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6379         {
6380           if (pinfo2 & INSN_LOAD_MEMORY)
6381            return 3;
6382         }
6383     }
6384
6385   /* If working around VR4120 errata, check for combinations that need
6386      a single intervening instruction.  */
6387   if (mips_fix_vr4120 && !mips_opts.micromips)
6388     {
6389       unsigned int class1, class2;
6390
6391       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6392       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6393         {
6394           if (insn2 == NULL)
6395             return 1;
6396           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6397           if (vr4120_conflicts[class1] & (1 << class2))
6398             return 1;
6399         }
6400     }
6401
6402   if (!HAVE_CODE_COMPRESSION)
6403     {
6404       /* Check for GPR or coprocessor load delays.  All such delays
6405          are on the RT register.  */
6406       /* Itbl support may require additional care here.  */
6407       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6408           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6409         {
6410           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6411             return 1;
6412         }
6413
6414       /* Check for generic coprocessor hazards.
6415
6416          This case is not handled very well.  There is no special
6417          knowledge of CP0 handling, and the coprocessors other than
6418          the floating point unit are not distinguished at all.  */
6419       /* Itbl support may require additional care here. FIXME!
6420          Need to modify this to include knowledge about
6421          user specified delays!  */
6422       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6423                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6424         {
6425           /* Handle cases where INSN1 writes to a known general coprocessor
6426              register.  There must be a one instruction delay before INSN2
6427              if INSN2 reads that register, otherwise no delay is needed.  */
6428           mask = fpr_write_mask (insn1);
6429           if (mask != 0)
6430             {
6431               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6432                 return 1;
6433             }
6434           else
6435             {
6436               /* Read-after-write dependencies on the control registers
6437                  require a two-instruction gap.  */
6438               if ((pinfo1 & INSN_WRITE_COND_CODE)
6439                   && (pinfo2 & INSN_READ_COND_CODE))
6440                 return 2;
6441
6442               /* We don't know exactly what INSN1 does.  If INSN2 is
6443                  also a coprocessor instruction, assume there must be
6444                  a one instruction gap.  */
6445               if (pinfo2 & INSN_COP)
6446                 return 1;
6447             }
6448         }
6449
6450       /* Check for read-after-write dependencies on the coprocessor
6451          control registers in cases where INSN1 does not need a general
6452          coprocessor delay.  This means that INSN1 is a floating point
6453          comparison instruction.  */
6454       /* Itbl support may require additional care here.  */
6455       else if (!cop_interlocks
6456                && (pinfo1 & INSN_WRITE_COND_CODE)
6457                && (pinfo2 & INSN_READ_COND_CODE))
6458         return 1;
6459     }
6460
6461   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6462      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6463      and pause.  */
6464   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6465       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6466           || (insn2 && delayed_branch_p (insn2))))
6467     return 1;
6468
6469   return 0;
6470 }
6471
6472 /* Return the number of nops that would be needed to work around the
6473    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6474    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6475    that are contained within the first IGNORE instructions of HIST.  */
6476
6477 static int
6478 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6479                  const struct mips_cl_insn *insn)
6480 {
6481   int i, j;
6482   unsigned int mask;
6483
6484   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6485      are not affected by the errata.  */
6486   if (insn != 0
6487       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6488           || strcmp (insn->insn_mo->name, "mtlo") == 0
6489           || strcmp (insn->insn_mo->name, "mthi") == 0))
6490     return 0;
6491
6492   /* Search for the first MFLO or MFHI.  */
6493   for (i = 0; i < MAX_VR4130_NOPS; i++)
6494     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6495       {
6496         /* Extract the destination register.  */
6497         mask = gpr_write_mask (&hist[i]);
6498
6499         /* No nops are needed if INSN reads that register.  */
6500         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6501           return 0;
6502
6503         /* ...or if any of the intervening instructions do.  */
6504         for (j = 0; j < i; j++)
6505           if (gpr_read_mask (&hist[j]) & mask)
6506             return 0;
6507
6508         if (i >= ignore)
6509           return MAX_VR4130_NOPS - i;
6510       }
6511   return 0;
6512 }
6513
6514 #define BASE_REG_EQ(INSN1, INSN2)       \
6515   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6516       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6517
6518 /* Return the minimum alignment for this store instruction.  */
6519
6520 static int
6521 fix_24k_align_to (const struct mips_opcode *mo)
6522 {
6523   if (strcmp (mo->name, "sh") == 0)
6524     return 2;
6525
6526   if (strcmp (mo->name, "swc1") == 0
6527       || strcmp (mo->name, "swc2") == 0
6528       || strcmp (mo->name, "sw") == 0
6529       || strcmp (mo->name, "sc") == 0
6530       || strcmp (mo->name, "s.s") == 0)
6531     return 4;
6532
6533   if (strcmp (mo->name, "sdc1") == 0
6534       || strcmp (mo->name, "sdc2") == 0
6535       || strcmp (mo->name, "s.d") == 0)
6536     return 8;
6537
6538   /* sb, swl, swr */
6539   return 1;
6540 }
6541
6542 struct fix_24k_store_info
6543   {
6544     /* Immediate offset, if any, for this store instruction.  */
6545     short off;
6546     /* Alignment required by this store instruction.  */
6547     int align_to;
6548     /* True for register offsets.  */
6549     int register_offset;
6550   };
6551
6552 /* Comparison function used by qsort.  */
6553
6554 static int
6555 fix_24k_sort (const void *a, const void *b)
6556 {
6557   const struct fix_24k_store_info *pos1 = a;
6558   const struct fix_24k_store_info *pos2 = b;
6559
6560   return (pos1->off - pos2->off);
6561 }
6562
6563 /* INSN is a store instruction.  Try to record the store information
6564    in STINFO.  Return false if the information isn't known.  */
6565
6566 static bfd_boolean
6567 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6568                            const struct mips_cl_insn *insn)
6569 {
6570   /* The instruction must have a known offset.  */
6571   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6572     return FALSE;
6573
6574   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6575   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6576   return TRUE;
6577 }
6578
6579 /* Return the number of nops that would be needed to work around the 24k
6580    "lost data on stores during refill" errata if instruction INSN
6581    immediately followed the 2 instructions described by HIST.
6582    Ignore hazards that are contained within the first IGNORE
6583    instructions of HIST.
6584
6585    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6586    for the data cache refills and store data. The following describes
6587    the scenario where the store data could be lost.
6588
6589    * A data cache miss, due to either a load or a store, causing fill
6590      data to be supplied by the memory subsystem
6591    * The first three doublewords of fill data are returned and written
6592      into the cache
6593    * A sequence of four stores occurs in consecutive cycles around the
6594      final doubleword of the fill:
6595    * Store A
6596    * Store B
6597    * Store C
6598    * Zero, One or more instructions
6599    * Store D
6600
6601    The four stores A-D must be to different doublewords of the line that
6602    is being filled. The fourth instruction in the sequence above permits
6603    the fill of the final doubleword to be transferred from the FSB into
6604    the cache. In the sequence above, the stores may be either integer
6605    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6606    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6607    different doublewords on the line. If the floating point unit is
6608    running in 1:2 mode, it is not possible to create the sequence above
6609    using only floating point store instructions.
6610
6611    In this case, the cache line being filled is incorrectly marked
6612    invalid, thereby losing the data from any store to the line that
6613    occurs between the original miss and the completion of the five
6614    cycle sequence shown above.
6615
6616    The workarounds are:
6617
6618    * Run the data cache in write-through mode.
6619    * Insert a non-store instruction between
6620      Store A and Store B or Store B and Store C.  */
6621
6622 static int
6623 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6624               const struct mips_cl_insn *insn)
6625 {
6626   struct fix_24k_store_info pos[3];
6627   int align, i, base_offset;
6628
6629   if (ignore >= 2)
6630     return 0;
6631
6632   /* If the previous instruction wasn't a store, there's nothing to
6633      worry about.  */
6634   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6635     return 0;
6636
6637   /* If the instructions after the previous one are unknown, we have
6638      to assume the worst.  */
6639   if (!insn)
6640     return 1;
6641
6642   /* Check whether we are dealing with three consecutive stores.  */
6643   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6644       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6645     return 0;
6646
6647   /* If we don't know the relationship between the store addresses,
6648      assume the worst.  */
6649   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6650       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6651     return 1;
6652
6653   if (!fix_24k_record_store_info (&pos[0], insn)
6654       || !fix_24k_record_store_info (&pos[1], &hist[0])
6655       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6656     return 1;
6657
6658   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6659
6660   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6661      X bytes and such that the base register + X is known to be aligned
6662      to align bytes.  */
6663
6664   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6665     align = 8;
6666   else
6667     {
6668       align = pos[0].align_to;
6669       base_offset = pos[0].off;
6670       for (i = 1; i < 3; i++)
6671         if (align < pos[i].align_to)
6672           {
6673             align = pos[i].align_to;
6674             base_offset = pos[i].off;
6675           }
6676       for (i = 0; i < 3; i++)
6677         pos[i].off -= base_offset;
6678     }
6679
6680   pos[0].off &= ~align + 1;
6681   pos[1].off &= ~align + 1;
6682   pos[2].off &= ~align + 1;
6683
6684   /* If any two stores write to the same chunk, they also write to the
6685      same doubleword.  The offsets are still sorted at this point.  */
6686   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6687     return 0;
6688
6689   /* A range of at least 9 bytes is needed for the stores to be in
6690      non-overlapping doublewords.  */
6691   if (pos[2].off - pos[0].off <= 8)
6692     return 0;
6693
6694   if (pos[2].off - pos[1].off >= 24
6695       || pos[1].off - pos[0].off >= 24
6696       || pos[2].off - pos[0].off >= 32)
6697     return 0;
6698
6699   return 1;
6700 }
6701
6702 /* Return the number of nops that would be needed if instruction INSN
6703    immediately followed the MAX_NOPS instructions given by HIST,
6704    where HIST[0] is the most recent instruction.  Ignore hazards
6705    between INSN and the first IGNORE instructions in HIST.
6706
6707    If INSN is null, return the worse-case number of nops for any
6708    instruction.  */
6709
6710 static int
6711 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6712                const struct mips_cl_insn *insn)
6713 {
6714   int i, nops, tmp_nops;
6715
6716   nops = 0;
6717   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6718     {
6719       tmp_nops = insns_between (hist + i, insn) - i;
6720       if (tmp_nops > nops)
6721         nops = tmp_nops;
6722     }
6723
6724   if (mips_fix_vr4130 && !mips_opts.micromips)
6725     {
6726       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6727       if (tmp_nops > nops)
6728         nops = tmp_nops;
6729     }
6730
6731   if (mips_fix_24k && !mips_opts.micromips)
6732     {
6733       tmp_nops = nops_for_24k (ignore, hist, insn);
6734       if (tmp_nops > nops)
6735         nops = tmp_nops;
6736     }
6737
6738   return nops;
6739 }
6740
6741 /* The variable arguments provide NUM_INSNS extra instructions that
6742    might be added to HIST.  Return the largest number of nops that
6743    would be needed after the extended sequence, ignoring hazards
6744    in the first IGNORE instructions.  */
6745
6746 static int
6747 nops_for_sequence (int num_insns, int ignore,
6748                    const struct mips_cl_insn *hist, ...)
6749 {
6750   va_list args;
6751   struct mips_cl_insn buffer[MAX_NOPS];
6752   struct mips_cl_insn *cursor;
6753   int nops;
6754
6755   va_start (args, hist);
6756   cursor = buffer + num_insns;
6757   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6758   while (cursor > buffer)
6759     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6760
6761   nops = nops_for_insn (ignore, buffer, NULL);
6762   va_end (args);
6763   return nops;
6764 }
6765
6766 /* Like nops_for_insn, but if INSN is a branch, take into account the
6767    worst-case delay for the branch target.  */
6768
6769 static int
6770 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6771                          const struct mips_cl_insn *insn)
6772 {
6773   int nops, tmp_nops;
6774
6775   nops = nops_for_insn (ignore, hist, insn);
6776   if (delayed_branch_p (insn))
6777     {
6778       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6779                                     hist, insn, get_delay_slot_nop (insn));
6780       if (tmp_nops > nops)
6781         nops = tmp_nops;
6782     }
6783   else if (compact_branch_p (insn))
6784     {
6785       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6786       if (tmp_nops > nops)
6787         nops = tmp_nops;
6788     }
6789   return nops;
6790 }
6791
6792 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6793
6794 static void
6795 fix_loongson2f_nop (struct mips_cl_insn * ip)
6796 {
6797   gas_assert (!HAVE_CODE_COMPRESSION);
6798   if (strcmp (ip->insn_mo->name, "nop") == 0)
6799     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6800 }
6801
6802 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6803                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6804
6805 static void
6806 fix_loongson2f_jump (struct mips_cl_insn * ip)
6807 {
6808   gas_assert (!HAVE_CODE_COMPRESSION);
6809   if (strcmp (ip->insn_mo->name, "j") == 0
6810       || strcmp (ip->insn_mo->name, "jr") == 0
6811       || strcmp (ip->insn_mo->name, "jalr") == 0)
6812     {
6813       int sreg;
6814       expressionS ep;
6815
6816       if (! mips_opts.at)
6817         return;
6818
6819       sreg = EXTRACT_OPERAND (0, RS, *ip);
6820       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6821         return;
6822
6823       ep.X_op = O_constant;
6824       ep.X_add_number = 0xcfff0000;
6825       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6826       ep.X_add_number = 0xffff;
6827       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6828       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6829     }
6830 }
6831
6832 static void
6833 fix_loongson2f (struct mips_cl_insn * ip)
6834 {
6835   if (mips_fix_loongson2f_nop)
6836     fix_loongson2f_nop (ip);
6837
6838   if (mips_fix_loongson2f_jump)
6839     fix_loongson2f_jump (ip);
6840 }
6841
6842 /* IP is a branch that has a delay slot, and we need to fill it
6843    automatically.   Return true if we can do that by swapping IP
6844    with the previous instruction.
6845    ADDRESS_EXPR is an operand of the instruction to be used with
6846    RELOC_TYPE.  */
6847
6848 static bfd_boolean
6849 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6850                    bfd_reloc_code_real_type *reloc_type)
6851 {
6852   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6853   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6854   unsigned int fpr_read, prev_fpr_write;
6855
6856   /* -O2 and above is required for this optimization.  */
6857   if (mips_optimize < 2)
6858     return FALSE;
6859
6860   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6861   if (mips_opts.nomove)
6862     return FALSE;
6863
6864   /* We can't swap if the previous instruction's position is fixed.  */
6865   if (history[0].fixed_p)
6866     return FALSE;
6867
6868   /* If the previous previous insn was in a .set noreorder, we can't
6869      swap.  Actually, the MIPS assembler will swap in this situation.
6870      However, gcc configured -with-gnu-as will generate code like
6871
6872         .set    noreorder
6873         lw      $4,XXX
6874         .set    reorder
6875         INSN
6876         bne     $4,$0,foo
6877
6878      in which we can not swap the bne and INSN.  If gcc is not configured
6879      -with-gnu-as, it does not output the .set pseudo-ops.  */
6880   if (history[1].noreorder_p)
6881     return FALSE;
6882
6883   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6884      This means that the previous instruction was a 4-byte one anyhow.  */
6885   if (mips_opts.mips16 && history[0].fixp[0])
6886     return FALSE;
6887
6888   /* If the branch is itself the target of a branch, we can not swap.
6889      We cheat on this; all we check for is whether there is a label on
6890      this instruction.  If there are any branches to anything other than
6891      a label, users must use .set noreorder.  */
6892   if (seg_info (now_seg)->label_list)
6893     return FALSE;
6894
6895   /* If the previous instruction is in a variant frag other than this
6896      branch's one, we cannot do the swap.  This does not apply to
6897      MIPS16 code, which uses variant frags for different purposes.  */
6898   if (!mips_opts.mips16
6899       && history[0].frag
6900       && history[0].frag->fr_type == rs_machine_dependent)
6901     return FALSE;
6902
6903   /* We do not swap with instructions that cannot architecturally
6904      be placed in a branch delay slot, such as SYNC or ERET.  We
6905      also refrain from swapping with a trap instruction, since it
6906      complicates trap handlers to have the trap instruction be in
6907      a delay slot.  */
6908   prev_pinfo = history[0].insn_mo->pinfo;
6909   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6910     return FALSE;
6911
6912   /* Check for conflicts between the branch and the instructions
6913      before the candidate delay slot.  */
6914   if (nops_for_insn (0, history + 1, ip) > 0)
6915     return FALSE;
6916
6917   /* Check for conflicts between the swapped sequence and the
6918      target of the branch.  */
6919   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6920     return FALSE;
6921
6922   /* If the branch reads a register that the previous
6923      instruction sets, we can not swap.  */
6924   gpr_read = gpr_read_mask (ip);
6925   prev_gpr_write = gpr_write_mask (&history[0]);
6926   if (gpr_read & prev_gpr_write)
6927     return FALSE;
6928
6929   fpr_read = fpr_read_mask (ip);
6930   prev_fpr_write = fpr_write_mask (&history[0]);
6931   if (fpr_read & prev_fpr_write)
6932     return FALSE;
6933
6934   /* If the branch writes a register that the previous
6935      instruction sets, we can not swap.  */
6936   gpr_write = gpr_write_mask (ip);
6937   if (gpr_write & prev_gpr_write)
6938     return FALSE;
6939
6940   /* If the branch writes a register that the previous
6941      instruction reads, we can not swap.  */
6942   prev_gpr_read = gpr_read_mask (&history[0]);
6943   if (gpr_write & prev_gpr_read)
6944     return FALSE;
6945
6946   /* If one instruction sets a condition code and the
6947      other one uses a condition code, we can not swap.  */
6948   pinfo = ip->insn_mo->pinfo;
6949   if ((pinfo & INSN_READ_COND_CODE)
6950       && (prev_pinfo & INSN_WRITE_COND_CODE))
6951     return FALSE;
6952   if ((pinfo & INSN_WRITE_COND_CODE)
6953       && (prev_pinfo & INSN_READ_COND_CODE))
6954     return FALSE;
6955
6956   /* If the previous instruction uses the PC, we can not swap.  */
6957   prev_pinfo2 = history[0].insn_mo->pinfo2;
6958   if (prev_pinfo2 & INSN2_READ_PC)
6959     return FALSE;
6960
6961   /* If the previous instruction has an incorrect size for a fixed
6962      branch delay slot in microMIPS mode, we cannot swap.  */
6963   pinfo2 = ip->insn_mo->pinfo2;
6964   if (mips_opts.micromips
6965       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6966       && insn_length (history) != 2)
6967     return FALSE;
6968   if (mips_opts.micromips
6969       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6970       && insn_length (history) != 4)
6971     return FALSE;
6972
6973   /* On R5900 short loops need to be fixed by inserting a nop in
6974      the branch delay slots.
6975      A short loop can be terminated too early.  */
6976   if (mips_opts.arch == CPU_R5900
6977       /* Check if instruction has a parameter, ignore "j $31". */
6978       && (address_expr != NULL)
6979       /* Parameter must be 16 bit. */
6980       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6981       /* Branch to same segment. */
6982       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6983       /* Branch to same code fragment. */
6984       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6985       /* Can only calculate branch offset if value is known. */
6986       && symbol_constant_p (address_expr->X_add_symbol)
6987       /* Check if branch is really conditional. */
6988       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6989         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6990         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6991     {
6992       int distance;
6993       /* Check if loop is shorter than 6 instructions including
6994          branch and delay slot.  */
6995       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
6996       if (distance <= 20)
6997         {
6998           int i;
6999           int rv;
7000
7001           rv = FALSE;
7002           /* When the loop includes branches or jumps,
7003              it is not a short loop. */
7004           for (i = 0; i < (distance / 4); i++)
7005             {
7006               if ((history[i].cleared_p)
7007                   || delayed_branch_p (&history[i]))
7008                 {
7009                   rv = TRUE;
7010                   break;
7011                 }
7012             }
7013           if (!rv)
7014             {
7015               /* Insert nop after branch to fix short loop. */
7016               return FALSE;
7017             }
7018         }
7019     }
7020
7021   return TRUE;
7022 }
7023
7024 /* Decide how we should add IP to the instruction stream.
7025    ADDRESS_EXPR is an operand of the instruction to be used with
7026    RELOC_TYPE.  */
7027
7028 static enum append_method
7029 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
7030                    bfd_reloc_code_real_type *reloc_type)
7031 {
7032   /* The relaxed version of a macro sequence must be inherently
7033      hazard-free.  */
7034   if (mips_relax.sequence == 2)
7035     return APPEND_ADD;
7036
7037   /* We must not dabble with instructions in a ".set noreorder" block.  */
7038   if (mips_opts.noreorder)
7039     return APPEND_ADD;
7040
7041   /* Otherwise, it's our responsibility to fill branch delay slots.  */
7042   if (delayed_branch_p (ip))
7043     {
7044       if (!branch_likely_p (ip)
7045           && can_swap_branch_p (ip, address_expr, reloc_type))
7046         return APPEND_SWAP;
7047
7048       if (mips_opts.mips16
7049           && ISA_SUPPORTS_MIPS16E
7050           && gpr_read_mask (ip) != 0)
7051         return APPEND_ADD_COMPACT;
7052
7053       if (mips_opts.micromips
7054           && ((ip->insn_opcode & 0xffe0) == 0x4580
7055               || (!forced_insn_length
7056                   && ((ip->insn_opcode & 0xfc00) == 0xcc00
7057                       || (ip->insn_opcode & 0xdc00) == 0x8c00))
7058               || (ip->insn_opcode & 0xdfe00000) == 0x94000000
7059               || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
7060         return APPEND_ADD_COMPACT;
7061
7062       return APPEND_ADD_WITH_NOP;
7063     }
7064
7065   return APPEND_ADD;
7066 }
7067
7068 /* IP is an instruction whose opcode we have just changed, END points
7069    to the end of the opcode table processed.  Point IP->insn_mo to the
7070    new opcode's definition.  */
7071
7072 static void
7073 find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
7074 {
7075   const struct mips_opcode *mo;
7076
7077   for (mo = ip->insn_mo; mo < end; mo++)
7078     if (mo->pinfo != INSN_MACRO
7079         && (ip->insn_opcode & mo->mask) == mo->match)
7080       {
7081         ip->insn_mo = mo;
7082         return;
7083       }
7084   abort ();
7085 }
7086
7087 /* IP is a MIPS16 instruction whose opcode we have just changed.
7088    Point IP->insn_mo to the new opcode's definition.  */
7089
7090 static void
7091 find_altered_mips16_opcode (struct mips_cl_insn *ip)
7092 {
7093   find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
7094 }
7095
7096 /* IP is a microMIPS instruction whose opcode we have just changed.
7097    Point IP->insn_mo to the new opcode's definition.  */
7098
7099 static void
7100 find_altered_micromips_opcode (struct mips_cl_insn *ip)
7101 {
7102   find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
7103 }
7104
7105 /* For microMIPS macros, we need to generate a local number label
7106    as the target of branches.  */
7107 #define MICROMIPS_LABEL_CHAR            '\037'
7108 static unsigned long micromips_target_label;
7109 static char micromips_target_name[32];
7110
7111 static char *
7112 micromips_label_name (void)
7113 {
7114   char *p = micromips_target_name;
7115   char symbol_name_temporary[24];
7116   unsigned long l;
7117   int i;
7118
7119   if (*p)
7120     return p;
7121
7122   i = 0;
7123   l = micromips_target_label;
7124 #ifdef LOCAL_LABEL_PREFIX
7125   *p++ = LOCAL_LABEL_PREFIX;
7126 #endif
7127   *p++ = 'L';
7128   *p++ = MICROMIPS_LABEL_CHAR;
7129   do
7130     {
7131       symbol_name_temporary[i++] = l % 10 + '0';
7132       l /= 10;
7133     }
7134   while (l != 0);
7135   while (i > 0)
7136     *p++ = symbol_name_temporary[--i];
7137   *p = '\0';
7138
7139   return micromips_target_name;
7140 }
7141
7142 static void
7143 micromips_label_expr (expressionS *label_expr)
7144 {
7145   label_expr->X_op = O_symbol;
7146   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
7147   label_expr->X_add_number = 0;
7148 }
7149
7150 static void
7151 micromips_label_inc (void)
7152 {
7153   micromips_target_label++;
7154   *micromips_target_name = '\0';
7155 }
7156
7157 static void
7158 micromips_add_label (void)
7159 {
7160   symbolS *s;
7161
7162   s = colon (micromips_label_name ());
7163   micromips_label_inc ();
7164   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
7165 }
7166
7167 /* If assembling microMIPS code, then return the microMIPS reloc
7168    corresponding to the requested one if any.  Otherwise return
7169    the reloc unchanged.  */
7170
7171 static bfd_reloc_code_real_type
7172 micromips_map_reloc (bfd_reloc_code_real_type reloc)
7173 {
7174   static const bfd_reloc_code_real_type relocs[][2] =
7175     {
7176       /* Keep sorted incrementally by the left-hand key.  */
7177       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7178       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7179       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7180       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7181       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7182       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7183       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7184       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7185       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7186       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7187       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7188       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7189       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7190       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7191       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7192       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7193       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7194       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7195       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7196       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7197       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7198       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7199       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7200       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7201       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7202       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7203       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7204     };
7205   bfd_reloc_code_real_type r;
7206   size_t i;
7207
7208   if (!mips_opts.micromips)
7209     return reloc;
7210   for (i = 0; i < ARRAY_SIZE (relocs); i++)
7211     {
7212       r = relocs[i][0];
7213       if (r > reloc)
7214         return reloc;
7215       if (r == reloc)
7216         return relocs[i][1];
7217     }
7218   return reloc;
7219 }
7220
7221 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7222    Return true on success, storing the resolved value in RESULT.  */
7223
7224 static bfd_boolean
7225 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7226                  offsetT *result)
7227 {
7228   switch (reloc)
7229     {
7230     case BFD_RELOC_MIPS_HIGHEST:
7231     case BFD_RELOC_MICROMIPS_HIGHEST:
7232       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7233       return TRUE;
7234
7235     case BFD_RELOC_MIPS_HIGHER:
7236     case BFD_RELOC_MICROMIPS_HIGHER:
7237       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7238       return TRUE;
7239
7240     case BFD_RELOC_HI16_S:
7241     case BFD_RELOC_HI16_S_PCREL:
7242     case BFD_RELOC_MICROMIPS_HI16_S:
7243     case BFD_RELOC_MIPS16_HI16_S:
7244       *result = ((operand + 0x8000) >> 16) & 0xffff;
7245       return TRUE;
7246
7247     case BFD_RELOC_HI16:
7248     case BFD_RELOC_MICROMIPS_HI16:
7249     case BFD_RELOC_MIPS16_HI16:
7250       *result = (operand >> 16) & 0xffff;
7251       return TRUE;
7252
7253     case BFD_RELOC_LO16:
7254     case BFD_RELOC_LO16_PCREL:
7255     case BFD_RELOC_MICROMIPS_LO16:
7256     case BFD_RELOC_MIPS16_LO16:
7257       *result = operand & 0xffff;
7258       return TRUE;
7259
7260     case BFD_RELOC_UNUSED:
7261       *result = operand;
7262       return TRUE;
7263
7264     default:
7265       return FALSE;
7266     }
7267 }
7268
7269 /* Output an instruction.  IP is the instruction information.
7270    ADDRESS_EXPR is an operand of the instruction to be used with
7271    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7272    a macro expansion.  */
7273
7274 static void
7275 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7276              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7277 {
7278   unsigned long prev_pinfo2, pinfo;
7279   bfd_boolean relaxed_branch = FALSE;
7280   enum append_method method;
7281   bfd_boolean relax32;
7282   int branch_disp;
7283
7284   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7285     fix_loongson2f (ip);
7286
7287   file_ase_mips16 |= mips_opts.mips16;
7288   file_ase_micromips |= mips_opts.micromips;
7289
7290   prev_pinfo2 = history[0].insn_mo->pinfo2;
7291   pinfo = ip->insn_mo->pinfo;
7292
7293   /* Don't raise alarm about `nods' frags as they'll fill in the right
7294      kind of nop in relaxation if required.  */
7295   if (mips_opts.micromips
7296       && !expansionp
7297       && !(history[0].frag
7298            && history[0].frag->fr_type == rs_machine_dependent
7299            && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7300            && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7301       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7302            && micromips_insn_length (ip->insn_mo) != 2)
7303           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7304               && micromips_insn_length (ip->insn_mo) != 4)))
7305     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7306              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7307
7308   if (address_expr == NULL)
7309     ip->complete_p = 1;
7310   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7311            && reloc_type[1] == BFD_RELOC_UNUSED
7312            && reloc_type[2] == BFD_RELOC_UNUSED
7313            && address_expr->X_op == O_constant)
7314     {
7315       switch (*reloc_type)
7316         {
7317         case BFD_RELOC_MIPS_JMP:
7318           {
7319             int shift;
7320
7321             /* Shift is 2, unusually, for microMIPS JALX.  */
7322             shift = (mips_opts.micromips
7323                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7324             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7325               as_bad (_("jump to misaligned address (0x%lx)"),
7326                       (unsigned long) address_expr->X_add_number);
7327             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7328                                 & 0x3ffffff);
7329             ip->complete_p = 1;
7330           }
7331           break;
7332
7333         case BFD_RELOC_MIPS16_JMP:
7334           if ((address_expr->X_add_number & 3) != 0)
7335             as_bad (_("jump to misaligned address (0x%lx)"),
7336                     (unsigned long) address_expr->X_add_number);
7337           ip->insn_opcode |=
7338             (((address_expr->X_add_number & 0x7c0000) << 3)
7339                | ((address_expr->X_add_number & 0xf800000) >> 7)
7340                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7341           ip->complete_p = 1;
7342           break;
7343
7344         case BFD_RELOC_16_PCREL_S2:
7345           {
7346             int shift;
7347
7348             shift = mips_opts.micromips ? 1 : 2;
7349             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7350               as_bad (_("branch to misaligned address (0x%lx)"),
7351                       (unsigned long) address_expr->X_add_number);
7352             if (!mips_relax_branch)
7353               {
7354                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7355                     & ~((1 << (shift + 16)) - 1))
7356                   as_bad (_("branch address range overflow (0x%lx)"),
7357                           (unsigned long) address_expr->X_add_number);
7358                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7359                                     & 0xffff);
7360               }
7361           }
7362           break;
7363
7364         case BFD_RELOC_MIPS_21_PCREL_S2:
7365           {
7366             int shift;
7367
7368             shift = 2;
7369             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7370               as_bad (_("branch to misaligned address (0x%lx)"),
7371                       (unsigned long) address_expr->X_add_number);
7372             if ((address_expr->X_add_number + (1 << (shift + 20)))
7373                 & ~((1 << (shift + 21)) - 1))
7374               as_bad (_("branch address range overflow (0x%lx)"),
7375                       (unsigned long) address_expr->X_add_number);
7376             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7377                                 & 0x1fffff);
7378           }
7379           break;
7380
7381         case BFD_RELOC_MIPS_26_PCREL_S2:
7382           {
7383             int shift;
7384
7385             shift = 2;
7386             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7387               as_bad (_("branch to misaligned address (0x%lx)"),
7388                       (unsigned long) address_expr->X_add_number);
7389             if ((address_expr->X_add_number + (1 << (shift + 25)))
7390                 & ~((1 << (shift + 26)) - 1))
7391               as_bad (_("branch address range overflow (0x%lx)"),
7392                       (unsigned long) address_expr->X_add_number);
7393             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7394                                 & 0x3ffffff);
7395           }
7396           break;
7397
7398         default:
7399           {
7400             offsetT value;
7401
7402             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7403                                  &value))
7404               {
7405                 ip->insn_opcode |= value & 0xffff;
7406                 ip->complete_p = 1;
7407               }
7408           }
7409           break;
7410         }
7411     }
7412
7413   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7414     {
7415       /* There are a lot of optimizations we could do that we don't.
7416          In particular, we do not, in general, reorder instructions.
7417          If you use gcc with optimization, it will reorder
7418          instructions and generally do much more optimization then we
7419          do here; repeating all that work in the assembler would only
7420          benefit hand written assembly code, and does not seem worth
7421          it.  */
7422       int nops = (mips_optimize == 0
7423                   ? nops_for_insn (0, history, NULL)
7424                   : nops_for_insn_or_target (0, history, ip));
7425       if (nops > 0)
7426         {
7427           fragS *old_frag;
7428           unsigned long old_frag_offset;
7429           int i;
7430
7431           old_frag = frag_now;
7432           old_frag_offset = frag_now_fix ();
7433
7434           for (i = 0; i < nops; i++)
7435             add_fixed_insn (NOP_INSN);
7436           insert_into_history (0, nops, NOP_INSN);
7437
7438           if (listing)
7439             {
7440               listing_prev_line ();
7441               /* We may be at the start of a variant frag.  In case we
7442                  are, make sure there is enough space for the frag
7443                  after the frags created by listing_prev_line.  The
7444                  argument to frag_grow here must be at least as large
7445                  as the argument to all other calls to frag_grow in
7446                  this file.  We don't have to worry about being in the
7447                  middle of a variant frag, because the variants insert
7448                  all needed nop instructions themselves.  */
7449               frag_grow (40);
7450             }
7451
7452           mips_move_text_labels ();
7453
7454 #ifndef NO_ECOFF_DEBUGGING
7455           if (ECOFF_DEBUGGING)
7456             ecoff_fix_loc (old_frag, old_frag_offset);
7457 #endif
7458         }
7459     }
7460   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7461     {
7462       int nops;
7463
7464       /* Work out how many nops in prev_nop_frag are needed by IP,
7465          ignoring hazards generated by the first prev_nop_frag_since
7466          instructions.  */
7467       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7468       gas_assert (nops <= prev_nop_frag_holds);
7469
7470       /* Enforce NOPS as a minimum.  */
7471       if (nops > prev_nop_frag_required)
7472         prev_nop_frag_required = nops;
7473
7474       if (prev_nop_frag_holds == prev_nop_frag_required)
7475         {
7476           /* Settle for the current number of nops.  Update the history
7477              accordingly (for the benefit of any future .set reorder code).  */
7478           prev_nop_frag = NULL;
7479           insert_into_history (prev_nop_frag_since,
7480                                prev_nop_frag_holds, NOP_INSN);
7481         }
7482       else
7483         {
7484           /* Allow this instruction to replace one of the nops that was
7485              tentatively added to prev_nop_frag.  */
7486           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7487           prev_nop_frag_holds--;
7488           prev_nop_frag_since++;
7489         }
7490     }
7491
7492   method = get_append_method (ip, address_expr, reloc_type);
7493   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7494
7495   dwarf2_emit_insn (0);
7496   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7497      so "move" the instruction address accordingly.
7498
7499      Also, it doesn't seem appropriate for the assembler to reorder .loc
7500      entries.  If this instruction is a branch that we are going to swap
7501      with the previous instruction, the two instructions should be
7502      treated as a unit, and the debug information for both instructions
7503      should refer to the start of the branch sequence.  Using the
7504      current position is certainly wrong when swapping a 32-bit branch
7505      and a 16-bit delay slot, since the current position would then be
7506      in the middle of a branch.  */
7507   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7508
7509   relax32 = (mips_relax_branch
7510              /* Don't try branch relaxation within .set nomacro, or within
7511                 .set noat if we use $at for PIC computations.  If it turns
7512                 out that the branch was out-of-range, we'll get an error.  */
7513              && !mips_opts.warn_about_macros
7514              && (mips_opts.at || mips_pic == NO_PIC)
7515              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7516                 as they have no complementing branches.  */
7517              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7518
7519   if (!HAVE_CODE_COMPRESSION
7520       && address_expr
7521       && relax32
7522       && *reloc_type == BFD_RELOC_16_PCREL_S2
7523       && delayed_branch_p (ip))
7524     {
7525       relaxed_branch = TRUE;
7526       add_relaxed_insn (ip, (relaxed_branch_length
7527                              (NULL, NULL,
7528                               uncond_branch_p (ip) ? -1
7529                               : branch_likely_p (ip) ? 1
7530                               : 0)), 4,
7531                         RELAX_BRANCH_ENCODE
7532                         (AT, mips_pic != NO_PIC,
7533                          uncond_branch_p (ip),
7534                          branch_likely_p (ip),
7535                          pinfo & INSN_WRITE_GPR_31,
7536                          0),
7537                         address_expr->X_add_symbol,
7538                         address_expr->X_add_number);
7539       *reloc_type = BFD_RELOC_UNUSED;
7540     }
7541   else if (mips_opts.micromips
7542            && address_expr
7543            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7544                || *reloc_type > BFD_RELOC_UNUSED)
7545            && (delayed_branch_p (ip) || compact_branch_p (ip))
7546            /* Don't try branch relaxation when users specify
7547               16-bit/32-bit instructions.  */
7548            && !forced_insn_length)
7549     {
7550       bfd_boolean relax16 = (method != APPEND_ADD_COMPACT
7551                              && *reloc_type > BFD_RELOC_UNUSED);
7552       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7553       int uncond = uncond_branch_p (ip) ? -1 : 0;
7554       int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7555       int nods = method == APPEND_ADD_WITH_NOP;
7556       int al = pinfo & INSN_WRITE_GPR_31;
7557       int length32 = nods ? 8 : 4;
7558
7559       gas_assert (address_expr != NULL);
7560       gas_assert (!mips_relax.sequence);
7561
7562       relaxed_branch = TRUE;
7563       if (nods)
7564         method = APPEND_ADD;
7565       if (relax32)
7566         length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7567       add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7568                         RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7569                                                 mips_pic != NO_PIC,
7570                                                 uncond, compact, al, nods,
7571                                                 relax32, 0, 0),
7572                         address_expr->X_add_symbol,
7573                         address_expr->X_add_number);
7574       *reloc_type = BFD_RELOC_UNUSED;
7575     }
7576   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7577     {
7578       bfd_boolean require_unextended;
7579       bfd_boolean require_extended;
7580       symbolS *symbol;
7581       offsetT offset;
7582
7583       if (forced_insn_length != 0)
7584         {
7585           require_unextended = forced_insn_length == 2;
7586           require_extended = forced_insn_length == 4;
7587         }
7588       else
7589         {
7590           require_unextended = (mips_opts.noautoextend
7591                                 && !mips_opcode_32bit_p (ip->insn_mo));
7592           require_extended = 0;
7593         }
7594
7595       /* We need to set up a variant frag.  */
7596       gas_assert (address_expr != NULL);
7597       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7598          symbol created by `make_expr_symbol' may not get a necessary
7599          external relocation produced.  */
7600       if (address_expr->X_op == O_symbol)
7601         {
7602           symbol = address_expr->X_add_symbol;
7603           offset = address_expr->X_add_number;
7604         }
7605       else
7606         {
7607           symbol = make_expr_symbol (address_expr);
7608           symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7609           offset = 0;
7610         }
7611       add_relaxed_insn (ip, 12, 0,
7612                         RELAX_MIPS16_ENCODE
7613                         (*reloc_type - BFD_RELOC_UNUSED,
7614                          mips_opts.ase & ASE_MIPS16E2,
7615                          mips_pic != NO_PIC,
7616                          HAVE_32BIT_SYMBOLS,
7617                          mips_opts.warn_about_macros,
7618                          require_unextended, require_extended,
7619                          delayed_branch_p (&history[0]),
7620                          history[0].mips16_absolute_jump_p),
7621                         symbol, offset);
7622     }
7623   else if (mips_opts.mips16 && insn_length (ip) == 2)
7624     {
7625       if (!delayed_branch_p (ip))
7626         /* Make sure there is enough room to swap this instruction with
7627            a following jump instruction.  */
7628         frag_grow (6);
7629       add_fixed_insn (ip);
7630     }
7631   else
7632     {
7633       if (mips_opts.mips16
7634           && mips_opts.noreorder
7635           && delayed_branch_p (&history[0]))
7636         as_warn (_("extended instruction in delay slot"));
7637
7638       if (mips_relax.sequence)
7639         {
7640           /* If we've reached the end of this frag, turn it into a variant
7641              frag and record the information for the instructions we've
7642              written so far.  */
7643           if (frag_room () < 4)
7644             relax_close_frag ();
7645           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7646         }
7647
7648       if (mips_relax.sequence != 2)
7649         {
7650           if (mips_macro_warning.first_insn_sizes[0] == 0)
7651             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7652           mips_macro_warning.sizes[0] += insn_length (ip);
7653           mips_macro_warning.insns[0]++;
7654         }
7655       if (mips_relax.sequence != 1)
7656         {
7657           if (mips_macro_warning.first_insn_sizes[1] == 0)
7658             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7659           mips_macro_warning.sizes[1] += insn_length (ip);
7660           mips_macro_warning.insns[1]++;
7661         }
7662
7663       if (mips_opts.mips16)
7664         {
7665           ip->fixed_p = 1;
7666           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7667         }
7668       add_fixed_insn (ip);
7669     }
7670
7671   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7672     {
7673       bfd_reloc_code_real_type final_type[3];
7674       reloc_howto_type *howto0;
7675       reloc_howto_type *howto;
7676       int i;
7677
7678       /* Perform any necessary conversion to microMIPS relocations
7679          and find out how many relocations there actually are.  */
7680       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7681         final_type[i] = micromips_map_reloc (reloc_type[i]);
7682
7683       /* In a compound relocation, it is the final (outermost)
7684          operator that determines the relocated field.  */
7685       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7686       if (!howto)
7687         abort ();
7688
7689       if (i > 1)
7690         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7691       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7692                                  bfd_get_reloc_size (howto),
7693                                  address_expr,
7694                                  howto0 && howto0->pc_relative,
7695                                  final_type[0]);
7696       /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7697       ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7698
7699       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7700       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7701         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7702
7703       /* These relocations can have an addend that won't fit in
7704          4 octets for 64bit assembly.  */
7705       if (GPR_SIZE == 64
7706           && ! howto->partial_inplace
7707           && (reloc_type[0] == BFD_RELOC_16
7708               || reloc_type[0] == BFD_RELOC_32
7709               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7710               || reloc_type[0] == BFD_RELOC_GPREL16
7711               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7712               || reloc_type[0] == BFD_RELOC_GPREL32
7713               || reloc_type[0] == BFD_RELOC_64
7714               || reloc_type[0] == BFD_RELOC_CTOR
7715               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7716               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7717               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7718               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7719               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7720               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7721               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7722               || hi16_reloc_p (reloc_type[0])
7723               || lo16_reloc_p (reloc_type[0])))
7724         ip->fixp[0]->fx_no_overflow = 1;
7725
7726       /* These relocations can have an addend that won't fit in 2 octets.  */
7727       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7728           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7729         ip->fixp[0]->fx_no_overflow = 1;
7730
7731       if (mips_relax.sequence)
7732         {
7733           if (mips_relax.first_fixup == 0)
7734             mips_relax.first_fixup = ip->fixp[0];
7735         }
7736       else if (reloc_needs_lo_p (*reloc_type))
7737         {
7738           struct mips_hi_fixup *hi_fixup;
7739
7740           /* Reuse the last entry if it already has a matching %lo.  */
7741           hi_fixup = mips_hi_fixup_list;
7742           if (hi_fixup == 0
7743               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7744             {
7745               hi_fixup = XNEW (struct mips_hi_fixup);
7746               hi_fixup->next = mips_hi_fixup_list;
7747               mips_hi_fixup_list = hi_fixup;
7748             }
7749           hi_fixup->fixp = ip->fixp[0];
7750           hi_fixup->seg = now_seg;
7751         }
7752
7753       /* Add fixups for the second and third relocations, if given.
7754          Note that the ABI allows the second relocation to be
7755          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7756          moment we only use RSS_UNDEF, but we could add support
7757          for the others if it ever becomes necessary.  */
7758       for (i = 1; i < 3; i++)
7759         if (reloc_type[i] != BFD_RELOC_UNUSED)
7760           {
7761             ip->fixp[i] = fix_new (ip->frag, ip->where,
7762                                    ip->fixp[0]->fx_size, NULL, 0,
7763                                    FALSE, final_type[i]);
7764
7765             /* Use fx_tcbit to mark compound relocs.  */
7766             ip->fixp[0]->fx_tcbit = 1;
7767             ip->fixp[i]->fx_tcbit = 1;
7768           }
7769     }
7770
7771   /* Update the register mask information.  */
7772   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7773   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7774
7775   switch (method)
7776     {
7777     case APPEND_ADD:
7778       insert_into_history (0, 1, ip);
7779       break;
7780
7781     case APPEND_ADD_WITH_NOP:
7782       {
7783         struct mips_cl_insn *nop;
7784
7785         insert_into_history (0, 1, ip);
7786         nop = get_delay_slot_nop (ip);
7787         add_fixed_insn (nop);
7788         insert_into_history (0, 1, nop);
7789         if (mips_relax.sequence)
7790           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7791       }
7792       break;
7793
7794     case APPEND_ADD_COMPACT:
7795       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7796       if (mips_opts.mips16)
7797         {
7798           ip->insn_opcode |= 0x0080;
7799           find_altered_mips16_opcode (ip);
7800         }
7801       /* Convert microMIPS instructions.  */
7802       else if (mips_opts.micromips)
7803         {
7804           /* jr16->jrc */
7805           if ((ip->insn_opcode & 0xffe0) == 0x4580)
7806             ip->insn_opcode |= 0x0020;
7807           /* b16->bc */
7808           else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
7809             ip->insn_opcode = 0x40e00000;
7810           /* beqz16->beqzc, bnez16->bnezc */
7811           else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
7812             {
7813               unsigned long regno;
7814
7815               regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
7816               regno &= MICROMIPSOP_MASK_MD;
7817               regno = micromips_to_32_reg_d_map[regno];
7818               ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
7819                                  | (regno << MICROMIPSOP_SH_RS)
7820                                  | 0x40a00000) ^ 0x00400000;
7821             }
7822           /* beqz->beqzc, bnez->bnezc */
7823           else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
7824             ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
7825                                | ((ip->insn_opcode >> 7) & 0x00400000)
7826                                | 0x40a00000) ^ 0x00400000;
7827           /* beq $0->beqzc, bne $0->bnezc */
7828           else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
7829             ip->insn_opcode = (((ip->insn_opcode >>
7830                                  (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
7831                                 & (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
7832                                | ((ip->insn_opcode >> 7) & 0x00400000)
7833                                | 0x40a00000) ^ 0x00400000;
7834           else
7835             abort ();
7836           find_altered_micromips_opcode (ip);
7837         }
7838       else
7839         abort ();
7840       install_insn (ip);
7841       insert_into_history (0, 1, ip);
7842       break;
7843
7844     case APPEND_SWAP:
7845       {
7846         struct mips_cl_insn delay = history[0];
7847
7848         if (relaxed_branch || delay.frag != ip->frag)
7849           {
7850             /* Add the delay slot instruction to the end of the
7851                current frag and shrink the fixed part of the
7852                original frag.  If the branch occupies the tail of
7853                the latter, move it backwards to cover the gap.  */
7854             delay.frag->fr_fix -= branch_disp;
7855             if (delay.frag == ip->frag)
7856               move_insn (ip, ip->frag, ip->where - branch_disp);
7857             add_fixed_insn (&delay);
7858           }
7859         else
7860           {
7861             /* If this is not a relaxed branch and we are in the
7862                same frag, then just swap the instructions.  */
7863             move_insn (ip, delay.frag, delay.where);
7864             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7865           }
7866         history[0] = *ip;
7867         delay.fixed_p = 1;
7868         insert_into_history (0, 1, &delay);
7869       }
7870       break;
7871     }
7872
7873   /* If we have just completed an unconditional branch, clear the history.  */
7874   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7875       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7876     {
7877       unsigned int i;
7878
7879       mips_no_prev_insn ();
7880
7881       for (i = 0; i < ARRAY_SIZE (history); i++)
7882         history[i].cleared_p = 1;
7883     }
7884
7885   /* We need to emit a label at the end of branch-likely macros.  */
7886   if (emit_branch_likely_macro)
7887     {
7888       emit_branch_likely_macro = FALSE;
7889       micromips_add_label ();
7890     }
7891
7892   /* We just output an insn, so the next one doesn't have a label.  */
7893   mips_clear_insn_labels ();
7894 }
7895
7896 /* Forget that there was any previous instruction or label.
7897    When BRANCH is true, the branch history is also flushed.  */
7898
7899 static void
7900 mips_no_prev_insn (void)
7901 {
7902   prev_nop_frag = NULL;
7903   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7904   mips_clear_insn_labels ();
7905 }
7906
7907 /* This function must be called before we emit something other than
7908    instructions.  It is like mips_no_prev_insn except that it inserts
7909    any NOPS that might be needed by previous instructions.  */
7910
7911 void
7912 mips_emit_delays (void)
7913 {
7914   if (! mips_opts.noreorder)
7915     {
7916       int nops = nops_for_insn (0, history, NULL);
7917       if (nops > 0)
7918         {
7919           while (nops-- > 0)
7920             add_fixed_insn (NOP_INSN);
7921           mips_move_text_labels ();
7922         }
7923     }
7924   mips_no_prev_insn ();
7925 }
7926
7927 /* Start a (possibly nested) noreorder block.  */
7928
7929 static void
7930 start_noreorder (void)
7931 {
7932   if (mips_opts.noreorder == 0)
7933     {
7934       unsigned int i;
7935       int nops;
7936
7937       /* None of the instructions before the .set noreorder can be moved.  */
7938       for (i = 0; i < ARRAY_SIZE (history); i++)
7939         history[i].fixed_p = 1;
7940
7941       /* Insert any nops that might be needed between the .set noreorder
7942          block and the previous instructions.  We will later remove any
7943          nops that turn out not to be needed.  */
7944       nops = nops_for_insn (0, history, NULL);
7945       if (nops > 0)
7946         {
7947           if (mips_optimize != 0)
7948             {
7949               /* Record the frag which holds the nop instructions, so
7950                  that we can remove them if we don't need them.  */
7951               frag_grow (nops * NOP_INSN_SIZE);
7952               prev_nop_frag = frag_now;
7953               prev_nop_frag_holds = nops;
7954               prev_nop_frag_required = 0;
7955               prev_nop_frag_since = 0;
7956             }
7957
7958           for (; nops > 0; --nops)
7959             add_fixed_insn (NOP_INSN);
7960
7961           /* Move on to a new frag, so that it is safe to simply
7962              decrease the size of prev_nop_frag.  */
7963           frag_wane (frag_now);
7964           frag_new (0);
7965           mips_move_text_labels ();
7966         }
7967       mips_mark_labels ();
7968       mips_clear_insn_labels ();
7969     }
7970   mips_opts.noreorder++;
7971   mips_any_noreorder = 1;
7972 }
7973
7974 /* End a nested noreorder block.  */
7975
7976 static void
7977 end_noreorder (void)
7978 {
7979   mips_opts.noreorder--;
7980   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7981     {
7982       /* Commit to inserting prev_nop_frag_required nops and go back to
7983          handling nop insertion the .set reorder way.  */
7984       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7985                                 * NOP_INSN_SIZE);
7986       insert_into_history (prev_nop_frag_since,
7987                            prev_nop_frag_required, NOP_INSN);
7988       prev_nop_frag = NULL;
7989     }
7990 }
7991
7992 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7993    higher bits unset.  */
7994
7995 static void
7996 normalize_constant_expr (expressionS *ex)
7997 {
7998   if (ex->X_op == O_constant
7999       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8000     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8001                         - 0x80000000);
8002 }
8003
8004 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
8005    all higher bits unset.  */
8006
8007 static void
8008 normalize_address_expr (expressionS *ex)
8009 {
8010   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
8011         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
8012       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8013     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8014                         - 0x80000000);
8015 }
8016
8017 /* Try to match TOKENS against OPCODE, storing the result in INSN.
8018    Return true if the match was successful.
8019
8020    OPCODE_EXTRA is a value that should be ORed into the opcode
8021    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
8022    there are more alternatives after OPCODE and SOFT_MATCH is
8023    as for mips_arg_info.  */
8024
8025 static bfd_boolean
8026 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8027             struct mips_operand_token *tokens, unsigned int opcode_extra,
8028             bfd_boolean lax_match, bfd_boolean complete_p)
8029 {
8030   const char *args;
8031   struct mips_arg_info arg;
8032   const struct mips_operand *operand;
8033   char c;
8034
8035   imm_expr.X_op = O_absent;
8036   offset_expr.X_op = O_absent;
8037   offset_reloc[0] = BFD_RELOC_UNUSED;
8038   offset_reloc[1] = BFD_RELOC_UNUSED;
8039   offset_reloc[2] = BFD_RELOC_UNUSED;
8040
8041   create_insn (insn, opcode);
8042   /* When no opcode suffix is specified, assume ".xyzw". */
8043   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
8044     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
8045   else
8046     insn->insn_opcode |= opcode_extra;
8047   memset (&arg, 0, sizeof (arg));
8048   arg.insn = insn;
8049   arg.token = tokens;
8050   arg.argnum = 1;
8051   arg.last_regno = ILLEGAL_REG;
8052   arg.dest_regno = ILLEGAL_REG;
8053   arg.lax_match = lax_match;
8054   for (args = opcode->args;; ++args)
8055     {
8056       if (arg.token->type == OT_END)
8057         {
8058           /* Handle unary instructions in which only one operand is given.
8059              The source is then the same as the destination.  */
8060           if (arg.opnum == 1 && *args == ',')
8061             {
8062               operand = (mips_opts.micromips
8063                          ? decode_micromips_operand (args + 1)
8064                          : decode_mips_operand (args + 1));
8065               if (operand && mips_optional_operand_p (operand))
8066                 {
8067                   arg.token = tokens;
8068                   arg.argnum = 1;
8069                   continue;
8070                 }
8071             }
8072
8073           /* Treat elided base registers as $0.  */
8074           if (strcmp (args, "(b)") == 0)
8075             args += 3;
8076
8077           if (args[0] == '+')
8078             switch (args[1])
8079               {
8080               case 'K':
8081               case 'N':
8082                 /* The register suffix is optional. */
8083                 args += 2;
8084                 break;
8085               }
8086
8087           /* Fail the match if there were too few operands.  */
8088           if (*args)
8089             return FALSE;
8090
8091           /* Successful match.  */
8092           if (!complete_p)
8093             return TRUE;
8094           clear_insn_error ();
8095           if (arg.dest_regno == arg.last_regno
8096               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
8097             {
8098               if (arg.opnum == 2)
8099                 set_insn_error
8100                   (0, _("source and destination must be different"));
8101               else if (arg.last_regno == 31)
8102                 set_insn_error
8103                   (0, _("a destination register must be supplied"));
8104             }
8105           else if (arg.last_regno == 31
8106                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
8107                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
8108             set_insn_error (0, _("the source register must not be $31"));
8109           check_completed_insn (&arg);
8110           return TRUE;
8111         }
8112
8113       /* Fail the match if the line has too many operands.   */
8114       if (*args == 0)
8115         return FALSE;
8116
8117       /* Handle characters that need to match exactly.  */
8118       if (*args == '(' || *args == ')' || *args == ',')
8119         {
8120           if (match_char (&arg, *args))
8121             continue;
8122           return FALSE;
8123         }
8124       if (*args == '#')
8125         {
8126           ++args;
8127           if (arg.token->type == OT_DOUBLE_CHAR
8128               && arg.token->u.ch == *args)
8129             {
8130               ++arg.token;
8131               continue;
8132             }
8133           return FALSE;
8134         }
8135
8136       /* Handle special macro operands.  Work out the properties of
8137          other operands.  */
8138       arg.opnum += 1;
8139       switch (*args)
8140         {
8141         case '-':
8142           switch (args[1])
8143             {
8144             case 'A':
8145               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
8146               break;
8147
8148             case 'B':
8149               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
8150               break;
8151             }
8152           break;
8153
8154         case '+':
8155           switch (args[1])
8156             {
8157             case 'i':
8158               *offset_reloc = BFD_RELOC_MIPS_JMP;
8159               break;
8160
8161             case '\'':
8162               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
8163               break;
8164
8165             case '\"':
8166               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
8167               break;
8168             }
8169           break;
8170
8171         case 'I':
8172           if (!match_const_int (&arg, &imm_expr.X_add_number))
8173             return FALSE;
8174           imm_expr.X_op = O_constant;
8175           if (GPR_SIZE == 32)
8176             normalize_constant_expr (&imm_expr);
8177           continue;
8178
8179         case 'A':
8180           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8181             {
8182               /* Assume that the offset has been elided and that what
8183                  we saw was a base register.  The match will fail later
8184                  if that assumption turns out to be wrong.  */
8185               offset_expr.X_op = O_constant;
8186               offset_expr.X_add_number = 0;
8187             }
8188           else
8189             {
8190               if (!match_expression (&arg, &offset_expr, offset_reloc))
8191                 return FALSE;
8192               normalize_address_expr (&offset_expr);
8193             }
8194           continue;
8195
8196         case 'F':
8197           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8198                                      8, TRUE))
8199             return FALSE;
8200           continue;
8201
8202         case 'L':
8203           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8204                                      8, FALSE))
8205             return FALSE;
8206           continue;
8207
8208         case 'f':
8209           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8210                                      4, TRUE))
8211             return FALSE;
8212           continue;
8213
8214         case 'l':
8215           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8216                                      4, FALSE))
8217             return FALSE;
8218           continue;
8219
8220         case 'p':
8221           *offset_reloc = BFD_RELOC_16_PCREL_S2;
8222           break;
8223
8224         case 'a':
8225           *offset_reloc = BFD_RELOC_MIPS_JMP;
8226           break;
8227
8228         case 'm':
8229           gas_assert (mips_opts.micromips);
8230           c = args[1];
8231           switch (c)
8232             {
8233             case 'D':
8234             case 'E':
8235               if (!forced_insn_length)
8236                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
8237               else if (c == 'D')
8238                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8239               else
8240                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8241               break;
8242             }
8243           break;
8244         }
8245
8246       operand = (mips_opts.micromips
8247                  ? decode_micromips_operand (args)
8248                  : decode_mips_operand (args));
8249       if (!operand)
8250         abort ();
8251
8252       /* Skip prefixes.  */
8253       if (*args == '+' || *args == 'm' || *args == '-')
8254         args++;
8255
8256       if (mips_optional_operand_p (operand)
8257           && args[1] == ','
8258           && (arg.token[0].type != OT_REG
8259               || arg.token[1].type == OT_END))
8260         {
8261           /* Assume that the register has been elided and is the
8262              same as the first operand.  */
8263           arg.token = tokens;
8264           arg.argnum = 1;
8265         }
8266
8267       if (!match_operand (&arg, operand))
8268         return FALSE;
8269     }
8270 }
8271
8272 /* Like match_insn, but for MIPS16.  */
8273
8274 static bfd_boolean
8275 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8276                    struct mips_operand_token *tokens)
8277 {
8278   const char *args;
8279   const struct mips_operand *operand;
8280   const struct mips_operand *ext_operand;
8281   bfd_boolean pcrel = FALSE;
8282   int required_insn_length;
8283   struct mips_arg_info arg;
8284   int relax_char;
8285
8286   if (forced_insn_length)
8287     required_insn_length = forced_insn_length;
8288   else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8289     required_insn_length = 2;
8290   else
8291     required_insn_length = 0;
8292
8293   create_insn (insn, opcode);
8294   imm_expr.X_op = O_absent;
8295   offset_expr.X_op = O_absent;
8296   offset_reloc[0] = BFD_RELOC_UNUSED;
8297   offset_reloc[1] = BFD_RELOC_UNUSED;
8298   offset_reloc[2] = BFD_RELOC_UNUSED;
8299   relax_char = 0;
8300
8301   memset (&arg, 0, sizeof (arg));
8302   arg.insn = insn;
8303   arg.token = tokens;
8304   arg.argnum = 1;
8305   arg.last_regno = ILLEGAL_REG;
8306   arg.dest_regno = ILLEGAL_REG;
8307   relax_char = 0;
8308   for (args = opcode->args;; ++args)
8309     {
8310       int c;
8311
8312       if (arg.token->type == OT_END)
8313         {
8314           offsetT value;
8315
8316           /* Handle unary instructions in which only one operand is given.
8317              The source is then the same as the destination.  */
8318           if (arg.opnum == 1 && *args == ',')
8319             {
8320               operand = decode_mips16_operand (args[1], FALSE);
8321               if (operand && mips_optional_operand_p (operand))
8322                 {
8323                   arg.token = tokens;
8324                   arg.argnum = 1;
8325                   continue;
8326                 }
8327             }
8328
8329           /* Fail the match if there were too few operands.  */
8330           if (*args)
8331             return FALSE;
8332
8333           /* Successful match.  Stuff the immediate value in now, if
8334              we can.  */
8335           clear_insn_error ();
8336           if (opcode->pinfo == INSN_MACRO)
8337             {
8338               gas_assert (relax_char == 0 || relax_char == 'p');
8339               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8340             }
8341           else if (relax_char
8342                    && offset_expr.X_op == O_constant
8343                    && !pcrel
8344                    && calculate_reloc (*offset_reloc,
8345                                        offset_expr.X_add_number,
8346                                        &value))
8347             {
8348               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8349                             required_insn_length, &insn->insn_opcode);
8350               offset_expr.X_op = O_absent;
8351               *offset_reloc = BFD_RELOC_UNUSED;
8352             }
8353           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8354             {
8355               if (required_insn_length == 2)
8356                 set_insn_error (0, _("invalid unextended operand value"));
8357               else if (!mips_opcode_32bit_p (opcode))
8358                 {
8359                   forced_insn_length = 4;
8360                   insn->insn_opcode |= MIPS16_EXTEND;
8361                 }
8362             }
8363           else if (relax_char)
8364             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8365
8366           check_completed_insn (&arg);
8367           return TRUE;
8368         }
8369
8370       /* Fail the match if the line has too many operands.   */
8371       if (*args == 0)
8372         return FALSE;
8373
8374       /* Handle characters that need to match exactly.  */
8375       if (*args == '(' || *args == ')' || *args == ',')
8376         {
8377           if (match_char (&arg, *args))
8378             continue;
8379           return FALSE;
8380         }
8381
8382       arg.opnum += 1;
8383       c = *args;
8384       switch (c)
8385         {
8386         case 'p':
8387         case 'q':
8388         case 'A':
8389         case 'B':
8390         case 'E':
8391         case 'V':
8392         case 'u':
8393           relax_char = c;
8394           break;
8395
8396         case 'I':
8397           if (!match_const_int (&arg, &imm_expr.X_add_number))
8398             return FALSE;
8399           imm_expr.X_op = O_constant;
8400           if (GPR_SIZE == 32)
8401             normalize_constant_expr (&imm_expr);
8402           continue;
8403
8404         case 'a':
8405         case 'i':
8406           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8407           break;
8408         }
8409
8410       operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8411       if (!operand)
8412         abort ();
8413
8414       if (operand->type == OP_PCREL)
8415         pcrel = TRUE;
8416       else
8417         {
8418           ext_operand = decode_mips16_operand (c, TRUE);
8419           if (operand != ext_operand)
8420             {
8421               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8422                 {
8423                   offset_expr.X_op = O_constant;
8424                   offset_expr.X_add_number = 0;
8425                   relax_char = c;
8426                   continue;
8427                 }
8428
8429               if (!match_expression (&arg, &offset_expr, offset_reloc))
8430                 return FALSE;
8431
8432               /* '8' is used for SLTI(U) and has traditionally not
8433                  been allowed to take relocation operators.  */
8434               if (offset_reloc[0] != BFD_RELOC_UNUSED
8435                   && (ext_operand->size != 16 || c == '8'))
8436                 {
8437                   match_not_constant (&arg);
8438                   return FALSE;
8439                 }
8440
8441               if (offset_expr.X_op == O_big)
8442                 {
8443                   match_out_of_range (&arg);
8444                   return FALSE;
8445                 }
8446
8447               relax_char = c;
8448               continue;
8449             }
8450         }
8451
8452       if (mips_optional_operand_p (operand)
8453           && args[1] == ','
8454           && (arg.token[0].type != OT_REG
8455               || arg.token[1].type == OT_END))
8456         {
8457           /* Assume that the register has been elided and is the
8458              same as the first operand.  */
8459           arg.token = tokens;
8460           arg.argnum = 1;
8461         }
8462
8463       if (!match_operand (&arg, operand))
8464         return FALSE;
8465     }
8466 }
8467
8468 /* Record that the current instruction is invalid for the current ISA.  */
8469
8470 static void
8471 match_invalid_for_isa (void)
8472 {
8473   set_insn_error_ss
8474     (0, _("opcode not supported on this processor: %s (%s)"),
8475      mips_cpu_info_from_arch (mips_opts.arch)->name,
8476      mips_cpu_info_from_isa (mips_opts.isa)->name);
8477 }
8478
8479 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8480    Return true if a definite match or failure was found, storing any match
8481    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8482    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8483    tried and failed to match under normal conditions and now want to try a
8484    more relaxed match.  */
8485
8486 static bfd_boolean
8487 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8488              const struct mips_opcode *past, struct mips_operand_token *tokens,
8489              int opcode_extra, bfd_boolean lax_match)
8490 {
8491   const struct mips_opcode *opcode;
8492   const struct mips_opcode *invalid_delay_slot;
8493   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8494
8495   /* Search for a match, ignoring alternatives that don't satisfy the
8496      current ISA or forced_length.  */
8497   invalid_delay_slot = 0;
8498   seen_valid_for_isa = FALSE;
8499   seen_valid_for_size = FALSE;
8500   opcode = first;
8501   do
8502     {
8503       gas_assert (strcmp (opcode->name, first->name) == 0);
8504       if (is_opcode_valid (opcode))
8505         {
8506           seen_valid_for_isa = TRUE;
8507           if (is_size_valid (opcode))
8508             {
8509               bfd_boolean delay_slot_ok;
8510
8511               seen_valid_for_size = TRUE;
8512               delay_slot_ok = is_delay_slot_valid (opcode);
8513               if (match_insn (insn, opcode, tokens, opcode_extra,
8514                               lax_match, delay_slot_ok))
8515                 {
8516                   if (!delay_slot_ok)
8517                     {
8518                       if (!invalid_delay_slot)
8519                         invalid_delay_slot = opcode;
8520                     }
8521                   else
8522                     return TRUE;
8523                 }
8524             }
8525         }
8526       ++opcode;
8527     }
8528   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8529
8530   /* If the only matches we found had the wrong length for the delay slot,
8531      pick the first such match.  We'll issue an appropriate warning later.  */
8532   if (invalid_delay_slot)
8533     {
8534       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8535                       lax_match, TRUE))
8536         return TRUE;
8537       abort ();
8538     }
8539
8540   /* Handle the case where we didn't try to match an instruction because
8541      all the alternatives were incompatible with the current ISA.  */
8542   if (!seen_valid_for_isa)
8543     {
8544       match_invalid_for_isa ();
8545       return TRUE;
8546     }
8547
8548   /* Handle the case where we didn't try to match an instruction because
8549      all the alternatives were of the wrong size.  */
8550   if (!seen_valid_for_size)
8551     {
8552       if (mips_opts.insn32)
8553         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8554       else
8555         set_insn_error_i
8556           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8557            8 * forced_insn_length);
8558       return TRUE;
8559     }
8560
8561   return FALSE;
8562 }
8563
8564 /* Like match_insns, but for MIPS16.  */
8565
8566 static bfd_boolean
8567 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8568                     struct mips_operand_token *tokens)
8569 {
8570   const struct mips_opcode *opcode;
8571   bfd_boolean seen_valid_for_isa;
8572   bfd_boolean seen_valid_for_size;
8573
8574   /* Search for a match, ignoring alternatives that don't satisfy the
8575      current ISA.  There are no separate entries for extended forms so
8576      we deal with forced_length later.  */
8577   seen_valid_for_isa = FALSE;
8578   seen_valid_for_size = FALSE;
8579   opcode = first;
8580   do
8581     {
8582       gas_assert (strcmp (opcode->name, first->name) == 0);
8583       if (is_opcode_valid_16 (opcode))
8584         {
8585           seen_valid_for_isa = TRUE;
8586           if (is_size_valid_16 (opcode))
8587             {
8588               seen_valid_for_size = TRUE;
8589               if (match_mips16_insn (insn, opcode, tokens))
8590                 return TRUE;
8591             }
8592         }
8593       ++opcode;
8594     }
8595   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8596          && strcmp (opcode->name, first->name) == 0);
8597
8598   /* Handle the case where we didn't try to match an instruction because
8599      all the alternatives were incompatible with the current ISA.  */
8600   if (!seen_valid_for_isa)
8601     {
8602       match_invalid_for_isa ();
8603       return TRUE;
8604     }
8605
8606   /* Handle the case where we didn't try to match an instruction because
8607      all the alternatives were of the wrong size.  */
8608   if (!seen_valid_for_size)
8609     {
8610       if (forced_insn_length == 2)
8611         set_insn_error
8612           (0, _("unrecognized unextended version of MIPS16 opcode"));
8613       else
8614         set_insn_error
8615           (0, _("unrecognized extended version of MIPS16 opcode"));
8616       return TRUE;
8617     }
8618
8619   return FALSE;
8620 }
8621
8622 /* Set up global variables for the start of a new macro.  */
8623
8624 static void
8625 macro_start (void)
8626 {
8627   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8628   memset (&mips_macro_warning.first_insn_sizes, 0,
8629           sizeof (mips_macro_warning.first_insn_sizes));
8630   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8631   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8632                                      && delayed_branch_p (&history[0]));
8633   if (history[0].frag
8634       && history[0].frag->fr_type == rs_machine_dependent
8635       && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8636       && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8637     mips_macro_warning.delay_slot_length = 0;
8638   else
8639     switch (history[0].insn_mo->pinfo2
8640             & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8641       {
8642       case INSN2_BRANCH_DELAY_32BIT:
8643         mips_macro_warning.delay_slot_length = 4;
8644         break;
8645       case INSN2_BRANCH_DELAY_16BIT:
8646         mips_macro_warning.delay_slot_length = 2;
8647         break;
8648       default:
8649         mips_macro_warning.delay_slot_length = 0;
8650         break;
8651       }
8652   mips_macro_warning.first_frag = NULL;
8653 }
8654
8655 /* Given that a macro is longer than one instruction or of the wrong size,
8656    return the appropriate warning for it.  Return null if no warning is
8657    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8658    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8659    and RELAX_NOMACRO.  */
8660
8661 static const char *
8662 macro_warning (relax_substateT subtype)
8663 {
8664   if (subtype & RELAX_DELAY_SLOT)
8665     return _("macro instruction expanded into multiple instructions"
8666              " in a branch delay slot");
8667   else if (subtype & RELAX_NOMACRO)
8668     return _("macro instruction expanded into multiple instructions");
8669   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8670                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8671     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8672             ? _("macro instruction expanded into a wrong size instruction"
8673                 " in a 16-bit branch delay slot")
8674             : _("macro instruction expanded into a wrong size instruction"
8675                 " in a 32-bit branch delay slot"));
8676   else
8677     return 0;
8678 }
8679
8680 /* Finish up a macro.  Emit warnings as appropriate.  */
8681
8682 static void
8683 macro_end (void)
8684 {
8685   /* Relaxation warning flags.  */
8686   relax_substateT subtype = 0;
8687
8688   /* Check delay slot size requirements.  */
8689   if (mips_macro_warning.delay_slot_length == 2)
8690     subtype |= RELAX_DELAY_SLOT_16BIT;
8691   if (mips_macro_warning.delay_slot_length != 0)
8692     {
8693       if (mips_macro_warning.delay_slot_length
8694           != mips_macro_warning.first_insn_sizes[0])
8695         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8696       if (mips_macro_warning.delay_slot_length
8697           != mips_macro_warning.first_insn_sizes[1])
8698         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8699     }
8700
8701   /* Check instruction count requirements.  */
8702   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8703     {
8704       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8705         subtype |= RELAX_SECOND_LONGER;
8706       if (mips_opts.warn_about_macros)
8707         subtype |= RELAX_NOMACRO;
8708       if (mips_macro_warning.delay_slot_p)
8709         subtype |= RELAX_DELAY_SLOT;
8710     }
8711
8712   /* If both alternatives fail to fill a delay slot correctly,
8713      emit the warning now.  */
8714   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8715       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8716     {
8717       relax_substateT s;
8718       const char *msg;
8719
8720       s = subtype & (RELAX_DELAY_SLOT_16BIT
8721                      | RELAX_DELAY_SLOT_SIZE_FIRST
8722                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8723       msg = macro_warning (s);
8724       if (msg != NULL)
8725         as_warn ("%s", msg);
8726       subtype &= ~s;
8727     }
8728
8729   /* If both implementations are longer than 1 instruction, then emit the
8730      warning now.  */
8731   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8732     {
8733       relax_substateT s;
8734       const char *msg;
8735
8736       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8737       msg = macro_warning (s);
8738       if (msg != NULL)
8739         as_warn ("%s", msg);
8740       subtype &= ~s;
8741     }
8742
8743   /* If any flags still set, then one implementation might need a warning
8744      and the other either will need one of a different kind or none at all.
8745      Pass any remaining flags over to relaxation.  */
8746   if (mips_macro_warning.first_frag != NULL)
8747     mips_macro_warning.first_frag->fr_subtype |= subtype;
8748 }
8749
8750 /* Instruction operand formats used in macros that vary between
8751    standard MIPS and microMIPS code.  */
8752
8753 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8754 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8755 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8756 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8757 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8758 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8759 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8760 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8761
8762 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8763 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8764                                              : cop12_fmt[mips_opts.micromips])
8765 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8766 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8767 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8768 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8769                                              : mem12_fmt[mips_opts.micromips])
8770 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8771 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8772 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8773
8774 /* Read a macro's relocation codes from *ARGS and store them in *R.
8775    The first argument in *ARGS will be either the code for a single
8776    relocation or -1 followed by the three codes that make up a
8777    composite relocation.  */
8778
8779 static void
8780 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8781 {
8782   int i, next;
8783
8784   next = va_arg (*args, int);
8785   if (next >= 0)
8786     r[0] = (bfd_reloc_code_real_type) next;
8787   else
8788     {
8789       for (i = 0; i < 3; i++)
8790         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8791       /* This function is only used for 16-bit relocation fields.
8792          To make the macro code simpler, treat an unrelocated value
8793          in the same way as BFD_RELOC_LO16.  */
8794       if (r[0] == BFD_RELOC_UNUSED)
8795         r[0] = BFD_RELOC_LO16;
8796     }
8797 }
8798
8799 /* Build an instruction created by a macro expansion.  This is passed
8800    a pointer to the count of instructions created so far, an
8801    expression, the name of the instruction to build, an operand format
8802    string, and corresponding arguments.  */
8803
8804 static void
8805 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8806 {
8807   const struct mips_opcode *mo = NULL;
8808   bfd_reloc_code_real_type r[3];
8809   const struct mips_opcode *amo;
8810   const struct mips_operand *operand;
8811   struct hash_control *hash;
8812   struct mips_cl_insn insn;
8813   va_list args;
8814   unsigned int uval;
8815
8816   va_start (args, fmt);
8817
8818   if (mips_opts.mips16)
8819     {
8820       mips16_macro_build (ep, name, fmt, &args);
8821       va_end (args);
8822       return;
8823     }
8824
8825   r[0] = BFD_RELOC_UNUSED;
8826   r[1] = BFD_RELOC_UNUSED;
8827   r[2] = BFD_RELOC_UNUSED;
8828   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8829   amo = (struct mips_opcode *) hash_find (hash, name);
8830   gas_assert (amo);
8831   gas_assert (strcmp (name, amo->name) == 0);
8832
8833   do
8834     {
8835       /* Search until we get a match for NAME.  It is assumed here that
8836          macros will never generate MDMX, MIPS-3D, or MT instructions.
8837          We try to match an instruction that fulfills the branch delay
8838          slot instruction length requirement (if any) of the previous
8839          instruction.  While doing this we record the first instruction
8840          seen that matches all the other conditions and use it anyway
8841          if the requirement cannot be met; we will issue an appropriate
8842          warning later on.  */
8843       if (strcmp (fmt, amo->args) == 0
8844           && amo->pinfo != INSN_MACRO
8845           && is_opcode_valid (amo)
8846           && is_size_valid (amo))
8847         {
8848           if (is_delay_slot_valid (amo))
8849             {
8850               mo = amo;
8851               break;
8852             }
8853           else if (!mo)
8854             mo = amo;
8855         }
8856
8857       ++amo;
8858       gas_assert (amo->name);
8859     }
8860   while (strcmp (name, amo->name) == 0);
8861
8862   gas_assert (mo);
8863   create_insn (&insn, mo);
8864   for (; *fmt; ++fmt)
8865     {
8866       switch (*fmt)
8867         {
8868         case ',':
8869         case '(':
8870         case ')':
8871         case 'z':
8872           break;
8873
8874         case 'i':
8875         case 'j':
8876           macro_read_relocs (&args, r);
8877           gas_assert (*r == BFD_RELOC_GPREL16
8878                       || *r == BFD_RELOC_MIPS_HIGHER
8879                       || *r == BFD_RELOC_HI16_S
8880                       || *r == BFD_RELOC_LO16
8881                       || *r == BFD_RELOC_MIPS_GOT_OFST
8882                       || (mips_opts.micromips
8883                           && (*r == BFD_RELOC_16
8884                               || *r == BFD_RELOC_MIPS_GOT16
8885                               || *r == BFD_RELOC_MIPS_CALL16
8886                               || *r == BFD_RELOC_MIPS_GOT_HI16
8887                               || *r == BFD_RELOC_MIPS_GOT_LO16
8888                               || *r == BFD_RELOC_MIPS_CALL_HI16
8889                               || *r == BFD_RELOC_MIPS_CALL_LO16
8890                               || *r == BFD_RELOC_MIPS_SUB
8891                               || *r == BFD_RELOC_MIPS_GOT_PAGE
8892                               || *r == BFD_RELOC_MIPS_HIGHEST
8893                               || *r == BFD_RELOC_MIPS_GOT_DISP
8894                               || *r == BFD_RELOC_MIPS_TLS_GD
8895                               || *r == BFD_RELOC_MIPS_TLS_LDM
8896                               || *r == BFD_RELOC_MIPS_TLS_DTPREL_HI16
8897                               || *r == BFD_RELOC_MIPS_TLS_DTPREL_LO16
8898                               || *r == BFD_RELOC_MIPS_TLS_GOTTPREL
8899                               || *r == BFD_RELOC_MIPS_TLS_TPREL_HI16
8900                               || *r == BFD_RELOC_MIPS_TLS_TPREL_LO16)));
8901           break;
8902
8903         case 'o':
8904           macro_read_relocs (&args, r);
8905           break;
8906
8907         case 'u':
8908           macro_read_relocs (&args, r);
8909           gas_assert (ep != NULL
8910                       && (ep->X_op == O_constant
8911                           || (ep->X_op == O_symbol
8912                               && (*r == BFD_RELOC_MIPS_HIGHEST
8913                                   || *r == BFD_RELOC_HI16_S
8914                                   || *r == BFD_RELOC_HI16
8915                                   || *r == BFD_RELOC_GPREL16
8916                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8917                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8918           break;
8919
8920         case 'p':
8921           gas_assert (ep != NULL);
8922
8923           /*
8924            * This allows macro() to pass an immediate expression for
8925            * creating short branches without creating a symbol.
8926            *
8927            * We don't allow branch relaxation for these branches, as
8928            * they should only appear in ".set nomacro" anyway.
8929            */
8930           if (ep->X_op == O_constant)
8931             {
8932               /* For microMIPS we always use relocations for branches.
8933                  So we should not resolve immediate values.  */
8934               gas_assert (!mips_opts.micromips);
8935
8936               if ((ep->X_add_number & 3) != 0)
8937                 as_bad (_("branch to misaligned address (0x%lx)"),
8938                         (unsigned long) ep->X_add_number);
8939               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8940                 as_bad (_("branch address range overflow (0x%lx)"),
8941                         (unsigned long) ep->X_add_number);
8942               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8943               ep = NULL;
8944             }
8945           else
8946             *r = BFD_RELOC_16_PCREL_S2;
8947           break;
8948
8949         case 'a':
8950           gas_assert (ep != NULL);
8951           *r = BFD_RELOC_MIPS_JMP;
8952           break;
8953
8954         default:
8955           operand = (mips_opts.micromips
8956                      ? decode_micromips_operand (fmt)
8957                      : decode_mips_operand (fmt));
8958           if (!operand)
8959             abort ();
8960
8961           uval = va_arg (args, int);
8962           if (operand->type == OP_CLO_CLZ_DEST)
8963             uval |= (uval << 5);
8964           insn_insert_operand (&insn, operand, uval);
8965
8966           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8967             ++fmt;
8968           break;
8969         }
8970     }
8971   va_end (args);
8972   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8973
8974   append_insn (&insn, ep, r, TRUE);
8975 }
8976
8977 static void
8978 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8979                     va_list *args)
8980 {
8981   struct mips_opcode *mo;
8982   struct mips_cl_insn insn;
8983   const struct mips_operand *operand;
8984   bfd_reloc_code_real_type r[3]
8985     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8986
8987   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8988   gas_assert (mo);
8989   gas_assert (strcmp (name, mo->name) == 0);
8990
8991   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8992     {
8993       ++mo;
8994       gas_assert (mo->name);
8995       gas_assert (strcmp (name, mo->name) == 0);
8996     }
8997
8998   create_insn (&insn, mo);
8999   for (; *fmt; ++fmt)
9000     {
9001       int c;
9002
9003       c = *fmt;
9004       switch (c)
9005         {
9006         case ',':
9007         case '(':
9008         case ')':
9009           break;
9010
9011         case '.':
9012         case 'S':
9013         case 'P':
9014         case 'R':
9015           break;
9016
9017         case '<':
9018         case '5':
9019         case 'F':
9020         case 'H':
9021         case 'W':
9022         case 'D':
9023         case 'j':
9024         case '8':
9025         case 'V':
9026         case 'C':
9027         case 'U':
9028         case 'k':
9029         case 'K':
9030         case 'p':
9031         case 'q':
9032           {
9033             offsetT value;
9034
9035             gas_assert (ep != NULL);
9036
9037             if (ep->X_op != O_constant)
9038               *r = (int) BFD_RELOC_UNUSED + c;
9039             else if (calculate_reloc (*r, ep->X_add_number, &value))
9040               {
9041                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
9042                 ep = NULL;
9043                 *r = BFD_RELOC_UNUSED;
9044               }
9045           }
9046           break;
9047
9048         default:
9049           operand = decode_mips16_operand (c, FALSE);
9050           if (!operand)
9051             abort ();
9052
9053           insn_insert_operand (&insn, operand, va_arg (*args, int));
9054           break;
9055         }
9056     }
9057
9058   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
9059
9060   append_insn (&insn, ep, r, TRUE);
9061 }
9062
9063 /*
9064  * Generate a "jalr" instruction with a relocation hint to the called
9065  * function.  This occurs in NewABI PIC code.
9066  */
9067 static void
9068 macro_build_jalr (expressionS *ep, int cprestore)
9069 {
9070   static const bfd_reloc_code_real_type jalr_relocs[2]
9071     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
9072   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
9073   const char *jalr;
9074   char *f = NULL;
9075
9076   if (MIPS_JALR_HINT_P (ep))
9077     {
9078       frag_grow (8);
9079       f = frag_more (0);
9080     }
9081   if (mips_opts.micromips)
9082     {
9083       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
9084               ? "jalr" : "jalrs");
9085       if (MIPS_JALR_HINT_P (ep)
9086           || mips_opts.insn32
9087           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9088         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
9089       else
9090         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
9091     }
9092   else
9093     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
9094   if (MIPS_JALR_HINT_P (ep))
9095     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
9096 }
9097
9098 /*
9099  * Generate a "lui" instruction.
9100  */
9101 static void
9102 macro_build_lui (expressionS *ep, int regnum)
9103 {
9104   gas_assert (! mips_opts.mips16);
9105
9106   if (ep->X_op != O_constant)
9107     {
9108       gas_assert (ep->X_op == O_symbol);
9109       /* _gp_disp is a special case, used from s_cpload.
9110          __gnu_local_gp is used if mips_no_shared.  */
9111       gas_assert (mips_pic == NO_PIC
9112               || (! HAVE_NEWABI
9113                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
9114               || (! mips_in_shared
9115                   && strcmp (S_GET_NAME (ep->X_add_symbol),
9116                              "__gnu_local_gp") == 0));
9117     }
9118
9119   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
9120 }
9121
9122 /* Generate a sequence of instructions to do a load or store from a constant
9123    offset off of a base register (breg) into/from a target register (treg),
9124    using AT if necessary.  */
9125 static void
9126 macro_build_ldst_constoffset (expressionS *ep, const char *op,
9127                               int treg, int breg, int dbl)
9128 {
9129   gas_assert (ep->X_op == O_constant);
9130
9131   /* Sign-extending 32-bit constants makes their handling easier.  */
9132   if (!dbl)
9133     normalize_constant_expr (ep);
9134
9135   /* Right now, this routine can only handle signed 32-bit constants.  */
9136   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
9137     as_warn (_("operand overflow"));
9138
9139   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
9140     {
9141       /* Signed 16-bit offset will fit in the op.  Easy!  */
9142       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
9143     }
9144   else
9145     {
9146       /* 32-bit offset, need multiple instructions and AT, like:
9147            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
9148            addu     $tempreg,$tempreg,$breg
9149            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
9150          to handle the complete offset.  */
9151       macro_build_lui (ep, AT);
9152       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
9153       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
9154
9155       if (!mips_opts.at)
9156         as_bad (_("macro used $at after \".set noat\""));
9157     }
9158 }
9159
9160 /*                      set_at()
9161  * Generates code to set the $at register to true (one)
9162  * if reg is less than the immediate expression.
9163  */
9164 static void
9165 set_at (int reg, int unsignedp)
9166 {
9167   if (imm_expr.X_add_number >= -0x8000
9168       && imm_expr.X_add_number < 0x8000)
9169     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
9170                  AT, reg, BFD_RELOC_LO16);
9171   else
9172     {
9173       load_register (AT, &imm_expr, GPR_SIZE == 64);
9174       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
9175     }
9176 }
9177
9178 /* Count the leading zeroes by performing a binary chop. This is a
9179    bulky bit of source, but performance is a LOT better for the
9180    majority of values than a simple loop to count the bits:
9181        for (lcnt = 0; (lcnt < 32); lcnt++)
9182          if ((v) & (1 << (31 - lcnt)))
9183            break;
9184   However it is not code size friendly, and the gain will drop a bit
9185   on certain cached systems.
9186 */
9187 #define COUNT_TOP_ZEROES(v)             \
9188   (((v) & ~0xffff) == 0                 \
9189    ? ((v) & ~0xff) == 0                 \
9190      ? ((v) & ~0xf) == 0                \
9191        ? ((v) & ~0x3) == 0              \
9192          ? ((v) & ~0x1) == 0            \
9193            ? !(v)                       \
9194              ? 32                       \
9195              : 31                       \
9196            : 30                         \
9197          : ((v) & ~0x7) == 0            \
9198            ? 29                         \
9199            : 28                         \
9200        : ((v) & ~0x3f) == 0             \
9201          ? ((v) & ~0x1f) == 0           \
9202            ? 27                         \
9203            : 26                         \
9204          : ((v) & ~0x7f) == 0           \
9205            ? 25                         \
9206            : 24                         \
9207      : ((v) & ~0xfff) == 0              \
9208        ? ((v) & ~0x3ff) == 0            \
9209          ? ((v) & ~0x1ff) == 0          \
9210            ? 23                         \
9211            : 22                         \
9212          : ((v) & ~0x7ff) == 0          \
9213            ? 21                         \
9214            : 20                         \
9215        : ((v) & ~0x3fff) == 0           \
9216          ? ((v) & ~0x1fff) == 0         \
9217            ? 19                         \
9218            : 18                         \
9219          : ((v) & ~0x7fff) == 0         \
9220            ? 17                         \
9221            : 16                         \
9222    : ((v) & ~0xffffff) == 0             \
9223      ? ((v) & ~0xfffff) == 0            \
9224        ? ((v) & ~0x3ffff) == 0          \
9225          ? ((v) & ~0x1ffff) == 0        \
9226            ? 15                         \
9227            : 14                         \
9228          : ((v) & ~0x7ffff) == 0        \
9229            ? 13                         \
9230            : 12                         \
9231        : ((v) & ~0x3fffff) == 0         \
9232          ? ((v) & ~0x1fffff) == 0       \
9233            ? 11                         \
9234            : 10                         \
9235          : ((v) & ~0x7fffff) == 0       \
9236            ? 9                          \
9237            : 8                          \
9238      : ((v) & ~0xfffffff) == 0          \
9239        ? ((v) & ~0x3ffffff) == 0        \
9240          ? ((v) & ~0x1ffffff) == 0      \
9241            ? 7                          \
9242            : 6                          \
9243          : ((v) & ~0x7ffffff) == 0      \
9244            ? 5                          \
9245            : 4                          \
9246        : ((v) & ~0x3fffffff) == 0       \
9247          ? ((v) & ~0x1fffffff) == 0     \
9248            ? 3                          \
9249            : 2                          \
9250          : ((v) & ~0x7fffffff) == 0     \
9251            ? 1                          \
9252            : 0)
9253
9254 /*                      load_register()
9255  *  This routine generates the least number of instructions necessary to load
9256  *  an absolute expression value into a register.
9257  */
9258 static void
9259 load_register (int reg, expressionS *ep, int dbl)
9260 {
9261   int freg;
9262   expressionS hi32, lo32;
9263
9264   if (ep->X_op != O_big)
9265     {
9266       gas_assert (ep->X_op == O_constant);
9267
9268       /* Sign-extending 32-bit constants makes their handling easier.  */
9269       if (!dbl)
9270         normalize_constant_expr (ep);
9271
9272       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9273         {
9274           /* We can handle 16 bit signed values with an addiu to
9275              $zero.  No need to ever use daddiu here, since $zero and
9276              the result are always correct in 32 bit mode.  */
9277           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9278           return;
9279         }
9280       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9281         {
9282           /* We can handle 16 bit unsigned values with an ori to
9283              $zero.  */
9284           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9285           return;
9286         }
9287       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9288         {
9289           /* 32 bit values require an lui.  */
9290           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9291           if ((ep->X_add_number & 0xffff) != 0)
9292             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9293           return;
9294         }
9295     }
9296
9297   /* The value is larger than 32 bits.  */
9298
9299   if (!dbl || GPR_SIZE == 32)
9300     {
9301       char value[32];
9302
9303       sprintf_vma (value, ep->X_add_number);
9304       as_bad (_("number (0x%s) larger than 32 bits"), value);
9305       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9306       return;
9307     }
9308
9309   if (ep->X_op != O_big)
9310     {
9311       hi32 = *ep;
9312       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9313       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9314       hi32.X_add_number &= 0xffffffff;
9315       lo32 = *ep;
9316       lo32.X_add_number &= 0xffffffff;
9317     }
9318   else
9319     {
9320       gas_assert (ep->X_add_number > 2);
9321       if (ep->X_add_number == 3)
9322         generic_bignum[3] = 0;
9323       else if (ep->X_add_number > 4)
9324         as_bad (_("number larger than 64 bits"));
9325       lo32.X_op = O_constant;
9326       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9327       hi32.X_op = O_constant;
9328       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9329     }
9330
9331   if (hi32.X_add_number == 0)
9332     freg = 0;
9333   else
9334     {
9335       int shift, bit;
9336       unsigned long hi, lo;
9337
9338       if (hi32.X_add_number == (offsetT) 0xffffffff)
9339         {
9340           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9341             {
9342               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9343               return;
9344             }
9345           if (lo32.X_add_number & 0x80000000)
9346             {
9347               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9348               if (lo32.X_add_number & 0xffff)
9349                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9350               return;
9351             }
9352         }
9353
9354       /* Check for 16bit shifted constant.  We know that hi32 is
9355          non-zero, so start the mask on the first bit of the hi32
9356          value.  */
9357       shift = 17;
9358       do
9359         {
9360           unsigned long himask, lomask;
9361
9362           if (shift < 32)
9363             {
9364               himask = 0xffff >> (32 - shift);
9365               lomask = (0xffff << shift) & 0xffffffff;
9366             }
9367           else
9368             {
9369               himask = 0xffff << (shift - 32);
9370               lomask = 0;
9371             }
9372           if ((hi32.X_add_number & ~(offsetT) himask) == 0
9373               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9374             {
9375               expressionS tmp;
9376
9377               tmp.X_op = O_constant;
9378               if (shift < 32)
9379                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9380                                     | (lo32.X_add_number >> shift));
9381               else
9382                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9383               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9384               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9385                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9386               return;
9387             }
9388           ++shift;
9389         }
9390       while (shift <= (64 - 16));
9391
9392       /* Find the bit number of the lowest one bit, and store the
9393          shifted value in hi/lo.  */
9394       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9395       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9396       if (lo != 0)
9397         {
9398           bit = 0;
9399           while ((lo & 1) == 0)
9400             {
9401               lo >>= 1;
9402               ++bit;
9403             }
9404           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9405           hi >>= bit;
9406         }
9407       else
9408         {
9409           bit = 32;
9410           while ((hi & 1) == 0)
9411             {
9412               hi >>= 1;
9413               ++bit;
9414             }
9415           lo = hi;
9416           hi = 0;
9417         }
9418
9419       /* Optimize if the shifted value is a (power of 2) - 1.  */
9420       if ((hi == 0 && ((lo + 1) & lo) == 0)
9421           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9422         {
9423           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9424           if (shift != 0)
9425             {
9426               expressionS tmp;
9427
9428               /* This instruction will set the register to be all
9429                  ones.  */
9430               tmp.X_op = O_constant;
9431               tmp.X_add_number = (offsetT) -1;
9432               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9433               if (bit != 0)
9434                 {
9435                   bit += shift;
9436                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9437                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9438                 }
9439               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9440                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9441               return;
9442             }
9443         }
9444
9445       /* Sign extend hi32 before calling load_register, because we can
9446          generally get better code when we load a sign extended value.  */
9447       if ((hi32.X_add_number & 0x80000000) != 0)
9448         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9449       load_register (reg, &hi32, 0);
9450       freg = reg;
9451     }
9452   if ((lo32.X_add_number & 0xffff0000) == 0)
9453     {
9454       if (freg != 0)
9455         {
9456           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9457           freg = reg;
9458         }
9459     }
9460   else
9461     {
9462       expressionS mid16;
9463
9464       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9465         {
9466           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9467           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9468           return;
9469         }
9470
9471       if (freg != 0)
9472         {
9473           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9474           freg = reg;
9475         }
9476       mid16 = lo32;
9477       mid16.X_add_number >>= 16;
9478       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9479       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9480       freg = reg;
9481     }
9482   if ((lo32.X_add_number & 0xffff) != 0)
9483     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9484 }
9485
9486 static inline void
9487 load_delay_nop (void)
9488 {
9489   if (!gpr_interlocks)
9490     macro_build (NULL, "nop", "");
9491 }
9492
9493 /* Load an address into a register.  */
9494
9495 static void
9496 load_address (int reg, expressionS *ep, int *used_at)
9497 {
9498   if (ep->X_op != O_constant
9499       && ep->X_op != O_symbol)
9500     {
9501       as_bad (_("expression too complex"));
9502       ep->X_op = O_constant;
9503     }
9504
9505   if (ep->X_op == O_constant)
9506     {
9507       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9508       return;
9509     }
9510
9511   if (mips_pic == NO_PIC)
9512     {
9513       /* If this is a reference to a GP relative symbol, we want
9514            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9515          Otherwise we want
9516            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9517            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9518          If we have an addend, we always use the latter form.
9519
9520          With 64bit address space and a usable $at we want
9521            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9522            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9523            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9524            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9525            dsll32       $reg,0
9526            daddu        $reg,$reg,$at
9527
9528          If $at is already in use, we use a path which is suboptimal
9529          on superscalar processors.
9530            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9531            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9532            dsll         $reg,16
9533            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9534            dsll         $reg,16
9535            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9536
9537          For GP relative symbols in 64bit address space we can use
9538          the same sequence as in 32bit address space.  */
9539       if (HAVE_64BIT_SYMBOLS)
9540         {
9541           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9542               && !nopic_need_relax (ep->X_add_symbol, 1))
9543             {
9544               relax_start (ep->X_add_symbol);
9545               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9546                            mips_gp_register, BFD_RELOC_GPREL16);
9547               relax_switch ();
9548             }
9549
9550           if (*used_at == 0 && mips_opts.at)
9551             {
9552               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9553               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9554               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9555                            BFD_RELOC_MIPS_HIGHER);
9556               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9557               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9558               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9559               *used_at = 1;
9560             }
9561           else
9562             {
9563               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9564               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9565                            BFD_RELOC_MIPS_HIGHER);
9566               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9567               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9568               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9569               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9570             }
9571
9572           if (mips_relax.sequence)
9573             relax_end ();
9574         }
9575       else
9576         {
9577           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9578               && !nopic_need_relax (ep->X_add_symbol, 1))
9579             {
9580               relax_start (ep->X_add_symbol);
9581               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9582                            mips_gp_register, BFD_RELOC_GPREL16);
9583               relax_switch ();
9584             }
9585           macro_build_lui (ep, reg);
9586           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9587                        reg, reg, BFD_RELOC_LO16);
9588           if (mips_relax.sequence)
9589             relax_end ();
9590         }
9591     }
9592   else if (!mips_big_got)
9593     {
9594       expressionS ex;
9595
9596       /* If this is a reference to an external symbol, we want
9597            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9598          Otherwise we want
9599            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9600            nop
9601            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9602          If there is a constant, it must be added in after.
9603
9604          If we have NewABI, we want
9605            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9606          unless we're referencing a global symbol with a non-zero
9607          offset, in which case cst must be added separately.  */
9608       if (HAVE_NEWABI)
9609         {
9610           if (ep->X_add_number)
9611             {
9612               ex.X_add_number = ep->X_add_number;
9613               ep->X_add_number = 0;
9614               relax_start (ep->X_add_symbol);
9615               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9616                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9617               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9618                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9619               ex.X_op = O_constant;
9620               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9621                            reg, reg, BFD_RELOC_LO16);
9622               ep->X_add_number = ex.X_add_number;
9623               relax_switch ();
9624             }
9625           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9626                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9627           if (mips_relax.sequence)
9628             relax_end ();
9629         }
9630       else
9631         {
9632           ex.X_add_number = ep->X_add_number;
9633           ep->X_add_number = 0;
9634           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9635                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9636           load_delay_nop ();
9637           relax_start (ep->X_add_symbol);
9638           relax_switch ();
9639           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9640                        BFD_RELOC_LO16);
9641           relax_end ();
9642
9643           if (ex.X_add_number != 0)
9644             {
9645               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9646                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9647               ex.X_op = O_constant;
9648               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9649                            reg, reg, BFD_RELOC_LO16);
9650             }
9651         }
9652     }
9653   else if (mips_big_got)
9654     {
9655       expressionS ex;
9656
9657       /* This is the large GOT case.  If this is a reference to an
9658          external symbol, we want
9659            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9660            addu         $reg,$reg,$gp
9661            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9662
9663          Otherwise, for a reference to a local symbol in old ABI, we want
9664            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9665            nop
9666            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9667          If there is a constant, it must be added in after.
9668
9669          In the NewABI, for local symbols, with or without offsets, we want:
9670            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9671            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9672       */
9673       if (HAVE_NEWABI)
9674         {
9675           ex.X_add_number = ep->X_add_number;
9676           ep->X_add_number = 0;
9677           relax_start (ep->X_add_symbol);
9678           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9679           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9680                        reg, reg, mips_gp_register);
9681           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9682                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9683           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9684             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9685           else if (ex.X_add_number)
9686             {
9687               ex.X_op = O_constant;
9688               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9689                            BFD_RELOC_LO16);
9690             }
9691
9692           ep->X_add_number = ex.X_add_number;
9693           relax_switch ();
9694           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9695                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9696           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9697                        BFD_RELOC_MIPS_GOT_OFST);
9698           relax_end ();
9699         }
9700       else
9701         {
9702           ex.X_add_number = ep->X_add_number;
9703           ep->X_add_number = 0;
9704           relax_start (ep->X_add_symbol);
9705           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9706           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9707                        reg, reg, mips_gp_register);
9708           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9709                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9710           relax_switch ();
9711           if (reg_needs_delay (mips_gp_register))
9712             {
9713               /* We need a nop before loading from $gp.  This special
9714                  check is required because the lui which starts the main
9715                  instruction stream does not refer to $gp, and so will not
9716                  insert the nop which may be required.  */
9717               macro_build (NULL, "nop", "");
9718             }
9719           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9720                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9721           load_delay_nop ();
9722           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9723                        BFD_RELOC_LO16);
9724           relax_end ();
9725
9726           if (ex.X_add_number != 0)
9727             {
9728               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9729                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9730               ex.X_op = O_constant;
9731               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9732                            BFD_RELOC_LO16);
9733             }
9734         }
9735     }
9736   else
9737     abort ();
9738
9739   if (!mips_opts.at && *used_at == 1)
9740     as_bad (_("macro used $at after \".set noat\""));
9741 }
9742
9743 /* Move the contents of register SOURCE into register DEST.  */
9744
9745 static void
9746 move_register (int dest, int source)
9747 {
9748   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9749      instruction specifically requires a 32-bit one.  */
9750   if (mips_opts.micromips
9751       && !mips_opts.insn32
9752       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9753     macro_build (NULL, "move", "mp,mj", dest, source);
9754   else
9755     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9756 }
9757
9758 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9759    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9760    The two alternatives are:
9761
9762    Global symbol                Local symbol
9763    -------------                ------------
9764    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9765    ...                          ...
9766    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9767
9768    load_got_offset emits the first instruction and add_got_offset
9769    emits the second for a 16-bit offset or add_got_offset_hilo emits
9770    a sequence to add a 32-bit offset using a scratch register.  */
9771
9772 static void
9773 load_got_offset (int dest, expressionS *local)
9774 {
9775   expressionS global;
9776
9777   global = *local;
9778   global.X_add_number = 0;
9779
9780   relax_start (local->X_add_symbol);
9781   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9782                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9783   relax_switch ();
9784   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9785                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9786   relax_end ();
9787 }
9788
9789 static void
9790 add_got_offset (int dest, expressionS *local)
9791 {
9792   expressionS global;
9793
9794   global.X_op = O_constant;
9795   global.X_op_symbol = NULL;
9796   global.X_add_symbol = NULL;
9797   global.X_add_number = local->X_add_number;
9798
9799   relax_start (local->X_add_symbol);
9800   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9801                dest, dest, BFD_RELOC_LO16);
9802   relax_switch ();
9803   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9804   relax_end ();
9805 }
9806
9807 static void
9808 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9809 {
9810   expressionS global;
9811   int hold_mips_optimize;
9812
9813   global.X_op = O_constant;
9814   global.X_op_symbol = NULL;
9815   global.X_add_symbol = NULL;
9816   global.X_add_number = local->X_add_number;
9817
9818   relax_start (local->X_add_symbol);
9819   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9820   relax_switch ();
9821   /* Set mips_optimize around the lui instruction to avoid
9822      inserting an unnecessary nop after the lw.  */
9823   hold_mips_optimize = mips_optimize;
9824   mips_optimize = 2;
9825   macro_build_lui (&global, tmp);
9826   mips_optimize = hold_mips_optimize;
9827   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9828   relax_end ();
9829
9830   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9831 }
9832
9833 /* Emit a sequence of instructions to emulate a branch likely operation.
9834    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9835    is its complementing branch with the original condition negated.
9836    CALL is set if the original branch specified the link operation.
9837    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9838
9839    Code like this is produced in the noreorder mode:
9840
9841         BRNEG   <args>, 1f
9842          nop
9843         b       <sym>
9844          delay slot (executed only if branch taken)
9845     1:
9846
9847    or, if CALL is set:
9848
9849         BRNEG   <args>, 1f
9850          nop
9851         bal     <sym>
9852          delay slot (executed only if branch taken)
9853     1:
9854
9855    In the reorder mode the delay slot would be filled with a nop anyway,
9856    so code produced is simply:
9857
9858         BR      <args>, <sym>
9859          nop
9860
9861    This function is used when producing code for the microMIPS ASE that
9862    does not implement branch likely instructions in hardware.  */
9863
9864 static void
9865 macro_build_branch_likely (const char *br, const char *brneg,
9866                            int call, expressionS *ep, const char *fmt,
9867                            unsigned int sreg, unsigned int treg)
9868 {
9869   int noreorder = mips_opts.noreorder;
9870   expressionS expr1;
9871
9872   gas_assert (mips_opts.micromips);
9873   start_noreorder ();
9874   if (noreorder)
9875     {
9876       micromips_label_expr (&expr1);
9877       macro_build (&expr1, brneg, fmt, sreg, treg);
9878       macro_build (NULL, "nop", "");
9879       macro_build (ep, call ? "bal" : "b", "p");
9880
9881       /* Set to true so that append_insn adds a label.  */
9882       emit_branch_likely_macro = TRUE;
9883     }
9884   else
9885     {
9886       macro_build (ep, br, fmt, sreg, treg);
9887       macro_build (NULL, "nop", "");
9888     }
9889   end_noreorder ();
9890 }
9891
9892 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9893    the condition code tested.  EP specifies the branch target.  */
9894
9895 static void
9896 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9897 {
9898   const int call = 0;
9899   const char *brneg;
9900   const char *br;
9901
9902   switch (type)
9903     {
9904     case M_BC1FL:
9905       br = "bc1f";
9906       brneg = "bc1t";
9907       break;
9908     case M_BC1TL:
9909       br = "bc1t";
9910       brneg = "bc1f";
9911       break;
9912     case M_BC2FL:
9913       br = "bc2f";
9914       brneg = "bc2t";
9915       break;
9916     case M_BC2TL:
9917       br = "bc2t";
9918       brneg = "bc2f";
9919       break;
9920     default:
9921       abort ();
9922     }
9923   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9924 }
9925
9926 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9927    the register tested.  EP specifies the branch target.  */
9928
9929 static void
9930 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9931 {
9932   const char *brneg = NULL;
9933   const char *br;
9934   int call = 0;
9935
9936   switch (type)
9937     {
9938     case M_BGEZ:
9939       br = "bgez";
9940       break;
9941     case M_BGEZL:
9942       br = mips_opts.micromips ? "bgez" : "bgezl";
9943       brneg = "bltz";
9944       break;
9945     case M_BGEZALL:
9946       gas_assert (mips_opts.micromips);
9947       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9948       brneg = "bltz";
9949       call = 1;
9950       break;
9951     case M_BGTZ:
9952       br = "bgtz";
9953       break;
9954     case M_BGTZL:
9955       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9956       brneg = "blez";
9957       break;
9958     case M_BLEZ:
9959       br = "blez";
9960       break;
9961     case M_BLEZL:
9962       br = mips_opts.micromips ? "blez" : "blezl";
9963       brneg = "bgtz";
9964       break;
9965     case M_BLTZ:
9966       br = "bltz";
9967       break;
9968     case M_BLTZL:
9969       br = mips_opts.micromips ? "bltz" : "bltzl";
9970       brneg = "bgez";
9971       break;
9972     case M_BLTZALL:
9973       gas_assert (mips_opts.micromips);
9974       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9975       brneg = "bgez";
9976       call = 1;
9977       break;
9978     default:
9979       abort ();
9980     }
9981   if (mips_opts.micromips && brneg)
9982     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9983   else
9984     macro_build (ep, br, "s,p", sreg);
9985 }
9986
9987 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9988    TREG as the registers tested.  EP specifies the branch target.  */
9989
9990 static void
9991 macro_build_branch_rsrt (int type, expressionS *ep,
9992                          unsigned int sreg, unsigned int treg)
9993 {
9994   const char *brneg = NULL;
9995   const int call = 0;
9996   const char *br;
9997
9998   switch (type)
9999     {
10000     case M_BEQ:
10001     case M_BEQ_I:
10002       br = "beq";
10003       break;
10004     case M_BEQL:
10005     case M_BEQL_I:
10006       br = mips_opts.micromips ? "beq" : "beql";
10007       brneg = "bne";
10008       break;
10009     case M_BNE:
10010     case M_BNE_I:
10011       br = "bne";
10012       break;
10013     case M_BNEL:
10014     case M_BNEL_I:
10015       br = mips_opts.micromips ? "bne" : "bnel";
10016       brneg = "beq";
10017       break;
10018     default:
10019       abort ();
10020     }
10021   if (mips_opts.micromips && brneg)
10022     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
10023   else
10024     macro_build (ep, br, "s,t,p", sreg, treg);
10025 }
10026
10027 /* Return the high part that should be loaded in order to make the low
10028    part of VALUE accessible using an offset of OFFBITS bits.  */
10029
10030 static offsetT
10031 offset_high_part (offsetT value, unsigned int offbits)
10032 {
10033   offsetT bias;
10034   addressT low_mask;
10035
10036   if (offbits == 0)
10037     return value;
10038   bias = 1 << (offbits - 1);
10039   low_mask = bias * 2 - 1;
10040   return (value + bias) & ~low_mask;
10041 }
10042
10043 /* Return true if the value stored in offset_expr and offset_reloc
10044    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
10045    amount that the caller wants to add without inducing overflow
10046    and ALIGN is the known alignment of the value in bytes.  */
10047
10048 static bfd_boolean
10049 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
10050 {
10051   if (offbits == 16)
10052     {
10053       /* Accept any relocation operator if overflow isn't a concern.  */
10054       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
10055         return TRUE;
10056
10057       /* These relocations are guaranteed not to overflow in correct links.  */
10058       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
10059           || gprel16_reloc_p (*offset_reloc))
10060         return TRUE;
10061     }
10062   if (offset_expr.X_op == O_constant
10063       && offset_high_part (offset_expr.X_add_number, offbits) == 0
10064       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
10065     return TRUE;
10066   return FALSE;
10067 }
10068
10069 /*
10070  *                      Build macros
10071  *   This routine implements the seemingly endless macro or synthesized
10072  * instructions and addressing modes in the mips assembly language. Many
10073  * of these macros are simple and are similar to each other. These could
10074  * probably be handled by some kind of table or grammar approach instead of
10075  * this verbose method. Others are not simple macros but are more like
10076  * optimizing code generation.
10077  *   One interesting optimization is when several store macros appear
10078  * consecutively that would load AT with the upper half of the same address.
10079  * The ensuing load upper instructions are omitted. This implies some kind
10080  * of global optimization. We currently only optimize within a single macro.
10081  *   For many of the load and store macros if the address is specified as a
10082  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
10083  * first load register 'at' with zero and use it as the base register. The
10084  * mips assembler simply uses register $zero. Just one tiny optimization
10085  * we're missing.
10086  */
10087 static void
10088 macro (struct mips_cl_insn *ip, char *str)
10089 {
10090   const struct mips_operand_array *operands;
10091   unsigned int breg, i;
10092   unsigned int tempreg;
10093   int mask;
10094   int used_at = 0;
10095   expressionS label_expr;
10096   expressionS expr1;
10097   expressionS *ep;
10098   const char *s;
10099   const char *s2;
10100   const char *fmt;
10101   int likely = 0;
10102   int coproc = 0;
10103   int offbits = 16;
10104   int call = 0;
10105   int jals = 0;
10106   int dbl = 0;
10107   int imm = 0;
10108   int ust = 0;
10109   int lp = 0;
10110   bfd_boolean large_offset;
10111   int off;
10112   int hold_mips_optimize;
10113   unsigned int align;
10114   unsigned int op[MAX_OPERANDS];
10115
10116   gas_assert (! mips_opts.mips16);
10117
10118   operands = insn_operands (ip);
10119   for (i = 0; i < MAX_OPERANDS; i++)
10120     if (operands->operand[i])
10121       op[i] = insn_extract_operand (ip, operands->operand[i]);
10122     else
10123       op[i] = -1;
10124
10125   mask = ip->insn_mo->mask;
10126
10127   label_expr.X_op = O_constant;
10128   label_expr.X_op_symbol = NULL;
10129   label_expr.X_add_symbol = NULL;
10130   label_expr.X_add_number = 0;
10131
10132   expr1.X_op = O_constant;
10133   expr1.X_op_symbol = NULL;
10134   expr1.X_add_symbol = NULL;
10135   expr1.X_add_number = 1;
10136   align = 1;
10137
10138   switch (mask)
10139     {
10140     case M_DABS:
10141       dbl = 1;
10142       /* Fall through.  */
10143     case M_ABS:
10144       /*    bgez    $a0,1f
10145             move    v0,$a0
10146             sub     v0,$zero,$a0
10147          1:
10148        */
10149
10150       start_noreorder ();
10151
10152       if (mips_opts.micromips)
10153         micromips_label_expr (&label_expr);
10154       else
10155         label_expr.X_add_number = 8;
10156       macro_build (&label_expr, "bgez", "s,p", op[1]);
10157       if (op[0] == op[1])
10158         macro_build (NULL, "nop", "");
10159       else
10160         move_register (op[0], op[1]);
10161       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
10162       if (mips_opts.micromips)
10163         micromips_add_label ();
10164
10165       end_noreorder ();
10166       break;
10167
10168     case M_ADD_I:
10169       s = "addi";
10170       s2 = "add";
10171       goto do_addi;
10172     case M_ADDU_I:
10173       s = "addiu";
10174       s2 = "addu";
10175       goto do_addi;
10176     case M_DADD_I:
10177       dbl = 1;
10178       s = "daddi";
10179       s2 = "dadd";
10180       if (!mips_opts.micromips)
10181         goto do_addi;
10182       if (imm_expr.X_add_number >= -0x200
10183           && imm_expr.X_add_number < 0x200)
10184         {
10185           macro_build (NULL, s, "t,r,.", op[0], op[1],
10186                        (int) imm_expr.X_add_number);
10187           break;
10188         }
10189       goto do_addi_i;
10190     case M_DADDU_I:
10191       dbl = 1;
10192       s = "daddiu";
10193       s2 = "daddu";
10194     do_addi:
10195       if (imm_expr.X_add_number >= -0x8000
10196           && imm_expr.X_add_number < 0x8000)
10197         {
10198           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
10199           break;
10200         }
10201     do_addi_i:
10202       used_at = 1;
10203       load_register (AT, &imm_expr, dbl);
10204       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10205       break;
10206
10207     case M_AND_I:
10208       s = "andi";
10209       s2 = "and";
10210       goto do_bit;
10211     case M_OR_I:
10212       s = "ori";
10213       s2 = "or";
10214       goto do_bit;
10215     case M_NOR_I:
10216       s = "";
10217       s2 = "nor";
10218       goto do_bit;
10219     case M_XOR_I:
10220       s = "xori";
10221       s2 = "xor";
10222     do_bit:
10223       if (imm_expr.X_add_number >= 0
10224           && imm_expr.X_add_number < 0x10000)
10225         {
10226           if (mask != M_NOR_I)
10227             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10228           else
10229             {
10230               macro_build (&imm_expr, "ori", "t,r,i",
10231                            op[0], op[1], BFD_RELOC_LO16);
10232               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10233             }
10234           break;
10235         }
10236
10237       used_at = 1;
10238       load_register (AT, &imm_expr, GPR_SIZE == 64);
10239       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10240       break;
10241
10242     case M_BALIGN:
10243       switch (imm_expr.X_add_number)
10244         {
10245         case 0:
10246           macro_build (NULL, "nop", "");
10247           break;
10248         case 2:
10249           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10250           break;
10251         case 1:
10252         case 3:
10253           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10254                        (int) imm_expr.X_add_number);
10255           break;
10256         default:
10257           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10258                   (unsigned long) imm_expr.X_add_number);
10259           break;
10260         }
10261       break;
10262
10263     case M_BC1FL:
10264     case M_BC1TL:
10265     case M_BC2FL:
10266     case M_BC2TL:
10267       gas_assert (mips_opts.micromips);
10268       macro_build_branch_ccl (mask, &offset_expr,
10269                               EXTRACT_OPERAND (1, BCC, *ip));
10270       break;
10271
10272     case M_BEQ_I:
10273     case M_BEQL_I:
10274     case M_BNE_I:
10275     case M_BNEL_I:
10276       if (imm_expr.X_add_number == 0)
10277         op[1] = 0;
10278       else
10279         {
10280           op[1] = AT;
10281           used_at = 1;
10282           load_register (op[1], &imm_expr, GPR_SIZE == 64);
10283         }
10284       /* Fall through.  */
10285     case M_BEQL:
10286     case M_BNEL:
10287       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10288       break;
10289
10290     case M_BGEL:
10291       likely = 1;
10292       /* Fall through.  */
10293     case M_BGE:
10294       if (op[1] == 0)
10295         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10296       else if (op[0] == 0)
10297         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10298       else
10299         {
10300           used_at = 1;
10301           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10302           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10303                                    &offset_expr, AT, ZERO);
10304         }
10305       break;
10306
10307     case M_BGEZL:
10308     case M_BGEZALL:
10309     case M_BGTZL:
10310     case M_BLEZL:
10311     case M_BLTZL:
10312     case M_BLTZALL:
10313       macro_build_branch_rs (mask, &offset_expr, op[0]);
10314       break;
10315
10316     case M_BGTL_I:
10317       likely = 1;
10318       /* Fall through.  */
10319     case M_BGT_I:
10320       /* Check for > max integer.  */
10321       if (imm_expr.X_add_number >= GPR_SMAX)
10322         {
10323         do_false:
10324           /* Result is always false.  */
10325           if (! likely)
10326             macro_build (NULL, "nop", "");
10327           else
10328             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10329           break;
10330         }
10331       ++imm_expr.X_add_number;
10332       /* FALLTHROUGH */
10333     case M_BGE_I:
10334     case M_BGEL_I:
10335       if (mask == M_BGEL_I)
10336         likely = 1;
10337       if (imm_expr.X_add_number == 0)
10338         {
10339           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10340                                  &offset_expr, op[0]);
10341           break;
10342         }
10343       if (imm_expr.X_add_number == 1)
10344         {
10345           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10346                                  &offset_expr, op[0]);
10347           break;
10348         }
10349       if (imm_expr.X_add_number <= GPR_SMIN)
10350         {
10351         do_true:
10352           /* result is always true */
10353           as_warn (_("branch %s is always true"), ip->insn_mo->name);
10354           macro_build (&offset_expr, "b", "p");
10355           break;
10356         }
10357       used_at = 1;
10358       set_at (op[0], 0);
10359       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10360                                &offset_expr, AT, ZERO);
10361       break;
10362
10363     case M_BGEUL:
10364       likely = 1;
10365       /* Fall through.  */
10366     case M_BGEU:
10367       if (op[1] == 0)
10368         goto do_true;
10369       else if (op[0] == 0)
10370         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10371                                  &offset_expr, ZERO, op[1]);
10372       else
10373         {
10374           used_at = 1;
10375           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10376           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10377                                    &offset_expr, AT, ZERO);
10378         }
10379       break;
10380
10381     case M_BGTUL_I:
10382       likely = 1;
10383       /* Fall through.  */
10384     case M_BGTU_I:
10385       if (op[0] == 0
10386           || (GPR_SIZE == 32
10387               && imm_expr.X_add_number == -1))
10388         goto do_false;
10389       ++imm_expr.X_add_number;
10390       /* FALLTHROUGH */
10391     case M_BGEU_I:
10392     case M_BGEUL_I:
10393       if (mask == M_BGEUL_I)
10394         likely = 1;
10395       if (imm_expr.X_add_number == 0)
10396         goto do_true;
10397       else if (imm_expr.X_add_number == 1)
10398         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10399                                  &offset_expr, op[0], ZERO);
10400       else
10401         {
10402           used_at = 1;
10403           set_at (op[0], 1);
10404           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10405                                    &offset_expr, AT, ZERO);
10406         }
10407       break;
10408
10409     case M_BGTL:
10410       likely = 1;
10411       /* Fall through.  */
10412     case M_BGT:
10413       if (op[1] == 0)
10414         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10415       else if (op[0] == 0)
10416         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10417       else
10418         {
10419           used_at = 1;
10420           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10421           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10422                                    &offset_expr, AT, ZERO);
10423         }
10424       break;
10425
10426     case M_BGTUL:
10427       likely = 1;
10428       /* Fall through.  */
10429     case M_BGTU:
10430       if (op[1] == 0)
10431         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10432                                  &offset_expr, op[0], ZERO);
10433       else if (op[0] == 0)
10434         goto do_false;
10435       else
10436         {
10437           used_at = 1;
10438           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10439           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10440                                    &offset_expr, AT, ZERO);
10441         }
10442       break;
10443
10444     case M_BLEL:
10445       likely = 1;
10446       /* Fall through.  */
10447     case M_BLE:
10448       if (op[1] == 0)
10449         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10450       else if (op[0] == 0)
10451         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10452       else
10453         {
10454           used_at = 1;
10455           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10456           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10457                                    &offset_expr, AT, ZERO);
10458         }
10459       break;
10460
10461     case M_BLEL_I:
10462       likely = 1;
10463       /* Fall through.  */
10464     case M_BLE_I:
10465       if (imm_expr.X_add_number >= GPR_SMAX)
10466         goto do_true;
10467       ++imm_expr.X_add_number;
10468       /* FALLTHROUGH */
10469     case M_BLT_I:
10470     case M_BLTL_I:
10471       if (mask == M_BLTL_I)
10472         likely = 1;
10473       if (imm_expr.X_add_number == 0)
10474         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10475       else if (imm_expr.X_add_number == 1)
10476         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10477       else
10478         {
10479           used_at = 1;
10480           set_at (op[0], 0);
10481           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10482                                    &offset_expr, AT, ZERO);
10483         }
10484       break;
10485
10486     case M_BLEUL:
10487       likely = 1;
10488       /* Fall through.  */
10489     case M_BLEU:
10490       if (op[1] == 0)
10491         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10492                                  &offset_expr, op[0], ZERO);
10493       else if (op[0] == 0)
10494         goto do_true;
10495       else
10496         {
10497           used_at = 1;
10498           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10499           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10500                                    &offset_expr, AT, ZERO);
10501         }
10502       break;
10503
10504     case M_BLEUL_I:
10505       likely = 1;
10506       /* Fall through.  */
10507     case M_BLEU_I:
10508       if (op[0] == 0
10509           || (GPR_SIZE == 32
10510               && imm_expr.X_add_number == -1))
10511         goto do_true;
10512       ++imm_expr.X_add_number;
10513       /* FALLTHROUGH */
10514     case M_BLTU_I:
10515     case M_BLTUL_I:
10516       if (mask == M_BLTUL_I)
10517         likely = 1;
10518       if (imm_expr.X_add_number == 0)
10519         goto do_false;
10520       else if (imm_expr.X_add_number == 1)
10521         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10522                                  &offset_expr, op[0], ZERO);
10523       else
10524         {
10525           used_at = 1;
10526           set_at (op[0], 1);
10527           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10528                                    &offset_expr, AT, ZERO);
10529         }
10530       break;
10531
10532     case M_BLTL:
10533       likely = 1;
10534       /* Fall through.  */
10535     case M_BLT:
10536       if (op[1] == 0)
10537         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10538       else if (op[0] == 0)
10539         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10540       else
10541         {
10542           used_at = 1;
10543           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10544           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10545                                    &offset_expr, AT, ZERO);
10546         }
10547       break;
10548
10549     case M_BLTUL:
10550       likely = 1;
10551       /* Fall through.  */
10552     case M_BLTU:
10553       if (op[1] == 0)
10554         goto do_false;
10555       else if (op[0] == 0)
10556         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10557                                  &offset_expr, ZERO, op[1]);
10558       else
10559         {
10560           used_at = 1;
10561           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10562           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10563                                    &offset_expr, AT, ZERO);
10564         }
10565       break;
10566
10567     case M_DDIV_3:
10568       dbl = 1;
10569       /* Fall through.  */
10570     case M_DIV_3:
10571       s = "mflo";
10572       goto do_div3;
10573     case M_DREM_3:
10574       dbl = 1;
10575       /* Fall through.  */
10576     case M_REM_3:
10577       s = "mfhi";
10578     do_div3:
10579       if (op[2] == 0)
10580         {
10581           as_warn (_("divide by zero"));
10582           if (mips_trap)
10583             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10584           else
10585             macro_build (NULL, "break", BRK_FMT, 7);
10586           break;
10587         }
10588
10589       start_noreorder ();
10590       if (mips_trap)
10591         {
10592           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10593           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10594         }
10595       else
10596         {
10597           if (mips_opts.micromips)
10598             micromips_label_expr (&label_expr);
10599           else
10600             label_expr.X_add_number = 8;
10601           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10602           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10603           macro_build (NULL, "break", BRK_FMT, 7);
10604           if (mips_opts.micromips)
10605             micromips_add_label ();
10606         }
10607       expr1.X_add_number = -1;
10608       used_at = 1;
10609       load_register (AT, &expr1, dbl);
10610       if (mips_opts.micromips)
10611         micromips_label_expr (&label_expr);
10612       else
10613         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10614       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10615       if (dbl)
10616         {
10617           expr1.X_add_number = 1;
10618           load_register (AT, &expr1, dbl);
10619           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10620         }
10621       else
10622         {
10623           expr1.X_add_number = 0x80000000;
10624           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10625         }
10626       if (mips_trap)
10627         {
10628           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10629           /* We want to close the noreorder block as soon as possible, so
10630              that later insns are available for delay slot filling.  */
10631           end_noreorder ();
10632         }
10633       else
10634         {
10635           if (mips_opts.micromips)
10636             micromips_label_expr (&label_expr);
10637           else
10638             label_expr.X_add_number = 8;
10639           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10640           macro_build (NULL, "nop", "");
10641
10642           /* We want to close the noreorder block as soon as possible, so
10643              that later insns are available for delay slot filling.  */
10644           end_noreorder ();
10645
10646           macro_build (NULL, "break", BRK_FMT, 6);
10647         }
10648       if (mips_opts.micromips)
10649         micromips_add_label ();
10650       macro_build (NULL, s, MFHL_FMT, op[0]);
10651       break;
10652
10653     case M_DIV_3I:
10654       s = "div";
10655       s2 = "mflo";
10656       goto do_divi;
10657     case M_DIVU_3I:
10658       s = "divu";
10659       s2 = "mflo";
10660       goto do_divi;
10661     case M_REM_3I:
10662       s = "div";
10663       s2 = "mfhi";
10664       goto do_divi;
10665     case M_REMU_3I:
10666       s = "divu";
10667       s2 = "mfhi";
10668       goto do_divi;
10669     case M_DDIV_3I:
10670       dbl = 1;
10671       s = "ddiv";
10672       s2 = "mflo";
10673       goto do_divi;
10674     case M_DDIVU_3I:
10675       dbl = 1;
10676       s = "ddivu";
10677       s2 = "mflo";
10678       goto do_divi;
10679     case M_DREM_3I:
10680       dbl = 1;
10681       s = "ddiv";
10682       s2 = "mfhi";
10683       goto do_divi;
10684     case M_DREMU_3I:
10685       dbl = 1;
10686       s = "ddivu";
10687       s2 = "mfhi";
10688     do_divi:
10689       if (imm_expr.X_add_number == 0)
10690         {
10691           as_warn (_("divide by zero"));
10692           if (mips_trap)
10693             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10694           else
10695             macro_build (NULL, "break", BRK_FMT, 7);
10696           break;
10697         }
10698       if (imm_expr.X_add_number == 1)
10699         {
10700           if (strcmp (s2, "mflo") == 0)
10701             move_register (op[0], op[1]);
10702           else
10703             move_register (op[0], ZERO);
10704           break;
10705         }
10706       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10707         {
10708           if (strcmp (s2, "mflo") == 0)
10709             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10710           else
10711             move_register (op[0], ZERO);
10712           break;
10713         }
10714
10715       used_at = 1;
10716       load_register (AT, &imm_expr, dbl);
10717       macro_build (NULL, s, "z,s,t", op[1], AT);
10718       macro_build (NULL, s2, MFHL_FMT, op[0]);
10719       break;
10720
10721     case M_DIVU_3:
10722       s = "divu";
10723       s2 = "mflo";
10724       goto do_divu3;
10725     case M_REMU_3:
10726       s = "divu";
10727       s2 = "mfhi";
10728       goto do_divu3;
10729     case M_DDIVU_3:
10730       s = "ddivu";
10731       s2 = "mflo";
10732       goto do_divu3;
10733     case M_DREMU_3:
10734       s = "ddivu";
10735       s2 = "mfhi";
10736     do_divu3:
10737       start_noreorder ();
10738       if (mips_trap)
10739         {
10740           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10741           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10742           /* We want to close the noreorder block as soon as possible, so
10743              that later insns are available for delay slot filling.  */
10744           end_noreorder ();
10745         }
10746       else
10747         {
10748           if (mips_opts.micromips)
10749             micromips_label_expr (&label_expr);
10750           else
10751             label_expr.X_add_number = 8;
10752           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10753           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10754
10755           /* We want to close the noreorder block as soon as possible, so
10756              that later insns are available for delay slot filling.  */
10757           end_noreorder ();
10758           macro_build (NULL, "break", BRK_FMT, 7);
10759           if (mips_opts.micromips)
10760             micromips_add_label ();
10761         }
10762       macro_build (NULL, s2, MFHL_FMT, op[0]);
10763       break;
10764
10765     case M_DLCA_AB:
10766       dbl = 1;
10767       /* Fall through.  */
10768     case M_LCA_AB:
10769       call = 1;
10770       goto do_la;
10771     case M_DLA_AB:
10772       dbl = 1;
10773       /* Fall through.  */
10774     case M_LA_AB:
10775     do_la:
10776       /* Load the address of a symbol into a register.  If breg is not
10777          zero, we then add a base register to it.  */
10778
10779       breg = op[2];
10780       if (dbl && GPR_SIZE == 32)
10781         as_warn (_("dla used to load 32-bit register; recommend using la "
10782                    "instead"));
10783
10784       if (!dbl && HAVE_64BIT_OBJECTS)
10785         as_warn (_("la used to load 64-bit address; recommend using dla "
10786                    "instead"));
10787
10788       if (small_offset_p (0, align, 16))
10789         {
10790           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10791                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10792           break;
10793         }
10794
10795       if (mips_opts.at && (op[0] == breg))
10796         {
10797           tempreg = AT;
10798           used_at = 1;
10799         }
10800       else
10801         tempreg = op[0];
10802
10803       if (offset_expr.X_op != O_symbol
10804           && offset_expr.X_op != O_constant)
10805         {
10806           as_bad (_("expression too complex"));
10807           offset_expr.X_op = O_constant;
10808         }
10809
10810       if (offset_expr.X_op == O_constant)
10811         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10812       else if (mips_pic == NO_PIC)
10813         {
10814           /* If this is a reference to a GP relative symbol, we want
10815                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10816              Otherwise we want
10817                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10818                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10819              If we have a constant, we need two instructions anyhow,
10820              so we may as well always use the latter form.
10821
10822              With 64bit address space and a usable $at we want
10823                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10824                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10825                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10826                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10827                dsll32   $tempreg,0
10828                daddu    $tempreg,$tempreg,$at
10829
10830              If $at is already in use, we use a path which is suboptimal
10831              on superscalar processors.
10832                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10833                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10834                dsll     $tempreg,16
10835                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10836                dsll     $tempreg,16
10837                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10838
10839              For GP relative symbols in 64bit address space we can use
10840              the same sequence as in 32bit address space.  */
10841           if (HAVE_64BIT_SYMBOLS)
10842             {
10843               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10844                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10845                 {
10846                   relax_start (offset_expr.X_add_symbol);
10847                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10848                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10849                   relax_switch ();
10850                 }
10851
10852               if (used_at == 0 && mips_opts.at)
10853                 {
10854                   macro_build (&offset_expr, "lui", LUI_FMT,
10855                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10856                   macro_build (&offset_expr, "lui", LUI_FMT,
10857                                AT, BFD_RELOC_HI16_S);
10858                   macro_build (&offset_expr, "daddiu", "t,r,j",
10859                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10860                   macro_build (&offset_expr, "daddiu", "t,r,j",
10861                                AT, AT, BFD_RELOC_LO16);
10862                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10863                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10864                   used_at = 1;
10865                 }
10866               else
10867                 {
10868                   macro_build (&offset_expr, "lui", LUI_FMT,
10869                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10870                   macro_build (&offset_expr, "daddiu", "t,r,j",
10871                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10872                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10873                   macro_build (&offset_expr, "daddiu", "t,r,j",
10874                                tempreg, tempreg, BFD_RELOC_HI16_S);
10875                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10876                   macro_build (&offset_expr, "daddiu", "t,r,j",
10877                                tempreg, tempreg, BFD_RELOC_LO16);
10878                 }
10879
10880               if (mips_relax.sequence)
10881                 relax_end ();
10882             }
10883           else
10884             {
10885               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10886                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10887                 {
10888                   relax_start (offset_expr.X_add_symbol);
10889                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10890                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10891                   relax_switch ();
10892                 }
10893               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10894                 as_bad (_("offset too large"));
10895               macro_build_lui (&offset_expr, tempreg);
10896               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10897                            tempreg, tempreg, BFD_RELOC_LO16);
10898               if (mips_relax.sequence)
10899                 relax_end ();
10900             }
10901         }
10902       else if (!mips_big_got && !HAVE_NEWABI)
10903         {
10904           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10905
10906           /* If this is a reference to an external symbol, and there
10907              is no constant, we want
10908                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10909              or for lca or if tempreg is PIC_CALL_REG
10910                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10911              For a local symbol, we want
10912                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10913                nop
10914                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10915
10916              If we have a small constant, and this is a reference to
10917              an external symbol, we want
10918                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10919                nop
10920                addiu    $tempreg,$tempreg,<constant>
10921              For a local symbol, we want the same instruction
10922              sequence, but we output a BFD_RELOC_LO16 reloc on the
10923              addiu instruction.
10924
10925              If we have a large constant, and this is a reference to
10926              an external symbol, we want
10927                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10928                lui      $at,<hiconstant>
10929                addiu    $at,$at,<loconstant>
10930                addu     $tempreg,$tempreg,$at
10931              For a local symbol, we want the same instruction
10932              sequence, but we output a BFD_RELOC_LO16 reloc on the
10933              addiu instruction.
10934            */
10935
10936           if (offset_expr.X_add_number == 0)
10937             {
10938               if (mips_pic == SVR4_PIC
10939                   && breg == 0
10940                   && (call || tempreg == PIC_CALL_REG))
10941                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10942
10943               relax_start (offset_expr.X_add_symbol);
10944               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10945                            lw_reloc_type, mips_gp_register);
10946               if (breg != 0)
10947                 {
10948                   /* We're going to put in an addu instruction using
10949                      tempreg, so we may as well insert the nop right
10950                      now.  */
10951                   load_delay_nop ();
10952                 }
10953               relax_switch ();
10954               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10955                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10956               load_delay_nop ();
10957               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10958                            tempreg, tempreg, BFD_RELOC_LO16);
10959               relax_end ();
10960               /* FIXME: If breg == 0, and the next instruction uses
10961                  $tempreg, then if this variant case is used an extra
10962                  nop will be generated.  */
10963             }
10964           else if (offset_expr.X_add_number >= -0x8000
10965                    && offset_expr.X_add_number < 0x8000)
10966             {
10967               load_got_offset (tempreg, &offset_expr);
10968               load_delay_nop ();
10969               add_got_offset (tempreg, &offset_expr);
10970             }
10971           else
10972             {
10973               expr1.X_add_number = offset_expr.X_add_number;
10974               offset_expr.X_add_number =
10975                 SEXT_16BIT (offset_expr.X_add_number);
10976               load_got_offset (tempreg, &offset_expr);
10977               offset_expr.X_add_number = expr1.X_add_number;
10978               /* If we are going to add in a base register, and the
10979                  target register and the base register are the same,
10980                  then we are using AT as a temporary register.  Since
10981                  we want to load the constant into AT, we add our
10982                  current AT (from the global offset table) and the
10983                  register into the register now, and pretend we were
10984                  not using a base register.  */
10985               if (breg == op[0])
10986                 {
10987                   load_delay_nop ();
10988                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10989                                op[0], AT, breg);
10990                   breg = 0;
10991                   tempreg = op[0];
10992                 }
10993               add_got_offset_hilo (tempreg, &offset_expr, AT);
10994               used_at = 1;
10995             }
10996         }
10997       else if (!mips_big_got && HAVE_NEWABI)
10998         {
10999           int add_breg_early = 0;
11000
11001           /* If this is a reference to an external, and there is no
11002              constant, or local symbol (*), with or without a
11003              constant, we want
11004                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11005              or for lca or if tempreg is PIC_CALL_REG
11006                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
11007
11008              If we have a small constant, and this is a reference to
11009              an external symbol, we want
11010                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11011                addiu    $tempreg,$tempreg,<constant>
11012
11013              If we have a large constant, and this is a reference to
11014              an external symbol, we want
11015                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11016                lui      $at,<hiconstant>
11017                addiu    $at,$at,<loconstant>
11018                addu     $tempreg,$tempreg,$at
11019
11020              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
11021              local symbols, even though it introduces an additional
11022              instruction.  */
11023
11024           if (offset_expr.X_add_number)
11025             {
11026               expr1.X_add_number = offset_expr.X_add_number;
11027               offset_expr.X_add_number = 0;
11028
11029               relax_start (offset_expr.X_add_symbol);
11030               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11031                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11032
11033               if (expr1.X_add_number >= -0x8000
11034                   && expr1.X_add_number < 0x8000)
11035                 {
11036                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11037                                tempreg, tempreg, BFD_RELOC_LO16);
11038                 }
11039               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11040                 {
11041                   unsigned int dreg;
11042
11043                   /* If we are going to add in a base register, and the
11044                      target register and the base register are the same,
11045                      then we are using AT as a temporary register.  Since
11046                      we want to load the constant into AT, we add our
11047                      current AT (from the global offset table) and the
11048                      register into the register now, and pretend we were
11049                      not using a base register.  */
11050                   if (breg != op[0])
11051                     dreg = tempreg;
11052                   else
11053                     {
11054                       gas_assert (tempreg == AT);
11055                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11056                                    op[0], AT, breg);
11057                       dreg = op[0];
11058                       add_breg_early = 1;
11059                     }
11060
11061                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11062                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11063                                dreg, dreg, AT);
11064
11065                   used_at = 1;
11066                 }
11067               else
11068                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11069
11070               relax_switch ();
11071               offset_expr.X_add_number = expr1.X_add_number;
11072
11073               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11074                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11075               if (add_breg_early)
11076                 {
11077                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11078                                op[0], tempreg, breg);
11079                   breg = 0;
11080                   tempreg = op[0];
11081                 }
11082               relax_end ();
11083             }
11084           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
11085             {
11086               relax_start (offset_expr.X_add_symbol);
11087               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11088                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
11089               relax_switch ();
11090               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11091                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11092               relax_end ();
11093             }
11094           else
11095             {
11096               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11097                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11098             }
11099         }
11100       else if (mips_big_got && !HAVE_NEWABI)
11101         {
11102           int gpdelay;
11103           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11104           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11105           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11106
11107           /* This is the large GOT case.  If this is a reference to an
11108              external symbol, and there is no constant, we want
11109                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11110                addu     $tempreg,$tempreg,$gp
11111                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11112              or for lca or if tempreg is PIC_CALL_REG
11113                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11114                addu     $tempreg,$tempreg,$gp
11115                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11116              For a local symbol, we want
11117                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11118                nop
11119                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11120
11121              If we have a small constant, and this is a reference to
11122              an external symbol, we want
11123                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11124                addu     $tempreg,$tempreg,$gp
11125                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11126                nop
11127                addiu    $tempreg,$tempreg,<constant>
11128              For a local symbol, we want
11129                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11130                nop
11131                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
11132
11133              If we have a large constant, and this is a reference to
11134              an external symbol, we want
11135                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11136                addu     $tempreg,$tempreg,$gp
11137                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11138                lui      $at,<hiconstant>
11139                addiu    $at,$at,<loconstant>
11140                addu     $tempreg,$tempreg,$at
11141              For a local symbol, we want
11142                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11143                lui      $at,<hiconstant>
11144                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
11145                addu     $tempreg,$tempreg,$at
11146           */
11147
11148           expr1.X_add_number = offset_expr.X_add_number;
11149           offset_expr.X_add_number = 0;
11150           relax_start (offset_expr.X_add_symbol);
11151           gpdelay = reg_needs_delay (mips_gp_register);
11152           if (expr1.X_add_number == 0 && breg == 0
11153               && (call || tempreg == PIC_CALL_REG))
11154             {
11155               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11156               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11157             }
11158           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11159           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11160                        tempreg, tempreg, mips_gp_register);
11161           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11162                        tempreg, lw_reloc_type, tempreg);
11163           if (expr1.X_add_number == 0)
11164             {
11165               if (breg != 0)
11166                 {
11167                   /* We're going to put in an addu instruction using
11168                      tempreg, so we may as well insert the nop right
11169                      now.  */
11170                   load_delay_nop ();
11171                 }
11172             }
11173           else if (expr1.X_add_number >= -0x8000
11174                    && expr1.X_add_number < 0x8000)
11175             {
11176               load_delay_nop ();
11177               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11178                            tempreg, tempreg, BFD_RELOC_LO16);
11179             }
11180           else
11181             {
11182               unsigned int dreg;
11183
11184               /* If we are going to add in a base register, and the
11185                  target register and the base register are the same,
11186                  then we are using AT as a temporary register.  Since
11187                  we want to load the constant into AT, we add our
11188                  current AT (from the global offset table) and the
11189                  register into the register now, and pretend we were
11190                  not using a base register.  */
11191               if (breg != op[0])
11192                 dreg = tempreg;
11193               else
11194                 {
11195                   gas_assert (tempreg == AT);
11196                   load_delay_nop ();
11197                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11198                                op[0], AT, breg);
11199                   dreg = op[0];
11200                 }
11201
11202               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11203               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11204
11205               used_at = 1;
11206             }
11207           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11208           relax_switch ();
11209
11210           if (gpdelay)
11211             {
11212               /* This is needed because this instruction uses $gp, but
11213                  the first instruction on the main stream does not.  */
11214               macro_build (NULL, "nop", "");
11215             }
11216
11217           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11218                        local_reloc_type, mips_gp_register);
11219           if (expr1.X_add_number >= -0x8000
11220               && expr1.X_add_number < 0x8000)
11221             {
11222               load_delay_nop ();
11223               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11224                            tempreg, tempreg, BFD_RELOC_LO16);
11225               /* FIXME: If add_number is 0, and there was no base
11226                  register, the external symbol case ended with a load,
11227                  so if the symbol turns out to not be external, and
11228                  the next instruction uses tempreg, an unnecessary nop
11229                  will be inserted.  */
11230             }
11231           else
11232             {
11233               if (breg == op[0])
11234                 {
11235                   /* We must add in the base register now, as in the
11236                      external symbol case.  */
11237                   gas_assert (tempreg == AT);
11238                   load_delay_nop ();
11239                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11240                                op[0], AT, breg);
11241                   tempreg = op[0];
11242                   /* We set breg to 0 because we have arranged to add
11243                      it in in both cases.  */
11244                   breg = 0;
11245                 }
11246
11247               macro_build_lui (&expr1, AT);
11248               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11249                            AT, AT, BFD_RELOC_LO16);
11250               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11251                            tempreg, tempreg, AT);
11252               used_at = 1;
11253             }
11254           relax_end ();
11255         }
11256       else if (mips_big_got && HAVE_NEWABI)
11257         {
11258           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11259           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11260           int add_breg_early = 0;
11261
11262           /* This is the large GOT case.  If this is a reference to an
11263              external symbol, and there is no constant, we want
11264                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11265                add      $tempreg,$tempreg,$gp
11266                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11267              or for lca or if tempreg is PIC_CALL_REG
11268                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11269                add      $tempreg,$tempreg,$gp
11270                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11271
11272              If we have a small constant, and this is a reference to
11273              an external symbol, we want
11274                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11275                add      $tempreg,$tempreg,$gp
11276                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11277                addi     $tempreg,$tempreg,<constant>
11278
11279              If we have a large constant, and this is a reference to
11280              an external symbol, we want
11281                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11282                addu     $tempreg,$tempreg,$gp
11283                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11284                lui      $at,<hiconstant>
11285                addi     $at,$at,<loconstant>
11286                add      $tempreg,$tempreg,$at
11287
11288              If we have NewABI, and we know it's a local symbol, we want
11289                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
11290                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
11291              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11292
11293           relax_start (offset_expr.X_add_symbol);
11294
11295           expr1.X_add_number = offset_expr.X_add_number;
11296           offset_expr.X_add_number = 0;
11297
11298           if (expr1.X_add_number == 0 && breg == 0
11299               && (call || tempreg == PIC_CALL_REG))
11300             {
11301               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11302               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11303             }
11304           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11305           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11306                        tempreg, tempreg, mips_gp_register);
11307           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11308                        tempreg, lw_reloc_type, tempreg);
11309
11310           if (expr1.X_add_number == 0)
11311             ;
11312           else if (expr1.X_add_number >= -0x8000
11313                    && expr1.X_add_number < 0x8000)
11314             {
11315               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11316                            tempreg, tempreg, BFD_RELOC_LO16);
11317             }
11318           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11319             {
11320               unsigned int dreg;
11321
11322               /* If we are going to add in a base register, and the
11323                  target register and the base register are the same,
11324                  then we are using AT as a temporary register.  Since
11325                  we want to load the constant into AT, we add our
11326                  current AT (from the global offset table) and the
11327                  register into the register now, and pretend we were
11328                  not using a base register.  */
11329               if (breg != op[0])
11330                 dreg = tempreg;
11331               else
11332                 {
11333                   gas_assert (tempreg == AT);
11334                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11335                                op[0], AT, breg);
11336                   dreg = op[0];
11337                   add_breg_early = 1;
11338                 }
11339
11340               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11341               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11342
11343               used_at = 1;
11344             }
11345           else
11346             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11347
11348           relax_switch ();
11349           offset_expr.X_add_number = expr1.X_add_number;
11350           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11351                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11352           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11353                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
11354           if (add_breg_early)
11355             {
11356               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11357                            op[0], tempreg, breg);
11358               breg = 0;
11359               tempreg = op[0];
11360             }
11361           relax_end ();
11362         }
11363       else
11364         abort ();
11365
11366       if (breg != 0)
11367         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11368       break;
11369
11370     case M_MSGSND:
11371       gas_assert (!mips_opts.micromips);
11372       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11373       break;
11374
11375     case M_MSGLD:
11376       gas_assert (!mips_opts.micromips);
11377       macro_build (NULL, "c2", "C", 0x02);
11378       break;
11379
11380     case M_MSGLD_T:
11381       gas_assert (!mips_opts.micromips);
11382       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11383       break;
11384
11385     case M_MSGWAIT:
11386       gas_assert (!mips_opts.micromips);
11387       macro_build (NULL, "c2", "C", 3);
11388       break;
11389
11390     case M_MSGWAIT_T:
11391       gas_assert (!mips_opts.micromips);
11392       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11393       break;
11394
11395     case M_J_A:
11396       /* The j instruction may not be used in PIC code, since it
11397          requires an absolute address.  We convert it to a b
11398          instruction.  */
11399       if (mips_pic == NO_PIC)
11400         macro_build (&offset_expr, "j", "a");
11401       else
11402         macro_build (&offset_expr, "b", "p");
11403       break;
11404
11405       /* The jal instructions must be handled as macros because when
11406          generating PIC code they expand to multi-instruction
11407          sequences.  Normally they are simple instructions.  */
11408     case M_JALS_1:
11409       op[1] = op[0];
11410       op[0] = RA;
11411       /* Fall through.  */
11412     case M_JALS_2:
11413       gas_assert (mips_opts.micromips);
11414       if (mips_opts.insn32)
11415         {
11416           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11417           break;
11418         }
11419       jals = 1;
11420       goto jal;
11421     case M_JAL_1:
11422       op[1] = op[0];
11423       op[0] = RA;
11424       /* Fall through.  */
11425     case M_JAL_2:
11426     jal:
11427       if (mips_pic == NO_PIC)
11428         {
11429           s = jals ? "jalrs" : "jalr";
11430           if (mips_opts.micromips
11431               && !mips_opts.insn32
11432               && op[0] == RA
11433               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11434             macro_build (NULL, s, "mj", op[1]);
11435           else
11436             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11437         }
11438       else
11439         {
11440           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11441                            && mips_cprestore_offset >= 0);
11442
11443           if (op[1] != PIC_CALL_REG)
11444             as_warn (_("MIPS PIC call to register other than $25"));
11445
11446           s = ((mips_opts.micromips
11447                 && !mips_opts.insn32
11448                 && (!mips_opts.noreorder || cprestore))
11449                ? "jalrs" : "jalr");
11450           if (mips_opts.micromips
11451               && !mips_opts.insn32
11452               && op[0] == RA
11453               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11454             macro_build (NULL, s, "mj", op[1]);
11455           else
11456             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11457           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11458             {
11459               if (mips_cprestore_offset < 0)
11460                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11461               else
11462                 {
11463                   if (!mips_frame_reg_valid)
11464                     {
11465                       as_warn (_("no .frame pseudo-op used in PIC code"));
11466                       /* Quiet this warning.  */
11467                       mips_frame_reg_valid = 1;
11468                     }
11469                   if (!mips_cprestore_valid)
11470                     {
11471                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11472                       /* Quiet this warning.  */
11473                       mips_cprestore_valid = 1;
11474                     }
11475                   if (mips_opts.noreorder)
11476                     macro_build (NULL, "nop", "");
11477                   expr1.X_add_number = mips_cprestore_offset;
11478                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11479                                                 mips_gp_register,
11480                                                 mips_frame_reg,
11481                                                 HAVE_64BIT_ADDRESSES);
11482                 }
11483             }
11484         }
11485
11486       break;
11487
11488     case M_JALS_A:
11489       gas_assert (mips_opts.micromips);
11490       if (mips_opts.insn32)
11491         {
11492           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11493           break;
11494         }
11495       jals = 1;
11496       /* Fall through.  */
11497     case M_JAL_A:
11498       if (mips_pic == NO_PIC)
11499         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11500       else if (mips_pic == SVR4_PIC)
11501         {
11502           /* If this is a reference to an external symbol, and we are
11503              using a small GOT, we want
11504                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11505                nop
11506                jalr     $ra,$25
11507                nop
11508                lw       $gp,cprestore($sp)
11509              The cprestore value is set using the .cprestore
11510              pseudo-op.  If we are using a big GOT, we want
11511                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11512                addu     $25,$25,$gp
11513                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11514                nop
11515                jalr     $ra,$25
11516                nop
11517                lw       $gp,cprestore($sp)
11518              If the symbol is not external, we want
11519                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11520                nop
11521                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11522                jalr     $ra,$25
11523                nop
11524                lw $gp,cprestore($sp)
11525
11526              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11527              sequences above, minus nops, unless the symbol is local,
11528              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11529              GOT_DISP.  */
11530           if (HAVE_NEWABI)
11531             {
11532               if (!mips_big_got)
11533                 {
11534                   relax_start (offset_expr.X_add_symbol);
11535                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11536                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11537                                mips_gp_register);
11538                   relax_switch ();
11539                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11540                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11541                                mips_gp_register);
11542                   relax_end ();
11543                 }
11544               else
11545                 {
11546                   relax_start (offset_expr.X_add_symbol);
11547                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11548                                BFD_RELOC_MIPS_CALL_HI16);
11549                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11550                                PIC_CALL_REG, mips_gp_register);
11551                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11552                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11553                                PIC_CALL_REG);
11554                   relax_switch ();
11555                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11556                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11557                                mips_gp_register);
11558                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11559                                PIC_CALL_REG, PIC_CALL_REG,
11560                                BFD_RELOC_MIPS_GOT_OFST);
11561                   relax_end ();
11562                 }
11563
11564               macro_build_jalr (&offset_expr, 0);
11565             }
11566           else
11567             {
11568               relax_start (offset_expr.X_add_symbol);
11569               if (!mips_big_got)
11570                 {
11571                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11572                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11573                                mips_gp_register);
11574                   load_delay_nop ();
11575                   relax_switch ();
11576                 }
11577               else
11578                 {
11579                   int gpdelay;
11580
11581                   gpdelay = reg_needs_delay (mips_gp_register);
11582                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11583                                BFD_RELOC_MIPS_CALL_HI16);
11584                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11585                                PIC_CALL_REG, mips_gp_register);
11586                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11587                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11588                                PIC_CALL_REG);
11589                   load_delay_nop ();
11590                   relax_switch ();
11591                   if (gpdelay)
11592                     macro_build (NULL, "nop", "");
11593                 }
11594               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11595                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11596                            mips_gp_register);
11597               load_delay_nop ();
11598               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11599                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11600               relax_end ();
11601               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11602
11603               if (mips_cprestore_offset < 0)
11604                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11605               else
11606                 {
11607                   if (!mips_frame_reg_valid)
11608                     {
11609                       as_warn (_("no .frame pseudo-op used in PIC code"));
11610                       /* Quiet this warning.  */
11611                       mips_frame_reg_valid = 1;
11612                     }
11613                   if (!mips_cprestore_valid)
11614                     {
11615                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11616                       /* Quiet this warning.  */
11617                       mips_cprestore_valid = 1;
11618                     }
11619                   if (mips_opts.noreorder)
11620                     macro_build (NULL, "nop", "");
11621                   expr1.X_add_number = mips_cprestore_offset;
11622                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11623                                                 mips_gp_register,
11624                                                 mips_frame_reg,
11625                                                 HAVE_64BIT_ADDRESSES);
11626                 }
11627             }
11628         }
11629       else if (mips_pic == VXWORKS_PIC)
11630         as_bad (_("non-PIC jump used in PIC library"));
11631       else
11632         abort ();
11633
11634       break;
11635
11636     case M_LBUE_AB:
11637       s = "lbue";
11638       fmt = "t,+j(b)";
11639       offbits = 9;
11640       goto ld_st;
11641     case M_LHUE_AB:
11642       s = "lhue";
11643       fmt = "t,+j(b)";
11644       offbits = 9;
11645       goto ld_st;
11646     case M_LBE_AB:
11647       s = "lbe";
11648       fmt = "t,+j(b)";
11649       offbits = 9;
11650       goto ld_st;
11651     case M_LHE_AB:
11652       s = "lhe";
11653       fmt = "t,+j(b)";
11654       offbits = 9;
11655       goto ld_st;
11656     case M_LLE_AB:
11657       s = "lle";
11658       fmt = "t,+j(b)";
11659       offbits = 9;
11660       goto ld_st;
11661     case M_LWE_AB:
11662       s = "lwe";
11663       fmt = "t,+j(b)";
11664       offbits = 9;
11665       goto ld_st;
11666     case M_LWLE_AB:
11667       s = "lwle";
11668       fmt = "t,+j(b)";
11669       offbits = 9;
11670       goto ld_st;
11671     case M_LWRE_AB:
11672       s = "lwre";
11673       fmt = "t,+j(b)";
11674       offbits = 9;
11675       goto ld_st;
11676     case M_SBE_AB:
11677       s = "sbe";
11678       fmt = "t,+j(b)";
11679       offbits = 9;
11680       goto ld_st;
11681     case M_SCE_AB:
11682       s = "sce";
11683       fmt = "t,+j(b)";
11684       offbits = 9;
11685       goto ld_st;
11686     case M_SHE_AB:
11687       s = "she";
11688       fmt = "t,+j(b)";
11689       offbits = 9;
11690       goto ld_st;
11691     case M_SWE_AB:
11692       s = "swe";
11693       fmt = "t,+j(b)";
11694       offbits = 9;
11695       goto ld_st;
11696     case M_SWLE_AB:
11697       s = "swle";
11698       fmt = "t,+j(b)";
11699       offbits = 9;
11700       goto ld_st;
11701     case M_SWRE_AB:
11702       s = "swre";
11703       fmt = "t,+j(b)";
11704       offbits = 9;
11705       goto ld_st;
11706     case M_ACLR_AB:
11707       s = "aclr";
11708       fmt = "\\,~(b)";
11709       offbits = 12;
11710       goto ld_st;
11711     case M_ASET_AB:
11712       s = "aset";
11713       fmt = "\\,~(b)";
11714       offbits = 12;
11715       goto ld_st;
11716     case M_LB_AB:
11717       s = "lb";
11718       fmt = "t,o(b)";
11719       goto ld;
11720     case M_LBU_AB:
11721       s = "lbu";
11722       fmt = "t,o(b)";
11723       goto ld;
11724     case M_LH_AB:
11725       s = "lh";
11726       fmt = "t,o(b)";
11727       goto ld;
11728     case M_LHU_AB:
11729       s = "lhu";
11730       fmt = "t,o(b)";
11731       goto ld;
11732     case M_LW_AB:
11733       s = "lw";
11734       fmt = "t,o(b)";
11735       goto ld;
11736     case M_LWC0_AB:
11737       gas_assert (!mips_opts.micromips);
11738       s = "lwc0";
11739       fmt = "E,o(b)";
11740       /* Itbl support may require additional care here.  */
11741       coproc = 1;
11742       goto ld_st;
11743     case M_LWC1_AB:
11744       s = "lwc1";
11745       fmt = "T,o(b)";
11746       /* Itbl support may require additional care here.  */
11747       coproc = 1;
11748       goto ld_st;
11749     case M_LWC2_AB:
11750       s = "lwc2";
11751       fmt = COP12_FMT;
11752       offbits = (mips_opts.micromips ? 12
11753                  : ISA_IS_R6 (mips_opts.isa) ? 11
11754                  : 16);
11755       /* Itbl support may require additional care here.  */
11756       coproc = 1;
11757       goto ld_st;
11758     case M_LWC3_AB:
11759       gas_assert (!mips_opts.micromips);
11760       s = "lwc3";
11761       fmt = "E,o(b)";
11762       /* Itbl support may require additional care here.  */
11763       coproc = 1;
11764       goto ld_st;
11765     case M_LWL_AB:
11766       s = "lwl";
11767       fmt = MEM12_FMT;
11768       offbits = (mips_opts.micromips ? 12 : 16);
11769       goto ld_st;
11770     case M_LWR_AB:
11771       s = "lwr";
11772       fmt = MEM12_FMT;
11773       offbits = (mips_opts.micromips ? 12 : 16);
11774       goto ld_st;
11775     case M_LDC1_AB:
11776       s = "ldc1";
11777       fmt = "T,o(b)";
11778       /* Itbl support may require additional care here.  */
11779       coproc = 1;
11780       goto ld_st;
11781     case M_LDC2_AB:
11782       s = "ldc2";
11783       fmt = COP12_FMT;
11784       offbits = (mips_opts.micromips ? 12
11785                  : ISA_IS_R6 (mips_opts.isa) ? 11
11786                  : 16);
11787       /* Itbl support may require additional care here.  */
11788       coproc = 1;
11789       goto ld_st;
11790     case M_LQC2_AB:
11791       s = "lqc2";
11792       fmt = "+7,o(b)";
11793       /* Itbl support may require additional care here.  */
11794       coproc = 1;
11795       goto ld_st;
11796     case M_LDC3_AB:
11797       s = "ldc3";
11798       fmt = "E,o(b)";
11799       /* Itbl support may require additional care here.  */
11800       coproc = 1;
11801       goto ld_st;
11802     case M_LDL_AB:
11803       s = "ldl";
11804       fmt = MEM12_FMT;
11805       offbits = (mips_opts.micromips ? 12 : 16);
11806       goto ld_st;
11807     case M_LDR_AB:
11808       s = "ldr";
11809       fmt = MEM12_FMT;
11810       offbits = (mips_opts.micromips ? 12 : 16);
11811       goto ld_st;
11812     case M_LL_AB:
11813       s = "ll";
11814       fmt = LL_SC_FMT;
11815       offbits = (mips_opts.micromips ? 12
11816                  : ISA_IS_R6 (mips_opts.isa) ? 9
11817                  : 16);
11818       goto ld;
11819     case M_LLD_AB:
11820       s = "lld";
11821       fmt = LL_SC_FMT;
11822       offbits = (mips_opts.micromips ? 12
11823                  : ISA_IS_R6 (mips_opts.isa) ? 9
11824                  : 16);
11825       goto ld;
11826     case M_LWU_AB:
11827       s = "lwu";
11828       fmt = MEM12_FMT;
11829       offbits = (mips_opts.micromips ? 12 : 16);
11830       goto ld;
11831     case M_LWP_AB:
11832       gas_assert (mips_opts.micromips);
11833       s = "lwp";
11834       fmt = "t,~(b)";
11835       offbits = 12;
11836       lp = 1;
11837       goto ld;
11838     case M_LDP_AB:
11839       gas_assert (mips_opts.micromips);
11840       s = "ldp";
11841       fmt = "t,~(b)";
11842       offbits = 12;
11843       lp = 1;
11844       goto ld;
11845     case M_LWM_AB:
11846       gas_assert (mips_opts.micromips);
11847       s = "lwm";
11848       fmt = "n,~(b)";
11849       offbits = 12;
11850       goto ld_st;
11851     case M_LDM_AB:
11852       gas_assert (mips_opts.micromips);
11853       s = "ldm";
11854       fmt = "n,~(b)";
11855       offbits = 12;
11856       goto ld_st;
11857
11858     ld:
11859       /* We don't want to use $0 as tempreg.  */
11860       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11861         goto ld_st;
11862       else
11863         tempreg = op[0] + lp;
11864       goto ld_noat;
11865
11866     case M_SB_AB:
11867       s = "sb";
11868       fmt = "t,o(b)";
11869       goto ld_st;
11870     case M_SH_AB:
11871       s = "sh";
11872       fmt = "t,o(b)";
11873       goto ld_st;
11874     case M_SW_AB:
11875       s = "sw";
11876       fmt = "t,o(b)";
11877       goto ld_st;
11878     case M_SWC0_AB:
11879       gas_assert (!mips_opts.micromips);
11880       s = "swc0";
11881       fmt = "E,o(b)";
11882       /* Itbl support may require additional care here.  */
11883       coproc = 1;
11884       goto ld_st;
11885     case M_SWC1_AB:
11886       s = "swc1";
11887       fmt = "T,o(b)";
11888       /* Itbl support may require additional care here.  */
11889       coproc = 1;
11890       goto ld_st;
11891     case M_SWC2_AB:
11892       s = "swc2";
11893       fmt = COP12_FMT;
11894       offbits = (mips_opts.micromips ? 12
11895                  : ISA_IS_R6 (mips_opts.isa) ? 11
11896                  : 16);
11897       /* Itbl support may require additional care here.  */
11898       coproc = 1;
11899       goto ld_st;
11900     case M_SWC3_AB:
11901       gas_assert (!mips_opts.micromips);
11902       s = "swc3";
11903       fmt = "E,o(b)";
11904       /* Itbl support may require additional care here.  */
11905       coproc = 1;
11906       goto ld_st;
11907     case M_SWL_AB:
11908       s = "swl";
11909       fmt = MEM12_FMT;
11910       offbits = (mips_opts.micromips ? 12 : 16);
11911       goto ld_st;
11912     case M_SWR_AB:
11913       s = "swr";
11914       fmt = MEM12_FMT;
11915       offbits = (mips_opts.micromips ? 12 : 16);
11916       goto ld_st;
11917     case M_SC_AB:
11918       s = "sc";
11919       fmt = LL_SC_FMT;
11920       offbits = (mips_opts.micromips ? 12
11921                  : ISA_IS_R6 (mips_opts.isa) ? 9
11922                  : 16);
11923       goto ld_st;
11924     case M_SCD_AB:
11925       s = "scd";
11926       fmt = LL_SC_FMT;
11927       offbits = (mips_opts.micromips ? 12
11928                  : ISA_IS_R6 (mips_opts.isa) ? 9
11929                  : 16);
11930       goto ld_st;
11931     case M_CACHE_AB:
11932       s = "cache";
11933       fmt = (mips_opts.micromips ? "k,~(b)"
11934              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11935              : "k,o(b)");
11936       offbits = (mips_opts.micromips ? 12
11937                  : ISA_IS_R6 (mips_opts.isa) ? 9
11938                  : 16);
11939       goto ld_st;
11940     case M_CACHEE_AB:
11941       s = "cachee";
11942       fmt = "k,+j(b)";
11943       offbits = 9;
11944       goto ld_st;
11945     case M_PREF_AB:
11946       s = "pref";
11947       fmt = (mips_opts.micromips ? "k,~(b)"
11948              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11949              : "k,o(b)");
11950       offbits = (mips_opts.micromips ? 12
11951                  : ISA_IS_R6 (mips_opts.isa) ? 9
11952                  : 16);
11953       goto ld_st;
11954     case M_PREFE_AB:
11955       s = "prefe";
11956       fmt = "k,+j(b)";
11957       offbits = 9;
11958       goto ld_st;
11959     case M_SDC1_AB:
11960       s = "sdc1";
11961       fmt = "T,o(b)";
11962       coproc = 1;
11963       /* Itbl support may require additional care here.  */
11964       goto ld_st;
11965     case M_SDC2_AB:
11966       s = "sdc2";
11967       fmt = COP12_FMT;
11968       offbits = (mips_opts.micromips ? 12
11969                  : ISA_IS_R6 (mips_opts.isa) ? 11
11970                  : 16);
11971       /* Itbl support may require additional care here.  */
11972       coproc = 1;
11973       goto ld_st;
11974     case M_SQC2_AB:
11975       s = "sqc2";
11976       fmt = "+7,o(b)";
11977       /* Itbl support may require additional care here.  */
11978       coproc = 1;
11979       goto ld_st;
11980     case M_SDC3_AB:
11981       gas_assert (!mips_opts.micromips);
11982       s = "sdc3";
11983       fmt = "E,o(b)";
11984       /* Itbl support may require additional care here.  */
11985       coproc = 1;
11986       goto ld_st;
11987     case M_SDL_AB:
11988       s = "sdl";
11989       fmt = MEM12_FMT;
11990       offbits = (mips_opts.micromips ? 12 : 16);
11991       goto ld_st;
11992     case M_SDR_AB:
11993       s = "sdr";
11994       fmt = MEM12_FMT;
11995       offbits = (mips_opts.micromips ? 12 : 16);
11996       goto ld_st;
11997     case M_SWP_AB:
11998       gas_assert (mips_opts.micromips);
11999       s = "swp";
12000       fmt = "t,~(b)";
12001       offbits = 12;
12002       goto ld_st;
12003     case M_SDP_AB:
12004       gas_assert (mips_opts.micromips);
12005       s = "sdp";
12006       fmt = "t,~(b)";
12007       offbits = 12;
12008       goto ld_st;
12009     case M_SWM_AB:
12010       gas_assert (mips_opts.micromips);
12011       s = "swm";
12012       fmt = "n,~(b)";
12013       offbits = 12;
12014       goto ld_st;
12015     case M_SDM_AB:
12016       gas_assert (mips_opts.micromips);
12017       s = "sdm";
12018       fmt = "n,~(b)";
12019       offbits = 12;
12020
12021     ld_st:
12022       tempreg = AT;
12023     ld_noat:
12024       breg = op[2];
12025       if (small_offset_p (0, align, 16))
12026         {
12027           /* The first case exists for M_LD_AB and M_SD_AB, which are
12028              macros for o32 but which should act like normal instructions
12029              otherwise.  */
12030           if (offbits == 16)
12031             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
12032                          offset_reloc[1], offset_reloc[2], breg);
12033           else if (small_offset_p (0, align, offbits))
12034             {
12035               if (offbits == 0)
12036                 macro_build (NULL, s, fmt, op[0], breg);
12037               else
12038                 macro_build (NULL, s, fmt, op[0],
12039                              (int) offset_expr.X_add_number, breg);
12040             }
12041           else
12042             {
12043               if (tempreg == AT)
12044                 used_at = 1;
12045               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
12046                            tempreg, breg, -1, offset_reloc[0],
12047                            offset_reloc[1], offset_reloc[2]);
12048               if (offbits == 0)
12049                 macro_build (NULL, s, fmt, op[0], tempreg);
12050               else
12051                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
12052             }
12053           break;
12054         }
12055
12056       if (tempreg == AT)
12057         used_at = 1;
12058
12059       if (offset_expr.X_op != O_constant
12060           && offset_expr.X_op != O_symbol)
12061         {
12062           as_bad (_("expression too complex"));
12063           offset_expr.X_op = O_constant;
12064         }
12065
12066       if (HAVE_32BIT_ADDRESSES
12067           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12068         {
12069           char value [32];
12070
12071           sprintf_vma (value, offset_expr.X_add_number);
12072           as_bad (_("number (0x%s) larger than 32 bits"), value);
12073         }
12074
12075       /* A constant expression in PIC code can be handled just as it
12076          is in non PIC code.  */
12077       if (offset_expr.X_op == O_constant)
12078         {
12079           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
12080                                                  offbits == 0 ? 16 : offbits);
12081           offset_expr.X_add_number -= expr1.X_add_number;
12082
12083           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
12084           if (breg != 0)
12085             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12086                          tempreg, tempreg, breg);
12087           if (offbits == 0)
12088             {
12089               if (offset_expr.X_add_number != 0)
12090                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
12091                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
12092               macro_build (NULL, s, fmt, op[0], tempreg);
12093             }
12094           else if (offbits == 16)
12095             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12096           else
12097             macro_build (NULL, s, fmt, op[0],
12098                          (int) offset_expr.X_add_number, tempreg);
12099         }
12100       else if (offbits != 16)
12101         {
12102           /* The offset field is too narrow to be used for a low-part
12103              relocation, so load the whole address into the auxiliary
12104              register.  */
12105           load_address (tempreg, &offset_expr, &used_at);
12106           if (breg != 0)
12107             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12108                          tempreg, tempreg, breg);
12109           if (offbits == 0)
12110             macro_build (NULL, s, fmt, op[0], tempreg);
12111           else
12112             macro_build (NULL, s, fmt, op[0], 0, tempreg);
12113         }
12114       else if (mips_pic == NO_PIC)
12115         {
12116           /* If this is a reference to a GP relative symbol, and there
12117              is no base register, we want
12118                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12119              Otherwise, if there is no base register, we want
12120                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12121                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12122              If we have a constant, we need two instructions anyhow,
12123              so we always use the latter form.
12124
12125              If we have a base register, and this is a reference to a
12126              GP relative symbol, we want
12127                addu     $tempreg,$breg,$gp
12128                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
12129              Otherwise we want
12130                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12131                addu     $tempreg,$tempreg,$breg
12132                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12133              With a constant we always use the latter case.
12134
12135              With 64bit address space and no base register and $at usable,
12136              we want
12137                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12138                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12139                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12140                dsll32   $tempreg,0
12141                daddu    $tempreg,$at
12142                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12143              If we have a base register, we want
12144                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12145                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12146                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12147                daddu    $at,$breg
12148                dsll32   $tempreg,0
12149                daddu    $tempreg,$at
12150                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12151
12152              Without $at we can't generate the optimal path for superscalar
12153              processors here since this would require two temporary registers.
12154                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12155                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12156                dsll     $tempreg,16
12157                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12158                dsll     $tempreg,16
12159                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12160              If we have a base register, we want
12161                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12162                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12163                dsll     $tempreg,16
12164                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12165                dsll     $tempreg,16
12166                daddu    $tempreg,$tempreg,$breg
12167                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12168
12169              For GP relative symbols in 64bit address space we can use
12170              the same sequence as in 32bit address space.  */
12171           if (HAVE_64BIT_SYMBOLS)
12172             {
12173               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12174                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12175                 {
12176                   relax_start (offset_expr.X_add_symbol);
12177                   if (breg == 0)
12178                     {
12179                       macro_build (&offset_expr, s, fmt, op[0],
12180                                    BFD_RELOC_GPREL16, mips_gp_register);
12181                     }
12182                   else
12183                     {
12184                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12185                                    tempreg, breg, mips_gp_register);
12186                       macro_build (&offset_expr, s, fmt, op[0],
12187                                    BFD_RELOC_GPREL16, tempreg);
12188                     }
12189                   relax_switch ();
12190                 }
12191
12192               if (used_at == 0 && mips_opts.at)
12193                 {
12194                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12195                                BFD_RELOC_MIPS_HIGHEST);
12196                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
12197                                BFD_RELOC_HI16_S);
12198                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12199                                tempreg, BFD_RELOC_MIPS_HIGHER);
12200                   if (breg != 0)
12201                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12202                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12203                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12204                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12205                                tempreg);
12206                   used_at = 1;
12207                 }
12208               else
12209                 {
12210                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12211                                BFD_RELOC_MIPS_HIGHEST);
12212                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12213                                tempreg, BFD_RELOC_MIPS_HIGHER);
12214                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12215                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12216                                tempreg, BFD_RELOC_HI16_S);
12217                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12218                   if (breg != 0)
12219                     macro_build (NULL, "daddu", "d,v,t",
12220                                  tempreg, tempreg, breg);
12221                   macro_build (&offset_expr, s, fmt, op[0],
12222                                BFD_RELOC_LO16, tempreg);
12223                 }
12224
12225               if (mips_relax.sequence)
12226                 relax_end ();
12227               break;
12228             }
12229
12230           if (breg == 0)
12231             {
12232               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12233                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12234                 {
12235                   relax_start (offset_expr.X_add_symbol);
12236                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12237                                mips_gp_register);
12238                   relax_switch ();
12239                 }
12240               macro_build_lui (&offset_expr, tempreg);
12241               macro_build (&offset_expr, s, fmt, op[0],
12242                            BFD_RELOC_LO16, tempreg);
12243               if (mips_relax.sequence)
12244                 relax_end ();
12245             }
12246           else
12247             {
12248               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12249                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12250                 {
12251                   relax_start (offset_expr.X_add_symbol);
12252                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12253                                tempreg, breg, mips_gp_register);
12254                   macro_build (&offset_expr, s, fmt, op[0],
12255                                BFD_RELOC_GPREL16, tempreg);
12256                   relax_switch ();
12257                 }
12258               macro_build_lui (&offset_expr, tempreg);
12259               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12260                            tempreg, tempreg, breg);
12261               macro_build (&offset_expr, s, fmt, op[0],
12262                            BFD_RELOC_LO16, tempreg);
12263               if (mips_relax.sequence)
12264                 relax_end ();
12265             }
12266         }
12267       else if (!mips_big_got)
12268         {
12269           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12270
12271           /* If this is a reference to an external symbol, we want
12272                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12273                nop
12274                <op>     op[0],0($tempreg)
12275              Otherwise we want
12276                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12277                nop
12278                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12279                <op>     op[0],0($tempreg)
12280
12281              For NewABI, we want
12282                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12283                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12284
12285              If there is a base register, we add it to $tempreg before
12286              the <op>.  If there is a constant, we stick it in the
12287              <op> instruction.  We don't handle constants larger than
12288              16 bits, because we have no way to load the upper 16 bits
12289              (actually, we could handle them for the subset of cases
12290              in which we are not using $at).  */
12291           gas_assert (offset_expr.X_op == O_symbol);
12292           if (HAVE_NEWABI)
12293             {
12294               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12295                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12296               if (breg != 0)
12297                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12298                              tempreg, tempreg, breg);
12299               macro_build (&offset_expr, s, fmt, op[0],
12300                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
12301               break;
12302             }
12303           expr1.X_add_number = offset_expr.X_add_number;
12304           offset_expr.X_add_number = 0;
12305           if (expr1.X_add_number < -0x8000
12306               || expr1.X_add_number >= 0x8000)
12307             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12308           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12309                        lw_reloc_type, mips_gp_register);
12310           load_delay_nop ();
12311           relax_start (offset_expr.X_add_symbol);
12312           relax_switch ();
12313           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12314                        tempreg, BFD_RELOC_LO16);
12315           relax_end ();
12316           if (breg != 0)
12317             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12318                          tempreg, tempreg, breg);
12319           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12320         }
12321       else if (mips_big_got && !HAVE_NEWABI)
12322         {
12323           int gpdelay;
12324
12325           /* If this is a reference to an external symbol, we want
12326                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12327                addu     $tempreg,$tempreg,$gp
12328                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12329                <op>     op[0],0($tempreg)
12330              Otherwise we want
12331                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12332                nop
12333                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12334                <op>     op[0],0($tempreg)
12335              If there is a base register, we add it to $tempreg before
12336              the <op>.  If there is a constant, we stick it in the
12337              <op> instruction.  We don't handle constants larger than
12338              16 bits, because we have no way to load the upper 16 bits
12339              (actually, we could handle them for the subset of cases
12340              in which we are not using $at).  */
12341           gas_assert (offset_expr.X_op == O_symbol);
12342           expr1.X_add_number = offset_expr.X_add_number;
12343           offset_expr.X_add_number = 0;
12344           if (expr1.X_add_number < -0x8000
12345               || expr1.X_add_number >= 0x8000)
12346             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12347           gpdelay = reg_needs_delay (mips_gp_register);
12348           relax_start (offset_expr.X_add_symbol);
12349           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12350                        BFD_RELOC_MIPS_GOT_HI16);
12351           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12352                        mips_gp_register);
12353           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12354                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12355           relax_switch ();
12356           if (gpdelay)
12357             macro_build (NULL, "nop", "");
12358           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12359                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12360           load_delay_nop ();
12361           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12362                        tempreg, BFD_RELOC_LO16);
12363           relax_end ();
12364
12365           if (breg != 0)
12366             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12367                          tempreg, tempreg, breg);
12368           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12369         }
12370       else if (mips_big_got && HAVE_NEWABI)
12371         {
12372           /* If this is a reference to an external symbol, we want
12373                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12374                add      $tempreg,$tempreg,$gp
12375                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12376                <op>     op[0],<ofst>($tempreg)
12377              Otherwise, for local symbols, we want:
12378                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12379                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12380           gas_assert (offset_expr.X_op == O_symbol);
12381           expr1.X_add_number = offset_expr.X_add_number;
12382           offset_expr.X_add_number = 0;
12383           if (expr1.X_add_number < -0x8000
12384               || expr1.X_add_number >= 0x8000)
12385             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12386           relax_start (offset_expr.X_add_symbol);
12387           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12388                        BFD_RELOC_MIPS_GOT_HI16);
12389           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12390                        mips_gp_register);
12391           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12392                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12393           if (breg != 0)
12394             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12395                          tempreg, tempreg, breg);
12396           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12397
12398           relax_switch ();
12399           offset_expr.X_add_number = expr1.X_add_number;
12400           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12401                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12402           if (breg != 0)
12403             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12404                          tempreg, tempreg, breg);
12405           macro_build (&offset_expr, s, fmt, op[0],
12406                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12407           relax_end ();
12408         }
12409       else
12410         abort ();
12411
12412       break;
12413
12414     case M_JRADDIUSP:
12415       gas_assert (mips_opts.micromips);
12416       gas_assert (mips_opts.insn32);
12417       start_noreorder ();
12418       macro_build (NULL, "jr", "s", RA);
12419       expr1.X_add_number = op[0] << 2;
12420       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12421       end_noreorder ();
12422       break;
12423
12424     case M_JRC:
12425       gas_assert (mips_opts.micromips);
12426       gas_assert (mips_opts.insn32);
12427       macro_build (NULL, "jr", "s", op[0]);
12428       if (mips_opts.noreorder)
12429         macro_build (NULL, "nop", "");
12430       break;
12431
12432     case M_LI:
12433     case M_LI_S:
12434       load_register (op[0], &imm_expr, 0);
12435       break;
12436
12437     case M_DLI:
12438       load_register (op[0], &imm_expr, 1);
12439       break;
12440
12441     case M_LI_SS:
12442       if (imm_expr.X_op == O_constant)
12443         {
12444           used_at = 1;
12445           load_register (AT, &imm_expr, 0);
12446           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12447           break;
12448         }
12449       else
12450         {
12451           gas_assert (imm_expr.X_op == O_absent
12452                       && offset_expr.X_op == O_symbol
12453                       && strcmp (segment_name (S_GET_SEGMENT
12454                                                (offset_expr.X_add_symbol)),
12455                                  ".lit4") == 0
12456                       && offset_expr.X_add_number == 0);
12457           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12458                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12459           break;
12460         }
12461
12462     case M_LI_D:
12463       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12464          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12465          order 32 bits of the value and the low order 32 bits are either
12466          zero or in OFFSET_EXPR.  */
12467       if (imm_expr.X_op == O_constant)
12468         {
12469           if (GPR_SIZE == 64)
12470             load_register (op[0], &imm_expr, 1);
12471           else
12472             {
12473               int hreg, lreg;
12474
12475               if (target_big_endian)
12476                 {
12477                   hreg = op[0];
12478                   lreg = op[0] + 1;
12479                 }
12480               else
12481                 {
12482                   hreg = op[0] + 1;
12483                   lreg = op[0];
12484                 }
12485
12486               if (hreg <= 31)
12487                 load_register (hreg, &imm_expr, 0);
12488               if (lreg <= 31)
12489                 {
12490                   if (offset_expr.X_op == O_absent)
12491                     move_register (lreg, 0);
12492                   else
12493                     {
12494                       gas_assert (offset_expr.X_op == O_constant);
12495                       load_register (lreg, &offset_expr, 0);
12496                     }
12497                 }
12498             }
12499           break;
12500         }
12501       gas_assert (imm_expr.X_op == O_absent);
12502
12503       /* We know that sym is in the .rdata section.  First we get the
12504          upper 16 bits of the address.  */
12505       if (mips_pic == NO_PIC)
12506         {
12507           macro_build_lui (&offset_expr, AT);
12508           used_at = 1;
12509         }
12510       else
12511         {
12512           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12513                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12514           used_at = 1;
12515         }
12516
12517       /* Now we load the register(s).  */
12518       if (GPR_SIZE == 64)
12519         {
12520           used_at = 1;
12521           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12522                        BFD_RELOC_LO16, AT);
12523         }
12524       else
12525         {
12526           used_at = 1;
12527           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12528                        BFD_RELOC_LO16, AT);
12529           if (op[0] != RA)
12530             {
12531               /* FIXME: How in the world do we deal with the possible
12532                  overflow here?  */
12533               offset_expr.X_add_number += 4;
12534               macro_build (&offset_expr, "lw", "t,o(b)",
12535                            op[0] + 1, BFD_RELOC_LO16, AT);
12536             }
12537         }
12538       break;
12539
12540     case M_LI_DD:
12541       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12542          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12543          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12544          the value and the low order 32 bits are either zero or in
12545          OFFSET_EXPR.  */
12546       if (imm_expr.X_op == O_constant)
12547         {
12548           used_at = 1;
12549           load_register (AT, &imm_expr, FPR_SIZE == 64);
12550           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12551             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12552           else
12553             {
12554               if (ISA_HAS_MXHC1 (mips_opts.isa))
12555                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12556               else if (FPR_SIZE != 32)
12557                 as_bad (_("Unable to generate `%s' compliant code "
12558                           "without mthc1"),
12559                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12560               else
12561                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12562               if (offset_expr.X_op == O_absent)
12563                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12564               else
12565                 {
12566                   gas_assert (offset_expr.X_op == O_constant);
12567                   load_register (AT, &offset_expr, 0);
12568                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12569                 }
12570             }
12571           break;
12572         }
12573
12574       gas_assert (imm_expr.X_op == O_absent
12575                   && offset_expr.X_op == O_symbol
12576                   && offset_expr.X_add_number == 0);
12577       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12578       if (strcmp (s, ".lit8") == 0)
12579         {
12580           op[2] = mips_gp_register;
12581           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12582           offset_reloc[1] = BFD_RELOC_UNUSED;
12583           offset_reloc[2] = BFD_RELOC_UNUSED;
12584         }
12585       else
12586         {
12587           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12588           used_at = 1;
12589           if (mips_pic != NO_PIC)
12590             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12591                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12592           else
12593             {
12594               /* FIXME: This won't work for a 64 bit address.  */
12595               macro_build_lui (&offset_expr, AT);
12596             }
12597
12598           op[2] = AT;
12599           offset_reloc[0] = BFD_RELOC_LO16;
12600           offset_reloc[1] = BFD_RELOC_UNUSED;
12601           offset_reloc[2] = BFD_RELOC_UNUSED;
12602         }
12603       align = 8;
12604       /* Fall through */
12605
12606     case M_L_DAB:
12607       /*
12608        * The MIPS assembler seems to check for X_add_number not
12609        * being double aligned and generating:
12610        *        lui     at,%hi(foo+1)
12611        *        addu    at,at,v1
12612        *        addiu   at,at,%lo(foo+1)
12613        *        lwc1    f2,0(at)
12614        *        lwc1    f3,4(at)
12615        * But, the resulting address is the same after relocation so why
12616        * generate the extra instruction?
12617        */
12618       /* Itbl support may require additional care here.  */
12619       coproc = 1;
12620       fmt = "T,o(b)";
12621       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12622         {
12623           s = "ldc1";
12624           goto ld_st;
12625         }
12626       s = "lwc1";
12627       goto ldd_std;
12628
12629     case M_S_DAB:
12630       gas_assert (!mips_opts.micromips);
12631       /* Itbl support may require additional care here.  */
12632       coproc = 1;
12633       fmt = "T,o(b)";
12634       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12635         {
12636           s = "sdc1";
12637           goto ld_st;
12638         }
12639       s = "swc1";
12640       goto ldd_std;
12641
12642     case M_LQ_AB:
12643       fmt = "t,o(b)";
12644       s = "lq";
12645       goto ld;
12646
12647     case M_SQ_AB:
12648       fmt = "t,o(b)";
12649       s = "sq";
12650       goto ld_st;
12651
12652     case M_LD_AB:
12653       fmt = "t,o(b)";
12654       if (GPR_SIZE == 64)
12655         {
12656           s = "ld";
12657           goto ld;
12658         }
12659       s = "lw";
12660       goto ldd_std;
12661
12662     case M_SD_AB:
12663       fmt = "t,o(b)";
12664       if (GPR_SIZE == 64)
12665         {
12666           s = "sd";
12667           goto ld_st;
12668         }
12669       s = "sw";
12670
12671     ldd_std:
12672       /* Even on a big endian machine $fn comes before $fn+1.  We have
12673          to adjust when loading from memory.  We set coproc if we must
12674          load $fn+1 first.  */
12675       /* Itbl support may require additional care here.  */
12676       if (!target_big_endian)
12677         coproc = 0;
12678
12679       breg = op[2];
12680       if (small_offset_p (0, align, 16))
12681         {
12682           ep = &offset_expr;
12683           if (!small_offset_p (4, align, 16))
12684             {
12685               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12686                            -1, offset_reloc[0], offset_reloc[1],
12687                            offset_reloc[2]);
12688               expr1.X_add_number = 0;
12689               ep = &expr1;
12690               breg = AT;
12691               used_at = 1;
12692               offset_reloc[0] = BFD_RELOC_LO16;
12693               offset_reloc[1] = BFD_RELOC_UNUSED;
12694               offset_reloc[2] = BFD_RELOC_UNUSED;
12695             }
12696           if (strcmp (s, "lw") == 0 && op[0] == breg)
12697             {
12698               ep->X_add_number += 4;
12699               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12700                            offset_reloc[1], offset_reloc[2], breg);
12701               ep->X_add_number -= 4;
12702               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12703                            offset_reloc[1], offset_reloc[2], breg);
12704             }
12705           else
12706             {
12707               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12708                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12709                            breg);
12710               ep->X_add_number += 4;
12711               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12712                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12713                            breg);
12714             }
12715           break;
12716         }
12717
12718       if (offset_expr.X_op != O_symbol
12719           && offset_expr.X_op != O_constant)
12720         {
12721           as_bad (_("expression too complex"));
12722           offset_expr.X_op = O_constant;
12723         }
12724
12725       if (HAVE_32BIT_ADDRESSES
12726           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12727         {
12728           char value [32];
12729
12730           sprintf_vma (value, offset_expr.X_add_number);
12731           as_bad (_("number (0x%s) larger than 32 bits"), value);
12732         }
12733
12734       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12735         {
12736           /* If this is a reference to a GP relative symbol, we want
12737                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12738                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12739              If we have a base register, we use this
12740                addu     $at,$breg,$gp
12741                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12742                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12743              If this is not a GP relative symbol, we want
12744                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12745                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12746                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12747              If there is a base register, we add it to $at after the
12748              lui instruction.  If there is a constant, we always use
12749              the last case.  */
12750           if (offset_expr.X_op == O_symbol
12751               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12752               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12753             {
12754               relax_start (offset_expr.X_add_symbol);
12755               if (breg == 0)
12756                 {
12757                   tempreg = mips_gp_register;
12758                 }
12759               else
12760                 {
12761                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12762                                AT, breg, mips_gp_register);
12763                   tempreg = AT;
12764                   used_at = 1;
12765                 }
12766
12767               /* Itbl support may require additional care here.  */
12768               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12769                            BFD_RELOC_GPREL16, tempreg);
12770               offset_expr.X_add_number += 4;
12771
12772               /* Set mips_optimize to 2 to avoid inserting an
12773                  undesired nop.  */
12774               hold_mips_optimize = mips_optimize;
12775               mips_optimize = 2;
12776               /* Itbl support may require additional care here.  */
12777               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12778                            BFD_RELOC_GPREL16, tempreg);
12779               mips_optimize = hold_mips_optimize;
12780
12781               relax_switch ();
12782
12783               offset_expr.X_add_number -= 4;
12784             }
12785           used_at = 1;
12786           if (offset_high_part (offset_expr.X_add_number, 16)
12787               != offset_high_part (offset_expr.X_add_number + 4, 16))
12788             {
12789               load_address (AT, &offset_expr, &used_at);
12790               offset_expr.X_op = O_constant;
12791               offset_expr.X_add_number = 0;
12792             }
12793           else
12794             macro_build_lui (&offset_expr, AT);
12795           if (breg != 0)
12796             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12797           /* Itbl support may require additional care here.  */
12798           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12799                        BFD_RELOC_LO16, AT);
12800           /* FIXME: How do we handle overflow here?  */
12801           offset_expr.X_add_number += 4;
12802           /* Itbl support may require additional care here.  */
12803           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12804                        BFD_RELOC_LO16, AT);
12805           if (mips_relax.sequence)
12806             relax_end ();
12807         }
12808       else if (!mips_big_got)
12809         {
12810           /* If this is a reference to an external symbol, we want
12811                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12812                nop
12813                <op>     op[0],0($at)
12814                <op>     op[0]+1,4($at)
12815              Otherwise we want
12816                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12817                nop
12818                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12819                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12820              If there is a base register we add it to $at before the
12821              lwc1 instructions.  If there is a constant we include it
12822              in the lwc1 instructions.  */
12823           used_at = 1;
12824           expr1.X_add_number = offset_expr.X_add_number;
12825           if (expr1.X_add_number < -0x8000
12826               || expr1.X_add_number >= 0x8000 - 4)
12827             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12828           load_got_offset (AT, &offset_expr);
12829           load_delay_nop ();
12830           if (breg != 0)
12831             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12832
12833           /* Set mips_optimize to 2 to avoid inserting an undesired
12834              nop.  */
12835           hold_mips_optimize = mips_optimize;
12836           mips_optimize = 2;
12837
12838           /* Itbl support may require additional care here.  */
12839           relax_start (offset_expr.X_add_symbol);
12840           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12841                        BFD_RELOC_LO16, AT);
12842           expr1.X_add_number += 4;
12843           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12844                        BFD_RELOC_LO16, AT);
12845           relax_switch ();
12846           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12847                        BFD_RELOC_LO16, AT);
12848           offset_expr.X_add_number += 4;
12849           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12850                        BFD_RELOC_LO16, AT);
12851           relax_end ();
12852
12853           mips_optimize = hold_mips_optimize;
12854         }
12855       else if (mips_big_got)
12856         {
12857           int gpdelay;
12858
12859           /* If this is a reference to an external symbol, we want
12860                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12861                addu     $at,$at,$gp
12862                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12863                nop
12864                <op>     op[0],0($at)
12865                <op>     op[0]+1,4($at)
12866              Otherwise we want
12867                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12868                nop
12869                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12870                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12871              If there is a base register we add it to $at before the
12872              lwc1 instructions.  If there is a constant we include it
12873              in the lwc1 instructions.  */
12874           used_at = 1;
12875           expr1.X_add_number = offset_expr.X_add_number;
12876           offset_expr.X_add_number = 0;
12877           if (expr1.X_add_number < -0x8000
12878               || expr1.X_add_number >= 0x8000 - 4)
12879             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12880           gpdelay = reg_needs_delay (mips_gp_register);
12881           relax_start (offset_expr.X_add_symbol);
12882           macro_build (&offset_expr, "lui", LUI_FMT,
12883                        AT, BFD_RELOC_MIPS_GOT_HI16);
12884           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12885                        AT, AT, mips_gp_register);
12886           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12887                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12888           load_delay_nop ();
12889           if (breg != 0)
12890             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12891           /* Itbl support may require additional care here.  */
12892           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12893                        BFD_RELOC_LO16, AT);
12894           expr1.X_add_number += 4;
12895
12896           /* Set mips_optimize to 2 to avoid inserting an undesired
12897              nop.  */
12898           hold_mips_optimize = mips_optimize;
12899           mips_optimize = 2;
12900           /* Itbl support may require additional care here.  */
12901           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12902                        BFD_RELOC_LO16, AT);
12903           mips_optimize = hold_mips_optimize;
12904           expr1.X_add_number -= 4;
12905
12906           relax_switch ();
12907           offset_expr.X_add_number = expr1.X_add_number;
12908           if (gpdelay)
12909             macro_build (NULL, "nop", "");
12910           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12911                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12912           load_delay_nop ();
12913           if (breg != 0)
12914             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12915           /* Itbl support may require additional care here.  */
12916           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12917                        BFD_RELOC_LO16, AT);
12918           offset_expr.X_add_number += 4;
12919
12920           /* Set mips_optimize to 2 to avoid inserting an undesired
12921              nop.  */
12922           hold_mips_optimize = mips_optimize;
12923           mips_optimize = 2;
12924           /* Itbl support may require additional care here.  */
12925           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12926                        BFD_RELOC_LO16, AT);
12927           mips_optimize = hold_mips_optimize;
12928           relax_end ();
12929         }
12930       else
12931         abort ();
12932
12933       break;
12934
12935     case M_SAA_AB:
12936       s = "saa";
12937       goto saa_saad;
12938     case M_SAAD_AB:
12939       s = "saad";
12940     saa_saad:
12941       gas_assert (!mips_opts.micromips);
12942       offbits = 0;
12943       fmt = "t,(b)";
12944       goto ld_st;
12945
12946    /* New code added to support COPZ instructions.
12947       This code builds table entries out of the macros in mip_opcodes.
12948       R4000 uses interlocks to handle coproc delays.
12949       Other chips (like the R3000) require nops to be inserted for delays.
12950
12951       FIXME: Currently, we require that the user handle delays.
12952       In order to fill delay slots for non-interlocked chips,
12953       we must have a way to specify delays based on the coprocessor.
12954       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12955       What are the side-effects of the cop instruction?
12956       What cache support might we have and what are its effects?
12957       Both coprocessor & memory require delays. how long???
12958       What registers are read/set/modified?
12959
12960       If an itbl is provided to interpret cop instructions,
12961       this knowledge can be encoded in the itbl spec.  */
12962
12963     case M_COP0:
12964       s = "c0";
12965       goto copz;
12966     case M_COP1:
12967       s = "c1";
12968       goto copz;
12969     case M_COP2:
12970       s = "c2";
12971       goto copz;
12972     case M_COP3:
12973       s = "c3";
12974     copz:
12975       gas_assert (!mips_opts.micromips);
12976       /* For now we just do C (same as Cz).  The parameter will be
12977          stored in insn_opcode by mips_ip.  */
12978       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12979       break;
12980
12981     case M_MOVE:
12982       move_register (op[0], op[1]);
12983       break;
12984
12985     case M_MOVEP:
12986       gas_assert (mips_opts.micromips);
12987       gas_assert (mips_opts.insn32);
12988       move_register (micromips_to_32_reg_h_map1[op[0]],
12989                      micromips_to_32_reg_m_map[op[1]]);
12990       move_register (micromips_to_32_reg_h_map2[op[0]],
12991                      micromips_to_32_reg_n_map[op[2]]);
12992       break;
12993
12994     case M_DMUL:
12995       dbl = 1;
12996       /* Fall through.  */
12997     case M_MUL:
12998       if (mips_opts.arch == CPU_R5900)
12999         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
13000                      op[2]);
13001       else
13002         {
13003           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
13004           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13005         }
13006       break;
13007
13008     case M_DMUL_I:
13009       dbl = 1;
13010       /* Fall through.  */
13011     case M_MUL_I:
13012       /* The MIPS assembler some times generates shifts and adds.  I'm
13013          not trying to be that fancy. GCC should do this for us
13014          anyway.  */
13015       used_at = 1;
13016       load_register (AT, &imm_expr, dbl);
13017       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
13018       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13019       break;
13020
13021     case M_DMULO_I:
13022       dbl = 1;
13023       /* Fall through.  */
13024     case M_MULO_I:
13025       imm = 1;
13026       goto do_mulo;
13027
13028     case M_DMULO:
13029       dbl = 1;
13030       /* Fall through.  */
13031     case M_MULO:
13032     do_mulo:
13033       start_noreorder ();
13034       used_at = 1;
13035       if (imm)
13036         load_register (AT, &imm_expr, dbl);
13037       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
13038                    op[1], imm ? AT : op[2]);
13039       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13040       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
13041       macro_build (NULL, "mfhi", MFHL_FMT, AT);
13042       if (mips_trap)
13043         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
13044       else
13045         {
13046           if (mips_opts.micromips)
13047             micromips_label_expr (&label_expr);
13048           else
13049             label_expr.X_add_number = 8;
13050           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
13051           macro_build (NULL, "nop", "");
13052           macro_build (NULL, "break", BRK_FMT, 6);
13053           if (mips_opts.micromips)
13054             micromips_add_label ();
13055         }
13056       end_noreorder ();
13057       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13058       break;
13059
13060     case M_DMULOU_I:
13061       dbl = 1;
13062       /* Fall through.  */
13063     case M_MULOU_I:
13064       imm = 1;
13065       goto do_mulou;
13066
13067     case M_DMULOU:
13068       dbl = 1;
13069       /* Fall through.  */
13070     case M_MULOU:
13071     do_mulou:
13072       start_noreorder ();
13073       used_at = 1;
13074       if (imm)
13075         load_register (AT, &imm_expr, dbl);
13076       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
13077                    op[1], imm ? AT : op[2]);
13078       macro_build (NULL, "mfhi", MFHL_FMT, AT);
13079       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13080       if (mips_trap)
13081         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
13082       else
13083         {
13084           if (mips_opts.micromips)
13085             micromips_label_expr (&label_expr);
13086           else
13087             label_expr.X_add_number = 8;
13088           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
13089           macro_build (NULL, "nop", "");
13090           macro_build (NULL, "break", BRK_FMT, 6);
13091           if (mips_opts.micromips)
13092             micromips_add_label ();
13093         }
13094       end_noreorder ();
13095       break;
13096
13097     case M_DROL:
13098       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13099         {
13100           if (op[0] == op[1])
13101             {
13102               tempreg = AT;
13103               used_at = 1;
13104             }
13105           else
13106             tempreg = op[0];
13107           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
13108           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
13109           break;
13110         }
13111       used_at = 1;
13112       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13113       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
13114       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
13115       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13116       break;
13117
13118     case M_ROL:
13119       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13120         {
13121           if (op[0] == op[1])
13122             {
13123               tempreg = AT;
13124               used_at = 1;
13125             }
13126           else
13127             tempreg = op[0];
13128           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
13129           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
13130           break;
13131         }
13132       used_at = 1;
13133       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13134       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
13135       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
13136       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13137       break;
13138
13139     case M_DROL_I:
13140       {
13141         unsigned int rot;
13142         const char *l;
13143         const char *rr;
13144
13145         rot = imm_expr.X_add_number & 0x3f;
13146         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13147           {
13148             rot = (64 - rot) & 0x3f;
13149             if (rot >= 32)
13150               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13151             else
13152               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13153             break;
13154           }
13155         if (rot == 0)
13156           {
13157             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13158             break;
13159           }
13160         l = (rot < 0x20) ? "dsll" : "dsll32";
13161         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
13162         rot &= 0x1f;
13163         used_at = 1;
13164         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
13165         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13166         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13167       }
13168       break;
13169
13170     case M_ROL_I:
13171       {
13172         unsigned int rot;
13173
13174         rot = imm_expr.X_add_number & 0x1f;
13175         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13176           {
13177             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
13178                          (32 - rot) & 0x1f);
13179             break;
13180           }
13181         if (rot == 0)
13182           {
13183             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13184             break;
13185           }
13186         used_at = 1;
13187         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
13188         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13189         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13190       }
13191       break;
13192
13193     case M_DROR:
13194       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13195         {
13196           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
13197           break;
13198         }
13199       used_at = 1;
13200       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13201       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13202       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13203       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13204       break;
13205
13206     case M_ROR:
13207       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13208         {
13209           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13210           break;
13211         }
13212       used_at = 1;
13213       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13214       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13215       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13216       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13217       break;
13218
13219     case M_DROR_I:
13220       {
13221         unsigned int rot;
13222         const char *l;
13223         const char *rr;
13224
13225         rot = imm_expr.X_add_number & 0x3f;
13226         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13227           {
13228             if (rot >= 32)
13229               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13230             else
13231               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13232             break;
13233           }
13234         if (rot == 0)
13235           {
13236             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13237             break;
13238           }
13239         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13240         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13241         rot &= 0x1f;
13242         used_at = 1;
13243         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13244         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13245         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13246       }
13247       break;
13248
13249     case M_ROR_I:
13250       {
13251         unsigned int rot;
13252
13253         rot = imm_expr.X_add_number & 0x1f;
13254         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13255           {
13256             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13257             break;
13258           }
13259         if (rot == 0)
13260           {
13261             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13262             break;
13263           }
13264         used_at = 1;
13265         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13266         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13267         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13268       }
13269       break;
13270
13271     case M_SEQ:
13272       if (op[1] == 0)
13273         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13274       else if (op[2] == 0)
13275         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13276       else
13277         {
13278           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13279           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13280         }
13281       break;
13282
13283     case M_SEQ_I:
13284       if (imm_expr.X_add_number == 0)
13285         {
13286           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13287           break;
13288         }
13289       if (op[1] == 0)
13290         {
13291           as_warn (_("instruction %s: result is always false"),
13292                    ip->insn_mo->name);
13293           move_register (op[0], 0);
13294           break;
13295         }
13296       if (CPU_HAS_SEQ (mips_opts.arch)
13297           && -512 <= imm_expr.X_add_number
13298           && imm_expr.X_add_number < 512)
13299         {
13300           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13301                        (int) imm_expr.X_add_number);
13302           break;
13303         }
13304       if (imm_expr.X_add_number >= 0
13305           && imm_expr.X_add_number < 0x10000)
13306         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13307       else if (imm_expr.X_add_number > -0x8000
13308                && imm_expr.X_add_number < 0)
13309         {
13310           imm_expr.X_add_number = -imm_expr.X_add_number;
13311           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13312                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13313         }
13314       else if (CPU_HAS_SEQ (mips_opts.arch))
13315         {
13316           used_at = 1;
13317           load_register (AT, &imm_expr, GPR_SIZE == 64);
13318           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13319           break;
13320         }
13321       else
13322         {
13323           load_register (AT, &imm_expr, GPR_SIZE == 64);
13324           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13325           used_at = 1;
13326         }
13327       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13328       break;
13329
13330     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
13331       s = "slt";
13332       goto sge;
13333     case M_SGEU:
13334       s = "sltu";
13335     sge:
13336       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13337       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13338       break;
13339
13340     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
13341     case M_SGEU_I:
13342       if (imm_expr.X_add_number >= -0x8000
13343           && imm_expr.X_add_number < 0x8000)
13344         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13345                      op[0], op[1], BFD_RELOC_LO16);
13346       else
13347         {
13348           load_register (AT, &imm_expr, GPR_SIZE == 64);
13349           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13350                        op[0], op[1], AT);
13351           used_at = 1;
13352         }
13353       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13354       break;
13355
13356     case M_SGT:         /* X > Y  <==>  Y < X */
13357       s = "slt";
13358       goto sgt;
13359     case M_SGTU:
13360       s = "sltu";
13361     sgt:
13362       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13363       break;
13364
13365     case M_SGT_I:       /* X > I  <==>  I < X */
13366       s = "slt";
13367       goto sgti;
13368     case M_SGTU_I:
13369       s = "sltu";
13370     sgti:
13371       used_at = 1;
13372       load_register (AT, &imm_expr, GPR_SIZE == 64);
13373       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13374       break;
13375
13376     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
13377       s = "slt";
13378       goto sle;
13379     case M_SLEU:
13380       s = "sltu";
13381     sle:
13382       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13383       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13384       break;
13385
13386     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
13387       s = "slt";
13388       goto slei;
13389     case M_SLEU_I:
13390       s = "sltu";
13391     slei:
13392       used_at = 1;
13393       load_register (AT, &imm_expr, GPR_SIZE == 64);
13394       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13395       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13396       break;
13397
13398     case M_SLT_I:
13399       if (imm_expr.X_add_number >= -0x8000
13400           && imm_expr.X_add_number < 0x8000)
13401         {
13402           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13403                        BFD_RELOC_LO16);
13404           break;
13405         }
13406       used_at = 1;
13407       load_register (AT, &imm_expr, GPR_SIZE == 64);
13408       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13409       break;
13410
13411     case M_SLTU_I:
13412       if (imm_expr.X_add_number >= -0x8000
13413           && imm_expr.X_add_number < 0x8000)
13414         {
13415           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13416                        BFD_RELOC_LO16);
13417           break;
13418         }
13419       used_at = 1;
13420       load_register (AT, &imm_expr, GPR_SIZE == 64);
13421       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13422       break;
13423
13424     case M_SNE:
13425       if (op[1] == 0)
13426         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13427       else if (op[2] == 0)
13428         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13429       else
13430         {
13431           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13432           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13433         }
13434       break;
13435
13436     case M_SNE_I:
13437       if (imm_expr.X_add_number == 0)
13438         {
13439           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13440           break;
13441         }
13442       if (op[1] == 0)
13443         {
13444           as_warn (_("instruction %s: result is always true"),
13445                    ip->insn_mo->name);
13446           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13447                        op[0], 0, BFD_RELOC_LO16);
13448           break;
13449         }
13450       if (CPU_HAS_SEQ (mips_opts.arch)
13451           && -512 <= imm_expr.X_add_number
13452           && imm_expr.X_add_number < 512)
13453         {
13454           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13455                        (int) imm_expr.X_add_number);
13456           break;
13457         }
13458       if (imm_expr.X_add_number >= 0
13459           && imm_expr.X_add_number < 0x10000)
13460         {
13461           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13462                        BFD_RELOC_LO16);
13463         }
13464       else if (imm_expr.X_add_number > -0x8000
13465                && imm_expr.X_add_number < 0)
13466         {
13467           imm_expr.X_add_number = -imm_expr.X_add_number;
13468           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13469                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13470         }
13471       else if (CPU_HAS_SEQ (mips_opts.arch))
13472         {
13473           used_at = 1;
13474           load_register (AT, &imm_expr, GPR_SIZE == 64);
13475           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13476           break;
13477         }
13478       else
13479         {
13480           load_register (AT, &imm_expr, GPR_SIZE == 64);
13481           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13482           used_at = 1;
13483         }
13484       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13485       break;
13486
13487     case M_SUB_I:
13488       s = "addi";
13489       s2 = "sub";
13490       goto do_subi;
13491     case M_SUBU_I:
13492       s = "addiu";
13493       s2 = "subu";
13494       goto do_subi;
13495     case M_DSUB_I:
13496       dbl = 1;
13497       s = "daddi";
13498       s2 = "dsub";
13499       if (!mips_opts.micromips)
13500         goto do_subi;
13501       if (imm_expr.X_add_number > -0x200
13502           && imm_expr.X_add_number <= 0x200)
13503         {
13504           macro_build (NULL, s, "t,r,.", op[0], op[1],
13505                        (int) -imm_expr.X_add_number);
13506           break;
13507         }
13508       goto do_subi_i;
13509     case M_DSUBU_I:
13510       dbl = 1;
13511       s = "daddiu";
13512       s2 = "dsubu";
13513     do_subi:
13514       if (imm_expr.X_add_number > -0x8000
13515           && imm_expr.X_add_number <= 0x8000)
13516         {
13517           imm_expr.X_add_number = -imm_expr.X_add_number;
13518           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13519           break;
13520         }
13521     do_subi_i:
13522       used_at = 1;
13523       load_register (AT, &imm_expr, dbl);
13524       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13525       break;
13526
13527     case M_TEQ_I:
13528       s = "teq";
13529       goto trap;
13530     case M_TGE_I:
13531       s = "tge";
13532       goto trap;
13533     case M_TGEU_I:
13534       s = "tgeu";
13535       goto trap;
13536     case M_TLT_I:
13537       s = "tlt";
13538       goto trap;
13539     case M_TLTU_I:
13540       s = "tltu";
13541       goto trap;
13542     case M_TNE_I:
13543       s = "tne";
13544     trap:
13545       used_at = 1;
13546       load_register (AT, &imm_expr, GPR_SIZE == 64);
13547       macro_build (NULL, s, "s,t", op[0], AT);
13548       break;
13549
13550     case M_TRUNCWS:
13551     case M_TRUNCWD:
13552       gas_assert (!mips_opts.micromips);
13553       gas_assert (mips_opts.isa == ISA_MIPS1);
13554       used_at = 1;
13555
13556       /*
13557        * Is the double cfc1 instruction a bug in the mips assembler;
13558        * or is there a reason for it?
13559        */
13560       start_noreorder ();
13561       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13562       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13563       macro_build (NULL, "nop", "");
13564       expr1.X_add_number = 3;
13565       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13566       expr1.X_add_number = 2;
13567       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13568       macro_build (NULL, "ctc1", "t,G", AT, RA);
13569       macro_build (NULL, "nop", "");
13570       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13571                    op[0], op[1]);
13572       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13573       macro_build (NULL, "nop", "");
13574       end_noreorder ();
13575       break;
13576
13577     case M_ULH_AB:
13578       s = "lb";
13579       s2 = "lbu";
13580       off = 1;
13581       goto uld_st;
13582     case M_ULHU_AB:
13583       s = "lbu";
13584       s2 = "lbu";
13585       off = 1;
13586       goto uld_st;
13587     case M_ULW_AB:
13588       s = "lwl";
13589       s2 = "lwr";
13590       offbits = (mips_opts.micromips ? 12 : 16);
13591       off = 3;
13592       goto uld_st;
13593     case M_ULD_AB:
13594       s = "ldl";
13595       s2 = "ldr";
13596       offbits = (mips_opts.micromips ? 12 : 16);
13597       off = 7;
13598       goto uld_st;
13599     case M_USH_AB:
13600       s = "sb";
13601       s2 = "sb";
13602       off = 1;
13603       ust = 1;
13604       goto uld_st;
13605     case M_USW_AB:
13606       s = "swl";
13607       s2 = "swr";
13608       offbits = (mips_opts.micromips ? 12 : 16);
13609       off = 3;
13610       ust = 1;
13611       goto uld_st;
13612     case M_USD_AB:
13613       s = "sdl";
13614       s2 = "sdr";
13615       offbits = (mips_opts.micromips ? 12 : 16);
13616       off = 7;
13617       ust = 1;
13618
13619     uld_st:
13620       breg = op[2];
13621       large_offset = !small_offset_p (off, align, offbits);
13622       ep = &offset_expr;
13623       expr1.X_add_number = 0;
13624       if (large_offset)
13625         {
13626           used_at = 1;
13627           tempreg = AT;
13628           if (small_offset_p (0, align, 16))
13629             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13630                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13631           else
13632             {
13633               load_address (tempreg, ep, &used_at);
13634               if (breg != 0)
13635                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13636                              tempreg, tempreg, breg);
13637             }
13638           offset_reloc[0] = BFD_RELOC_LO16;
13639           offset_reloc[1] = BFD_RELOC_UNUSED;
13640           offset_reloc[2] = BFD_RELOC_UNUSED;
13641           breg = tempreg;
13642           tempreg = op[0];
13643           ep = &expr1;
13644         }
13645       else if (!ust && op[0] == breg)
13646         {
13647           used_at = 1;
13648           tempreg = AT;
13649         }
13650       else
13651         tempreg = op[0];
13652
13653       if (off == 1)
13654         goto ulh_sh;
13655
13656       if (!target_big_endian)
13657         ep->X_add_number += off;
13658       if (offbits == 12)
13659         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13660       else
13661         macro_build (ep, s, "t,o(b)", tempreg, -1,
13662                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13663
13664       if (!target_big_endian)
13665         ep->X_add_number -= off;
13666       else
13667         ep->X_add_number += off;
13668       if (offbits == 12)
13669         macro_build (NULL, s2, "t,~(b)",
13670                      tempreg, (int) ep->X_add_number, breg);
13671       else
13672         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13673                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13674
13675       /* If necessary, move the result in tempreg to the final destination.  */
13676       if (!ust && op[0] != tempreg)
13677         {
13678           /* Protect second load's delay slot.  */
13679           load_delay_nop ();
13680           move_register (op[0], tempreg);
13681         }
13682       break;
13683
13684     ulh_sh:
13685       used_at = 1;
13686       if (target_big_endian == ust)
13687         ep->X_add_number += off;
13688       tempreg = ust || large_offset ? op[0] : AT;
13689       macro_build (ep, s, "t,o(b)", tempreg, -1,
13690                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13691
13692       /* For halfword transfers we need a temporary register to shuffle
13693          bytes.  Unfortunately for M_USH_A we have none available before
13694          the next store as AT holds the base address.  We deal with this
13695          case by clobbering TREG and then restoring it as with ULH.  */
13696       tempreg = ust == large_offset ? op[0] : AT;
13697       if (ust)
13698         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13699
13700       if (target_big_endian == ust)
13701         ep->X_add_number -= off;
13702       else
13703         ep->X_add_number += off;
13704       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13705                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13706
13707       /* For M_USH_A re-retrieve the LSB.  */
13708       if (ust && large_offset)
13709         {
13710           if (target_big_endian)
13711             ep->X_add_number += off;
13712           else
13713             ep->X_add_number -= off;
13714           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13715                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13716         }
13717       /* For ULH and M_USH_A OR the LSB in.  */
13718       if (!ust || large_offset)
13719         {
13720           tempreg = !large_offset ? AT : op[0];
13721           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13722           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13723         }
13724       break;
13725
13726     default:
13727       /* FIXME: Check if this is one of the itbl macros, since they
13728          are added dynamically.  */
13729       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13730       break;
13731     }
13732   if (!mips_opts.at && used_at)
13733     as_bad (_("macro used $at after \".set noat\""));
13734 }
13735
13736 /* Implement macros in mips16 mode.  */
13737
13738 static void
13739 mips16_macro (struct mips_cl_insn *ip)
13740 {
13741   const struct mips_operand_array *operands;
13742   int mask;
13743   int tmp;
13744   expressionS expr1;
13745   int dbl;
13746   const char *s, *s2, *s3;
13747   unsigned int op[MAX_OPERANDS];
13748   unsigned int i;
13749
13750   mask = ip->insn_mo->mask;
13751
13752   operands = insn_operands (ip);
13753   for (i = 0; i < MAX_OPERANDS; i++)
13754     if (operands->operand[i])
13755       op[i] = insn_extract_operand (ip, operands->operand[i]);
13756     else
13757       op[i] = -1;
13758
13759   expr1.X_op = O_constant;
13760   expr1.X_op_symbol = NULL;
13761   expr1.X_add_symbol = NULL;
13762   expr1.X_add_number = 1;
13763
13764   dbl = 0;
13765
13766   switch (mask)
13767     {
13768     default:
13769       abort ();
13770
13771     case M_DDIV_3:
13772       dbl = 1;
13773       /* Fall through.  */
13774     case M_DIV_3:
13775       s = "mflo";
13776       goto do_div3;
13777     case M_DREM_3:
13778       dbl = 1;
13779       /* Fall through.  */
13780     case M_REM_3:
13781       s = "mfhi";
13782     do_div3:
13783       start_noreorder ();
13784       macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
13785       expr1.X_add_number = 2;
13786       macro_build (&expr1, "bnez", "x,p", op[2]);
13787       macro_build (NULL, "break", "6", 7);
13788
13789       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13790          since that causes an overflow.  We should do that as well,
13791          but I don't see how to do the comparisons without a temporary
13792          register.  */
13793       end_noreorder ();
13794       macro_build (NULL, s, "x", op[0]);
13795       break;
13796
13797     case M_DIVU_3:
13798       s = "divu";
13799       s2 = "mflo";
13800       goto do_divu3;
13801     case M_REMU_3:
13802       s = "divu";
13803       s2 = "mfhi";
13804       goto do_divu3;
13805     case M_DDIVU_3:
13806       s = "ddivu";
13807       s2 = "mflo";
13808       goto do_divu3;
13809     case M_DREMU_3:
13810       s = "ddivu";
13811       s2 = "mfhi";
13812     do_divu3:
13813       start_noreorder ();
13814       macro_build (NULL, s, ".,x,y", op[1], op[2]);
13815       expr1.X_add_number = 2;
13816       macro_build (&expr1, "bnez", "x,p", op[2]);
13817       macro_build (NULL, "break", "6", 7);
13818       end_noreorder ();
13819       macro_build (NULL, s2, "x", op[0]);
13820       break;
13821
13822     case M_DMUL:
13823       dbl = 1;
13824       /* Fall through.  */
13825     case M_MUL:
13826       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13827       macro_build (NULL, "mflo", "x", op[0]);
13828       break;
13829
13830     case M_DSUBU_I:
13831       dbl = 1;
13832       goto do_subu;
13833     case M_SUBU_I:
13834     do_subu:
13835       imm_expr.X_add_number = -imm_expr.X_add_number;
13836       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
13837       break;
13838
13839     case M_SUBU_I_2:
13840       imm_expr.X_add_number = -imm_expr.X_add_number;
13841       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13842       break;
13843
13844     case M_DSUBU_I_2:
13845       imm_expr.X_add_number = -imm_expr.X_add_number;
13846       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13847       break;
13848
13849     case M_BEQ:
13850       s = "cmp";
13851       s2 = "bteqz";
13852       goto do_branch;
13853     case M_BNE:
13854       s = "cmp";
13855       s2 = "btnez";
13856       goto do_branch;
13857     case M_BLT:
13858       s = "slt";
13859       s2 = "btnez";
13860       goto do_branch;
13861     case M_BLTU:
13862       s = "sltu";
13863       s2 = "btnez";
13864       goto do_branch;
13865     case M_BLE:
13866       s = "slt";
13867       s2 = "bteqz";
13868       goto do_reverse_branch;
13869     case M_BLEU:
13870       s = "sltu";
13871       s2 = "bteqz";
13872       goto do_reverse_branch;
13873     case M_BGE:
13874       s = "slt";
13875       s2 = "bteqz";
13876       goto do_branch;
13877     case M_BGEU:
13878       s = "sltu";
13879       s2 = "bteqz";
13880       goto do_branch;
13881     case M_BGT:
13882       s = "slt";
13883       s2 = "btnez";
13884       goto do_reverse_branch;
13885     case M_BGTU:
13886       s = "sltu";
13887       s2 = "btnez";
13888
13889     do_reverse_branch:
13890       tmp = op[1];
13891       op[1] = op[0];
13892       op[0] = tmp;
13893
13894     do_branch:
13895       macro_build (NULL, s, "x,y", op[0], op[1]);
13896       macro_build (&offset_expr, s2, "p");
13897       break;
13898
13899     case M_BEQ_I:
13900       s = "cmpi";
13901       s2 = "bteqz";
13902       s3 = "x,U";
13903       goto do_branch_i;
13904     case M_BNE_I:
13905       s = "cmpi";
13906       s2 = "btnez";
13907       s3 = "x,U";
13908       goto do_branch_i;
13909     case M_BLT_I:
13910       s = "slti";
13911       s2 = "btnez";
13912       s3 = "x,8";
13913       goto do_branch_i;
13914     case M_BLTU_I:
13915       s = "sltiu";
13916       s2 = "btnez";
13917       s3 = "x,8";
13918       goto do_branch_i;
13919     case M_BLE_I:
13920       s = "slti";
13921       s2 = "btnez";
13922       s3 = "x,8";
13923       goto do_addone_branch_i;
13924     case M_BLEU_I:
13925       s = "sltiu";
13926       s2 = "btnez";
13927       s3 = "x,8";
13928       goto do_addone_branch_i;
13929     case M_BGE_I:
13930       s = "slti";
13931       s2 = "bteqz";
13932       s3 = "x,8";
13933       goto do_branch_i;
13934     case M_BGEU_I:
13935       s = "sltiu";
13936       s2 = "bteqz";
13937       s3 = "x,8";
13938       goto do_branch_i;
13939     case M_BGT_I:
13940       s = "slti";
13941       s2 = "bteqz";
13942       s3 = "x,8";
13943       goto do_addone_branch_i;
13944     case M_BGTU_I:
13945       s = "sltiu";
13946       s2 = "bteqz";
13947       s3 = "x,8";
13948
13949     do_addone_branch_i:
13950       ++imm_expr.X_add_number;
13951
13952     do_branch_i:
13953       macro_build (&imm_expr, s, s3, op[0]);
13954       macro_build (&offset_expr, s2, "p");
13955       break;
13956
13957     case M_ABS:
13958       expr1.X_add_number = 0;
13959       macro_build (&expr1, "slti", "x,8", op[1]);
13960       if (op[0] != op[1])
13961         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13962       expr1.X_add_number = 2;
13963       macro_build (&expr1, "bteqz", "p");
13964       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13965       break;
13966     }
13967 }
13968
13969 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13970    opcode bits in *OPCODE_EXTRA.  */
13971
13972 static struct mips_opcode *
13973 mips_lookup_insn (struct hash_control *hash, const char *start,
13974                   ssize_t length, unsigned int *opcode_extra)
13975 {
13976   char *name, *dot, *p;
13977   unsigned int mask, suffix;
13978   ssize_t opend;
13979   struct mips_opcode *insn;
13980
13981   /* Make a copy of the instruction so that we can fiddle with it.  */
13982   name = xstrndup (start, length);
13983
13984   /* Look up the instruction as-is.  */
13985   insn = (struct mips_opcode *) hash_find (hash, name);
13986   if (insn)
13987     goto end;
13988
13989   dot = strchr (name, '.');
13990   if (dot && dot[1])
13991     {
13992       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13993       p = mips_parse_vu0_channels (dot + 1, &mask);
13994       if (*p == 0 && mask != 0)
13995         {
13996           *dot = 0;
13997           insn = (struct mips_opcode *) hash_find (hash, name);
13998           *dot = '.';
13999           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
14000             {
14001               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
14002               goto end;
14003             }
14004         }
14005     }
14006
14007   if (mips_opts.micromips)
14008     {
14009       /* See if there's an instruction size override suffix,
14010          either `16' or `32', at the end of the mnemonic proper,
14011          that defines the operation, i.e. before the first `.'
14012          character if any.  Strip it and retry.  */
14013       opend = dot != NULL ? dot - name : length;
14014       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
14015         suffix = 2;
14016       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
14017         suffix = 4;
14018       else
14019         suffix = 0;
14020       if (suffix)
14021         {
14022           memmove (name + opend - 2, name + opend, length - opend + 1);
14023           insn = (struct mips_opcode *) hash_find (hash, name);
14024           if (insn)
14025             {
14026               forced_insn_length = suffix;
14027               goto end;
14028             }
14029         }
14030     }
14031
14032   insn = NULL;
14033  end:
14034   free (name);
14035   return insn;
14036 }
14037
14038 /* Assemble an instruction into its binary format.  If the instruction
14039    is a macro, set imm_expr and offset_expr to the values associated
14040    with "I" and "A" operands respectively.  Otherwise store the value
14041    of the relocatable field (if any) in offset_expr.  In both cases
14042    set offset_reloc to the relocation operators applied to offset_expr.  */
14043
14044 static void
14045 mips_ip (char *str, struct mips_cl_insn *insn)
14046 {
14047   const struct mips_opcode *first, *past;
14048   struct hash_control *hash;
14049   char format;
14050   size_t end;
14051   struct mips_operand_token *tokens;
14052   unsigned int opcode_extra;
14053
14054   if (mips_opts.micromips)
14055     {
14056       hash = micromips_op_hash;
14057       past = &micromips_opcodes[bfd_micromips_num_opcodes];
14058     }
14059   else
14060     {
14061       hash = op_hash;
14062       past = &mips_opcodes[NUMOPCODES];
14063     }
14064   forced_insn_length = 0;
14065   opcode_extra = 0;
14066
14067   /* We first try to match an instruction up to a space or to the end.  */
14068   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
14069     continue;
14070
14071   first = mips_lookup_insn (hash, str, end, &opcode_extra);
14072   if (first == NULL)
14073     {
14074       set_insn_error (0, _("unrecognized opcode"));
14075       return;
14076     }
14077
14078   if (strcmp (first->name, "li.s") == 0)
14079     format = 'f';
14080   else if (strcmp (first->name, "li.d") == 0)
14081     format = 'd';
14082   else
14083     format = 0;
14084   tokens = mips_parse_arguments (str + end, format);
14085   if (!tokens)
14086     return;
14087
14088   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
14089       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
14090     set_insn_error (0, _("invalid operands"));
14091
14092   obstack_free (&mips_operand_tokens, tokens);
14093 }
14094
14095 /* As for mips_ip, but used when assembling MIPS16 code.
14096    Also set forced_insn_length to the resulting instruction size in
14097    bytes if the user explicitly requested a small or extended instruction.  */
14098
14099 static void
14100 mips16_ip (char *str, struct mips_cl_insn *insn)
14101 {
14102   char *end, *s, c;
14103   struct mips_opcode *first;
14104   struct mips_operand_token *tokens;
14105   unsigned int l;
14106
14107   for (s = str; *s != '\0' && *s != '.' && *s != ' '; ++s)
14108     ;
14109   end = s;
14110   c = *end;
14111
14112   l = 0;
14113   switch (c)
14114     {
14115     case '\0':
14116       break;
14117
14118     case ' ':
14119       s++;
14120       break;
14121
14122     case '.':
14123       s++;
14124       if (*s == 't')
14125         {
14126           l = 2;
14127           s++;
14128         }
14129       else if (*s == 'e')
14130         {
14131           l = 4;
14132           s++;
14133         }
14134       if (*s == '\0')
14135         break;
14136       else if (*s++ == ' ')
14137         break;
14138       set_insn_error (0, _("unrecognized opcode"));
14139       return;
14140     }
14141   forced_insn_length = l;
14142
14143   *end = 0;
14144   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
14145   *end = c;
14146
14147   if (!first)
14148     {
14149       set_insn_error (0, _("unrecognized opcode"));
14150       return;
14151     }
14152
14153   tokens = mips_parse_arguments (s, 0);
14154   if (!tokens)
14155     return;
14156
14157   if (!match_mips16_insns (insn, first, tokens))
14158     set_insn_error (0, _("invalid operands"));
14159
14160   obstack_free (&mips_operand_tokens, tokens);
14161 }
14162
14163 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14164    NBITS is the number of significant bits in VAL.  */
14165
14166 static unsigned long
14167 mips16_immed_extend (offsetT val, unsigned int nbits)
14168 {
14169   int extval;
14170
14171   extval = 0;
14172   val &= (1U << nbits) - 1;
14173   if (nbits == 16 || nbits == 9)
14174     {
14175       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14176       val &= 0x1f;
14177     }
14178   else if (nbits == 15)
14179     {
14180       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14181       val &= 0xf;
14182     }
14183   else if (nbits == 6)
14184     {
14185       extval = ((val & 0x1f) << 6) | (val & 0x20);
14186       val = 0;
14187     }
14188   return (extval << 16) | val;
14189 }
14190
14191 /* Like decode_mips16_operand, but require the operand to be defined and
14192    require it to be an integer.  */
14193
14194 static const struct mips_int_operand *
14195 mips16_immed_operand (int type, bfd_boolean extended_p)
14196 {
14197   const struct mips_operand *operand;
14198
14199   operand = decode_mips16_operand (type, extended_p);
14200   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
14201     abort ();
14202   return (const struct mips_int_operand *) operand;
14203 }
14204
14205 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14206
14207 static bfd_boolean
14208 mips16_immed_in_range_p (const struct mips_int_operand *operand,
14209                          bfd_reloc_code_real_type reloc, offsetT sval)
14210 {
14211   int min_val, max_val;
14212
14213   min_val = mips_int_operand_min (operand);
14214   max_val = mips_int_operand_max (operand);
14215   if (reloc != BFD_RELOC_UNUSED)
14216     {
14217       if (min_val < 0)
14218         sval = SEXT_16BIT (sval);
14219       else
14220         sval &= 0xffff;
14221     }
14222
14223   return (sval >= min_val
14224           && sval <= max_val
14225           && (sval & ((1 << operand->shift) - 1)) == 0);
14226 }
14227
14228 /* Install immediate value VAL into MIPS16 instruction *INSN,
14229    extending it if necessary.  The instruction in *INSN may
14230    already be extended.
14231
14232    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14233    if none.  In the former case, VAL is a 16-bit number with no
14234    defined signedness.
14235
14236    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14237    is the length that the user requested, or 0 if none.  */
14238
14239 static void
14240 mips16_immed (const char *file, unsigned int line, int type,
14241               bfd_reloc_code_real_type reloc, offsetT val,
14242               unsigned int user_insn_length, unsigned long *insn)
14243 {
14244   const struct mips_int_operand *operand;
14245   unsigned int uval, length;
14246
14247   operand = mips16_immed_operand (type, FALSE);
14248   if (!mips16_immed_in_range_p (operand, reloc, val))
14249     {
14250       /* We need an extended instruction.  */
14251       if (user_insn_length == 2)
14252         as_bad_where (file, line, _("invalid unextended operand value"));
14253       else
14254         *insn |= MIPS16_EXTEND;
14255     }
14256   else if (user_insn_length == 4)
14257     {
14258       /* The operand doesn't force an unextended instruction to be extended.
14259          Warn if the user wanted an extended instruction anyway.  */
14260       *insn |= MIPS16_EXTEND;
14261       as_warn_where (file, line,
14262                      _("extended operand requested but not required"));
14263     }
14264
14265   length = mips16_opcode_length (*insn);
14266   if (length == 4)
14267     {
14268       operand = mips16_immed_operand (type, TRUE);
14269       if (!mips16_immed_in_range_p (operand, reloc, val))
14270         as_bad_where (file, line,
14271                       _("operand value out of range for instruction"));
14272     }
14273   uval = ((unsigned int) val >> operand->shift) - operand->bias;
14274   if (length == 2 || operand->root.lsb != 0)
14275     *insn = mips_insert_operand (&operand->root, *insn, uval);
14276   else
14277     *insn |= mips16_immed_extend (uval, operand->root.size);
14278 }
14279 \f
14280 struct percent_op_match
14281 {
14282   const char *str;
14283   bfd_reloc_code_real_type reloc;
14284 };
14285
14286 static const struct percent_op_match mips_percent_op[] =
14287 {
14288   {"%lo", BFD_RELOC_LO16},
14289   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14290   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14291   {"%call16", BFD_RELOC_MIPS_CALL16},
14292   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14293   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14294   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14295   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14296   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14297   {"%got", BFD_RELOC_MIPS_GOT16},
14298   {"%gp_rel", BFD_RELOC_GPREL16},
14299   {"%gprel", BFD_RELOC_GPREL16},
14300   {"%half", BFD_RELOC_16},
14301   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14302   {"%higher", BFD_RELOC_MIPS_HIGHER},
14303   {"%neg", BFD_RELOC_MIPS_SUB},
14304   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14305   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14306   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14307   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14308   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14309   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14310   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14311   {"%hi", BFD_RELOC_HI16_S},
14312   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14313   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14314 };
14315
14316 static const struct percent_op_match mips16_percent_op[] =
14317 {
14318   {"%lo", BFD_RELOC_MIPS16_LO16},
14319   {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14320   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14321   {"%got", BFD_RELOC_MIPS16_GOT16},
14322   {"%call16", BFD_RELOC_MIPS16_CALL16},
14323   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14324   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14325   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14326   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14327   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14328   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14329   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14330   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14331 };
14332
14333
14334 /* Return true if *STR points to a relocation operator.  When returning true,
14335    move *STR over the operator and store its relocation code in *RELOC.
14336    Leave both *STR and *RELOC alone when returning false.  */
14337
14338 static bfd_boolean
14339 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14340 {
14341   const struct percent_op_match *percent_op;
14342   size_t limit, i;
14343
14344   if (mips_opts.mips16)
14345     {
14346       percent_op = mips16_percent_op;
14347       limit = ARRAY_SIZE (mips16_percent_op);
14348     }
14349   else
14350     {
14351       percent_op = mips_percent_op;
14352       limit = ARRAY_SIZE (mips_percent_op);
14353     }
14354
14355   for (i = 0; i < limit; i++)
14356     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14357       {
14358         int len = strlen (percent_op[i].str);
14359
14360         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14361           continue;
14362
14363         *str += strlen (percent_op[i].str);
14364         *reloc = percent_op[i].reloc;
14365
14366         /* Check whether the output BFD supports this relocation.
14367            If not, issue an error and fall back on something safe.  */
14368         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14369           {
14370             as_bad (_("relocation %s isn't supported by the current ABI"),
14371                     percent_op[i].str);
14372             *reloc = BFD_RELOC_UNUSED;
14373           }
14374         return TRUE;
14375       }
14376   return FALSE;
14377 }
14378
14379
14380 /* Parse string STR as a 16-bit relocatable operand.  Store the
14381    expression in *EP and the relocations in the array starting
14382    at RELOC.  Return the number of relocation operators used.
14383
14384    On exit, EXPR_END points to the first character after the expression.  */
14385
14386 static size_t
14387 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14388                        char *str)
14389 {
14390   bfd_reloc_code_real_type reversed_reloc[3];
14391   size_t reloc_index, i;
14392   int crux_depth, str_depth;
14393   char *crux;
14394
14395   /* Search for the start of the main expression, recoding relocations
14396      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14397      of the main expression and with CRUX_DEPTH containing the number
14398      of open brackets at that point.  */
14399   reloc_index = -1;
14400   str_depth = 0;
14401   do
14402     {
14403       reloc_index++;
14404       crux = str;
14405       crux_depth = str_depth;
14406
14407       /* Skip over whitespace and brackets, keeping count of the number
14408          of brackets.  */
14409       while (*str == ' ' || *str == '\t' || *str == '(')
14410         if (*str++ == '(')
14411           str_depth++;
14412     }
14413   while (*str == '%'
14414          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14415          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14416
14417   my_getExpression (ep, crux);
14418   str = expr_end;
14419
14420   /* Match every open bracket.  */
14421   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14422     if (*str++ == ')')
14423       crux_depth--;
14424
14425   if (crux_depth > 0)
14426     as_bad (_("unclosed '('"));
14427
14428   expr_end = str;
14429
14430   if (reloc_index != 0)
14431     {
14432       prev_reloc_op_frag = frag_now;
14433       for (i = 0; i < reloc_index; i++)
14434         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14435     }
14436
14437   return reloc_index;
14438 }
14439
14440 static void
14441 my_getExpression (expressionS *ep, char *str)
14442 {
14443   char *save_in;
14444
14445   save_in = input_line_pointer;
14446   input_line_pointer = str;
14447   expression (ep);
14448   expr_end = input_line_pointer;
14449   input_line_pointer = save_in;
14450 }
14451
14452 const char *
14453 md_atof (int type, char *litP, int *sizeP)
14454 {
14455   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14456 }
14457
14458 void
14459 md_number_to_chars (char *buf, valueT val, int n)
14460 {
14461   if (target_big_endian)
14462     number_to_chars_bigendian (buf, val, n);
14463   else
14464     number_to_chars_littleendian (buf, val, n);
14465 }
14466 \f
14467 static int support_64bit_objects(void)
14468 {
14469   const char **list, **l;
14470   int yes;
14471
14472   list = bfd_target_list ();
14473   for (l = list; *l != NULL; l++)
14474     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14475         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14476       break;
14477   yes = (*l != NULL);
14478   free (list);
14479   return yes;
14480 }
14481
14482 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14483    NEW_VALUE.  Warn if another value was already specified.  Note:
14484    we have to defer parsing the -march and -mtune arguments in order
14485    to handle 'from-abi' correctly, since the ABI might be specified
14486    in a later argument.  */
14487
14488 static void
14489 mips_set_option_string (const char **string_ptr, const char *new_value)
14490 {
14491   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14492     as_warn (_("a different %s was already specified, is now %s"),
14493              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14494              new_value);
14495
14496   *string_ptr = new_value;
14497 }
14498
14499 int
14500 md_parse_option (int c, const char *arg)
14501 {
14502   unsigned int i;
14503
14504   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14505     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14506       {
14507         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14508                                            c == mips_ases[i].option_on);
14509         return 1;
14510       }
14511
14512   switch (c)
14513     {
14514     case OPTION_CONSTRUCT_FLOATS:
14515       mips_disable_float_construction = 0;
14516       break;
14517
14518     case OPTION_NO_CONSTRUCT_FLOATS:
14519       mips_disable_float_construction = 1;
14520       break;
14521
14522     case OPTION_TRAP:
14523       mips_trap = 1;
14524       break;
14525
14526     case OPTION_BREAK:
14527       mips_trap = 0;
14528       break;
14529
14530     case OPTION_EB:
14531       target_big_endian = 1;
14532       break;
14533
14534     case OPTION_EL:
14535       target_big_endian = 0;
14536       break;
14537
14538     case 'O':
14539       if (arg == NULL)
14540         mips_optimize = 1;
14541       else if (arg[0] == '0')
14542         mips_optimize = 0;
14543       else if (arg[0] == '1')
14544         mips_optimize = 1;
14545       else
14546         mips_optimize = 2;
14547       break;
14548
14549     case 'g':
14550       if (arg == NULL)
14551         mips_debug = 2;
14552       else
14553         mips_debug = atoi (arg);
14554       break;
14555
14556     case OPTION_MIPS1:
14557       file_mips_opts.isa = ISA_MIPS1;
14558       break;
14559
14560     case OPTION_MIPS2:
14561       file_mips_opts.isa = ISA_MIPS2;
14562       break;
14563
14564     case OPTION_MIPS3:
14565       file_mips_opts.isa = ISA_MIPS3;
14566       break;
14567
14568     case OPTION_MIPS4:
14569       file_mips_opts.isa = ISA_MIPS4;
14570       break;
14571
14572     case OPTION_MIPS5:
14573       file_mips_opts.isa = ISA_MIPS5;
14574       break;
14575
14576     case OPTION_MIPS32:
14577       file_mips_opts.isa = ISA_MIPS32;
14578       break;
14579
14580     case OPTION_MIPS32R2:
14581       file_mips_opts.isa = ISA_MIPS32R2;
14582       break;
14583
14584     case OPTION_MIPS32R3:
14585       file_mips_opts.isa = ISA_MIPS32R3;
14586       break;
14587
14588     case OPTION_MIPS32R5:
14589       file_mips_opts.isa = ISA_MIPS32R5;
14590       break;
14591
14592     case OPTION_MIPS32R6:
14593       file_mips_opts.isa = ISA_MIPS32R6;
14594       break;
14595
14596     case OPTION_MIPS64R2:
14597       file_mips_opts.isa = ISA_MIPS64R2;
14598       break;
14599
14600     case OPTION_MIPS64R3:
14601       file_mips_opts.isa = ISA_MIPS64R3;
14602       break;
14603
14604     case OPTION_MIPS64R5:
14605       file_mips_opts.isa = ISA_MIPS64R5;
14606       break;
14607
14608     case OPTION_MIPS64R6:
14609       file_mips_opts.isa = ISA_MIPS64R6;
14610       break;
14611
14612     case OPTION_MIPS64:
14613       file_mips_opts.isa = ISA_MIPS64;
14614       break;
14615
14616     case OPTION_MTUNE:
14617       mips_set_option_string (&mips_tune_string, arg);
14618       break;
14619
14620     case OPTION_MARCH:
14621       mips_set_option_string (&mips_arch_string, arg);
14622       break;
14623
14624     case OPTION_M4650:
14625       mips_set_option_string (&mips_arch_string, "4650");
14626       mips_set_option_string (&mips_tune_string, "4650");
14627       break;
14628
14629     case OPTION_NO_M4650:
14630       break;
14631
14632     case OPTION_M4010:
14633       mips_set_option_string (&mips_arch_string, "4010");
14634       mips_set_option_string (&mips_tune_string, "4010");
14635       break;
14636
14637     case OPTION_NO_M4010:
14638       break;
14639
14640     case OPTION_M4100:
14641       mips_set_option_string (&mips_arch_string, "4100");
14642       mips_set_option_string (&mips_tune_string, "4100");
14643       break;
14644
14645     case OPTION_NO_M4100:
14646       break;
14647
14648     case OPTION_M3900:
14649       mips_set_option_string (&mips_arch_string, "3900");
14650       mips_set_option_string (&mips_tune_string, "3900");
14651       break;
14652
14653     case OPTION_NO_M3900:
14654       break;
14655
14656     case OPTION_MICROMIPS:
14657       if (file_mips_opts.mips16 == 1)
14658         {
14659           as_bad (_("-mmicromips cannot be used with -mips16"));
14660           return 0;
14661         }
14662       file_mips_opts.micromips = 1;
14663       mips_no_prev_insn ();
14664       break;
14665
14666     case OPTION_NO_MICROMIPS:
14667       file_mips_opts.micromips = 0;
14668       mips_no_prev_insn ();
14669       break;
14670
14671     case OPTION_MIPS16:
14672       if (file_mips_opts.micromips == 1)
14673         {
14674           as_bad (_("-mips16 cannot be used with -micromips"));
14675           return 0;
14676         }
14677       file_mips_opts.mips16 = 1;
14678       mips_no_prev_insn ();
14679       break;
14680
14681     case OPTION_NO_MIPS16:
14682       file_mips_opts.mips16 = 0;
14683       mips_no_prev_insn ();
14684       break;
14685
14686     case OPTION_FIX_24K:
14687       mips_fix_24k = 1;
14688       break;
14689
14690     case OPTION_NO_FIX_24K:
14691       mips_fix_24k = 0;
14692       break;
14693
14694     case OPTION_FIX_RM7000:
14695       mips_fix_rm7000 = 1;
14696       break;
14697
14698     case OPTION_NO_FIX_RM7000:
14699       mips_fix_rm7000 = 0;
14700       break;
14701
14702     case OPTION_FIX_LOONGSON2F_JUMP:
14703       mips_fix_loongson2f_jump = TRUE;
14704       break;
14705
14706     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14707       mips_fix_loongson2f_jump = FALSE;
14708       break;
14709
14710     case OPTION_FIX_LOONGSON2F_NOP:
14711       mips_fix_loongson2f_nop = TRUE;
14712       break;
14713
14714     case OPTION_NO_FIX_LOONGSON2F_NOP:
14715       mips_fix_loongson2f_nop = FALSE;
14716       break;
14717
14718     case OPTION_FIX_VR4120:
14719       mips_fix_vr4120 = 1;
14720       break;
14721
14722     case OPTION_NO_FIX_VR4120:
14723       mips_fix_vr4120 = 0;
14724       break;
14725
14726     case OPTION_FIX_VR4130:
14727       mips_fix_vr4130 = 1;
14728       break;
14729
14730     case OPTION_NO_FIX_VR4130:
14731       mips_fix_vr4130 = 0;
14732       break;
14733
14734     case OPTION_FIX_CN63XXP1:
14735       mips_fix_cn63xxp1 = TRUE;
14736       break;
14737
14738     case OPTION_NO_FIX_CN63XXP1:
14739       mips_fix_cn63xxp1 = FALSE;
14740       break;
14741
14742     case OPTION_RELAX_BRANCH:
14743       mips_relax_branch = 1;
14744       break;
14745
14746     case OPTION_NO_RELAX_BRANCH:
14747       mips_relax_branch = 0;
14748       break;
14749
14750     case OPTION_IGNORE_BRANCH_ISA:
14751       mips_ignore_branch_isa = TRUE;
14752       break;
14753
14754     case OPTION_NO_IGNORE_BRANCH_ISA:
14755       mips_ignore_branch_isa = FALSE;
14756       break;
14757
14758     case OPTION_INSN32:
14759       file_mips_opts.insn32 = TRUE;
14760       break;
14761
14762     case OPTION_NO_INSN32:
14763       file_mips_opts.insn32 = FALSE;
14764       break;
14765
14766     case OPTION_MSHARED:
14767       mips_in_shared = TRUE;
14768       break;
14769
14770     case OPTION_MNO_SHARED:
14771       mips_in_shared = FALSE;
14772       break;
14773
14774     case OPTION_MSYM32:
14775       file_mips_opts.sym32 = TRUE;
14776       break;
14777
14778     case OPTION_MNO_SYM32:
14779       file_mips_opts.sym32 = FALSE;
14780       break;
14781
14782       /* When generating ELF code, we permit -KPIC and -call_shared to
14783          select SVR4_PIC, and -non_shared to select no PIC.  This is
14784          intended to be compatible with Irix 5.  */
14785     case OPTION_CALL_SHARED:
14786       mips_pic = SVR4_PIC;
14787       mips_abicalls = TRUE;
14788       break;
14789
14790     case OPTION_CALL_NONPIC:
14791       mips_pic = NO_PIC;
14792       mips_abicalls = TRUE;
14793       break;
14794
14795     case OPTION_NON_SHARED:
14796       mips_pic = NO_PIC;
14797       mips_abicalls = FALSE;
14798       break;
14799
14800       /* The -xgot option tells the assembler to use 32 bit offsets
14801          when accessing the got in SVR4_PIC mode.  It is for Irix
14802          compatibility.  */
14803     case OPTION_XGOT:
14804       mips_big_got = 1;
14805       break;
14806
14807     case 'G':
14808       g_switch_value = atoi (arg);
14809       g_switch_seen = 1;
14810       break;
14811
14812       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14813          and -mabi=64.  */
14814     case OPTION_32:
14815       mips_abi = O32_ABI;
14816       break;
14817
14818     case OPTION_N32:
14819       mips_abi = N32_ABI;
14820       break;
14821
14822     case OPTION_64:
14823       mips_abi = N64_ABI;
14824       if (!support_64bit_objects())
14825         as_fatal (_("no compiled in support for 64 bit object file format"));
14826       break;
14827
14828     case OPTION_GP32:
14829       file_mips_opts.gp = 32;
14830       break;
14831
14832     case OPTION_GP64:
14833       file_mips_opts.gp = 64;
14834       break;
14835
14836     case OPTION_FP32:
14837       file_mips_opts.fp = 32;
14838       break;
14839
14840     case OPTION_FPXX:
14841       file_mips_opts.fp = 0;
14842       break;
14843
14844     case OPTION_FP64:
14845       file_mips_opts.fp = 64;
14846       break;
14847
14848     case OPTION_ODD_SPREG:
14849       file_mips_opts.oddspreg = 1;
14850       break;
14851
14852     case OPTION_NO_ODD_SPREG:
14853       file_mips_opts.oddspreg = 0;
14854       break;
14855
14856     case OPTION_SINGLE_FLOAT:
14857       file_mips_opts.single_float = 1;
14858       break;
14859
14860     case OPTION_DOUBLE_FLOAT:
14861       file_mips_opts.single_float = 0;
14862       break;
14863
14864     case OPTION_SOFT_FLOAT:
14865       file_mips_opts.soft_float = 1;
14866       break;
14867
14868     case OPTION_HARD_FLOAT:
14869       file_mips_opts.soft_float = 0;
14870       break;
14871
14872     case OPTION_MABI:
14873       if (strcmp (arg, "32") == 0)
14874         mips_abi = O32_ABI;
14875       else if (strcmp (arg, "o64") == 0)
14876         mips_abi = O64_ABI;
14877       else if (strcmp (arg, "n32") == 0)
14878         mips_abi = N32_ABI;
14879       else if (strcmp (arg, "64") == 0)
14880         {
14881           mips_abi = N64_ABI;
14882           if (! support_64bit_objects())
14883             as_fatal (_("no compiled in support for 64 bit object file "
14884                         "format"));
14885         }
14886       else if (strcmp (arg, "eabi") == 0)
14887         mips_abi = EABI_ABI;
14888       else
14889         {
14890           as_fatal (_("invalid abi -mabi=%s"), arg);
14891           return 0;
14892         }
14893       break;
14894
14895     case OPTION_M7000_HILO_FIX:
14896       mips_7000_hilo_fix = TRUE;
14897       break;
14898
14899     case OPTION_MNO_7000_HILO_FIX:
14900       mips_7000_hilo_fix = FALSE;
14901       break;
14902
14903     case OPTION_MDEBUG:
14904       mips_flag_mdebug = TRUE;
14905       break;
14906
14907     case OPTION_NO_MDEBUG:
14908       mips_flag_mdebug = FALSE;
14909       break;
14910
14911     case OPTION_PDR:
14912       mips_flag_pdr = TRUE;
14913       break;
14914
14915     case OPTION_NO_PDR:
14916       mips_flag_pdr = FALSE;
14917       break;
14918
14919     case OPTION_MVXWORKS_PIC:
14920       mips_pic = VXWORKS_PIC;
14921       break;
14922
14923     case OPTION_NAN:
14924       if (strcmp (arg, "2008") == 0)
14925         mips_nan2008 = 1;
14926       else if (strcmp (arg, "legacy") == 0)
14927         mips_nan2008 = 0;
14928       else
14929         {
14930           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14931           return 0;
14932         }
14933       break;
14934
14935     default:
14936       return 0;
14937     }
14938
14939     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14940
14941   return 1;
14942 }
14943 \f
14944 /* Set up globals to tune for the ISA or processor described by INFO.  */
14945
14946 static void
14947 mips_set_tune (const struct mips_cpu_info *info)
14948 {
14949   if (info != 0)
14950     mips_tune = info->cpu;
14951 }
14952
14953
14954 void
14955 mips_after_parse_args (void)
14956 {
14957   const struct mips_cpu_info *arch_info = 0;
14958   const struct mips_cpu_info *tune_info = 0;
14959
14960   /* GP relative stuff not working for PE */
14961   if (strncmp (TARGET_OS, "pe", 2) == 0)
14962     {
14963       if (g_switch_seen && g_switch_value != 0)
14964         as_bad (_("-G not supported in this configuration"));
14965       g_switch_value = 0;
14966     }
14967
14968   if (mips_abi == NO_ABI)
14969     mips_abi = MIPS_DEFAULT_ABI;
14970
14971   /* The following code determines the architecture.
14972      Similar code was added to GCC 3.3 (see override_options() in
14973      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14974      as much as possible.  */
14975
14976   if (mips_arch_string != 0)
14977     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14978
14979   if (file_mips_opts.isa != ISA_UNKNOWN)
14980     {
14981       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14982          ISA level specified by -mipsN, while arch_info->isa contains
14983          the -march selection (if any).  */
14984       if (arch_info != 0)
14985         {
14986           /* -march takes precedence over -mipsN, since it is more descriptive.
14987              There's no harm in specifying both as long as the ISA levels
14988              are the same.  */
14989           if (file_mips_opts.isa != arch_info->isa)
14990             as_bad (_("-%s conflicts with the other architecture options,"
14991                       " which imply -%s"),
14992                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14993                     mips_cpu_info_from_isa (arch_info->isa)->name);
14994         }
14995       else
14996         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14997     }
14998
14999   if (arch_info == 0)
15000     {
15001       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15002       gas_assert (arch_info);
15003     }
15004
15005   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15006     as_bad (_("-march=%s is not compatible with the selected ABI"),
15007             arch_info->name);
15008
15009   file_mips_opts.arch = arch_info->cpu;
15010   file_mips_opts.isa = arch_info->isa;
15011
15012   /* Set up initial mips_opts state.  */
15013   mips_opts = file_mips_opts;
15014
15015   /* The register size inference code is now placed in
15016      file_mips_check_options.  */
15017
15018   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
15019      processor.  */
15020   if (mips_tune_string != 0)
15021     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15022
15023   if (tune_info == 0)
15024     mips_set_tune (arch_info);
15025   else
15026     mips_set_tune (tune_info);
15027
15028   if (mips_flag_mdebug < 0)
15029     mips_flag_mdebug = 0;
15030 }
15031 \f
15032 void
15033 mips_init_after_args (void)
15034 {
15035   /* initialize opcodes */
15036   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15037   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15038 }
15039
15040 long
15041 md_pcrel_from (fixS *fixP)
15042 {
15043   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15044   switch (fixP->fx_r_type)
15045     {
15046     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15047     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15048       /* Return the address of the delay slot.  */
15049       return addr + 2;
15050
15051     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15052     case BFD_RELOC_MICROMIPS_JMP:
15053     case BFD_RELOC_MIPS16_16_PCREL_S1:
15054     case BFD_RELOC_16_PCREL_S2:
15055     case BFD_RELOC_MIPS_21_PCREL_S2:
15056     case BFD_RELOC_MIPS_26_PCREL_S2:
15057     case BFD_RELOC_MIPS_JMP:
15058       /* Return the address of the delay slot.  */
15059       return addr + 4;
15060
15061     case BFD_RELOC_MIPS_18_PCREL_S3:
15062       /* Return the aligned address of the doubleword containing
15063          the instruction.  */
15064       return addr & ~7;
15065
15066     default:
15067       return addr;
15068     }
15069 }
15070
15071 /* This is called before the symbol table is processed.  In order to
15072    work with gcc when using mips-tfile, we must keep all local labels.
15073    However, in other cases, we want to discard them.  If we were
15074    called with -g, but we didn't see any debugging information, it may
15075    mean that gcc is smuggling debugging information through to
15076    mips-tfile, in which case we must generate all local labels.  */
15077
15078 void
15079 mips_frob_file_before_adjust (void)
15080 {
15081 #ifndef NO_ECOFF_DEBUGGING
15082   if (ECOFF_DEBUGGING
15083       && mips_debug != 0
15084       && ! ecoff_debugging_seen)
15085     flag_keep_locals = 1;
15086 #endif
15087 }
15088
15089 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15090    the corresponding LO16 reloc.  This is called before md_apply_fix and
15091    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15092    relocation operators.
15093
15094    For our purposes, a %lo() expression matches a %got() or %hi()
15095    expression if:
15096
15097       (a) it refers to the same symbol; and
15098       (b) the offset applied in the %lo() expression is no lower than
15099           the offset applied in the %got() or %hi().
15100
15101    (b) allows us to cope with code like:
15102
15103         lui     $4,%hi(foo)
15104         lh      $4,%lo(foo+2)($4)
15105
15106    ...which is legal on RELA targets, and has a well-defined behaviour
15107    if the user knows that adding 2 to "foo" will not induce a carry to
15108    the high 16 bits.
15109
15110    When several %lo()s match a particular %got() or %hi(), we use the
15111    following rules to distinguish them:
15112
15113      (1) %lo()s with smaller offsets are a better match than %lo()s with
15114          higher offsets.
15115
15116      (2) %lo()s with no matching %got() or %hi() are better than those
15117          that already have a matching %got() or %hi().
15118
15119      (3) later %lo()s are better than earlier %lo()s.
15120
15121    These rules are applied in order.
15122
15123    (1) means, among other things, that %lo()s with identical offsets are
15124    chosen if they exist.
15125
15126    (2) means that we won't associate several high-part relocations with
15127    the same low-part relocation unless there's no alternative.  Having
15128    several high parts for the same low part is a GNU extension; this rule
15129    allows careful users to avoid it.
15130
15131    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15132    with the last high-part relocation being at the front of the list.
15133    It therefore makes sense to choose the last matching low-part
15134    relocation, all other things being equal.  It's also easier
15135    to code that way.  */
15136
15137 void
15138 mips_frob_file (void)
15139 {
15140   struct mips_hi_fixup *l;
15141   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15142
15143   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15144     {
15145       segment_info_type *seginfo;
15146       bfd_boolean matched_lo_p;
15147       fixS **hi_pos, **lo_pos, **pos;
15148
15149       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15150
15151       /* If a GOT16 relocation turns out to be against a global symbol,
15152          there isn't supposed to be a matching LO.  Ignore %gots against
15153          constants; we'll report an error for those later.  */
15154       if (got16_reloc_p (l->fixp->fx_r_type)
15155           && !(l->fixp->fx_addsy
15156                && pic_need_relax (l->fixp->fx_addsy)))
15157         continue;
15158
15159       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15160       if (fixup_has_matching_lo_p (l->fixp))
15161         continue;
15162
15163       seginfo = seg_info (l->seg);
15164
15165       /* Set HI_POS to the position of this relocation in the chain.
15166          Set LO_POS to the position of the chosen low-part relocation.
15167          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15168          relocation that matches an immediately-preceding high-part
15169          relocation.  */
15170       hi_pos = NULL;
15171       lo_pos = NULL;
15172       matched_lo_p = FALSE;
15173       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15174
15175       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15176         {
15177           if (*pos == l->fixp)
15178             hi_pos = pos;
15179
15180           if ((*pos)->fx_r_type == looking_for_rtype
15181               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15182               && (*pos)->fx_offset >= l->fixp->fx_offset
15183               && (lo_pos == NULL
15184                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15185                   || (!matched_lo_p
15186                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15187             lo_pos = pos;
15188
15189           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15190                           && fixup_has_matching_lo_p (*pos));
15191         }
15192
15193       /* If we found a match, remove the high-part relocation from its
15194          current position and insert it before the low-part relocation.
15195          Make the offsets match so that fixup_has_matching_lo_p()
15196          will return true.
15197
15198          We don't warn about unmatched high-part relocations since some
15199          versions of gcc have been known to emit dead "lui ...%hi(...)"
15200          instructions.  */
15201       if (lo_pos != NULL)
15202         {
15203           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15204           if (l->fixp->fx_next != *lo_pos)
15205             {
15206               *hi_pos = l->fixp->fx_next;
15207               l->fixp->fx_next = *lo_pos;
15208               *lo_pos = l->fixp;
15209             }
15210         }
15211     }
15212 }
15213
15214 int
15215 mips_force_relocation (fixS *fixp)
15216 {
15217   if (generic_force_reloc (fixp))
15218     return 1;
15219
15220   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15221      so that the linker relaxation can update targets.  */
15222   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15223       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15224       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15225     return 1;
15226
15227   /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15228      and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15229      microMIPS symbols so that we can do cross-mode branch diagnostics
15230      and BAL to JALX conversion by the linker.  */
15231   if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15232        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15233        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15234       && fixp->fx_addsy
15235       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15236     return 1;
15237
15238   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15239   if (ISA_IS_R6 (file_mips_opts.isa)
15240       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15241           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15242           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15243           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15244           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15245           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15246           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15247     return 1;
15248
15249   return 0;
15250 }
15251
15252 /* Implement TC_FORCE_RELOCATION_ABS.  */
15253
15254 bfd_boolean
15255 mips_force_relocation_abs (fixS *fixp)
15256 {
15257   if (generic_force_reloc (fixp))
15258     return TRUE;
15259
15260   /* These relocations do not have enough bits in the in-place addend
15261      to hold an arbitrary absolute section's offset.  */
15262   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15263     return TRUE;
15264
15265   return FALSE;
15266 }
15267
15268 /* Read the instruction associated with RELOC from BUF.  */
15269
15270 static unsigned int
15271 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15272 {
15273   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15274     return read_compressed_insn (buf, 4);
15275   else
15276     return read_insn (buf);
15277 }
15278
15279 /* Write instruction INSN to BUF, given that it has been relocated
15280    by RELOC.  */
15281
15282 static void
15283 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15284                   unsigned long insn)
15285 {
15286   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15287     write_compressed_insn (buf, insn, 4);
15288   else
15289     write_insn (buf, insn);
15290 }
15291
15292 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15293    to a symbol in another ISA mode, which cannot be converted to JALX.  */
15294
15295 static bfd_boolean
15296 fix_bad_cross_mode_jump_p (fixS *fixP)
15297 {
15298   unsigned long opcode;
15299   int other;
15300   char *buf;
15301
15302   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15303     return FALSE;
15304
15305   other = S_GET_OTHER (fixP->fx_addsy);
15306   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15307   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15308   switch (fixP->fx_r_type)
15309     {
15310     case BFD_RELOC_MIPS_JMP:
15311       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15312     case BFD_RELOC_MICROMIPS_JMP:
15313       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15314     default:
15315       return FALSE;
15316     }
15317 }
15318
15319 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15320    jump to a symbol in the same ISA mode.  */
15321
15322 static bfd_boolean
15323 fix_bad_same_mode_jalx_p (fixS *fixP)
15324 {
15325   unsigned long opcode;
15326   int other;
15327   char *buf;
15328
15329   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15330     return FALSE;
15331
15332   other = S_GET_OTHER (fixP->fx_addsy);
15333   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15334   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15335   switch (fixP->fx_r_type)
15336     {
15337     case BFD_RELOC_MIPS_JMP:
15338       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15339     case BFD_RELOC_MIPS16_JMP:
15340       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15341     case BFD_RELOC_MICROMIPS_JMP:
15342       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15343     default:
15344       return FALSE;
15345     }
15346 }
15347
15348 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15349    to a symbol whose value plus addend is not aligned according to the
15350    ultimate (after linker relaxation) jump instruction's immediate field
15351    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15352    regular MIPS code, to (1 << 2).  */
15353
15354 static bfd_boolean
15355 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15356 {
15357   bfd_boolean micro_to_mips_p;
15358   valueT val;
15359   int other;
15360
15361   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15362     return FALSE;
15363
15364   other = S_GET_OTHER (fixP->fx_addsy);
15365   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15366   val += fixP->fx_offset;
15367   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15368                      && !ELF_ST_IS_MICROMIPS (other));
15369   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15370           != ELF_ST_IS_COMPRESSED (other));
15371 }
15372
15373 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15374    to a symbol whose annotation indicates another ISA mode.  For absolute
15375    symbols check the ISA bit instead.
15376
15377    We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15378    symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15379    MIPS symbols and associated with BAL instructions as these instructions
15380    may be converted to JALX by the linker.  */
15381
15382 static bfd_boolean
15383 fix_bad_cross_mode_branch_p (fixS *fixP)
15384 {
15385   bfd_boolean absolute_p;
15386   unsigned long opcode;
15387   asection *symsec;
15388   valueT val;
15389   int other;
15390   char *buf;
15391
15392   if (mips_ignore_branch_isa)
15393     return FALSE;
15394
15395   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15396     return FALSE;
15397
15398   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15399   absolute_p = bfd_is_abs_section (symsec);
15400
15401   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15402   other = S_GET_OTHER (fixP->fx_addsy);
15403
15404   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15405   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15406   switch (fixP->fx_r_type)
15407     {
15408     case BFD_RELOC_16_PCREL_S2:
15409       return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15410               && opcode != 0x0411);
15411     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15412       return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15413               && opcode != 0x4060);
15414     case BFD_RELOC_MIPS_21_PCREL_S2:
15415     case BFD_RELOC_MIPS_26_PCREL_S2:
15416       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15417     case BFD_RELOC_MIPS16_16_PCREL_S1:
15418       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15419     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15420     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15421       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15422     default:
15423       abort ();
15424     }
15425 }
15426
15427 /* Return TRUE if the symbol plus addend associated with a regular MIPS
15428    branch instruction pointed to by FIXP is not aligned according to the
15429    branch instruction's immediate field requirement.  We need the addend
15430    to preserve the ISA bit and also the sum must not have bit 2 set.  We
15431    must explicitly OR in the ISA bit from symbol annotation as the bit
15432    won't be set in the symbol's value then.  */
15433
15434 static bfd_boolean
15435 fix_bad_misaligned_branch_p (fixS *fixP)
15436 {
15437   bfd_boolean absolute_p;
15438   asection *symsec;
15439   valueT isa_bit;
15440   valueT val;
15441   valueT off;
15442   int other;
15443
15444   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15445     return FALSE;
15446
15447   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15448   absolute_p = bfd_is_abs_section (symsec);
15449
15450   val = S_GET_VALUE (fixP->fx_addsy);
15451   other = S_GET_OTHER (fixP->fx_addsy);
15452   off = fixP->fx_offset;
15453
15454   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15455   val |= ELF_ST_IS_COMPRESSED (other);
15456   val += off;
15457   return (val & 0x3) != isa_bit;
15458 }
15459
15460 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15461    and its calculated value VAL.  */
15462
15463 static void
15464 fix_validate_branch (fixS *fixP, valueT val)
15465 {
15466   if (fixP->fx_done && (val & 0x3) != 0)
15467     as_bad_where (fixP->fx_file, fixP->fx_line,
15468                   _("branch to misaligned address (0x%lx)"),
15469                   (long) (val + md_pcrel_from (fixP)));
15470   else if (fix_bad_cross_mode_branch_p (fixP))
15471     as_bad_where (fixP->fx_file, fixP->fx_line,
15472                   _("branch to a symbol in another ISA mode"));
15473   else if (fix_bad_misaligned_branch_p (fixP))
15474     as_bad_where (fixP->fx_file, fixP->fx_line,
15475                   _("branch to misaligned address (0x%lx)"),
15476                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15477   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15478     as_bad_where (fixP->fx_file, fixP->fx_line,
15479                   _("cannot encode misaligned addend "
15480                     "in the relocatable field (0x%lx)"),
15481                   (long) fixP->fx_offset);
15482 }
15483
15484 /* Apply a fixup to the object file.  */
15485
15486 void
15487 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15488 {
15489   char *buf;
15490   unsigned long insn;
15491   reloc_howto_type *howto;
15492
15493   if (fixP->fx_pcrel)
15494     switch (fixP->fx_r_type)
15495       {
15496       case BFD_RELOC_16_PCREL_S2:
15497       case BFD_RELOC_MIPS16_16_PCREL_S1:
15498       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15499       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15500       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15501       case BFD_RELOC_32_PCREL:
15502       case BFD_RELOC_MIPS_21_PCREL_S2:
15503       case BFD_RELOC_MIPS_26_PCREL_S2:
15504       case BFD_RELOC_MIPS_18_PCREL_S3:
15505       case BFD_RELOC_MIPS_19_PCREL_S2:
15506       case BFD_RELOC_HI16_S_PCREL:
15507       case BFD_RELOC_LO16_PCREL:
15508         break;
15509
15510       case BFD_RELOC_32:
15511         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15512         break;
15513
15514       default:
15515         as_bad_where (fixP->fx_file, fixP->fx_line,
15516                       _("PC-relative reference to a different section"));
15517         break;
15518       }
15519
15520   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15521      that have no MIPS ELF equivalent.  */
15522   if (fixP->fx_r_type != BFD_RELOC_8)
15523     {
15524       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15525       if (!howto)
15526         return;
15527     }
15528
15529   gas_assert (fixP->fx_size == 2
15530               || fixP->fx_size == 4
15531               || fixP->fx_r_type == BFD_RELOC_8
15532               || fixP->fx_r_type == BFD_RELOC_16
15533               || fixP->fx_r_type == BFD_RELOC_64
15534               || fixP->fx_r_type == BFD_RELOC_CTOR
15535               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15536               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15537               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15538               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15539               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15540               || fixP->fx_r_type == BFD_RELOC_NONE);
15541
15542   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15543
15544   /* Don't treat parts of a composite relocation as done.  There are two
15545      reasons for this:
15546
15547      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15548          should nevertheless be emitted if the first part is.
15549
15550      (2) In normal usage, composite relocations are never assembly-time
15551          constants.  The easiest way of dealing with the pathological
15552          exceptions is to generate a relocation against STN_UNDEF and
15553          leave everything up to the linker.  */
15554   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15555     fixP->fx_done = 1;
15556
15557   switch (fixP->fx_r_type)
15558     {
15559     case BFD_RELOC_MIPS_TLS_GD:
15560     case BFD_RELOC_MIPS_TLS_LDM:
15561     case BFD_RELOC_MIPS_TLS_DTPREL32:
15562     case BFD_RELOC_MIPS_TLS_DTPREL64:
15563     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15564     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15565     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15566     case BFD_RELOC_MIPS_TLS_TPREL32:
15567     case BFD_RELOC_MIPS_TLS_TPREL64:
15568     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15569     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15570     case BFD_RELOC_MICROMIPS_TLS_GD:
15571     case BFD_RELOC_MICROMIPS_TLS_LDM:
15572     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15573     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15574     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15575     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15576     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15577     case BFD_RELOC_MIPS16_TLS_GD:
15578     case BFD_RELOC_MIPS16_TLS_LDM:
15579     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15580     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15581     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15582     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15583     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15584       if (fixP->fx_addsy)
15585         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15586       else
15587         as_bad_where (fixP->fx_file, fixP->fx_line,
15588                       _("TLS relocation against a constant"));
15589       break;
15590
15591     case BFD_RELOC_MIPS_JMP:
15592     case BFD_RELOC_MIPS16_JMP:
15593     case BFD_RELOC_MICROMIPS_JMP:
15594       {
15595         int shift;
15596
15597         gas_assert (!fixP->fx_done);
15598
15599         /* Shift is 2, unusually, for microMIPS JALX.  */
15600         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15601             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15602           shift = 1;
15603         else
15604           shift = 2;
15605
15606         if (fix_bad_cross_mode_jump_p (fixP))
15607           as_bad_where (fixP->fx_file, fixP->fx_line,
15608                         _("jump to a symbol in another ISA mode"));
15609         else if (fix_bad_same_mode_jalx_p (fixP))
15610           as_bad_where (fixP->fx_file, fixP->fx_line,
15611                         _("JALX to a symbol in the same ISA mode"));
15612         else if (fix_bad_misaligned_jump_p (fixP, shift))
15613           as_bad_where (fixP->fx_file, fixP->fx_line,
15614                         _("jump to misaligned address (0x%lx)"),
15615                         (long) (S_GET_VALUE (fixP->fx_addsy)
15616                                 + fixP->fx_offset));
15617         else if (HAVE_IN_PLACE_ADDENDS
15618                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15619           as_bad_where (fixP->fx_file, fixP->fx_line,
15620                         _("cannot encode misaligned addend "
15621                           "in the relocatable field (0x%lx)"),
15622                         (long) fixP->fx_offset);
15623       }
15624       /* Fall through.  */
15625
15626     case BFD_RELOC_MIPS_SHIFT5:
15627     case BFD_RELOC_MIPS_SHIFT6:
15628     case BFD_RELOC_MIPS_GOT_DISP:
15629     case BFD_RELOC_MIPS_GOT_PAGE:
15630     case BFD_RELOC_MIPS_GOT_OFST:
15631     case BFD_RELOC_MIPS_SUB:
15632     case BFD_RELOC_MIPS_INSERT_A:
15633     case BFD_RELOC_MIPS_INSERT_B:
15634     case BFD_RELOC_MIPS_DELETE:
15635     case BFD_RELOC_MIPS_HIGHEST:
15636     case BFD_RELOC_MIPS_HIGHER:
15637     case BFD_RELOC_MIPS_SCN_DISP:
15638     case BFD_RELOC_MIPS_REL16:
15639     case BFD_RELOC_MIPS_RELGOT:
15640     case BFD_RELOC_MIPS_JALR:
15641     case BFD_RELOC_HI16:
15642     case BFD_RELOC_HI16_S:
15643     case BFD_RELOC_LO16:
15644     case BFD_RELOC_GPREL16:
15645     case BFD_RELOC_MIPS_LITERAL:
15646     case BFD_RELOC_MIPS_CALL16:
15647     case BFD_RELOC_MIPS_GOT16:
15648     case BFD_RELOC_GPREL32:
15649     case BFD_RELOC_MIPS_GOT_HI16:
15650     case BFD_RELOC_MIPS_GOT_LO16:
15651     case BFD_RELOC_MIPS_CALL_HI16:
15652     case BFD_RELOC_MIPS_CALL_LO16:
15653     case BFD_RELOC_HI16_S_PCREL:
15654     case BFD_RELOC_LO16_PCREL:
15655     case BFD_RELOC_MIPS16_GPREL:
15656     case BFD_RELOC_MIPS16_GOT16:
15657     case BFD_RELOC_MIPS16_CALL16:
15658     case BFD_RELOC_MIPS16_HI16:
15659     case BFD_RELOC_MIPS16_HI16_S:
15660     case BFD_RELOC_MIPS16_LO16:
15661     case BFD_RELOC_MICROMIPS_GOT_DISP:
15662     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15663     case BFD_RELOC_MICROMIPS_GOT_OFST:
15664     case BFD_RELOC_MICROMIPS_SUB:
15665     case BFD_RELOC_MICROMIPS_HIGHEST:
15666     case BFD_RELOC_MICROMIPS_HIGHER:
15667     case BFD_RELOC_MICROMIPS_SCN_DISP:
15668     case BFD_RELOC_MICROMIPS_JALR:
15669     case BFD_RELOC_MICROMIPS_HI16:
15670     case BFD_RELOC_MICROMIPS_HI16_S:
15671     case BFD_RELOC_MICROMIPS_LO16:
15672     case BFD_RELOC_MICROMIPS_GPREL16:
15673     case BFD_RELOC_MICROMIPS_LITERAL:
15674     case BFD_RELOC_MICROMIPS_CALL16:
15675     case BFD_RELOC_MICROMIPS_GOT16:
15676     case BFD_RELOC_MICROMIPS_GOT_HI16:
15677     case BFD_RELOC_MICROMIPS_GOT_LO16:
15678     case BFD_RELOC_MICROMIPS_CALL_HI16:
15679     case BFD_RELOC_MICROMIPS_CALL_LO16:
15680     case BFD_RELOC_MIPS_EH:
15681       if (fixP->fx_done)
15682         {
15683           offsetT value;
15684
15685           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15686             {
15687               insn = read_reloc_insn (buf, fixP->fx_r_type);
15688               if (mips16_reloc_p (fixP->fx_r_type))
15689                 insn |= mips16_immed_extend (value, 16);
15690               else
15691                 insn |= (value & 0xffff);
15692               write_reloc_insn (buf, fixP->fx_r_type, insn);
15693             }
15694           else
15695             as_bad_where (fixP->fx_file, fixP->fx_line,
15696                           _("unsupported constant in relocation"));
15697         }
15698       break;
15699
15700     case BFD_RELOC_64:
15701       /* This is handled like BFD_RELOC_32, but we output a sign
15702          extended value if we are only 32 bits.  */
15703       if (fixP->fx_done)
15704         {
15705           if (8 <= sizeof (valueT))
15706             md_number_to_chars (buf, *valP, 8);
15707           else
15708             {
15709               valueT hiv;
15710
15711               if ((*valP & 0x80000000) != 0)
15712                 hiv = 0xffffffff;
15713               else
15714                 hiv = 0;
15715               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15716               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15717             }
15718         }
15719       break;
15720
15721     case BFD_RELOC_RVA:
15722     case BFD_RELOC_32:
15723     case BFD_RELOC_32_PCREL:
15724     case BFD_RELOC_16:
15725     case BFD_RELOC_8:
15726       /* If we are deleting this reloc entry, we must fill in the
15727          value now.  This can happen if we have a .word which is not
15728          resolved when it appears but is later defined.  */
15729       if (fixP->fx_done)
15730         md_number_to_chars (buf, *valP, fixP->fx_size);
15731       break;
15732
15733     case BFD_RELOC_MIPS_21_PCREL_S2:
15734       fix_validate_branch (fixP, *valP);
15735       if (!fixP->fx_done)
15736         break;
15737
15738       if (*valP + 0x400000 <= 0x7fffff)
15739         {
15740           insn = read_insn (buf);
15741           insn |= (*valP >> 2) & 0x1fffff;
15742           write_insn (buf, insn);
15743         }
15744       else
15745         as_bad_where (fixP->fx_file, fixP->fx_line,
15746                       _("branch out of range"));
15747       break;
15748
15749     case BFD_RELOC_MIPS_26_PCREL_S2:
15750       fix_validate_branch (fixP, *valP);
15751       if (!fixP->fx_done)
15752         break;
15753
15754       if (*valP + 0x8000000 <= 0xfffffff)
15755         {
15756           insn = read_insn (buf);
15757           insn |= (*valP >> 2) & 0x3ffffff;
15758           write_insn (buf, insn);
15759         }
15760       else
15761         as_bad_where (fixP->fx_file, fixP->fx_line,
15762                       _("branch out of range"));
15763       break;
15764
15765     case BFD_RELOC_MIPS_18_PCREL_S3:
15766       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15767         as_bad_where (fixP->fx_file, fixP->fx_line,
15768                       _("PC-relative access using misaligned symbol (%lx)"),
15769                       (long) S_GET_VALUE (fixP->fx_addsy));
15770       if ((fixP->fx_offset & 0x7) != 0)
15771         as_bad_where (fixP->fx_file, fixP->fx_line,
15772                       _("PC-relative access using misaligned offset (%lx)"),
15773                       (long) fixP->fx_offset);
15774       if (!fixP->fx_done)
15775         break;
15776
15777       if (*valP + 0x100000 <= 0x1fffff)
15778         {
15779           insn = read_insn (buf);
15780           insn |= (*valP >> 3) & 0x3ffff;
15781           write_insn (buf, insn);
15782         }
15783       else
15784         as_bad_where (fixP->fx_file, fixP->fx_line,
15785                       _("PC-relative access out of range"));
15786       break;
15787
15788     case BFD_RELOC_MIPS_19_PCREL_S2:
15789       if ((*valP & 0x3) != 0)
15790         as_bad_where (fixP->fx_file, fixP->fx_line,
15791                       _("PC-relative access to misaligned address (%lx)"),
15792                       (long) *valP);
15793       if (!fixP->fx_done)
15794         break;
15795
15796       if (*valP + 0x100000 <= 0x1fffff)
15797         {
15798           insn = read_insn (buf);
15799           insn |= (*valP >> 2) & 0x7ffff;
15800           write_insn (buf, insn);
15801         }
15802       else
15803         as_bad_where (fixP->fx_file, fixP->fx_line,
15804                       _("PC-relative access out of range"));
15805       break;
15806
15807     case BFD_RELOC_16_PCREL_S2:
15808       fix_validate_branch (fixP, *valP);
15809
15810       /* We need to save the bits in the instruction since fixup_segment()
15811          might be deleting the relocation entry (i.e., a branch within
15812          the current segment).  */
15813       if (! fixP->fx_done)
15814         break;
15815
15816       /* Update old instruction data.  */
15817       insn = read_insn (buf);
15818
15819       if (*valP + 0x20000 <= 0x3ffff)
15820         {
15821           insn |= (*valP >> 2) & 0xffff;
15822           write_insn (buf, insn);
15823         }
15824       else if (fixP->fx_tcbit2
15825                && fixP->fx_done
15826                && fixP->fx_frag->fr_address >= text_section->vma
15827                && (fixP->fx_frag->fr_address
15828                    < text_section->vma + bfd_get_section_size (text_section))
15829                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15830                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15831                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15832         {
15833           /* The branch offset is too large.  If this is an
15834              unconditional branch, and we are not generating PIC code,
15835              we can convert it to an absolute jump instruction.  */
15836           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15837             insn = 0x0c000000;  /* jal */
15838           else
15839             insn = 0x08000000;  /* j */
15840           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15841           fixP->fx_done = 0;
15842           fixP->fx_addsy = section_symbol (text_section);
15843           *valP += md_pcrel_from (fixP);
15844           write_insn (buf, insn);
15845         }
15846       else
15847         {
15848           /* If we got here, we have branch-relaxation disabled,
15849              and there's nothing we can do to fix this instruction
15850              without turning it into a longer sequence.  */
15851           as_bad_where (fixP->fx_file, fixP->fx_line,
15852                         _("branch out of range"));
15853         }
15854       break;
15855
15856     case BFD_RELOC_MIPS16_16_PCREL_S1:
15857     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15858     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15859     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15860       gas_assert (!fixP->fx_done);
15861       if (fix_bad_cross_mode_branch_p (fixP))
15862         as_bad_where (fixP->fx_file, fixP->fx_line,
15863                       _("branch to a symbol in another ISA mode"));
15864       else if (fixP->fx_addsy
15865                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15866                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15867                && (fixP->fx_offset & 0x1) != 0)
15868         as_bad_where (fixP->fx_file, fixP->fx_line,
15869                       _("branch to misaligned address (0x%lx)"),
15870                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15871       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15872         as_bad_where (fixP->fx_file, fixP->fx_line,
15873                       _("cannot encode misaligned addend "
15874                         "in the relocatable field (0x%lx)"),
15875                       (long) fixP->fx_offset);
15876       break;
15877
15878     case BFD_RELOC_VTABLE_INHERIT:
15879       fixP->fx_done = 0;
15880       if (fixP->fx_addsy
15881           && !S_IS_DEFINED (fixP->fx_addsy)
15882           && !S_IS_WEAK (fixP->fx_addsy))
15883         S_SET_WEAK (fixP->fx_addsy);
15884       break;
15885
15886     case BFD_RELOC_NONE:
15887     case BFD_RELOC_VTABLE_ENTRY:
15888       fixP->fx_done = 0;
15889       break;
15890
15891     default:
15892       abort ();
15893     }
15894
15895   /* Remember value for tc_gen_reloc.  */
15896   fixP->fx_addnumber = *valP;
15897 }
15898
15899 static symbolS *
15900 get_symbol (void)
15901 {
15902   int c;
15903   char *name;
15904   symbolS *p;
15905
15906   c = get_symbol_name (&name);
15907   p = (symbolS *) symbol_find_or_make (name);
15908   (void) restore_line_pointer (c);
15909   return p;
15910 }
15911
15912 /* Align the current frag to a given power of two.  If a particular
15913    fill byte should be used, FILL points to an integer that contains
15914    that byte, otherwise FILL is null.
15915
15916    This function used to have the comment:
15917
15918       The MIPS assembler also automatically adjusts any preceding label.
15919
15920    The implementation therefore applied the adjustment to a maximum of
15921    one label.  However, other label adjustments are applied to batches
15922    of labels, and adjusting just one caused problems when new labels
15923    were added for the sake of debugging or unwind information.
15924    We therefore adjust all preceding labels (given as LABELS) instead.  */
15925
15926 static void
15927 mips_align (int to, int *fill, struct insn_label_list *labels)
15928 {
15929   mips_emit_delays ();
15930   mips_record_compressed_mode ();
15931   if (fill == NULL && subseg_text_p (now_seg))
15932     frag_align_code (to, 0);
15933   else
15934     frag_align (to, fill ? *fill : 0, 0);
15935   record_alignment (now_seg, to);
15936   mips_move_labels (labels, FALSE);
15937 }
15938
15939 /* Align to a given power of two.  .align 0 turns off the automatic
15940    alignment used by the data creating pseudo-ops.  */
15941
15942 static void
15943 s_align (int x ATTRIBUTE_UNUSED)
15944 {
15945   int temp, fill_value, *fill_ptr;
15946   long max_alignment = 28;
15947
15948   /* o Note that the assembler pulls down any immediately preceding label
15949        to the aligned address.
15950      o It's not documented but auto alignment is reinstated by
15951        a .align pseudo instruction.
15952      o Note also that after auto alignment is turned off the mips assembler
15953        issues an error on attempt to assemble an improperly aligned data item.
15954        We don't.  */
15955
15956   temp = get_absolute_expression ();
15957   if (temp > max_alignment)
15958     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15959   else if (temp < 0)
15960     {
15961       as_warn (_("alignment negative, 0 assumed"));
15962       temp = 0;
15963     }
15964   if (*input_line_pointer == ',')
15965     {
15966       ++input_line_pointer;
15967       fill_value = get_absolute_expression ();
15968       fill_ptr = &fill_value;
15969     }
15970   else
15971     fill_ptr = 0;
15972   if (temp)
15973     {
15974       segment_info_type *si = seg_info (now_seg);
15975       struct insn_label_list *l = si->label_list;
15976       /* Auto alignment should be switched on by next section change.  */
15977       auto_align = 1;
15978       mips_align (temp, fill_ptr, l);
15979     }
15980   else
15981     {
15982       auto_align = 0;
15983     }
15984
15985   demand_empty_rest_of_line ();
15986 }
15987
15988 static void
15989 s_change_sec (int sec)
15990 {
15991   segT seg;
15992
15993   /* The ELF backend needs to know that we are changing sections, so
15994      that .previous works correctly.  We could do something like check
15995      for an obj_section_change_hook macro, but that might be confusing
15996      as it would not be appropriate to use it in the section changing
15997      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15998      This should be cleaner, somehow.  */
15999   obj_elf_section_change_hook ();
16000
16001   mips_emit_delays ();
16002
16003   switch (sec)
16004     {
16005     case 't':
16006       s_text (0);
16007       break;
16008     case 'd':
16009       s_data (0);
16010       break;
16011     case 'b':
16012       subseg_set (bss_section, (subsegT) get_absolute_expression ());
16013       demand_empty_rest_of_line ();
16014       break;
16015
16016     case 'r':
16017       seg = subseg_new (RDATA_SECTION_NAME,
16018                         (subsegT) get_absolute_expression ());
16019       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
16020                                               | SEC_READONLY | SEC_RELOC
16021                                               | SEC_DATA));
16022       if (strncmp (TARGET_OS, "elf", 3) != 0)
16023         record_alignment (seg, 4);
16024       demand_empty_rest_of_line ();
16025       break;
16026
16027     case 's':
16028       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
16029       bfd_set_section_flags (stdoutput, seg,
16030                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
16031       if (strncmp (TARGET_OS, "elf", 3) != 0)
16032         record_alignment (seg, 4);
16033       demand_empty_rest_of_line ();
16034       break;
16035
16036     case 'B':
16037       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
16038       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
16039       if (strncmp (TARGET_OS, "elf", 3) != 0)
16040         record_alignment (seg, 4);
16041       demand_empty_rest_of_line ();
16042       break;
16043     }
16044
16045   auto_align = 1;
16046 }
16047
16048 void
16049 s_change_section (int ignore ATTRIBUTE_UNUSED)
16050 {
16051   char *saved_ilp;
16052   char *section_name;
16053   char c, endc;
16054   char next_c = 0;
16055   int section_type;
16056   int section_flag;
16057   int section_entry_size;
16058   int section_alignment;
16059
16060   saved_ilp = input_line_pointer;
16061   endc = get_symbol_name (&section_name);
16062   c = (endc == '"' ? input_line_pointer[1] : endc);
16063   if (c)
16064     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
16065
16066   /* Do we have .section Name<,"flags">?  */
16067   if (c != ',' || (c == ',' && next_c == '"'))
16068     {
16069       /* Just after name is now '\0'.  */
16070       (void) restore_line_pointer (endc);
16071       input_line_pointer = saved_ilp;
16072       obj_elf_section (ignore);
16073       return;
16074     }
16075
16076   section_name = xstrdup (section_name);
16077   c = restore_line_pointer (endc);
16078
16079   input_line_pointer++;
16080
16081   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16082   if (c == ',')
16083     section_type = get_absolute_expression ();
16084   else
16085     section_type = 0;
16086
16087   if (*input_line_pointer++ == ',')
16088     section_flag = get_absolute_expression ();
16089   else
16090     section_flag = 0;
16091
16092   if (*input_line_pointer++ == ',')
16093     section_entry_size = get_absolute_expression ();
16094   else
16095     section_entry_size = 0;
16096
16097   if (*input_line_pointer++ == ',')
16098     section_alignment = get_absolute_expression ();
16099   else
16100     section_alignment = 0;
16101
16102   /* FIXME: really ignore?  */
16103   (void) section_alignment;
16104
16105   /* When using the generic form of .section (as implemented by obj-elf.c),
16106      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16107      traditionally had to fall back on the more common @progbits instead.
16108
16109      There's nothing really harmful in this, since bfd will correct
16110      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16111      means that, for backwards compatibility, the special_section entries
16112      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16113
16114      Even so, we shouldn't force users of the MIPS .section syntax to
16115      incorrectly label the sections as SHT_PROGBITS.  The best compromise
16116      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16117      generic type-checking code.  */
16118   if (section_type == SHT_MIPS_DWARF)
16119     section_type = SHT_PROGBITS;
16120
16121   obj_elf_change_section (section_name, section_type, 0, section_flag,
16122                           section_entry_size, 0, 0, 0);
16123
16124   if (now_seg->name != section_name)
16125     free (section_name);
16126 }
16127
16128 void
16129 mips_enable_auto_align (void)
16130 {
16131   auto_align = 1;
16132 }
16133
16134 static void
16135 s_cons (int log_size)
16136 {
16137   segment_info_type *si = seg_info (now_seg);
16138   struct insn_label_list *l = si->label_list;
16139
16140   mips_emit_delays ();
16141   if (log_size > 0 && auto_align)
16142     mips_align (log_size, 0, l);
16143   cons (1 << log_size);
16144   mips_clear_insn_labels ();
16145 }
16146
16147 static void
16148 s_float_cons (int type)
16149 {
16150   segment_info_type *si = seg_info (now_seg);
16151   struct insn_label_list *l = si->label_list;
16152
16153   mips_emit_delays ();
16154
16155   if (auto_align)
16156     {
16157       if (type == 'd')
16158         mips_align (3, 0, l);
16159       else
16160         mips_align (2, 0, l);
16161     }
16162
16163   float_cons (type);
16164   mips_clear_insn_labels ();
16165 }
16166
16167 /* Handle .globl.  We need to override it because on Irix 5 you are
16168    permitted to say
16169        .globl foo .text
16170    where foo is an undefined symbol, to mean that foo should be
16171    considered to be the address of a function.  */
16172
16173 static void
16174 s_mips_globl (int x ATTRIBUTE_UNUSED)
16175 {
16176   char *name;
16177   int c;
16178   symbolS *symbolP;
16179   flagword flag;
16180
16181   do
16182     {
16183       c = get_symbol_name (&name);
16184       symbolP = symbol_find_or_make (name);
16185       S_SET_EXTERNAL (symbolP);
16186
16187       *input_line_pointer = c;
16188       SKIP_WHITESPACE_AFTER_NAME ();
16189
16190       /* On Irix 5, every global symbol that is not explicitly labelled as
16191          being a function is apparently labelled as being an object.  */
16192       flag = BSF_OBJECT;
16193
16194       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16195           && (*input_line_pointer != ','))
16196         {
16197           char *secname;
16198           asection *sec;
16199
16200           c = get_symbol_name (&secname);
16201           sec = bfd_get_section_by_name (stdoutput, secname);
16202           if (sec == NULL)
16203             as_bad (_("%s: no such section"), secname);
16204           (void) restore_line_pointer (c);
16205
16206           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16207             flag = BSF_FUNCTION;
16208         }
16209
16210       symbol_get_bfdsym (symbolP)->flags |= flag;
16211
16212       c = *input_line_pointer;
16213       if (c == ',')
16214         {
16215           input_line_pointer++;
16216           SKIP_WHITESPACE ();
16217           if (is_end_of_line[(unsigned char) *input_line_pointer])
16218             c = '\n';
16219         }
16220     }
16221   while (c == ',');
16222
16223   demand_empty_rest_of_line ();
16224 }
16225
16226 static void
16227 s_option (int x ATTRIBUTE_UNUSED)
16228 {
16229   char *opt;
16230   char c;
16231
16232   c = get_symbol_name (&opt);
16233
16234   if (*opt == 'O')
16235     {
16236       /* FIXME: What does this mean?  */
16237     }
16238   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
16239     {
16240       int i;
16241
16242       i = atoi (opt + 3);
16243       if (i != 0 && i != 2)
16244         as_bad (_(".option pic%d not supported"), i);
16245       else if (mips_pic == VXWORKS_PIC)
16246         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16247       else if (i == 0)
16248         mips_pic = NO_PIC;
16249       else if (i == 2)
16250         {
16251           mips_pic = SVR4_PIC;
16252           mips_abicalls = TRUE;
16253         }
16254
16255       if (mips_pic == SVR4_PIC)
16256         {
16257           if (g_switch_seen && g_switch_value != 0)
16258             as_warn (_("-G may not be used with SVR4 PIC code"));
16259           g_switch_value = 0;
16260           bfd_set_gp_size (stdoutput, 0);
16261         }
16262     }
16263   else
16264     as_warn (_("unrecognized option \"%s\""), opt);
16265
16266   (void) restore_line_pointer (c);
16267   demand_empty_rest_of_line ();
16268 }
16269
16270 /* This structure is used to hold a stack of .set values.  */
16271
16272 struct mips_option_stack
16273 {
16274   struct mips_option_stack *next;
16275   struct mips_set_options options;
16276 };
16277
16278 static struct mips_option_stack *mips_opts_stack;
16279
16280 /* Return status for .set/.module option handling.  */
16281
16282 enum code_option_type
16283 {
16284   /* Unrecognized option.  */
16285   OPTION_TYPE_BAD = -1,
16286
16287   /* Ordinary option.  */
16288   OPTION_TYPE_NORMAL,
16289
16290   /* ISA changing option.  */
16291   OPTION_TYPE_ISA
16292 };
16293
16294 /* Handle common .set/.module options.  Return status indicating option
16295    type.  */
16296
16297 static enum code_option_type
16298 parse_code_option (char * name)
16299 {
16300   bfd_boolean isa_set = FALSE;
16301   const struct mips_ase *ase;
16302
16303   if (strncmp (name, "at=", 3) == 0)
16304     {
16305       char *s = name + 3;
16306
16307       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16308         as_bad (_("unrecognized register name `%s'"), s);
16309     }
16310   else if (strcmp (name, "at") == 0)
16311     mips_opts.at = ATREG;
16312   else if (strcmp (name, "noat") == 0)
16313     mips_opts.at = ZERO;
16314   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16315     mips_opts.nomove = 0;
16316   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16317     mips_opts.nomove = 1;
16318   else if (strcmp (name, "bopt") == 0)
16319     mips_opts.nobopt = 0;
16320   else if (strcmp (name, "nobopt") == 0)
16321     mips_opts.nobopt = 1;
16322   else if (strcmp (name, "gp=32") == 0)
16323     mips_opts.gp = 32;
16324   else if (strcmp (name, "gp=64") == 0)
16325     mips_opts.gp = 64;
16326   else if (strcmp (name, "fp=32") == 0)
16327     mips_opts.fp = 32;
16328   else if (strcmp (name, "fp=xx") == 0)
16329     mips_opts.fp = 0;
16330   else if (strcmp (name, "fp=64") == 0)
16331     mips_opts.fp = 64;
16332   else if (strcmp (name, "softfloat") == 0)
16333     mips_opts.soft_float = 1;
16334   else if (strcmp (name, "hardfloat") == 0)
16335     mips_opts.soft_float = 0;
16336   else if (strcmp (name, "singlefloat") == 0)
16337     mips_opts.single_float = 1;
16338   else if (strcmp (name, "doublefloat") == 0)
16339     mips_opts.single_float = 0;
16340   else if (strcmp (name, "nooddspreg") == 0)
16341     mips_opts.oddspreg = 0;
16342   else if (strcmp (name, "oddspreg") == 0)
16343     mips_opts.oddspreg = 1;
16344   else if (strcmp (name, "mips16") == 0
16345            || strcmp (name, "MIPS-16") == 0)
16346     mips_opts.mips16 = 1;
16347   else if (strcmp (name, "nomips16") == 0
16348            || strcmp (name, "noMIPS-16") == 0)
16349     mips_opts.mips16 = 0;
16350   else if (strcmp (name, "micromips") == 0)
16351     mips_opts.micromips = 1;
16352   else if (strcmp (name, "nomicromips") == 0)
16353     mips_opts.micromips = 0;
16354   else if (name[0] == 'n'
16355            && name[1] == 'o'
16356            && (ase = mips_lookup_ase (name + 2)))
16357     mips_set_ase (ase, &mips_opts, FALSE);
16358   else if ((ase = mips_lookup_ase (name)))
16359     mips_set_ase (ase, &mips_opts, TRUE);
16360   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16361     {
16362       /* Permit the user to change the ISA and architecture on the fly.
16363          Needless to say, misuse can cause serious problems.  */
16364       if (strncmp (name, "arch=", 5) == 0)
16365         {
16366           const struct mips_cpu_info *p;
16367
16368           p = mips_parse_cpu ("internal use", name + 5);
16369           if (!p)
16370             as_bad (_("unknown architecture %s"), name + 5);
16371           else
16372             {
16373               mips_opts.arch = p->cpu;
16374               mips_opts.isa = p->isa;
16375               isa_set = TRUE;
16376             }
16377         }
16378       else if (strncmp (name, "mips", 4) == 0)
16379         {
16380           const struct mips_cpu_info *p;
16381
16382           p = mips_parse_cpu ("internal use", name);
16383           if (!p)
16384             as_bad (_("unknown ISA level %s"), name + 4);
16385           else
16386             {
16387               mips_opts.arch = p->cpu;
16388               mips_opts.isa = p->isa;
16389               isa_set = TRUE;
16390             }
16391         }
16392       else
16393         as_bad (_("unknown ISA or architecture %s"), name);
16394     }
16395   else if (strcmp (name, "autoextend") == 0)
16396     mips_opts.noautoextend = 0;
16397   else if (strcmp (name, "noautoextend") == 0)
16398     mips_opts.noautoextend = 1;
16399   else if (strcmp (name, "insn32") == 0)
16400     mips_opts.insn32 = TRUE;
16401   else if (strcmp (name, "noinsn32") == 0)
16402     mips_opts.insn32 = FALSE;
16403   else if (strcmp (name, "sym32") == 0)
16404     mips_opts.sym32 = TRUE;
16405   else if (strcmp (name, "nosym32") == 0)
16406     mips_opts.sym32 = FALSE;
16407   else
16408     return OPTION_TYPE_BAD;
16409
16410   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16411 }
16412
16413 /* Handle the .set pseudo-op.  */
16414
16415 static void
16416 s_mipsset (int x ATTRIBUTE_UNUSED)
16417 {
16418   enum code_option_type type = OPTION_TYPE_NORMAL;
16419   char *name = input_line_pointer, ch;
16420
16421   file_mips_check_options ();
16422
16423   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16424     ++input_line_pointer;
16425   ch = *input_line_pointer;
16426   *input_line_pointer = '\0';
16427
16428   if (strchr (name, ','))
16429     {
16430       /* Generic ".set" directive; use the generic handler.  */
16431       *input_line_pointer = ch;
16432       input_line_pointer = name;
16433       s_set (0);
16434       return;
16435     }
16436
16437   if (strcmp (name, "reorder") == 0)
16438     {
16439       if (mips_opts.noreorder)
16440         end_noreorder ();
16441     }
16442   else if (strcmp (name, "noreorder") == 0)
16443     {
16444       if (!mips_opts.noreorder)
16445         start_noreorder ();
16446     }
16447   else if (strcmp (name, "macro") == 0)
16448     mips_opts.warn_about_macros = 0;
16449   else if (strcmp (name, "nomacro") == 0)
16450     {
16451       if (mips_opts.noreorder == 0)
16452         as_bad (_("`noreorder' must be set before `nomacro'"));
16453       mips_opts.warn_about_macros = 1;
16454     }
16455   else if (strcmp (name, "gp=default") == 0)
16456     mips_opts.gp = file_mips_opts.gp;
16457   else if (strcmp (name, "fp=default") == 0)
16458     mips_opts.fp = file_mips_opts.fp;
16459   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16460     {
16461       mips_opts.isa = file_mips_opts.isa;
16462       mips_opts.arch = file_mips_opts.arch;
16463       mips_opts.gp = file_mips_opts.gp;
16464       mips_opts.fp = file_mips_opts.fp;
16465     }
16466   else if (strcmp (name, "push") == 0)
16467     {
16468       struct mips_option_stack *s;
16469
16470       s = XNEW (struct mips_option_stack);
16471       s->next = mips_opts_stack;
16472       s->options = mips_opts;
16473       mips_opts_stack = s;
16474     }
16475   else if (strcmp (name, "pop") == 0)
16476     {
16477       struct mips_option_stack *s;
16478
16479       s = mips_opts_stack;
16480       if (s == NULL)
16481         as_bad (_(".set pop with no .set push"));
16482       else
16483         {
16484           /* If we're changing the reorder mode we need to handle
16485              delay slots correctly.  */
16486           if (s->options.noreorder && ! mips_opts.noreorder)
16487             start_noreorder ();
16488           else if (! s->options.noreorder && mips_opts.noreorder)
16489             end_noreorder ();
16490
16491           mips_opts = s->options;
16492           mips_opts_stack = s->next;
16493           free (s);
16494         }
16495     }
16496   else
16497     {
16498       type = parse_code_option (name);
16499       if (type == OPTION_TYPE_BAD)
16500         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16501     }
16502
16503   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16504      registers based on what is supported by the arch/cpu.  */
16505   if (type == OPTION_TYPE_ISA)
16506     {
16507       switch (mips_opts.isa)
16508         {
16509         case 0:
16510           break;
16511         case ISA_MIPS1:
16512           /* MIPS I cannot support FPXX.  */
16513           mips_opts.fp = 32;
16514           /* fall-through.  */
16515         case ISA_MIPS2:
16516         case ISA_MIPS32:
16517         case ISA_MIPS32R2:
16518         case ISA_MIPS32R3:
16519         case ISA_MIPS32R5:
16520           mips_opts.gp = 32;
16521           if (mips_opts.fp != 0)
16522             mips_opts.fp = 32;
16523           break;
16524         case ISA_MIPS32R6:
16525           mips_opts.gp = 32;
16526           mips_opts.fp = 64;
16527           break;
16528         case ISA_MIPS3:
16529         case ISA_MIPS4:
16530         case ISA_MIPS5:
16531         case ISA_MIPS64:
16532         case ISA_MIPS64R2:
16533         case ISA_MIPS64R3:
16534         case ISA_MIPS64R5:
16535         case ISA_MIPS64R6:
16536           mips_opts.gp = 64;
16537           if (mips_opts.fp != 0)
16538             {
16539               if (mips_opts.arch == CPU_R5900)
16540                 mips_opts.fp = 32;
16541               else
16542                 mips_opts.fp = 64;
16543             }
16544           break;
16545         default:
16546           as_bad (_("unknown ISA level %s"), name + 4);
16547           break;
16548         }
16549     }
16550
16551   mips_check_options (&mips_opts, FALSE);
16552
16553   mips_check_isa_supports_ases ();
16554   *input_line_pointer = ch;
16555   demand_empty_rest_of_line ();
16556 }
16557
16558 /* Handle the .module pseudo-op.  */
16559
16560 static void
16561 s_module (int ignore ATTRIBUTE_UNUSED)
16562 {
16563   char *name = input_line_pointer, ch;
16564
16565   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16566     ++input_line_pointer;
16567   ch = *input_line_pointer;
16568   *input_line_pointer = '\0';
16569
16570   if (!file_mips_opts_checked)
16571     {
16572       if (parse_code_option (name) == OPTION_TYPE_BAD)
16573         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16574
16575       /* Update module level settings from mips_opts.  */
16576       file_mips_opts = mips_opts;
16577     }
16578   else
16579     as_bad (_(".module is not permitted after generating code"));
16580
16581   *input_line_pointer = ch;
16582   demand_empty_rest_of_line ();
16583 }
16584
16585 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16586    .option pic2.  It means to generate SVR4 PIC calls.  */
16587
16588 static void
16589 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16590 {
16591   mips_pic = SVR4_PIC;
16592   mips_abicalls = TRUE;
16593
16594   if (g_switch_seen && g_switch_value != 0)
16595     as_warn (_("-G may not be used with SVR4 PIC code"));
16596   g_switch_value = 0;
16597
16598   bfd_set_gp_size (stdoutput, 0);
16599   demand_empty_rest_of_line ();
16600 }
16601
16602 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16603    PIC code.  It sets the $gp register for the function based on the
16604    function address, which is in the register named in the argument.
16605    This uses a relocation against _gp_disp, which is handled specially
16606    by the linker.  The result is:
16607         lui     $gp,%hi(_gp_disp)
16608         addiu   $gp,$gp,%lo(_gp_disp)
16609         addu    $gp,$gp,.cpload argument
16610    The .cpload argument is normally $25 == $t9.
16611
16612    The -mno-shared option changes this to:
16613         lui     $gp,%hi(__gnu_local_gp)
16614         addiu   $gp,$gp,%lo(__gnu_local_gp)
16615    and the argument is ignored.  This saves an instruction, but the
16616    resulting code is not position independent; it uses an absolute
16617    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16618    can go into an ordinary executable, but not into a shared library.  */
16619
16620 static void
16621 s_cpload (int ignore ATTRIBUTE_UNUSED)
16622 {
16623   expressionS ex;
16624   int reg;
16625   int in_shared;
16626
16627   file_mips_check_options ();
16628
16629   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16630      .cpload is ignored.  */
16631   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16632     {
16633       s_ignore (0);
16634       return;
16635     }
16636
16637   if (mips_opts.mips16)
16638     {
16639       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16640       ignore_rest_of_line ();
16641       return;
16642     }
16643
16644   /* .cpload should be in a .set noreorder section.  */
16645   if (mips_opts.noreorder == 0)
16646     as_warn (_(".cpload not in noreorder section"));
16647
16648   reg = tc_get_register (0);
16649
16650   /* If we need to produce a 64-bit address, we are better off using
16651      the default instruction sequence.  */
16652   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16653
16654   ex.X_op = O_symbol;
16655   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16656                                          "__gnu_local_gp");
16657   ex.X_op_symbol = NULL;
16658   ex.X_add_number = 0;
16659
16660   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16661   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16662
16663   mips_mark_labels ();
16664   mips_assembling_insn = TRUE;
16665
16666   macro_start ();
16667   macro_build_lui (&ex, mips_gp_register);
16668   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16669                mips_gp_register, BFD_RELOC_LO16);
16670   if (in_shared)
16671     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16672                  mips_gp_register, reg);
16673   macro_end ();
16674
16675   mips_assembling_insn = FALSE;
16676   demand_empty_rest_of_line ();
16677 }
16678
16679 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16680      .cpsetup $reg1, offset|$reg2, label
16681
16682    If offset is given, this results in:
16683      sd         $gp, offset($sp)
16684      lui        $gp, %hi(%neg(%gp_rel(label)))
16685      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16686      daddu      $gp, $gp, $reg1
16687
16688    If $reg2 is given, this results in:
16689      or         $reg2, $gp, $0
16690      lui        $gp, %hi(%neg(%gp_rel(label)))
16691      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16692      daddu      $gp, $gp, $reg1
16693    $reg1 is normally $25 == $t9.
16694
16695    The -mno-shared option replaces the last three instructions with
16696         lui     $gp,%hi(_gp)
16697         addiu   $gp,$gp,%lo(_gp)  */
16698
16699 static void
16700 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16701 {
16702   expressionS ex_off;
16703   expressionS ex_sym;
16704   int reg1;
16705
16706   file_mips_check_options ();
16707
16708   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16709      We also need NewABI support.  */
16710   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16711     {
16712       s_ignore (0);
16713       return;
16714     }
16715
16716   if (mips_opts.mips16)
16717     {
16718       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16719       ignore_rest_of_line ();
16720       return;
16721     }
16722
16723   reg1 = tc_get_register (0);
16724   SKIP_WHITESPACE ();
16725   if (*input_line_pointer != ',')
16726     {
16727       as_bad (_("missing argument separator ',' for .cpsetup"));
16728       return;
16729     }
16730   else
16731     ++input_line_pointer;
16732   SKIP_WHITESPACE ();
16733   if (*input_line_pointer == '$')
16734     {
16735       mips_cpreturn_register = tc_get_register (0);
16736       mips_cpreturn_offset = -1;
16737     }
16738   else
16739     {
16740       mips_cpreturn_offset = get_absolute_expression ();
16741       mips_cpreturn_register = -1;
16742     }
16743   SKIP_WHITESPACE ();
16744   if (*input_line_pointer != ',')
16745     {
16746       as_bad (_("missing argument separator ',' for .cpsetup"));
16747       return;
16748     }
16749   else
16750     ++input_line_pointer;
16751   SKIP_WHITESPACE ();
16752   expression (&ex_sym);
16753
16754   mips_mark_labels ();
16755   mips_assembling_insn = TRUE;
16756
16757   macro_start ();
16758   if (mips_cpreturn_register == -1)
16759     {
16760       ex_off.X_op = O_constant;
16761       ex_off.X_add_symbol = NULL;
16762       ex_off.X_op_symbol = NULL;
16763       ex_off.X_add_number = mips_cpreturn_offset;
16764
16765       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16766                    BFD_RELOC_LO16, SP);
16767     }
16768   else
16769     move_register (mips_cpreturn_register, mips_gp_register);
16770
16771   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16772     {
16773       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16774                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16775                    BFD_RELOC_HI16_S);
16776
16777       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16778                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16779                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16780
16781       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16782                    mips_gp_register, reg1);
16783     }
16784   else
16785     {
16786       expressionS ex;
16787
16788       ex.X_op = O_symbol;
16789       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16790       ex.X_op_symbol = NULL;
16791       ex.X_add_number = 0;
16792
16793       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16794       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16795
16796       macro_build_lui (&ex, mips_gp_register);
16797       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16798                    mips_gp_register, BFD_RELOC_LO16);
16799     }
16800
16801   macro_end ();
16802
16803   mips_assembling_insn = FALSE;
16804   demand_empty_rest_of_line ();
16805 }
16806
16807 static void
16808 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16809 {
16810   file_mips_check_options ();
16811
16812   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16813      .cplocal is ignored.  */
16814   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16815     {
16816       s_ignore (0);
16817       return;
16818     }
16819
16820   if (mips_opts.mips16)
16821     {
16822       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16823       ignore_rest_of_line ();
16824       return;
16825     }
16826
16827   mips_gp_register = tc_get_register (0);
16828   demand_empty_rest_of_line ();
16829 }
16830
16831 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16832    offset from $sp.  The offset is remembered, and after making a PIC
16833    call $gp is restored from that location.  */
16834
16835 static void
16836 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16837 {
16838   expressionS ex;
16839
16840   file_mips_check_options ();
16841
16842   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16843      .cprestore is ignored.  */
16844   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16845     {
16846       s_ignore (0);
16847       return;
16848     }
16849
16850   if (mips_opts.mips16)
16851     {
16852       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16853       ignore_rest_of_line ();
16854       return;
16855     }
16856
16857   mips_cprestore_offset = get_absolute_expression ();
16858   mips_cprestore_valid = 1;
16859
16860   ex.X_op = O_constant;
16861   ex.X_add_symbol = NULL;
16862   ex.X_op_symbol = NULL;
16863   ex.X_add_number = mips_cprestore_offset;
16864
16865   mips_mark_labels ();
16866   mips_assembling_insn = TRUE;
16867
16868   macro_start ();
16869   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16870                                 SP, HAVE_64BIT_ADDRESSES);
16871   macro_end ();
16872
16873   mips_assembling_insn = FALSE;
16874   demand_empty_rest_of_line ();
16875 }
16876
16877 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16878    was given in the preceding .cpsetup, it results in:
16879      ld         $gp, offset($sp)
16880
16881    If a register $reg2 was given there, it results in:
16882      or         $gp, $reg2, $0  */
16883
16884 static void
16885 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16886 {
16887   expressionS ex;
16888
16889   file_mips_check_options ();
16890
16891   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16892      We also need NewABI support.  */
16893   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16894     {
16895       s_ignore (0);
16896       return;
16897     }
16898
16899   if (mips_opts.mips16)
16900     {
16901       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16902       ignore_rest_of_line ();
16903       return;
16904     }
16905
16906   mips_mark_labels ();
16907   mips_assembling_insn = TRUE;
16908
16909   macro_start ();
16910   if (mips_cpreturn_register == -1)
16911     {
16912       ex.X_op = O_constant;
16913       ex.X_add_symbol = NULL;
16914       ex.X_op_symbol = NULL;
16915       ex.X_add_number = mips_cpreturn_offset;
16916
16917       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16918     }
16919   else
16920     move_register (mips_gp_register, mips_cpreturn_register);
16921
16922   macro_end ();
16923
16924   mips_assembling_insn = FALSE;
16925   demand_empty_rest_of_line ();
16926 }
16927
16928 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16929    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16930    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16931    debug information or MIPS16 TLS.  */
16932
16933 static void
16934 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16935                      bfd_reloc_code_real_type rtype)
16936 {
16937   expressionS ex;
16938   char *p;
16939
16940   expression (&ex);
16941
16942   if (ex.X_op != O_symbol)
16943     {
16944       as_bad (_("unsupported use of %s"), dirstr);
16945       ignore_rest_of_line ();
16946     }
16947
16948   p = frag_more (bytes);
16949   md_number_to_chars (p, 0, bytes);
16950   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16951   demand_empty_rest_of_line ();
16952   mips_clear_insn_labels ();
16953 }
16954
16955 /* Handle .dtprelword.  */
16956
16957 static void
16958 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16959 {
16960   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16961 }
16962
16963 /* Handle .dtpreldword.  */
16964
16965 static void
16966 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16967 {
16968   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16969 }
16970
16971 /* Handle .tprelword.  */
16972
16973 static void
16974 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16975 {
16976   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16977 }
16978
16979 /* Handle .tpreldword.  */
16980
16981 static void
16982 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16983 {
16984   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16985 }
16986
16987 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16988    code.  It sets the offset to use in gp_rel relocations.  */
16989
16990 static void
16991 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16992 {
16993   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16994      We also need NewABI support.  */
16995   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16996     {
16997       s_ignore (0);
16998       return;
16999     }
17000
17001   mips_gprel_offset = get_absolute_expression ();
17002
17003   demand_empty_rest_of_line ();
17004 }
17005
17006 /* Handle the .gpword pseudo-op.  This is used when generating PIC
17007    code.  It generates a 32 bit GP relative reloc.  */
17008
17009 static void
17010 s_gpword (int ignore ATTRIBUTE_UNUSED)
17011 {
17012   segment_info_type *si;
17013   struct insn_label_list *l;
17014   expressionS ex;
17015   char *p;
17016
17017   /* When not generating PIC code, this is treated as .word.  */
17018   if (mips_pic != SVR4_PIC)
17019     {
17020       s_cons (2);
17021       return;
17022     }
17023
17024   si = seg_info (now_seg);
17025   l = si->label_list;
17026   mips_emit_delays ();
17027   if (auto_align)
17028     mips_align (2, 0, l);
17029
17030   expression (&ex);
17031   mips_clear_insn_labels ();
17032
17033   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17034     {
17035       as_bad (_("unsupported use of .gpword"));
17036       ignore_rest_of_line ();
17037     }
17038
17039   p = frag_more (4);
17040   md_number_to_chars (p, 0, 4);
17041   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17042                BFD_RELOC_GPREL32);
17043
17044   demand_empty_rest_of_line ();
17045 }
17046
17047 static void
17048 s_gpdword (int ignore ATTRIBUTE_UNUSED)
17049 {
17050   segment_info_type *si;
17051   struct insn_label_list *l;
17052   expressionS ex;
17053   char *p;
17054
17055   /* When not generating PIC code, this is treated as .dword.  */
17056   if (mips_pic != SVR4_PIC)
17057     {
17058       s_cons (3);
17059       return;
17060     }
17061
17062   si = seg_info (now_seg);
17063   l = si->label_list;
17064   mips_emit_delays ();
17065   if (auto_align)
17066     mips_align (3, 0, l);
17067
17068   expression (&ex);
17069   mips_clear_insn_labels ();
17070
17071   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17072     {
17073       as_bad (_("unsupported use of .gpdword"));
17074       ignore_rest_of_line ();
17075     }
17076
17077   p = frag_more (8);
17078   md_number_to_chars (p, 0, 8);
17079   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17080                BFD_RELOC_GPREL32)->fx_tcbit = 1;
17081
17082   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17083   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17084            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
17085
17086   demand_empty_rest_of_line ();
17087 }
17088
17089 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
17090    tables.  It generates a R_MIPS_EH reloc.  */
17091
17092 static void
17093 s_ehword (int ignore ATTRIBUTE_UNUSED)
17094 {
17095   expressionS ex;
17096   char *p;
17097
17098   mips_emit_delays ();
17099
17100   expression (&ex);
17101   mips_clear_insn_labels ();
17102
17103   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17104     {
17105       as_bad (_("unsupported use of .ehword"));
17106       ignore_rest_of_line ();
17107     }
17108
17109   p = frag_more (4);
17110   md_number_to_chars (p, 0, 4);
17111   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17112                BFD_RELOC_32_PCREL);
17113
17114   demand_empty_rest_of_line ();
17115 }
17116
17117 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17118    tables in SVR4 PIC code.  */
17119
17120 static void
17121 s_cpadd (int ignore ATTRIBUTE_UNUSED)
17122 {
17123   int reg;
17124
17125   file_mips_check_options ();
17126
17127   /* This is ignored when not generating SVR4 PIC code.  */
17128   if (mips_pic != SVR4_PIC)
17129     {
17130       s_ignore (0);
17131       return;
17132     }
17133
17134   mips_mark_labels ();
17135   mips_assembling_insn = TRUE;
17136
17137   /* Add $gp to the register named as an argument.  */
17138   macro_start ();
17139   reg = tc_get_register (0);
17140   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17141   macro_end ();
17142
17143   mips_assembling_insn = FALSE;
17144   demand_empty_rest_of_line ();
17145 }
17146
17147 /* Handle the .insn pseudo-op.  This marks instruction labels in
17148    mips16/micromips mode.  This permits the linker to handle them specially,
17149    such as generating jalx instructions when needed.  We also make
17150    them odd for the duration of the assembly, in order to generate the
17151    right sort of code.  We will make them even in the adjust_symtab
17152    routine, while leaving them marked.  This is convenient for the
17153    debugger and the disassembler.  The linker knows to make them odd
17154    again.  */
17155
17156 static void
17157 s_insn (int ignore ATTRIBUTE_UNUSED)
17158 {
17159   file_mips_check_options ();
17160   file_ase_mips16 |= mips_opts.mips16;
17161   file_ase_micromips |= mips_opts.micromips;
17162
17163   mips_mark_labels ();
17164
17165   demand_empty_rest_of_line ();
17166 }
17167
17168 /* Handle the .nan pseudo-op.  */
17169
17170 static void
17171 s_nan (int ignore ATTRIBUTE_UNUSED)
17172 {
17173   static const char str_legacy[] = "legacy";
17174   static const char str_2008[] = "2008";
17175   size_t i;
17176
17177   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
17178
17179   if (i == sizeof (str_2008) - 1
17180       && memcmp (input_line_pointer, str_2008, i) == 0)
17181     mips_nan2008 = 1;
17182   else if (i == sizeof (str_legacy) - 1
17183            && memcmp (input_line_pointer, str_legacy, i) == 0)
17184     {
17185       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
17186         mips_nan2008 = 0;
17187       else
17188         as_bad (_("`%s' does not support legacy NaN"),
17189                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
17190     }
17191   else
17192     as_bad (_("bad .nan directive"));
17193
17194   input_line_pointer += i;
17195   demand_empty_rest_of_line ();
17196 }
17197
17198 /* Handle a .stab[snd] directive.  Ideally these directives would be
17199    implemented in a transparent way, so that removing them would not
17200    have any effect on the generated instructions.  However, s_stab
17201    internally changes the section, so in practice we need to decide
17202    now whether the preceding label marks compressed code.  We do not
17203    support changing the compression mode of a label after a .stab*
17204    directive, such as in:
17205
17206    foo:
17207         .stabs ...
17208         .set mips16
17209
17210    so the current mode wins.  */
17211
17212 static void
17213 s_mips_stab (int type)
17214 {
17215   file_mips_check_options ();
17216   mips_mark_labels ();
17217   s_stab (type);
17218 }
17219
17220 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17221
17222 static void
17223 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17224 {
17225   char *name;
17226   int c;
17227   symbolS *symbolP;
17228   expressionS exp;
17229
17230   c = get_symbol_name (&name);
17231   symbolP = symbol_find_or_make (name);
17232   S_SET_WEAK (symbolP);
17233   *input_line_pointer = c;
17234
17235   SKIP_WHITESPACE_AFTER_NAME ();
17236
17237   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17238     {
17239       if (S_IS_DEFINED (symbolP))
17240         {
17241           as_bad (_("ignoring attempt to redefine symbol %s"),
17242                   S_GET_NAME (symbolP));
17243           ignore_rest_of_line ();
17244           return;
17245         }
17246
17247       if (*input_line_pointer == ',')
17248         {
17249           ++input_line_pointer;
17250           SKIP_WHITESPACE ();
17251         }
17252
17253       expression (&exp);
17254       if (exp.X_op != O_symbol)
17255         {
17256           as_bad (_("bad .weakext directive"));
17257           ignore_rest_of_line ();
17258           return;
17259         }
17260       symbol_set_value_expression (symbolP, &exp);
17261     }
17262
17263   demand_empty_rest_of_line ();
17264 }
17265
17266 /* Parse a register string into a number.  Called from the ECOFF code
17267    to parse .frame.  The argument is non-zero if this is the frame
17268    register, so that we can record it in mips_frame_reg.  */
17269
17270 int
17271 tc_get_register (int frame)
17272 {
17273   unsigned int reg;
17274
17275   SKIP_WHITESPACE ();
17276   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17277     reg = 0;
17278   if (frame)
17279     {
17280       mips_frame_reg = reg != 0 ? reg : SP;
17281       mips_frame_reg_valid = 1;
17282       mips_cprestore_valid = 0;
17283     }
17284   return reg;
17285 }
17286
17287 valueT
17288 md_section_align (asection *seg, valueT addr)
17289 {
17290   int align = bfd_get_section_alignment (stdoutput, seg);
17291
17292   /* We don't need to align ELF sections to the full alignment.
17293      However, Irix 5 may prefer that we align them at least to a 16
17294      byte boundary.  We don't bother to align the sections if we
17295      are targeted for an embedded system.  */
17296   if (strncmp (TARGET_OS, "elf", 3) == 0)
17297     return addr;
17298   if (align > 4)
17299     align = 4;
17300
17301   return ((addr + (1 << align) - 1) & -(1 << align));
17302 }
17303
17304 /* Utility routine, called from above as well.  If called while the
17305    input file is still being read, it's only an approximation.  (For
17306    example, a symbol may later become defined which appeared to be
17307    undefined earlier.)  */
17308
17309 static int
17310 nopic_need_relax (symbolS *sym, int before_relaxing)
17311 {
17312   if (sym == 0)
17313     return 0;
17314
17315   if (g_switch_value > 0)
17316     {
17317       const char *symname;
17318       int change;
17319
17320       /* Find out whether this symbol can be referenced off the $gp
17321          register.  It can be if it is smaller than the -G size or if
17322          it is in the .sdata or .sbss section.  Certain symbols can
17323          not be referenced off the $gp, although it appears as though
17324          they can.  */
17325       symname = S_GET_NAME (sym);
17326       if (symname != (const char *) NULL
17327           && (strcmp (symname, "eprol") == 0
17328               || strcmp (symname, "etext") == 0
17329               || strcmp (symname, "_gp") == 0
17330               || strcmp (symname, "edata") == 0
17331               || strcmp (symname, "_fbss") == 0
17332               || strcmp (symname, "_fdata") == 0
17333               || strcmp (symname, "_ftext") == 0
17334               || strcmp (symname, "end") == 0
17335               || strcmp (symname, "_gp_disp") == 0))
17336         change = 1;
17337       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17338                && (0
17339 #ifndef NO_ECOFF_DEBUGGING
17340                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17341                        && (symbol_get_obj (sym)->ecoff_extern_size
17342                            <= g_switch_value))
17343 #endif
17344                    /* We must defer this decision until after the whole
17345                       file has been read, since there might be a .extern
17346                       after the first use of this symbol.  */
17347                    || (before_relaxing
17348 #ifndef NO_ECOFF_DEBUGGING
17349                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17350 #endif
17351                        && S_GET_VALUE (sym) == 0)
17352                    || (S_GET_VALUE (sym) != 0
17353                        && S_GET_VALUE (sym) <= g_switch_value)))
17354         change = 0;
17355       else
17356         {
17357           const char *segname;
17358
17359           segname = segment_name (S_GET_SEGMENT (sym));
17360           gas_assert (strcmp (segname, ".lit8") != 0
17361                   && strcmp (segname, ".lit4") != 0);
17362           change = (strcmp (segname, ".sdata") != 0
17363                     && strcmp (segname, ".sbss") != 0
17364                     && strncmp (segname, ".sdata.", 7) != 0
17365                     && strncmp (segname, ".sbss.", 6) != 0
17366                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17367                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17368         }
17369       return change;
17370     }
17371   else
17372     /* We are not optimizing for the $gp register.  */
17373     return 1;
17374 }
17375
17376
17377 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17378
17379 static bfd_boolean
17380 pic_need_relax (symbolS *sym)
17381 {
17382   asection *symsec;
17383
17384   /* Handle the case of a symbol equated to another symbol.  */
17385   while (symbol_equated_reloc_p (sym))
17386     {
17387       symbolS *n;
17388
17389       /* It's possible to get a loop here in a badly written program.  */
17390       n = symbol_get_value_expression (sym)->X_add_symbol;
17391       if (n == sym)
17392         break;
17393       sym = n;
17394     }
17395
17396   if (symbol_section_p (sym))
17397     return TRUE;
17398
17399   symsec = S_GET_SEGMENT (sym);
17400
17401   /* This must duplicate the test in adjust_reloc_syms.  */
17402   return (!bfd_is_und_section (symsec)
17403           && !bfd_is_abs_section (symsec)
17404           && !bfd_is_com_section (symsec)
17405           /* A global or weak symbol is treated as external.  */
17406           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17407 }
17408 \f
17409 /* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17410    convert a section-relative value VAL to the equivalent PC-relative
17411    value.  */
17412
17413 static offsetT
17414 mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17415                   offsetT val, long stretch)
17416 {
17417   fragS *sym_frag;
17418   addressT addr;
17419
17420   gas_assert (pcrel_op->root.root.type == OP_PCREL);
17421
17422   sym_frag = symbol_get_frag (fragp->fr_symbol);
17423
17424   /* If the relax_marker of the symbol fragment differs from the
17425      relax_marker of this fragment, we have not yet adjusted the
17426      symbol fragment fr_address.  We want to add in STRETCH in
17427      order to get a better estimate of the address.  This
17428      particularly matters because of the shift bits.  */
17429   if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17430     {
17431       fragS *f;
17432
17433       /* Adjust stretch for any alignment frag.  Note that if have
17434          been expanding the earlier code, the symbol may be
17435          defined in what appears to be an earlier frag.  FIXME:
17436          This doesn't handle the fr_subtype field, which specifies
17437          a maximum number of bytes to skip when doing an
17438          alignment.  */
17439       for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17440         {
17441           if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17442             {
17443               if (stretch < 0)
17444                 stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17445               else
17446                 stretch &= ~((1 << (int) f->fr_offset) - 1);
17447               if (stretch == 0)
17448                 break;
17449             }
17450         }
17451       if (f != NULL)
17452         val += stretch;
17453     }
17454
17455   addr = fragp->fr_address + fragp->fr_fix;
17456
17457   /* The base address rules are complicated.  The base address of
17458      a branch is the following instruction.  The base address of a
17459      PC relative load or add is the instruction itself, but if it
17460      is in a delay slot (in which case it can not be extended) use
17461      the address of the instruction whose delay slot it is in.  */
17462   if (pcrel_op->include_isa_bit)
17463     {
17464       addr += 2;
17465
17466       /* If we are currently assuming that this frag should be
17467          extended, then the current address is two bytes higher.  */
17468       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17469         addr += 2;
17470
17471       /* Ignore the low bit in the target, since it will be set
17472          for a text label.  */
17473       val &= -2;
17474     }
17475   else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17476     addr -= 4;
17477   else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17478     addr -= 2;
17479
17480   val -= addr & -(1 << pcrel_op->align_log2);
17481
17482   return val;
17483 }
17484
17485 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17486    extended opcode.  SEC is the section the frag is in.  */
17487
17488 static int
17489 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17490 {
17491   const struct mips_int_operand *operand;
17492   offsetT val;
17493   segT symsec;
17494   int type;
17495
17496   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17497     return 0;
17498   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17499     return 1;
17500
17501   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17502   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17503   operand = mips16_immed_operand (type, FALSE);
17504   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
17505       || (operand->root.type == OP_PCREL
17506           ? sec != symsec
17507           : !bfd_is_abs_section (symsec)))
17508     return 1;
17509
17510   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17511
17512   if (operand->root.type == OP_PCREL)
17513     {
17514       const struct mips_pcrel_operand *pcrel_op;
17515       offsetT maxtiny;
17516
17517       if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17518         return 1;
17519
17520       pcrel_op = (const struct mips_pcrel_operand *) operand;
17521       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17522
17523       /* If any of the shifted bits are set, we must use an extended
17524          opcode.  If the address depends on the size of this
17525          instruction, this can lead to a loop, so we arrange to always
17526          use an extended opcode.  */
17527       if ((val & ((1 << operand->shift) - 1)) != 0)
17528         {
17529           fragp->fr_subtype =
17530             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17531           return 1;
17532         }
17533
17534       /* If we are about to mark a frag as extended because the value
17535          is precisely the next value above maxtiny, then there is a
17536          chance of an infinite loop as in the following code:
17537              la $4,foo
17538              .skip      1020
17539              .align     2
17540            foo:
17541          In this case when the la is extended, foo is 0x3fc bytes
17542          away, so the la can be shrunk, but then foo is 0x400 away, so
17543          the la must be extended.  To avoid this loop, we mark the
17544          frag as extended if it was small, and is about to become
17545          extended with the next value above maxtiny.  */
17546       maxtiny = mips_int_operand_max (operand);
17547       if (val == maxtiny + (1 << operand->shift)
17548           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17549         {
17550           fragp->fr_subtype =
17551             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17552           return 1;
17553         }
17554     }
17555
17556   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17557 }
17558
17559 /* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
17560    macro expansion.  SEC is the section the frag is in.  We only
17561    support PC-relative instructions (LA, DLA, LW, LD) here, in
17562    non-PIC code using 32-bit addressing.  */
17563
17564 static int
17565 mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
17566 {
17567   const struct mips_pcrel_operand *pcrel_op;
17568   const struct mips_int_operand *operand;
17569   offsetT val;
17570   segT symsec;
17571   int type;
17572
17573   gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
17574
17575   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17576     return 0;
17577   if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
17578     return 0;
17579
17580   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17581   switch (type)
17582     {
17583     case 'A':
17584     case 'B':
17585     case 'E':
17586       symsec = S_GET_SEGMENT (fragp->fr_symbol);
17587       if (bfd_is_abs_section (symsec))
17588         return 1;
17589       if (RELAX_MIPS16_PIC (fragp->fr_subtype))
17590         return 0;
17591       if (S_FORCE_RELOC (fragp->fr_symbol, TRUE) || sec != symsec)
17592         return 1;
17593
17594       operand = mips16_immed_operand (type, TRUE);
17595       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17596       pcrel_op = (const struct mips_pcrel_operand *) operand;
17597       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17598
17599       return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17600
17601     default:
17602       return 0;
17603     }
17604 }
17605
17606 /* Compute the length of a branch sequence, and adjust the
17607    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17608    worst-case length is computed, with UPDATE being used to indicate
17609    whether an unconditional (-1), branch-likely (+1) or regular (0)
17610    branch is to be computed.  */
17611 static int
17612 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17613 {
17614   bfd_boolean toofar;
17615   int length;
17616
17617   if (fragp
17618       && S_IS_DEFINED (fragp->fr_symbol)
17619       && !S_IS_WEAK (fragp->fr_symbol)
17620       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17621     {
17622       addressT addr;
17623       offsetT val;
17624
17625       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17626
17627       addr = fragp->fr_address + fragp->fr_fix + 4;
17628
17629       val -= addr;
17630
17631       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17632     }
17633   else
17634     /* If the symbol is not defined or it's in a different segment,
17635        we emit the long sequence.  */
17636     toofar = TRUE;
17637
17638   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17639     fragp->fr_subtype
17640       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17641                              RELAX_BRANCH_PIC (fragp->fr_subtype),
17642                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17643                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17644                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17645                              toofar);
17646
17647   length = 4;
17648   if (toofar)
17649     {
17650       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17651         length += 8;
17652
17653       if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
17654         {
17655           /* Additional space for PIC loading of target address.  */
17656           length += 8;
17657           if (mips_opts.isa == ISA_MIPS1)
17658             /* Additional space for $at-stabilizing nop.  */
17659             length += 4;
17660         }
17661
17662       /* If branch is conditional.  */
17663       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17664         length += 8;
17665     }
17666
17667   return length;
17668 }
17669
17670 /* Get a FRAG's branch instruction delay slot size, either from the
17671    short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
17672    or SHORT_INSN_SIZE otherwise.  */
17673
17674 static int
17675 frag_branch_delay_slot_size (fragS *fragp, bfd_boolean al, int short_insn_size)
17676 {
17677   char *buf = fragp->fr_literal + fragp->fr_fix;
17678
17679   if (al)
17680     return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
17681   else
17682     return short_insn_size;
17683 }
17684
17685 /* Compute the length of a branch sequence, and adjust the
17686    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17687    worst-case length is computed, with UPDATE being used to indicate
17688    whether an unconditional (-1), or regular (0) branch is to be
17689    computed.  */
17690
17691 static int
17692 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17693 {
17694   bfd_boolean insn32 = TRUE;
17695   bfd_boolean nods = TRUE;
17696   bfd_boolean pic = TRUE;
17697   bfd_boolean al = TRUE;
17698   int short_insn_size;
17699   bfd_boolean toofar;
17700   int length;
17701
17702   if (fragp)
17703     {
17704       insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
17705       nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
17706       pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
17707       al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17708     }
17709   short_insn_size = insn32 ? 4 : 2;
17710
17711   if (fragp
17712       && S_IS_DEFINED (fragp->fr_symbol)
17713       && !S_IS_WEAK (fragp->fr_symbol)
17714       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17715     {
17716       addressT addr;
17717       offsetT val;
17718
17719       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17720       /* Ignore the low bit in the target, since it will be set
17721          for a text label.  */
17722       if ((val & 1) != 0)
17723         --val;
17724
17725       addr = fragp->fr_address + fragp->fr_fix + 4;
17726
17727       val -= addr;
17728
17729       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17730     }
17731   else
17732     /* If the symbol is not defined or it's in a different segment,
17733        we emit the long sequence.  */
17734     toofar = TRUE;
17735
17736   if (fragp && update
17737       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17738     fragp->fr_subtype = (toofar
17739                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17740                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17741
17742   length = 4;
17743   if (toofar)
17744     {
17745       bfd_boolean compact_known = fragp != NULL;
17746       bfd_boolean compact = FALSE;
17747       bfd_boolean uncond;
17748
17749       if (fragp)
17750         {
17751           compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17752           uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17753         }
17754       else
17755         uncond = update < 0;
17756
17757       /* If label is out of range, we turn branch <br>:
17758
17759                 <br>    label                   # 4 bytes
17760             0:
17761
17762          into:
17763
17764                 j       label                   # 4 bytes
17765                 nop                             # 2/4 bytes if
17766                                                 #  compact && (!PIC || insn32)
17767             0:
17768        */
17769       if ((!pic || insn32) && (!compact_known || compact))
17770         length += short_insn_size;
17771
17772       /* If assembling PIC code, we further turn:
17773
17774                         j       label                   # 4 bytes
17775
17776          into:
17777
17778                         lw/ld   at, %got(label)(gp)     # 4 bytes
17779                         d/addiu at, %lo(label)          # 4 bytes
17780                         jr/c    at                      # 2/4 bytes
17781        */
17782       if (pic)
17783         length += 4 + short_insn_size;
17784
17785       /* Add an extra nop if the jump has no compact form and we need
17786          to fill the delay slot.  */
17787       if ((!pic || al) && nods)
17788         length += (fragp
17789                    ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
17790                    : short_insn_size);
17791
17792       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17793
17794                         <brneg> 0f                      # 4 bytes
17795                         nop                             # 2/4 bytes if !compact
17796        */
17797       if (!uncond)
17798         length += (compact_known && compact) ? 4 : 4 + short_insn_size;
17799     }
17800   else if (nods)
17801     {
17802       /* Add an extra nop to fill the delay slot.  */
17803       gas_assert (fragp);
17804       length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
17805     }
17806
17807   return length;
17808 }
17809
17810 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17811    bit accordingly.  */
17812
17813 static int
17814 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17815 {
17816   bfd_boolean toofar;
17817
17818   if (fragp
17819       && S_IS_DEFINED (fragp->fr_symbol)
17820       && !S_IS_WEAK (fragp->fr_symbol)
17821       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17822     {
17823       addressT addr;
17824       offsetT val;
17825       int type;
17826
17827       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17828       /* Ignore the low bit in the target, since it will be set
17829          for a text label.  */
17830       if ((val & 1) != 0)
17831         --val;
17832
17833       /* Assume this is a 2-byte branch.  */
17834       addr = fragp->fr_address + fragp->fr_fix + 2;
17835
17836       /* We try to avoid the infinite loop by not adding 2 more bytes for
17837          long branches.  */
17838
17839       val -= addr;
17840
17841       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17842       if (type == 'D')
17843         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17844       else if (type == 'E')
17845         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17846       else
17847         abort ();
17848     }
17849   else
17850     /* If the symbol is not defined or it's in a different segment,
17851        we emit a normal 32-bit branch.  */
17852     toofar = TRUE;
17853
17854   if (fragp && update
17855       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17856     fragp->fr_subtype
17857       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17858                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17859
17860   if (toofar)
17861     return 4;
17862
17863   return 2;
17864 }
17865
17866 /* Estimate the size of a frag before relaxing.  Unless this is the
17867    mips16, we are not really relaxing here, and the final size is
17868    encoded in the subtype information.  For the mips16, we have to
17869    decide whether we are using an extended opcode or not.  */
17870
17871 int
17872 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17873 {
17874   int change;
17875
17876   if (RELAX_BRANCH_P (fragp->fr_subtype))
17877     {
17878
17879       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17880
17881       return fragp->fr_var;
17882     }
17883
17884   if (RELAX_MIPS16_P (fragp->fr_subtype))
17885     {
17886       /* We don't want to modify the EXTENDED bit here; it might get us
17887          into infinite loops.  We change it only in mips_relax_frag().  */
17888       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17889         return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 8 : 12;
17890       else
17891         return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
17892     }
17893
17894   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17895     {
17896       int length = 4;
17897
17898       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17899         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17900       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17901         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17902       fragp->fr_var = length;
17903
17904       return length;
17905     }
17906
17907   if (mips_pic == VXWORKS_PIC)
17908     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17909     change = 0;
17910   else if (RELAX_PIC (fragp->fr_subtype))
17911     change = pic_need_relax (fragp->fr_symbol);
17912   else
17913     change = nopic_need_relax (fragp->fr_symbol, 0);
17914
17915   if (change)
17916     {
17917       fragp->fr_subtype |= RELAX_USE_SECOND;
17918       return -RELAX_FIRST (fragp->fr_subtype);
17919     }
17920   else
17921     return -RELAX_SECOND (fragp->fr_subtype);
17922 }
17923
17924 /* This is called to see whether a reloc against a defined symbol
17925    should be converted into a reloc against a section.  */
17926
17927 int
17928 mips_fix_adjustable (fixS *fixp)
17929 {
17930   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17931       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17932     return 0;
17933
17934   if (fixp->fx_addsy == NULL)
17935     return 1;
17936
17937   /* Allow relocs used for EH tables.  */
17938   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17939     return 1;
17940
17941   /* If symbol SYM is in a mergeable section, relocations of the form
17942      SYM + 0 can usually be made section-relative.  The mergeable data
17943      is then identified by the section offset rather than by the symbol.
17944
17945      However, if we're generating REL LO16 relocations, the offset is split
17946      between the LO16 and partnering high part relocation.  The linker will
17947      need to recalculate the complete offset in order to correctly identify
17948      the merge data.
17949
17950      The linker has traditionally not looked for the partnering high part
17951      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17952      placed anywhere.  Rather than break backwards compatibility by changing
17953      this, it seems better not to force the issue, and instead keep the
17954      original symbol.  This will work with either linker behavior.  */
17955   if ((lo16_reloc_p (fixp->fx_r_type)
17956        || reloc_needs_lo_p (fixp->fx_r_type))
17957       && HAVE_IN_PLACE_ADDENDS
17958       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17959     return 0;
17960
17961   /* There is no place to store an in-place offset for JALR relocations.  */
17962   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17963     return 0;
17964
17965   /* Likewise an in-range offset of limited PC-relative relocations may
17966      overflow the in-place relocatable field if recalculated against the
17967      start address of the symbol's containing section.
17968
17969      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17970      section relative to allow linker relaxations to be performed later on.  */
17971   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17972       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17973     return 0;
17974
17975   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17976      to a floating-point stub.  The same is true for non-R_MIPS16_26
17977      relocations against MIPS16 functions; in this case, the stub becomes
17978      the function's canonical address.
17979
17980      Floating-point stubs are stored in unique .mips16.call.* or
17981      .mips16.fn.* sections.  If a stub T for function F is in section S,
17982      the first relocation in section S must be against F; this is how the
17983      linker determines the target function.  All relocations that might
17984      resolve to T must also be against F.  We therefore have the following
17985      restrictions, which are given in an intentionally-redundant way:
17986
17987        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17988           symbols.
17989
17990        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17991           if that stub might be used.
17992
17993        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17994           symbols.
17995
17996        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17997           that stub might be used.
17998
17999      There is a further restriction:
18000
18001        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
18002           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
18003           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
18004           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
18005           against MIPS16 or microMIPS symbols because we need to keep the
18006           MIPS16 or microMIPS symbol for the purpose of mode mismatch
18007           detection and JAL or BAL to JALX instruction conversion in the
18008           linker.
18009
18010      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
18011      against a MIPS16 symbol.  We deal with (5) by additionally leaving
18012      alone any jump and branch relocations against a microMIPS symbol.
18013
18014      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
18015      relocation against some symbol R, no relocation against R may be
18016      reduced.  (Note that this deals with (2) as well as (1) because
18017      relocations against global symbols will never be reduced on ELF
18018      targets.)  This approach is a little simpler than trying to detect
18019      stub sections, and gives the "all or nothing" per-symbol consistency
18020      that we have for MIPS16 symbols.  */
18021   if (fixp->fx_subsy == NULL
18022       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
18023           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
18024               && (jmp_reloc_p (fixp->fx_r_type)
18025                   || b_reloc_p (fixp->fx_r_type)))
18026           || *symbol_get_tc (fixp->fx_addsy)))
18027     return 0;
18028
18029   return 1;
18030 }
18031
18032 /* Translate internal representation of relocation info to BFD target
18033    format.  */
18034
18035 arelent **
18036 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
18037 {
18038   static arelent *retval[4];
18039   arelent *reloc;
18040   bfd_reloc_code_real_type code;
18041
18042   memset (retval, 0, sizeof(retval));
18043   reloc = retval[0] = XCNEW (arelent);
18044   reloc->sym_ptr_ptr = XNEW (asymbol *);
18045   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
18046   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
18047
18048   if (fixp->fx_pcrel)
18049     {
18050       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
18051                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
18052                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
18053                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
18054                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
18055                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
18056                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
18057                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
18058                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
18059                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
18060                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
18061                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
18062
18063       /* At this point, fx_addnumber is "symbol offset - pcrel address".
18064          Relocations want only the symbol offset.  */
18065       switch (fixp->fx_r_type)
18066         {
18067         case BFD_RELOC_MIPS_18_PCREL_S3:
18068           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
18069           break;
18070         default:
18071           reloc->addend = fixp->fx_addnumber + reloc->address;
18072           break;
18073         }
18074     }
18075   else if (HAVE_IN_PLACE_ADDENDS
18076            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
18077            && (read_compressed_insn (fixp->fx_frag->fr_literal
18078                                      + fixp->fx_where, 4) >> 26) == 0x3c)
18079     {
18080       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
18081          addend accordingly.  */
18082       reloc->addend = fixp->fx_addnumber >> 1;
18083     }
18084   else
18085     reloc->addend = fixp->fx_addnumber;
18086
18087   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18088      entry to be used in the relocation's section offset.  */
18089   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18090     {
18091       reloc->address = reloc->addend;
18092       reloc->addend = 0;
18093     }
18094
18095   code = fixp->fx_r_type;
18096
18097   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18098   if (reloc->howto == NULL)
18099     {
18100       as_bad_where (fixp->fx_file, fixp->fx_line,
18101                     _("cannot represent %s relocation in this object file"
18102                       " format"),
18103                     bfd_get_reloc_code_name (code));
18104       retval[0] = NULL;
18105     }
18106
18107   return retval;
18108 }
18109
18110 /* Relax a machine dependent frag.  This returns the amount by which
18111    the current size of the frag should change.  */
18112
18113 int
18114 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18115 {
18116   if (RELAX_BRANCH_P (fragp->fr_subtype))
18117     {
18118       offsetT old_var = fragp->fr_var;
18119
18120       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
18121
18122       return fragp->fr_var - old_var;
18123     }
18124
18125   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18126     {
18127       offsetT old_var = fragp->fr_var;
18128       offsetT new_var = 4;
18129
18130       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18131         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
18132       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18133         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
18134       fragp->fr_var = new_var;
18135
18136       return new_var - old_var;
18137     }
18138
18139   if (! RELAX_MIPS16_P (fragp->fr_subtype))
18140     return 0;
18141
18142   if (!mips16_extended_frag (fragp, sec, stretch))
18143     {
18144       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18145         {
18146           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18147           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -6 : -10;
18148         }
18149       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18150         {
18151           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18152           return -2;
18153         }
18154       else
18155         return 0;
18156     }
18157   else if (!mips16_macro_frag (fragp, sec, stretch))
18158     {
18159       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18160         {
18161           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18162           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18163           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -4 : -8;
18164         }
18165       else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18166         {
18167           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18168           return 2;
18169         }
18170       else
18171         return 0;
18172     }
18173   else
18174     {
18175       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18176         return 0;
18177       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18178         {
18179           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18180           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18181           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 4 : 8;
18182         }
18183       else
18184         {
18185           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18186           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 6 : 10;
18187         }
18188     }
18189
18190   return 0;
18191 }
18192
18193 /* Convert a machine dependent frag.  */
18194
18195 void
18196 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18197 {
18198   if (RELAX_BRANCH_P (fragp->fr_subtype))
18199     {
18200       char *buf;
18201       unsigned long insn;
18202       fixS *fixp;
18203
18204       buf = fragp->fr_literal + fragp->fr_fix;
18205       insn = read_insn (buf);
18206
18207       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18208         {
18209           /* We generate a fixup instead of applying it right now
18210              because, if there are linker relaxations, we're going to
18211              need the relocations.  */
18212           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18213                           fragp->fr_symbol, fragp->fr_offset,
18214                           TRUE, BFD_RELOC_16_PCREL_S2);
18215           fixp->fx_file = fragp->fr_file;
18216           fixp->fx_line = fragp->fr_line;
18217
18218           buf = write_insn (buf, insn);
18219         }
18220       else
18221         {
18222           int i;
18223
18224           as_warn_where (fragp->fr_file, fragp->fr_line,
18225                          _("relaxed out-of-range branch into a jump"));
18226
18227           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18228             goto uncond;
18229
18230           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18231             {
18232               /* Reverse the branch.  */
18233               switch ((insn >> 28) & 0xf)
18234                 {
18235                 case 4:
18236                   if ((insn & 0xff000000) == 0x47000000
18237                       || (insn & 0xff600000) == 0x45600000)
18238                     {
18239                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18240                          reversed by tweaking bit 23.  */
18241                       insn ^= 0x00800000;
18242                     }
18243                   else
18244                     {
18245                       /* bc[0-3][tf]l? instructions can have the condition
18246                          reversed by tweaking a single TF bit, and their
18247                          opcodes all have 0x4???????.  */
18248                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
18249                       insn ^= 0x00010000;
18250                     }
18251                   break;
18252
18253                 case 0:
18254                   /* bltz       0x04000000      bgez    0x04010000
18255                      bltzal     0x04100000      bgezal  0x04110000  */
18256                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18257                   insn ^= 0x00010000;
18258                   break;
18259
18260                 case 1:
18261                   /* beq        0x10000000      bne     0x14000000
18262                      blez       0x18000000      bgtz    0x1c000000  */
18263                   insn ^= 0x04000000;
18264                   break;
18265
18266                 default:
18267                   abort ();
18268                 }
18269             }
18270
18271           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18272             {
18273               /* Clear the and-link bit.  */
18274               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18275
18276               /* bltzal         0x04100000      bgezal  0x04110000
18277                  bltzall        0x04120000      bgezall 0x04130000  */
18278               insn &= ~0x00100000;
18279             }
18280
18281           /* Branch over the branch (if the branch was likely) or the
18282              full jump (not likely case).  Compute the offset from the
18283              current instruction to branch to.  */
18284           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18285             i = 16;
18286           else
18287             {
18288               /* How many bytes in instructions we've already emitted?  */
18289               i = buf - fragp->fr_literal - fragp->fr_fix;
18290               /* How many bytes in instructions from here to the end?  */
18291               i = fragp->fr_var - i;
18292             }
18293           /* Convert to instruction count.  */
18294           i >>= 2;
18295           /* Branch counts from the next instruction.  */
18296           i--;
18297           insn |= i;
18298           /* Branch over the jump.  */
18299           buf = write_insn (buf, insn);
18300
18301           /* nop */
18302           buf = write_insn (buf, 0);
18303
18304           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18305             {
18306               /* beql $0, $0, 2f */
18307               insn = 0x50000000;
18308               /* Compute the PC offset from the current instruction to
18309                  the end of the variable frag.  */
18310               /* How many bytes in instructions we've already emitted?  */
18311               i = buf - fragp->fr_literal - fragp->fr_fix;
18312               /* How many bytes in instructions from here to the end?  */
18313               i = fragp->fr_var - i;
18314               /* Convert to instruction count.  */
18315               i >>= 2;
18316               /* Don't decrement i, because we want to branch over the
18317                  delay slot.  */
18318               insn |= i;
18319
18320               buf = write_insn (buf, insn);
18321               buf = write_insn (buf, 0);
18322             }
18323
18324         uncond:
18325           if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18326             {
18327               /* j or jal.  */
18328               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18329                       ? 0x0c000000 : 0x08000000);
18330
18331               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18332                               fragp->fr_symbol, fragp->fr_offset,
18333                               FALSE, BFD_RELOC_MIPS_JMP);
18334               fixp->fx_file = fragp->fr_file;
18335               fixp->fx_line = fragp->fr_line;
18336
18337               buf = write_insn (buf, insn);
18338             }
18339           else
18340             {
18341               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18342
18343               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18344               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18345               insn |= at << OP_SH_RT;
18346
18347               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18348                               fragp->fr_symbol, fragp->fr_offset,
18349                               FALSE, BFD_RELOC_MIPS_GOT16);
18350               fixp->fx_file = fragp->fr_file;
18351               fixp->fx_line = fragp->fr_line;
18352
18353               buf = write_insn (buf, insn);
18354
18355               if (mips_opts.isa == ISA_MIPS1)
18356                 /* nop */
18357                 buf = write_insn (buf, 0);
18358
18359               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18360               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18361               insn |= at << OP_SH_RS | at << OP_SH_RT;
18362
18363               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18364                               fragp->fr_symbol, fragp->fr_offset,
18365                               FALSE, BFD_RELOC_LO16);
18366               fixp->fx_file = fragp->fr_file;
18367               fixp->fx_line = fragp->fr_line;
18368
18369               buf = write_insn (buf, insn);
18370
18371               /* j(al)r $at.  */
18372               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18373                 insn = 0x0000f809;
18374               else
18375                 insn = 0x00000008;
18376               insn |= at << OP_SH_RS;
18377
18378               buf = write_insn (buf, insn);
18379             }
18380         }
18381
18382       fragp->fr_fix += fragp->fr_var;
18383       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18384       return;
18385     }
18386
18387   /* Relax microMIPS branches.  */
18388   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18389     {
18390       char *buf = fragp->fr_literal + fragp->fr_fix;
18391       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18392       bfd_boolean insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18393       bfd_boolean nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18394       bfd_boolean pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18395       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18396       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18397       bfd_boolean short_ds;
18398       unsigned long insn;
18399       fixS *fixp;
18400
18401       fragp->fr_fix += fragp->fr_var;
18402
18403       /* Handle 16-bit branches that fit or are forced to fit.  */
18404       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18405         {
18406           /* We generate a fixup instead of applying it right now,
18407              because if there is linker relaxation, we're going to
18408              need the relocations.  */
18409           switch (type)
18410             {
18411             case 'D':
18412               fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18413                               fragp->fr_symbol, fragp->fr_offset,
18414                               TRUE, BFD_RELOC_MICROMIPS_10_PCREL_S1);
18415               break;
18416             case 'E':
18417               fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18418                               fragp->fr_symbol, fragp->fr_offset,
18419                               TRUE, BFD_RELOC_MICROMIPS_7_PCREL_S1);
18420               break;
18421             default:
18422               abort ();
18423             }
18424
18425           fixp->fx_file = fragp->fr_file;
18426           fixp->fx_line = fragp->fr_line;
18427
18428           /* These relocations can have an addend that won't fit in
18429              2 octets.  */
18430           fixp->fx_no_overflow = 1;
18431
18432           return;
18433         }
18434
18435       /* Handle 32-bit branches that fit or are forced to fit.  */
18436       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18437           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18438         {
18439           /* We generate a fixup instead of applying it right now,
18440              because if there is linker relaxation, we're going to
18441              need the relocations.  */
18442           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18443                           fragp->fr_symbol, fragp->fr_offset,
18444                           TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
18445           fixp->fx_file = fragp->fr_file;
18446           fixp->fx_line = fragp->fr_line;
18447
18448           if (type == 0)
18449             {
18450               insn = read_compressed_insn (buf, 4);
18451               buf += 4;
18452
18453               if (nods)
18454                 {
18455                   /* Check the short-delay-slot bit.  */
18456                   if (!al || (insn & 0x02000000) != 0)
18457                     buf = write_compressed_insn (buf, 0x0c00, 2);
18458                   else
18459                     buf = write_compressed_insn (buf, 0x00000000, 4);
18460                 }
18461
18462               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18463               return;
18464             }
18465         }
18466
18467       /* Relax 16-bit branches to 32-bit branches.  */
18468       if (type != 0)
18469         {
18470           insn = read_compressed_insn (buf, 2);
18471
18472           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18473             insn = 0x94000000;                          /* beq  */
18474           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18475             {
18476               unsigned long regno;
18477
18478               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18479               regno = micromips_to_32_reg_d_map [regno];
18480               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18481               insn |= regno << MICROMIPSOP_SH_RS;
18482             }
18483           else
18484             abort ();
18485
18486           /* Nothing else to do, just write it out.  */
18487           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18488               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18489             {
18490               buf = write_compressed_insn (buf, insn, 4);
18491               if (nods)
18492                 buf = write_compressed_insn (buf, 0x0c00, 2);
18493               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18494               return;
18495             }
18496         }
18497       else
18498         insn = read_compressed_insn (buf, 4);
18499
18500       /* Relax 32-bit branches to a sequence of instructions.  */
18501       as_warn_where (fragp->fr_file, fragp->fr_line,
18502                      _("relaxed out-of-range branch into a jump"));
18503
18504       /* Set the short-delay-slot bit.  */
18505       short_ds = !al || (insn & 0x02000000) != 0;
18506
18507       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18508         {
18509           symbolS *l;
18510
18511           /* Reverse the branch.  */
18512           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18513               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18514             insn ^= 0x20000000;
18515           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18516                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18517                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18518                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18519                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18520                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18521                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18522                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18523                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18524                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18525             insn ^= 0x00400000;
18526           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18527                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18528                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18529                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18530             insn ^= 0x00200000;
18531           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
18532                                                                    BNZ.df  */
18533                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
18534                                                                    BNZ.V */
18535             insn ^= 0x00800000;
18536           else
18537             abort ();
18538
18539           if (al)
18540             {
18541               /* Clear the and-link and short-delay-slot bits.  */
18542               gas_assert ((insn & 0xfda00000) == 0x40200000);
18543
18544               /* bltzal  0x40200000     bgezal  0x40600000  */
18545               /* bltzals 0x42200000     bgezals 0x42600000  */
18546               insn &= ~0x02200000;
18547             }
18548
18549           /* Make a label at the end for use with the branch.  */
18550           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18551           micromips_label_inc ();
18552           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18553
18554           /* Refer to it.  */
18555           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18556                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18557           fixp->fx_file = fragp->fr_file;
18558           fixp->fx_line = fragp->fr_line;
18559
18560           /* Branch over the jump.  */
18561           buf = write_compressed_insn (buf, insn, 4);
18562
18563           if (!compact)
18564             {
18565               /* nop  */
18566               if (insn32)
18567                 buf = write_compressed_insn (buf, 0x00000000, 4);
18568               else
18569                 buf = write_compressed_insn (buf, 0x0c00, 2);
18570             }
18571         }
18572
18573       if (!pic)
18574         {
18575           unsigned long jal = (short_ds || nods
18576                                ? 0x74000000 : 0xf4000000);      /* jal/s  */
18577
18578           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18579           insn = al ? jal : 0xd4000000;
18580
18581           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18582                           fragp->fr_symbol, fragp->fr_offset,
18583                           FALSE, BFD_RELOC_MICROMIPS_JMP);
18584           fixp->fx_file = fragp->fr_file;
18585           fixp->fx_line = fragp->fr_line;
18586
18587           buf = write_compressed_insn (buf, insn, 4);
18588
18589           if (compact || nods)
18590             {
18591               /* nop  */
18592               if (insn32)
18593                 buf = write_compressed_insn (buf, 0x00000000, 4);
18594               else
18595                 buf = write_compressed_insn (buf, 0x0c00, 2);
18596             }
18597         }
18598       else
18599         {
18600           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18601
18602           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18603           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18604           insn |= at << MICROMIPSOP_SH_RT;
18605
18606           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18607                           fragp->fr_symbol, fragp->fr_offset,
18608                           FALSE, BFD_RELOC_MICROMIPS_GOT16);
18609           fixp->fx_file = fragp->fr_file;
18610           fixp->fx_line = fragp->fr_line;
18611
18612           buf = write_compressed_insn (buf, insn, 4);
18613
18614           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18615           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18616           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18617
18618           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18619                           fragp->fr_symbol, fragp->fr_offset,
18620                           FALSE, BFD_RELOC_MICROMIPS_LO16);
18621           fixp->fx_file = fragp->fr_file;
18622           fixp->fx_line = fragp->fr_line;
18623
18624           buf = write_compressed_insn (buf, insn, 4);
18625
18626           if (insn32)
18627             {
18628               /* jr/jalr $at  */
18629               insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
18630               insn |= at << MICROMIPSOP_SH_RS;
18631
18632               buf = write_compressed_insn (buf, insn, 4);
18633
18634               if (compact || nods)
18635                 /* nop  */
18636                 buf = write_compressed_insn (buf, 0x00000000, 4);
18637             }
18638           else
18639             {
18640               /* jr/jrc/jalr/jalrs $at  */
18641               unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;  /* jalr/s  */
18642               unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
18643
18644               insn = al ? jalr : jr;
18645               insn |= at << MICROMIPSOP_SH_MJ;
18646
18647               buf = write_compressed_insn (buf, insn, 2);
18648               if (al && nods)
18649                 {
18650                   /* nop  */
18651                   if (short_ds)
18652                     buf = write_compressed_insn (buf, 0x0c00, 2);
18653                   else
18654                     buf = write_compressed_insn (buf, 0x00000000, 4);
18655                 }
18656             }
18657         }
18658
18659       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18660       return;
18661     }
18662
18663   if (RELAX_MIPS16_P (fragp->fr_subtype))
18664     {
18665       int type;
18666       const struct mips_int_operand *operand;
18667       offsetT val;
18668       char *buf;
18669       unsigned int user_length;
18670       bfd_boolean need_reloc;
18671       unsigned long insn;
18672       bfd_boolean mac;
18673       bfd_boolean ext;
18674       segT symsec;
18675
18676       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18677       operand = mips16_immed_operand (type, FALSE);
18678
18679       mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
18680       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18681       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18682
18683       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18684       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18685                     || (operand->root.type == OP_PCREL && !mac
18686                         ? asec != symsec
18687                         : !bfd_is_abs_section (symsec)));
18688
18689       if (operand->root.type == OP_PCREL && !mac)
18690         {
18691           const struct mips_pcrel_operand *pcrel_op;
18692
18693           pcrel_op = (const struct mips_pcrel_operand *) operand;
18694
18695           if (pcrel_op->include_isa_bit && !need_reloc)
18696             {
18697               if (!mips_ignore_branch_isa
18698                   && !ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18699                 as_bad_where (fragp->fr_file, fragp->fr_line,
18700                               _("branch to a symbol in another ISA mode"));
18701               else if ((fragp->fr_offset & 0x1) != 0)
18702                 as_bad_where (fragp->fr_file, fragp->fr_line,
18703                               _("branch to misaligned address (0x%lx)"),
18704                               (long) val);
18705             }
18706
18707           val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
18708
18709           /* Make sure the section winds up with the alignment we have
18710              assumed.  */
18711           if (operand->shift > 0)
18712             record_alignment (asec, operand->shift);
18713         }
18714
18715       if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18716           || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18717         {
18718           if (mac)
18719             as_warn_where (fragp->fr_file, fragp->fr_line,
18720                            _("macro instruction expanded into multiple "
18721                              "instructions in a branch delay slot"));
18722           else if (ext)
18723             as_warn_where (fragp->fr_file, fragp->fr_line,
18724                            _("extended instruction in a branch delay slot"));
18725         }
18726       else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
18727         as_warn_where (fragp->fr_file, fragp->fr_line,
18728                        _("macro instruction expanded into multiple "
18729                          "instructions"));
18730
18731       buf = fragp->fr_literal + fragp->fr_fix;
18732
18733       insn = read_compressed_insn (buf, 2);
18734       if (ext)
18735         insn |= MIPS16_EXTEND;
18736
18737       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18738         user_length = 4;
18739       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18740         user_length = 2;
18741       else
18742         user_length = 0;
18743
18744       if (mac)
18745         {
18746           unsigned long reg;
18747           unsigned long new;
18748           unsigned long op;
18749           bfd_boolean e2;
18750
18751           gas_assert (type == 'A' || type == 'B' || type == 'E');
18752           gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
18753
18754           e2 = RELAX_MIPS16_E2 (fragp->fr_subtype);
18755
18756           if (need_reloc)
18757             {
18758               fixS *fixp;
18759
18760               gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
18761
18762               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18763                               fragp->fr_symbol, fragp->fr_offset,
18764                               FALSE, BFD_RELOC_MIPS16_HI16_S);
18765               fixp->fx_file = fragp->fr_file;
18766               fixp->fx_line = fragp->fr_line;
18767
18768               fixp = fix_new (fragp, buf - fragp->fr_literal + (e2 ? 4 : 8), 4,
18769                               fragp->fr_symbol, fragp->fr_offset,
18770                               FALSE, BFD_RELOC_MIPS16_LO16);
18771               fixp->fx_file = fragp->fr_file;
18772               fixp->fx_line = fragp->fr_line;
18773
18774               val = 0;
18775             }
18776
18777           switch (insn & 0xf800)
18778             {
18779             case 0x0800:                                        /* ADDIU */
18780               reg = (insn >> 8) & 0x7;
18781               op = 0xf0004800 | (reg << 8);
18782               break;
18783             case 0xb000:                                        /* LW */
18784               reg = (insn >> 8) & 0x7;
18785               op = 0xf0009800 | (reg << 8) | (reg << 5);
18786               break;
18787             case 0xf800:                                        /* I64 */
18788               reg = (insn >> 5) & 0x7;
18789               switch (insn & 0x0700)
18790                 {
18791                 case 0x0400:                                    /* LD */
18792                   op = 0xf0003800 | (reg << 8) | (reg << 5);
18793                   break;
18794                 case 0x0600:                                    /* DADDIU */
18795                   op = 0xf000fd00 | (reg << 5);
18796                   break;
18797                 default:
18798                   abort ();
18799                 }
18800               break;
18801             default:
18802               abort ();
18803             }
18804
18805           new = (e2 ? 0xf0006820 : 0xf0006800) | (reg << 8);    /* LUI/LI */
18806           new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
18807           buf = write_compressed_insn (buf, new, 4);
18808           if (!e2)
18809             {
18810               new = 0xf4003000 | (reg << 8) | (reg << 5);       /* SLL */
18811               buf = write_compressed_insn (buf, new, 4);
18812             }
18813           op |= mips16_immed_extend (val, 16);
18814           buf = write_compressed_insn (buf, op, 4);
18815
18816           fragp->fr_fix += e2 ? 8 : 12;
18817         }
18818       else
18819         {
18820           unsigned int length = ext ? 4 : 2;
18821
18822           if (need_reloc)
18823             {
18824               bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18825               fixS *fixp;
18826
18827               switch (type)
18828                 {
18829                 case 'p':
18830                 case 'q':
18831                   reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18832                   break;
18833                 default:
18834                   break;
18835                 }
18836               if (mac || reloc == BFD_RELOC_NONE)
18837                 as_bad_where (fragp->fr_file, fragp->fr_line,
18838                               _("unsupported relocation"));
18839               else if (ext)
18840                 {
18841                   fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18842                                   fragp->fr_symbol, fragp->fr_offset,
18843                                   TRUE, reloc);
18844                   fixp->fx_file = fragp->fr_file;
18845                   fixp->fx_line = fragp->fr_line;
18846                 }
18847               else
18848                 as_bad_where (fragp->fr_file, fragp->fr_line,
18849                               _("invalid unextended operand value"));
18850             }
18851           else
18852             mips16_immed (fragp->fr_file, fragp->fr_line, type,
18853                           BFD_RELOC_UNUSED, val, user_length, &insn);
18854
18855           gas_assert (mips16_opcode_length (insn) == length);
18856           write_compressed_insn (buf, insn, length);
18857           fragp->fr_fix += length;
18858         }
18859     }
18860   else
18861     {
18862       relax_substateT subtype = fragp->fr_subtype;
18863       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18864       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18865       int first, second;
18866       fixS *fixp;
18867
18868       first = RELAX_FIRST (subtype);
18869       second = RELAX_SECOND (subtype);
18870       fixp = (fixS *) fragp->fr_opcode;
18871
18872       /* If the delay slot chosen does not match the size of the instruction,
18873          then emit a warning.  */
18874       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18875            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18876         {
18877           relax_substateT s;
18878           const char *msg;
18879
18880           s = subtype & (RELAX_DELAY_SLOT_16BIT
18881                          | RELAX_DELAY_SLOT_SIZE_FIRST
18882                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18883           msg = macro_warning (s);
18884           if (msg != NULL)
18885             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18886           subtype &= ~s;
18887         }
18888
18889       /* Possibly emit a warning if we've chosen the longer option.  */
18890       if (use_second == second_longer)
18891         {
18892           relax_substateT s;
18893           const char *msg;
18894
18895           s = (subtype
18896                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18897           msg = macro_warning (s);
18898           if (msg != NULL)
18899             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18900           subtype &= ~s;
18901         }
18902
18903       /* Go through all the fixups for the first sequence.  Disable them
18904          (by marking them as done) if we're going to use the second
18905          sequence instead.  */
18906       while (fixp
18907              && fixp->fx_frag == fragp
18908              && fixp->fx_where < fragp->fr_fix - second)
18909         {
18910           if (subtype & RELAX_USE_SECOND)
18911             fixp->fx_done = 1;
18912           fixp = fixp->fx_next;
18913         }
18914
18915       /* Go through the fixups for the second sequence.  Disable them if
18916          we're going to use the first sequence, otherwise adjust their
18917          addresses to account for the relaxation.  */
18918       while (fixp && fixp->fx_frag == fragp)
18919         {
18920           if (subtype & RELAX_USE_SECOND)
18921             fixp->fx_where -= first;
18922           else
18923             fixp->fx_done = 1;
18924           fixp = fixp->fx_next;
18925         }
18926
18927       /* Now modify the frag contents.  */
18928       if (subtype & RELAX_USE_SECOND)
18929         {
18930           char *start;
18931
18932           start = fragp->fr_literal + fragp->fr_fix - first - second;
18933           memmove (start, start + first, second);
18934           fragp->fr_fix -= first;
18935         }
18936       else
18937         fragp->fr_fix -= second;
18938     }
18939 }
18940
18941 /* This function is called after the relocs have been generated.
18942    We've been storing mips16 text labels as odd.  Here we convert them
18943    back to even for the convenience of the debugger.  */
18944
18945 void
18946 mips_frob_file_after_relocs (void)
18947 {
18948   asymbol **syms;
18949   unsigned int count, i;
18950
18951   syms = bfd_get_outsymbols (stdoutput);
18952   count = bfd_get_symcount (stdoutput);
18953   for (i = 0; i < count; i++, syms++)
18954     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18955         && ((*syms)->value & 1) != 0)
18956       {
18957         (*syms)->value &= ~1;
18958         /* If the symbol has an odd size, it was probably computed
18959            incorrectly, so adjust that as well.  */
18960         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18961           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18962       }
18963 }
18964
18965 /* This function is called whenever a label is defined, including fake
18966    labels instantiated off the dot special symbol.  It is used when
18967    handling branch delays; if a branch has a label, we assume we cannot
18968    move it.  This also bumps the value of the symbol by 1 in compressed
18969    code.  */
18970
18971 static void
18972 mips_record_label (symbolS *sym)
18973 {
18974   segment_info_type *si = seg_info (now_seg);
18975   struct insn_label_list *l;
18976
18977   if (free_insn_labels == NULL)
18978     l = XNEW (struct insn_label_list);
18979   else
18980     {
18981       l = free_insn_labels;
18982       free_insn_labels = l->next;
18983     }
18984
18985   l->label = sym;
18986   l->next = si->label_list;
18987   si->label_list = l;
18988 }
18989
18990 /* This function is called as tc_frob_label() whenever a label is defined
18991    and adds a DWARF-2 record we only want for true labels.  */
18992
18993 void
18994 mips_define_label (symbolS *sym)
18995 {
18996   mips_record_label (sym);
18997   dwarf2_emit_label (sym);
18998 }
18999
19000 /* This function is called by tc_new_dot_label whenever a new dot symbol
19001    is defined.  */
19002
19003 void
19004 mips_add_dot_label (symbolS *sym)
19005 {
19006   mips_record_label (sym);
19007   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
19008     mips_compressed_mark_label (sym);
19009 }
19010 \f
19011 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
19012 static unsigned int
19013 mips_convert_ase_flags (int ase)
19014 {
19015   unsigned int ext_ases = 0;
19016
19017   if (ase & ASE_DSP)
19018     ext_ases |= AFL_ASE_DSP;
19019   if (ase & ASE_DSPR2)
19020     ext_ases |= AFL_ASE_DSPR2;
19021   if (ase & ASE_DSPR3)
19022     ext_ases |= AFL_ASE_DSPR3;
19023   if (ase & ASE_EVA)
19024     ext_ases |= AFL_ASE_EVA;
19025   if (ase & ASE_MCU)
19026     ext_ases |= AFL_ASE_MCU;
19027   if (ase & ASE_MDMX)
19028     ext_ases |= AFL_ASE_MDMX;
19029   if (ase & ASE_MIPS3D)
19030     ext_ases |= AFL_ASE_MIPS3D;
19031   if (ase & ASE_MT)
19032     ext_ases |= AFL_ASE_MT;
19033   if (ase & ASE_SMARTMIPS)
19034     ext_ases |= AFL_ASE_SMARTMIPS;
19035   if (ase & ASE_VIRT)
19036     ext_ases |= AFL_ASE_VIRT;
19037   if (ase & ASE_MSA)
19038     ext_ases |= AFL_ASE_MSA;
19039   if (ase & ASE_XPA)
19040     ext_ases |= AFL_ASE_XPA;
19041   if (ase & ASE_MIPS16E2)
19042     ext_ases |= file_ase_mips16 ? AFL_ASE_MIPS16E2 : 0;
19043   if (ase & ASE_CRC)
19044     ext_ases |= AFL_ASE_CRC;
19045   if (ase & ASE_GINV)
19046     ext_ases |= AFL_ASE_GINV;
19047   if (ase & ASE_LOONGSON_MMI)
19048     ext_ases |= AFL_ASE_LOONGSON_MMI;
19049   if (ase & ASE_LOONGSON_CAM)
19050     ext_ases |= AFL_ASE_LOONGSON_CAM;
19051   if (ase & ASE_LOONGSON_EXT)
19052     ext_ases |= AFL_ASE_LOONGSON_EXT;
19053
19054   return ext_ases;
19055 }
19056 /* Some special processing for a MIPS ELF file.  */
19057
19058 void
19059 mips_elf_final_processing (void)
19060 {
19061   int fpabi;
19062   Elf_Internal_ABIFlags_v0 flags;
19063
19064   flags.version = 0;
19065   flags.isa_rev = 0;
19066   switch (file_mips_opts.isa)
19067     {
19068     case INSN_ISA1:
19069       flags.isa_level = 1;
19070       break;
19071     case INSN_ISA2:
19072       flags.isa_level = 2;
19073       break;
19074     case INSN_ISA3:
19075       flags.isa_level = 3;
19076       break;
19077     case INSN_ISA4:
19078       flags.isa_level = 4;
19079       break;
19080     case INSN_ISA5:
19081       flags.isa_level = 5;
19082       break;
19083     case INSN_ISA32:
19084       flags.isa_level = 32;
19085       flags.isa_rev = 1;
19086       break;
19087     case INSN_ISA32R2:
19088       flags.isa_level = 32;
19089       flags.isa_rev = 2;
19090       break;
19091     case INSN_ISA32R3:
19092       flags.isa_level = 32;
19093       flags.isa_rev = 3;
19094       break;
19095     case INSN_ISA32R5:
19096       flags.isa_level = 32;
19097       flags.isa_rev = 5;
19098       break;
19099     case INSN_ISA32R6:
19100       flags.isa_level = 32;
19101       flags.isa_rev = 6;
19102       break;
19103     case INSN_ISA64:
19104       flags.isa_level = 64;
19105       flags.isa_rev = 1;
19106       break;
19107     case INSN_ISA64R2:
19108       flags.isa_level = 64;
19109       flags.isa_rev = 2;
19110       break;
19111     case INSN_ISA64R3:
19112       flags.isa_level = 64;
19113       flags.isa_rev = 3;
19114       break;
19115     case INSN_ISA64R5:
19116       flags.isa_level = 64;
19117       flags.isa_rev = 5;
19118       break;
19119     case INSN_ISA64R6:
19120       flags.isa_level = 64;
19121       flags.isa_rev = 6;
19122       break;
19123     }
19124
19125   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
19126   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
19127                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
19128                     : (file_mips_opts.fp == 64) ? AFL_REG_64
19129                     : AFL_REG_32;
19130   flags.cpr2_size = AFL_REG_NONE;
19131   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19132                                            Tag_GNU_MIPS_ABI_FP);
19133   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
19134   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
19135   if (file_ase_mips16)
19136     flags.ases |= AFL_ASE_MIPS16;
19137   if (file_ase_micromips)
19138     flags.ases |= AFL_ASE_MICROMIPS;
19139   flags.flags1 = 0;
19140   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
19141        || file_mips_opts.fp == 64)
19142       && file_mips_opts.oddspreg)
19143     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
19144   flags.flags2 = 0;
19145
19146   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
19147                                      ((Elf_External_ABIFlags_v0 *)
19148                                      mips_flags_frag));
19149
19150   /* Write out the register information.  */
19151   if (mips_abi != N64_ABI)
19152     {
19153       Elf32_RegInfo s;
19154
19155       s.ri_gprmask = mips_gprmask;
19156       s.ri_cprmask[0] = mips_cprmask[0];
19157       s.ri_cprmask[1] = mips_cprmask[1];
19158       s.ri_cprmask[2] = mips_cprmask[2];
19159       s.ri_cprmask[3] = mips_cprmask[3];
19160       /* The gp_value field is set by the MIPS ELF backend.  */
19161
19162       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
19163                                        ((Elf32_External_RegInfo *)
19164                                         mips_regmask_frag));
19165     }
19166   else
19167     {
19168       Elf64_Internal_RegInfo s;
19169
19170       s.ri_gprmask = mips_gprmask;
19171       s.ri_pad = 0;
19172       s.ri_cprmask[0] = mips_cprmask[0];
19173       s.ri_cprmask[1] = mips_cprmask[1];
19174       s.ri_cprmask[2] = mips_cprmask[2];
19175       s.ri_cprmask[3] = mips_cprmask[3];
19176       /* The gp_value field is set by the MIPS ELF backend.  */
19177
19178       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
19179                                        ((Elf64_External_RegInfo *)
19180                                         mips_regmask_frag));
19181     }
19182
19183   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
19184      sort of BFD interface for this.  */
19185   if (mips_any_noreorder)
19186     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
19187   if (mips_pic != NO_PIC)
19188     {
19189       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19190       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19191     }
19192   if (mips_abicalls)
19193     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19194
19195   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19196      defined at present; this might need to change in future.  */
19197   if (file_ase_mips16)
19198     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19199   if (file_ase_micromips)
19200     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19201   if (file_mips_opts.ase & ASE_MDMX)
19202     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19203
19204   /* Set the MIPS ELF ABI flags.  */
19205   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19206     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19207   else if (mips_abi == O64_ABI)
19208     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19209   else if (mips_abi == EABI_ABI)
19210     {
19211       if (file_mips_opts.gp == 64)
19212         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19213       else
19214         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19215     }
19216
19217   /* Nothing to do for N32_ABI or N64_ABI.  */
19218
19219   if (mips_32bitmode)
19220     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19221
19222   if (mips_nan2008 == 1)
19223     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19224
19225   /* 32 bit code with 64 bit FP registers.  */
19226   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19227                                     Tag_GNU_MIPS_ABI_FP);
19228   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19229     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19230 }
19231 \f
19232 typedef struct proc {
19233   symbolS *func_sym;
19234   symbolS *func_end_sym;
19235   unsigned long reg_mask;
19236   unsigned long reg_offset;
19237   unsigned long fpreg_mask;
19238   unsigned long fpreg_offset;
19239   unsigned long frame_offset;
19240   unsigned long frame_reg;
19241   unsigned long pc_reg;
19242 } procS;
19243
19244 static procS cur_proc;
19245 static procS *cur_proc_ptr;
19246 static int numprocs;
19247
19248 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19249    as "2", and a normal nop as "0".  */
19250
19251 #define NOP_OPCODE_MIPS         0
19252 #define NOP_OPCODE_MIPS16       1
19253 #define NOP_OPCODE_MICROMIPS    2
19254
19255 char
19256 mips_nop_opcode (void)
19257 {
19258   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19259     return NOP_OPCODE_MICROMIPS;
19260   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19261     return NOP_OPCODE_MIPS16;
19262   else
19263     return NOP_OPCODE_MIPS;
19264 }
19265
19266 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19267    32-bit microMIPS NOPs here (if applicable).  */
19268
19269 void
19270 mips_handle_align (fragS *fragp)
19271 {
19272   char nop_opcode;
19273   char *p;
19274   int bytes, size, excess;
19275   valueT opcode;
19276
19277   if (fragp->fr_type != rs_align_code)
19278     return;
19279
19280   p = fragp->fr_literal + fragp->fr_fix;
19281   nop_opcode = *p;
19282   switch (nop_opcode)
19283     {
19284     case NOP_OPCODE_MICROMIPS:
19285       opcode = micromips_nop32_insn.insn_opcode;
19286       size = 4;
19287       break;
19288     case NOP_OPCODE_MIPS16:
19289       opcode = mips16_nop_insn.insn_opcode;
19290       size = 2;
19291       break;
19292     case NOP_OPCODE_MIPS:
19293     default:
19294       opcode = nop_insn.insn_opcode;
19295       size = 4;
19296       break;
19297     }
19298
19299   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19300   excess = bytes % size;
19301
19302   /* Handle the leading part if we're not inserting a whole number of
19303      instructions, and make it the end of the fixed part of the frag.
19304      Try to fit in a short microMIPS NOP if applicable and possible,
19305      and use zeroes otherwise.  */
19306   gas_assert (excess < 4);
19307   fragp->fr_fix += excess;
19308   switch (excess)
19309     {
19310     case 3:
19311       *p++ = '\0';
19312       /* Fall through.  */
19313     case 2:
19314       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19315         {
19316           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19317           break;
19318         }
19319       *p++ = '\0';
19320       /* Fall through.  */
19321     case 1:
19322       *p++ = '\0';
19323       /* Fall through.  */
19324     case 0:
19325       break;
19326     }
19327
19328   md_number_to_chars (p, opcode, size);
19329   fragp->fr_var = size;
19330 }
19331
19332 static long
19333 get_number (void)
19334 {
19335   int negative = 0;
19336   long val = 0;
19337
19338   if (*input_line_pointer == '-')
19339     {
19340       ++input_line_pointer;
19341       negative = 1;
19342     }
19343   if (!ISDIGIT (*input_line_pointer))
19344     as_bad (_("expected simple number"));
19345   if (input_line_pointer[0] == '0')
19346     {
19347       if (input_line_pointer[1] == 'x')
19348         {
19349           input_line_pointer += 2;
19350           while (ISXDIGIT (*input_line_pointer))
19351             {
19352               val <<= 4;
19353               val |= hex_value (*input_line_pointer++);
19354             }
19355           return negative ? -val : val;
19356         }
19357       else
19358         {
19359           ++input_line_pointer;
19360           while (ISDIGIT (*input_line_pointer))
19361             {
19362               val <<= 3;
19363               val |= *input_line_pointer++ - '0';
19364             }
19365           return negative ? -val : val;
19366         }
19367     }
19368   if (!ISDIGIT (*input_line_pointer))
19369     {
19370       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19371               *input_line_pointer, *input_line_pointer);
19372       as_warn (_("invalid number"));
19373       return -1;
19374     }
19375   while (ISDIGIT (*input_line_pointer))
19376     {
19377       val *= 10;
19378       val += *input_line_pointer++ - '0';
19379     }
19380   return negative ? -val : val;
19381 }
19382
19383 /* The .file directive; just like the usual .file directive, but there
19384    is an initial number which is the ECOFF file index.  In the non-ECOFF
19385    case .file implies DWARF-2.  */
19386
19387 static void
19388 s_mips_file (int x ATTRIBUTE_UNUSED)
19389 {
19390   static int first_file_directive = 0;
19391
19392   if (ECOFF_DEBUGGING)
19393     {
19394       get_number ();
19395       s_app_file (0);
19396     }
19397   else
19398     {
19399       char *filename;
19400
19401       filename = dwarf2_directive_filename ();
19402
19403       /* Versions of GCC up to 3.1 start files with a ".file"
19404          directive even for stabs output.  Make sure that this
19405          ".file" is handled.  Note that you need a version of GCC
19406          after 3.1 in order to support DWARF-2 on MIPS.  */
19407       if (filename != NULL && ! first_file_directive)
19408         {
19409           (void) new_logical_line (filename, -1);
19410           s_app_file_string (filename, 0);
19411         }
19412       first_file_directive = 1;
19413     }
19414 }
19415
19416 /* The .loc directive, implying DWARF-2.  */
19417
19418 static void
19419 s_mips_loc (int x ATTRIBUTE_UNUSED)
19420 {
19421   if (!ECOFF_DEBUGGING)
19422     dwarf2_directive_loc (0);
19423 }
19424
19425 /* The .end directive.  */
19426
19427 static void
19428 s_mips_end (int x ATTRIBUTE_UNUSED)
19429 {
19430   symbolS *p;
19431
19432   /* Following functions need their own .frame and .cprestore directives.  */
19433   mips_frame_reg_valid = 0;
19434   mips_cprestore_valid = 0;
19435
19436   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19437     {
19438       p = get_symbol ();
19439       demand_empty_rest_of_line ();
19440     }
19441   else
19442     p = NULL;
19443
19444   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19445     as_warn (_(".end not in text section"));
19446
19447   if (!cur_proc_ptr)
19448     {
19449       as_warn (_(".end directive without a preceding .ent directive"));
19450       demand_empty_rest_of_line ();
19451       return;
19452     }
19453
19454   if (p != NULL)
19455     {
19456       gas_assert (S_GET_NAME (p));
19457       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19458         as_warn (_(".end symbol does not match .ent symbol"));
19459
19460       if (debug_type == DEBUG_STABS)
19461         stabs_generate_asm_endfunc (S_GET_NAME (p),
19462                                     S_GET_NAME (p));
19463     }
19464   else
19465     as_warn (_(".end directive missing or unknown symbol"));
19466
19467   /* Create an expression to calculate the size of the function.  */
19468   if (p && cur_proc_ptr)
19469     {
19470       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19471       expressionS *exp = XNEW (expressionS);
19472
19473       obj->size = exp;
19474       exp->X_op = O_subtract;
19475       exp->X_add_symbol = symbol_temp_new_now ();
19476       exp->X_op_symbol = p;
19477       exp->X_add_number = 0;
19478
19479       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19480     }
19481
19482 #ifdef md_flush_pending_output
19483   md_flush_pending_output ();
19484 #endif
19485
19486   /* Generate a .pdr section.  */
19487   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19488     {
19489       segT saved_seg = now_seg;
19490       subsegT saved_subseg = now_subseg;
19491       expressionS exp;
19492       char *fragp;
19493
19494       gas_assert (pdr_seg);
19495       subseg_set (pdr_seg, 0);
19496
19497       /* Write the symbol.  */
19498       exp.X_op = O_symbol;
19499       exp.X_add_symbol = p;
19500       exp.X_add_number = 0;
19501       emit_expr (&exp, 4);
19502
19503       fragp = frag_more (7 * 4);
19504
19505       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19506       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19507       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19508       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19509       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19510       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19511       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19512
19513       subseg_set (saved_seg, saved_subseg);
19514     }
19515
19516   cur_proc_ptr = NULL;
19517 }
19518
19519 /* The .aent and .ent directives.  */
19520
19521 static void
19522 s_mips_ent (int aent)
19523 {
19524   symbolS *symbolP;
19525
19526   symbolP = get_symbol ();
19527   if (*input_line_pointer == ',')
19528     ++input_line_pointer;
19529   SKIP_WHITESPACE ();
19530   if (ISDIGIT (*input_line_pointer)
19531       || *input_line_pointer == '-')
19532     get_number ();
19533
19534   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19535     as_warn (_(".ent or .aent not in text section"));
19536
19537   if (!aent && cur_proc_ptr)
19538     as_warn (_("missing .end"));
19539
19540   if (!aent)
19541     {
19542       /* This function needs its own .frame and .cprestore directives.  */
19543       mips_frame_reg_valid = 0;
19544       mips_cprestore_valid = 0;
19545
19546       cur_proc_ptr = &cur_proc;
19547       memset (cur_proc_ptr, '\0', sizeof (procS));
19548
19549       cur_proc_ptr->func_sym = symbolP;
19550
19551       ++numprocs;
19552
19553       if (debug_type == DEBUG_STABS)
19554         stabs_generate_asm_func (S_GET_NAME (symbolP),
19555                                  S_GET_NAME (symbolP));
19556     }
19557
19558   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19559
19560   demand_empty_rest_of_line ();
19561 }
19562
19563 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19564    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19565    s_mips_frame is used so that we can set the PDR information correctly.
19566    We can't use the ecoff routines because they make reference to the ecoff
19567    symbol table (in the mdebug section).  */
19568
19569 static void
19570 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19571 {
19572   if (ECOFF_DEBUGGING)
19573     s_ignore (ignore);
19574   else
19575     {
19576       long val;
19577
19578       if (cur_proc_ptr == (procS *) NULL)
19579         {
19580           as_warn (_(".frame outside of .ent"));
19581           demand_empty_rest_of_line ();
19582           return;
19583         }
19584
19585       cur_proc_ptr->frame_reg = tc_get_register (1);
19586
19587       SKIP_WHITESPACE ();
19588       if (*input_line_pointer++ != ','
19589           || get_absolute_expression_and_terminator (&val) != ',')
19590         {
19591           as_warn (_("bad .frame directive"));
19592           --input_line_pointer;
19593           demand_empty_rest_of_line ();
19594           return;
19595         }
19596
19597       cur_proc_ptr->frame_offset = val;
19598       cur_proc_ptr->pc_reg = tc_get_register (0);
19599
19600       demand_empty_rest_of_line ();
19601     }
19602 }
19603
19604 /* The .fmask and .mask directives. If the mdebug section is present
19605    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19606    embedded targets, s_mips_mask is used so that we can set the PDR
19607    information correctly. We can't use the ecoff routines because they
19608    make reference to the ecoff symbol table (in the mdebug section).  */
19609
19610 static void
19611 s_mips_mask (int reg_type)
19612 {
19613   if (ECOFF_DEBUGGING)
19614     s_ignore (reg_type);
19615   else
19616     {
19617       long mask, off;
19618
19619       if (cur_proc_ptr == (procS *) NULL)
19620         {
19621           as_warn (_(".mask/.fmask outside of .ent"));
19622           demand_empty_rest_of_line ();
19623           return;
19624         }
19625
19626       if (get_absolute_expression_and_terminator (&mask) != ',')
19627         {
19628           as_warn (_("bad .mask/.fmask directive"));
19629           --input_line_pointer;
19630           demand_empty_rest_of_line ();
19631           return;
19632         }
19633
19634       off = get_absolute_expression ();
19635
19636       if (reg_type == 'F')
19637         {
19638           cur_proc_ptr->fpreg_mask = mask;
19639           cur_proc_ptr->fpreg_offset = off;
19640         }
19641       else
19642         {
19643           cur_proc_ptr->reg_mask = mask;
19644           cur_proc_ptr->reg_offset = off;
19645         }
19646
19647       demand_empty_rest_of_line ();
19648     }
19649 }
19650
19651 /* A table describing all the processors gas knows about.  Names are
19652    matched in the order listed.
19653
19654    To ease comparison, please keep this table in the same order as
19655    gcc's mips_cpu_info_table[].  */
19656 static const struct mips_cpu_info mips_cpu_info_table[] =
19657 {
19658   /* Entries for generic ISAs */
19659   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19660   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19661   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19662   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19663   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19664   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19665   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19666   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
19667   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
19668   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
19669   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19670   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19671   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
19672   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
19673   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
19674
19675   /* MIPS I */
19676   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19677   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19678   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19679
19680   /* MIPS II */
19681   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19682
19683   /* MIPS III */
19684   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19685   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19686   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19687   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19688   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19689   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19690   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19691   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19692   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19693   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19694   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19695   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19696   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19697   /* ST Microelectronics Loongson 2E and 2F cores */
19698   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19699   { "loongson2f",     0, ASE_LOONGSON_MMI,      ISA_MIPS3,    CPU_LOONGSON_2F },
19700
19701   /* MIPS IV */
19702   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19703   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19704   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19705   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19706   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19707   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19708   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19709   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19710   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19711   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19712   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19713   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19714   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19715   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19716   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19717
19718   /* MIPS 32 */
19719   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19720   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19721   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19722   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19723
19724   /* MIPS 32 Release 2 */
19725   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19726   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19727   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19728   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19729   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19730   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19731   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19732   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19733   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19734                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19735   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19736                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19737   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19738   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19739   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19740   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19741   /* Deprecated forms of the above.  */
19742   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19743   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19744   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19745   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19746   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19747   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19748   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19749   /* Deprecated forms of the above.  */
19750   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19751   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19752   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19753   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19754   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19755   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19756   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19757   /* Deprecated forms of the above.  */
19758   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19759   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19760   /* 34Kn is a 34kc without DSP.  */
19761   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19762   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19763   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19764   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19765   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19766   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19767   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19768   /* Deprecated forms of the above.  */
19769   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19770   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19771   /* 1004K cores are multiprocessor versions of the 34K.  */
19772   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19773   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19774   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19775   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19776   /* interaptiv is the new name for 1004kf */
19777   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19778   { "interaptiv-mr2", 0,
19779     ASE_DSP | ASE_EVA | ASE_MT | ASE_MIPS16E2 | ASE_MIPS16E2_MT,
19780     ISA_MIPS32R3, CPU_INTERAPTIV_MR2 },
19781   /* M5100 family */
19782   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19783   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19784   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19785   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19786
19787   /* MIPS 64 */
19788   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19789   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19790   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19791   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19792
19793   /* Broadcom SB-1 CPU core */
19794   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19795   /* Broadcom SB-1A CPU core */
19796   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19797
19798   /* MIPS 64 Release 2 */
19799   /* Loongson CPU core */
19800   { "loongson3a",     0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT,
19801      ISA_MIPS64R2,      CPU_LOONGSON_3A },
19802
19803   /* Cavium Networks Octeon CPU core */
19804   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19805   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19806   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19807   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19808
19809   /* RMI Xlr */
19810   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19811
19812   /* Broadcom XLP.
19813      XLP is mostly like XLR, with the prominent exception that it is
19814      MIPS64R2 rather than MIPS64.  */
19815   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19816
19817   /* MIPS 64 Release 6 */
19818   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19819   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19820
19821   /* End marker */
19822   { NULL, 0, 0, 0, 0 }
19823 };
19824
19825
19826 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19827    with a final "000" replaced by "k".  Ignore case.
19828
19829    Note: this function is shared between GCC and GAS.  */
19830
19831 static bfd_boolean
19832 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19833 {
19834   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19835     given++, canonical++;
19836
19837   return ((*given == 0 && *canonical == 0)
19838           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19839 }
19840
19841
19842 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19843    CPU name.  We've traditionally allowed a lot of variation here.
19844
19845    Note: this function is shared between GCC and GAS.  */
19846
19847 static bfd_boolean
19848 mips_matching_cpu_name_p (const char *canonical, const char *given)
19849 {
19850   /* First see if the name matches exactly, or with a final "000"
19851      turned into "k".  */
19852   if (mips_strict_matching_cpu_name_p (canonical, given))
19853     return TRUE;
19854
19855   /* If not, try comparing based on numerical designation alone.
19856      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19857   if (TOLOWER (*given) == 'r')
19858     given++;
19859   if (!ISDIGIT (*given))
19860     return FALSE;
19861
19862   /* Skip over some well-known prefixes in the canonical name,
19863      hoping to find a number there too.  */
19864   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19865     canonical += 2;
19866   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19867     canonical += 2;
19868   else if (TOLOWER (canonical[0]) == 'r')
19869     canonical += 1;
19870
19871   return mips_strict_matching_cpu_name_p (canonical, given);
19872 }
19873
19874
19875 /* Parse an option that takes the name of a processor as its argument.
19876    OPTION is the name of the option and CPU_STRING is the argument.
19877    Return the corresponding processor enumeration if the CPU_STRING is
19878    recognized, otherwise report an error and return null.
19879
19880    A similar function exists in GCC.  */
19881
19882 static const struct mips_cpu_info *
19883 mips_parse_cpu (const char *option, const char *cpu_string)
19884 {
19885   const struct mips_cpu_info *p;
19886
19887   /* 'from-abi' selects the most compatible architecture for the given
19888      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19889      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19890      version.  Look first at the -mgp options, if given, otherwise base
19891      the choice on MIPS_DEFAULT_64BIT.
19892
19893      Treat NO_ABI like the EABIs.  One reason to do this is that the
19894      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19895      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19896      'mips64', just as we did in the days before 'from-abi'.  */
19897   if (strcasecmp (cpu_string, "from-abi") == 0)
19898     {
19899       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19900         return mips_cpu_info_from_isa (ISA_MIPS1);
19901
19902       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19903         return mips_cpu_info_from_isa (ISA_MIPS3);
19904
19905       if (file_mips_opts.gp >= 0)
19906         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19907                                        ? ISA_MIPS1 : ISA_MIPS3);
19908
19909       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19910                                      ? ISA_MIPS3
19911                                      : ISA_MIPS1);
19912     }
19913
19914   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19915   if (strcasecmp (cpu_string, "default") == 0)
19916     return 0;
19917
19918   for (p = mips_cpu_info_table; p->name != 0; p++)
19919     if (mips_matching_cpu_name_p (p->name, cpu_string))
19920       return p;
19921
19922   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19923   return 0;
19924 }
19925
19926 /* Return the canonical processor information for ISA (a member of the
19927    ISA_MIPS* enumeration).  */
19928
19929 static const struct mips_cpu_info *
19930 mips_cpu_info_from_isa (int isa)
19931 {
19932   int i;
19933
19934   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19935     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19936         && isa == mips_cpu_info_table[i].isa)
19937       return (&mips_cpu_info_table[i]);
19938
19939   return NULL;
19940 }
19941
19942 static const struct mips_cpu_info *
19943 mips_cpu_info_from_arch (int arch)
19944 {
19945   int i;
19946
19947   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19948     if (arch == mips_cpu_info_table[i].cpu)
19949       return (&mips_cpu_info_table[i]);
19950
19951   return NULL;
19952 }
19953 \f
19954 static void
19955 show (FILE *stream, const char *string, int *col_p, int *first_p)
19956 {
19957   if (*first_p)
19958     {
19959       fprintf (stream, "%24s", "");
19960       *col_p = 24;
19961     }
19962   else
19963     {
19964       fprintf (stream, ", ");
19965       *col_p += 2;
19966     }
19967
19968   if (*col_p + strlen (string) > 72)
19969     {
19970       fprintf (stream, "\n%24s", "");
19971       *col_p = 24;
19972     }
19973
19974   fprintf (stream, "%s", string);
19975   *col_p += strlen (string);
19976
19977   *first_p = 0;
19978 }
19979
19980 void
19981 md_show_usage (FILE *stream)
19982 {
19983   int column, first;
19984   size_t i;
19985
19986   fprintf (stream, _("\
19987 MIPS options:\n\
19988 -EB                     generate big endian output\n\
19989 -EL                     generate little endian output\n\
19990 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19991 -G NUM                  allow referencing objects up to NUM bytes\n\
19992                         implicitly with the gp register [default 8]\n"));
19993   fprintf (stream, _("\
19994 -mips1                  generate MIPS ISA I instructions\n\
19995 -mips2                  generate MIPS ISA II instructions\n\
19996 -mips3                  generate MIPS ISA III instructions\n\
19997 -mips4                  generate MIPS ISA IV instructions\n\
19998 -mips5                  generate MIPS ISA V instructions\n\
19999 -mips32                 generate MIPS32 ISA instructions\n\
20000 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
20001 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
20002 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
20003 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
20004 -mips64                 generate MIPS64 ISA instructions\n\
20005 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
20006 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
20007 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
20008 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
20009 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
20010
20011   first = 1;
20012
20013   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
20014     show (stream, mips_cpu_info_table[i].name, &column, &first);
20015   show (stream, "from-abi", &column, &first);
20016   fputc ('\n', stream);
20017
20018   fprintf (stream, _("\
20019 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
20020 -no-mCPU                don't generate code specific to CPU.\n\
20021                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
20022
20023   first = 1;
20024
20025   show (stream, "3900", &column, &first);
20026   show (stream, "4010", &column, &first);
20027   show (stream, "4100", &column, &first);
20028   show (stream, "4650", &column, &first);
20029   fputc ('\n', stream);
20030
20031   fprintf (stream, _("\
20032 -mips16                 generate mips16 instructions\n\
20033 -no-mips16              do not generate mips16 instructions\n"));
20034   fprintf (stream, _("\
20035 -mmips16e2              generate MIPS16e2 instructions\n\
20036 -mno-mips16e2           do not generate MIPS16e2 instructions\n"));
20037   fprintf (stream, _("\
20038 -mmicromips             generate microMIPS instructions\n\
20039 -mno-micromips          do not generate microMIPS instructions\n"));
20040   fprintf (stream, _("\
20041 -msmartmips             generate smartmips instructions\n\
20042 -mno-smartmips          do not generate smartmips instructions\n"));
20043   fprintf (stream, _("\
20044 -mdsp                   generate DSP instructions\n\
20045 -mno-dsp                do not generate DSP instructions\n"));
20046   fprintf (stream, _("\
20047 -mdspr2                 generate DSP R2 instructions\n\
20048 -mno-dspr2              do not generate DSP R2 instructions\n"));
20049   fprintf (stream, _("\
20050 -mdspr3                 generate DSP R3 instructions\n\
20051 -mno-dspr3              do not generate DSP R3 instructions\n"));
20052   fprintf (stream, _("\
20053 -mmt                    generate MT instructions\n\
20054 -mno-mt                 do not generate MT instructions\n"));
20055   fprintf (stream, _("\
20056 -mmcu                   generate MCU instructions\n\
20057 -mno-mcu                do not generate MCU instructions\n"));
20058   fprintf (stream, _("\
20059 -mmsa                   generate MSA instructions\n\
20060 -mno-msa                do not generate MSA instructions\n"));
20061   fprintf (stream, _("\
20062 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
20063 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
20064   fprintf (stream, _("\
20065 -mvirt                  generate Virtualization instructions\n\
20066 -mno-virt               do not generate Virtualization instructions\n"));
20067   fprintf (stream, _("\
20068 -mcrc                   generate CRC instructions\n\
20069 -mno-crc                do not generate CRC instructions\n"));
20070   fprintf (stream, _("\
20071 -mginv                  generate Global INValidate (GINV) instructions\n\
20072 -mno-ginv               do not generate Global INValidate instructions\n"));
20073   fprintf (stream, _("\
20074 -mloongson-mmi          generate Loongson MultiMedia extensions Instructions (MMI) instructions\n\
20075 -mno-loongson-mmi       do not generate Loongson MultiMedia extensions Instructions\n"));
20076   fprintf (stream, _("\
20077 -mloongson-cam          generate Loongson Content Address Memory (CAM) instructions\n\
20078 -mno-loongson-cam       do not generate Loongson Content Address Memory Instructions\n"));
20079   fprintf (stream, _("\
20080 -mloongson-ext          generate Loongson EXTensions (EXT) instructions\n\
20081 -mno-loongson-ext       do not generate Loongson EXTensions Instructions\n"));
20082   fprintf (stream, _("\
20083 -minsn32                only generate 32-bit microMIPS instructions\n\
20084 -mno-insn32             generate all microMIPS instructions\n"));
20085   fprintf (stream, _("\
20086 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
20087 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
20088 -mfix-vr4120            work around certain VR4120 errata\n\
20089 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
20090 -mfix-24k               insert a nop after ERET and DERET instructions\n\
20091 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
20092 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
20093 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
20094 -msym32                 assume all symbols have 32-bit values\n\
20095 -O0                     do not remove unneeded NOPs, do not swap branches\n\
20096 -O, -O1                 remove unneeded NOPs, do not swap branches\n\
20097 -O2                     remove unneeded NOPs and swap branches\n\
20098 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
20099 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
20100   fprintf (stream, _("\
20101 -mhard-float            allow floating-point instructions\n\
20102 -msoft-float            do not allow floating-point instructions\n\
20103 -msingle-float          only allow 32-bit floating-point operations\n\
20104 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
20105 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
20106 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
20107 -mignore-branch-isa     accept invalid branches requiring an ISA mode switch\n\
20108 -mno-ignore-branch-isa  reject invalid branches requiring an ISA mode switch\n\
20109 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
20110
20111   first = 1;
20112
20113   show (stream, "legacy", &column, &first);
20114   show (stream, "2008", &column, &first);
20115
20116   fputc ('\n', stream);
20117
20118   fprintf (stream, _("\
20119 -KPIC, -call_shared     generate SVR4 position independent code\n\
20120 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
20121 -mvxworks-pic           generate VxWorks position independent code\n\
20122 -non_shared             do not generate code that can operate with DSOs\n\
20123 -xgot                   assume a 32 bit GOT\n\
20124 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
20125 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
20126                         position dependent (non shared) code\n\
20127 -mabi=ABI               create ABI conformant object file for:\n"));
20128
20129   first = 1;
20130
20131   show (stream, "32", &column, &first);
20132   show (stream, "o64", &column, &first);
20133   show (stream, "n32", &column, &first);
20134   show (stream, "64", &column, &first);
20135   show (stream, "eabi", &column, &first);
20136
20137   fputc ('\n', stream);
20138
20139   fprintf (stream, _("\
20140 -32                     create o32 ABI object file%s\n"),
20141            MIPS_DEFAULT_ABI == O32_ABI ? _(" (default)") : "");
20142   fprintf (stream, _("\
20143 -n32                    create n32 ABI object file%s\n"),
20144            MIPS_DEFAULT_ABI == N32_ABI ? _(" (default)") : "");
20145   fprintf (stream, _("\
20146 -64                     create 64 ABI object file%s\n"),
20147            MIPS_DEFAULT_ABI == N64_ABI ? _(" (default)") : "");
20148 }
20149
20150 #ifdef TE_IRIX
20151 enum dwarf2_format
20152 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
20153 {
20154   if (HAVE_64BIT_SYMBOLS)
20155     return dwarf2_format_64bit_irix;
20156   else
20157     return dwarf2_format_32bit;
20158 }
20159 #endif
20160
20161 int
20162 mips_dwarf2_addr_size (void)
20163 {
20164   if (HAVE_64BIT_OBJECTS)
20165     return 8;
20166   else
20167     return 4;
20168 }
20169
20170 /* Standard calling conventions leave the CFA at SP on entry.  */
20171 void
20172 mips_cfi_frame_initial_instructions (void)
20173 {
20174   cfi_add_CFA_def_cfa_register (SP);
20175 }
20176
20177 int
20178 tc_mips_regname_to_dw2regnum (char *regname)
20179 {
20180   unsigned int regnum = -1;
20181   unsigned int reg;
20182
20183   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
20184     regnum = reg;
20185
20186   return regnum;
20187 }
20188
20189 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
20190    Given a symbolic attribute NAME, return the proper integer value.
20191    Returns -1 if the attribute is not known.  */
20192
20193 int
20194 mips_convert_symbolic_attribute (const char *name)
20195 {
20196   static const struct
20197   {
20198     const char * name;
20199     const int    tag;
20200   }
20201   attribute_table[] =
20202     {
20203 #define T(tag) {#tag, tag}
20204       T (Tag_GNU_MIPS_ABI_FP),
20205       T (Tag_GNU_MIPS_ABI_MSA),
20206 #undef T
20207     };
20208   unsigned int i;
20209
20210   if (name == NULL)
20211     return -1;
20212
20213   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
20214     if (streq (name, attribute_table[i].name))
20215       return attribute_table[i].tag;
20216
20217   return -1;
20218 }
20219
20220 void
20221 md_mips_end (void)
20222 {
20223   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
20224
20225   mips_emit_delays ();
20226   if (cur_proc_ptr)
20227     as_warn (_("missing .end at end of assembly"));
20228
20229   /* Just in case no code was emitted, do the consistency check.  */
20230   file_mips_check_options ();
20231
20232   /* Set a floating-point ABI if the user did not.  */
20233   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20234     {
20235       /* Perform consistency checks on the floating-point ABI.  */
20236       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20237                                         Tag_GNU_MIPS_ABI_FP);
20238       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20239         check_fpabi (fpabi);
20240     }
20241   else
20242     {
20243       /* Soft-float gets precedence over single-float, the two options should
20244          not be used together so this should not matter.  */
20245       if (file_mips_opts.soft_float == 1)
20246         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20247       /* Single-float gets precedence over all double_float cases.  */
20248       else if (file_mips_opts.single_float == 1)
20249         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20250       else
20251         {
20252           switch (file_mips_opts.fp)
20253             {
20254             case 32:
20255               if (file_mips_opts.gp == 32)
20256                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20257               break;
20258             case 0:
20259               fpabi = Val_GNU_MIPS_ABI_FP_XX;
20260               break;
20261             case 64:
20262               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20263                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
20264               else if (file_mips_opts.gp == 32)
20265                 fpabi = Val_GNU_MIPS_ABI_FP_64;
20266               else
20267                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20268               break;
20269             }
20270         }
20271
20272       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20273                                 Tag_GNU_MIPS_ABI_FP, fpabi);
20274     }
20275 }
20276
20277 /*  Returns the relocation type required for a particular CFI encoding.  */
20278
20279 bfd_reloc_code_real_type
20280 mips_cfi_reloc_for_encoding (int encoding)
20281 {
20282   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20283     return BFD_RELOC_32_PCREL;
20284   else return BFD_RELOC_NONE;
20285 }