[MIPS] Add Loongson 3A2000/3A3000 proccessor support.
[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_GS464               \
426     || (CPU) != CPU_GS464E))
427
428 /* Return true if ISA supports move to/from high part of a 64-bit
429    floating-point register. */
430 #define ISA_HAS_MXHC1(ISA)              \
431   ((ISA) == ISA_MIPS32R2                \
432    || (ISA) == ISA_MIPS32R3             \
433    || (ISA) == ISA_MIPS32R5             \
434    || (ISA) == ISA_MIPS32R6             \
435    || (ISA) == ISA_MIPS64R2             \
436    || (ISA) == ISA_MIPS64R3             \
437    || (ISA) == ISA_MIPS64R5             \
438    || (ISA) == ISA_MIPS64R6)
439
440 /*  Return true if ISA supports legacy NAN.  */
441 #define ISA_HAS_LEGACY_NAN(ISA)         \
442   ((ISA) == ISA_MIPS1                   \
443    || (ISA) == ISA_MIPS2                \
444    || (ISA) == ISA_MIPS3                \
445    || (ISA) == ISA_MIPS4                \
446    || (ISA) == ISA_MIPS5                \
447    || (ISA) == ISA_MIPS32               \
448    || (ISA) == ISA_MIPS32R2             \
449    || (ISA) == ISA_MIPS32R3             \
450    || (ISA) == ISA_MIPS32R5             \
451    || (ISA) == ISA_MIPS64               \
452    || (ISA) == ISA_MIPS64R2             \
453    || (ISA) == ISA_MIPS64R3             \
454    || (ISA) == ISA_MIPS64R5)
455
456 #define GPR_SIZE \
457     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
458      ? 32 \
459      : mips_opts.gp)
460
461 #define FPR_SIZE \
462     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
463      ? 32 \
464      : mips_opts.fp)
465
466 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
467
468 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
469
470 /* True if relocations are stored in-place.  */
471 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
472
473 /* The ABI-derived address size.  */
474 #define HAVE_64BIT_ADDRESSES \
475   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
476 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
477
478 /* The size of symbolic constants (i.e., expressions of the form
479    "SYMBOL" or "SYMBOL + OFFSET").  */
480 #define HAVE_32BIT_SYMBOLS \
481   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
482 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
483
484 /* Addresses are loaded in different ways, depending on the address size
485    in use.  The n32 ABI Documentation also mandates the use of additions
486    with overflow checking, but existing implementations don't follow it.  */
487 #define ADDRESS_ADD_INSN                                                \
488    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
489
490 #define ADDRESS_ADDI_INSN                                               \
491    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
492
493 #define ADDRESS_LOAD_INSN                                               \
494    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
495
496 #define ADDRESS_STORE_INSN                                              \
497    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
498
499 /* Return true if the given CPU supports the MIPS16 ASE.  */
500 #define CPU_HAS_MIPS16(cpu)                                             \
501    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
502     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
503
504 /* Return true if the given CPU supports the microMIPS ASE.  */
505 #define CPU_HAS_MICROMIPS(cpu)  0
506
507 /* True if CPU has a dror instruction.  */
508 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
509
510 /* True if CPU has a ror instruction.  */
511 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
512
513 /* True if CPU is in the Octeon family */
514 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
515                             || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
516
517 /* True if CPU has seq/sne and seqi/snei instructions.  */
518 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
519
520 /* True, if CPU has support for ldc1 and sdc1. */
521 #define CPU_HAS_LDC1_SDC1(CPU)  \
522    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
523
524 /* True if mflo and mfhi can be immediately followed by instructions
525    which write to the HI and LO registers.
526
527    According to MIPS specifications, MIPS ISAs I, II, and III need
528    (at least) two instructions between the reads of HI/LO and
529    instructions which write them, and later ISAs do not.  Contradicting
530    the MIPS specifications, some MIPS IV processor user manuals (e.g.
531    the UM for the NEC Vr5000) document needing the instructions between
532    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
533    MIPS64 and later ISAs to have the interlocks, plus any specific
534    earlier-ISA CPUs for which CPU documentation declares that the
535    instructions are really interlocked.  */
536 #define hilo_interlocks \
537   (mips_opts.isa == ISA_MIPS32                        \
538    || mips_opts.isa == ISA_MIPS32R2                   \
539    || mips_opts.isa == ISA_MIPS32R3                   \
540    || mips_opts.isa == ISA_MIPS32R5                   \
541    || mips_opts.isa == ISA_MIPS32R6                   \
542    || mips_opts.isa == ISA_MIPS64                     \
543    || mips_opts.isa == ISA_MIPS64R2                   \
544    || mips_opts.isa == ISA_MIPS64R3                   \
545    || mips_opts.isa == ISA_MIPS64R5                   \
546    || mips_opts.isa == ISA_MIPS64R6                   \
547    || mips_opts.arch == CPU_R4010                     \
548    || mips_opts.arch == CPU_R5900                     \
549    || mips_opts.arch == CPU_R10000                    \
550    || mips_opts.arch == CPU_R12000                    \
551    || mips_opts.arch == CPU_R14000                    \
552    || mips_opts.arch == CPU_R16000                    \
553    || mips_opts.arch == CPU_RM7000                    \
554    || mips_opts.arch == CPU_VR5500                    \
555    || mips_opts.micromips                             \
556    )
557
558 /* Whether the processor uses hardware interlocks to protect reads
559    from the GPRs after they are loaded from memory, and thus does not
560    require nops to be inserted.  This applies to instructions marked
561    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
562    level I and microMIPS mode instructions are always interlocked.  */
563 #define gpr_interlocks                                \
564   (mips_opts.isa != ISA_MIPS1                         \
565    || mips_opts.arch == CPU_R3900                     \
566    || mips_opts.arch == CPU_R5900                     \
567    || mips_opts.micromips                             \
568    )
569
570 /* Whether the processor uses hardware interlocks to avoid delays
571    required by coprocessor instructions, and thus does not require
572    nops to be inserted.  This applies to instructions marked
573    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
574    instructions marked INSN_WRITE_COND_CODE and ones marked
575    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
576    levels I, II, and III and microMIPS mode instructions are always
577    interlocked.  */
578 /* Itbl support may require additional care here.  */
579 #define cop_interlocks                                \
580   ((mips_opts.isa != ISA_MIPS1                        \
581     && mips_opts.isa != ISA_MIPS2                     \
582     && mips_opts.isa != ISA_MIPS3)                    \
583    || mips_opts.arch == CPU_R4300                     \
584    || mips_opts.micromips                             \
585    )
586
587 /* Whether the processor uses hardware interlocks to protect reads
588    from coprocessor registers after they are loaded from memory, and
589    thus does not require nops to be inserted.  This applies to
590    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
591    requires at MIPS ISA level I and microMIPS mode instructions are
592    always interlocked.  */
593 #define cop_mem_interlocks                            \
594   (mips_opts.isa != ISA_MIPS1                         \
595    || mips_opts.micromips                             \
596    )
597
598 /* Is this a mfhi or mflo instruction?  */
599 #define MF_HILO_INSN(PINFO) \
600   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
601
602 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
603    has been selected.  This implies, in particular, that addresses of text
604    labels have their LSB set.  */
605 #define HAVE_CODE_COMPRESSION                                           \
606   ((mips_opts.mips16 | mips_opts.micromips) != 0)
607
608 /* The minimum and maximum signed values that can be stored in a GPR.  */
609 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
610 #define GPR_SMIN (-GPR_SMAX - 1)
611
612 /* MIPS PIC level.  */
613
614 enum mips_pic_level mips_pic;
615
616 /* 1 if we should generate 32 bit offsets from the $gp register in
617    SVR4_PIC mode.  Currently has no meaning in other modes.  */
618 static int mips_big_got = 0;
619
620 /* 1 if trap instructions should used for overflow rather than break
621    instructions.  */
622 static int mips_trap = 0;
623
624 /* 1 if double width floating point constants should not be constructed
625    by assembling two single width halves into two single width floating
626    point registers which just happen to alias the double width destination
627    register.  On some architectures this aliasing can be disabled by a bit
628    in the status register, and the setting of this bit cannot be determined
629    automatically at assemble time.  */
630 static int mips_disable_float_construction;
631
632 /* Non-zero if any .set noreorder directives were used.  */
633
634 static int mips_any_noreorder;
635
636 /* Non-zero if nops should be inserted when the register referenced in
637    an mfhi/mflo instruction is read in the next two instructions.  */
638 static int mips_7000_hilo_fix;
639
640 /* The size of objects in the small data section.  */
641 static unsigned int g_switch_value = 8;
642 /* Whether the -G option was used.  */
643 static int g_switch_seen = 0;
644
645 #define N_RMASK 0xc4
646 #define N_VFP   0xd4
647
648 /* If we can determine in advance that GP optimization won't be
649    possible, we can skip the relaxation stuff that tries to produce
650    GP-relative references.  This makes delay slot optimization work
651    better.
652
653    This function can only provide a guess, but it seems to work for
654    gcc output.  It needs to guess right for gcc, otherwise gcc
655    will put what it thinks is a GP-relative instruction in a branch
656    delay slot.
657
658    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
659    fixed it for the non-PIC mode.  KR 95/04/07  */
660 static int nopic_need_relax (symbolS *, int);
661
662 /* handle of the OPCODE hash table */
663 static struct hash_control *op_hash = NULL;
664
665 /* The opcode hash table we use for the mips16.  */
666 static struct hash_control *mips16_op_hash = NULL;
667
668 /* The opcode hash table we use for the microMIPS ASE.  */
669 static struct hash_control *micromips_op_hash = NULL;
670
671 /* This array holds the chars that always start a comment.  If the
672     pre-processor is disabled, these aren't very useful */
673 const char comment_chars[] = "#";
674
675 /* This array holds the chars that only start a comment at the beginning of
676    a line.  If the line seems to have the form '# 123 filename'
677    .line and .file directives will appear in the pre-processed output */
678 /* Note that input_file.c hand checks for '#' at the beginning of the
679    first line of the input file.  This is because the compiler outputs
680    #NO_APP at the beginning of its output.  */
681 /* Also note that C style comments are always supported.  */
682 const char line_comment_chars[] = "#";
683
684 /* This array holds machine specific line separator characters.  */
685 const char line_separator_chars[] = ";";
686
687 /* Chars that can be used to separate mant from exp in floating point nums */
688 const char EXP_CHARS[] = "eE";
689
690 /* Chars that mean this number is a floating point constant */
691 /* As in 0f12.456 */
692 /* or    0d1.2345e12 */
693 const char FLT_CHARS[] = "rRsSfFdDxXpP";
694
695 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
696    changed in read.c .  Ideally it shouldn't have to know about it at all,
697    but nothing is ideal around here.
698  */
699
700 /* Types of printf format used for instruction-related error messages.
701    "I" means int ("%d") and "S" means string ("%s"). */
702 enum mips_insn_error_format {
703   ERR_FMT_PLAIN,
704   ERR_FMT_I,
705   ERR_FMT_SS,
706 };
707
708 /* Information about an error that was found while assembling the current
709    instruction.  */
710 struct mips_insn_error {
711   /* We sometimes need to match an instruction against more than one
712      opcode table entry.  Errors found during this matching are reported
713      against a particular syntactic argument rather than against the
714      instruction as a whole.  We grade these messages so that errors
715      against argument N have a greater priority than an error against
716      any argument < N, since the former implies that arguments up to N
717      were acceptable and that the opcode entry was therefore a closer match.
718      If several matches report an error against the same argument,
719      we only use that error if it is the same in all cases.
720
721      min_argnum is the minimum argument number for which an error message
722      should be accepted.  It is 0 if MSG is against the instruction as
723      a whole.  */
724   int min_argnum;
725
726   /* The printf()-style message, including its format and arguments.  */
727   enum mips_insn_error_format format;
728   const char *msg;
729   union {
730     int i;
731     const char *ss[2];
732   } u;
733 };
734
735 /* The error that should be reported for the current instruction.  */
736 static struct mips_insn_error insn_error;
737
738 static int auto_align = 1;
739
740 /* When outputting SVR4 PIC code, the assembler needs to know the
741    offset in the stack frame from which to restore the $gp register.
742    This is set by the .cprestore pseudo-op, and saved in this
743    variable.  */
744 static offsetT mips_cprestore_offset = -1;
745
746 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
747    more optimizations, it can use a register value instead of a memory-saved
748    offset and even an other register than $gp as global pointer.  */
749 static offsetT mips_cpreturn_offset = -1;
750 static int mips_cpreturn_register = -1;
751 static int mips_gp_register = GP;
752 static int mips_gprel_offset = 0;
753
754 /* Whether mips_cprestore_offset has been set in the current function
755    (or whether it has already been warned about, if not).  */
756 static int mips_cprestore_valid = 0;
757
758 /* This is the register which holds the stack frame, as set by the
759    .frame pseudo-op.  This is needed to implement .cprestore.  */
760 static int mips_frame_reg = SP;
761
762 /* Whether mips_frame_reg has been set in the current function
763    (or whether it has already been warned about, if not).  */
764 static int mips_frame_reg_valid = 0;
765
766 /* To output NOP instructions correctly, we need to keep information
767    about the previous two instructions.  */
768
769 /* Whether we are optimizing.  The default value of 2 means to remove
770    unneeded NOPs and swap branch instructions when possible.  A value
771    of 1 means to not swap branches.  A value of 0 means to always
772    insert NOPs.  */
773 static int mips_optimize = 2;
774
775 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
776    equivalent to seeing no -g option at all.  */
777 static int mips_debug = 0;
778
779 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
780 #define MAX_VR4130_NOPS 4
781
782 /* The maximum number of NOPs needed to fill delay slots.  */
783 #define MAX_DELAY_NOPS 2
784
785 /* The maximum number of NOPs needed for any purpose.  */
786 #define MAX_NOPS 4
787
788 /* A list of previous instructions, with index 0 being the most recent.
789    We need to look back MAX_NOPS instructions when filling delay slots
790    or working around processor errata.  We need to look back one
791    instruction further if we're thinking about using history[0] to
792    fill a branch delay slot.  */
793 static struct mips_cl_insn history[1 + MAX_NOPS];
794
795 /* Arrays of operands for each instruction.  */
796 #define MAX_OPERANDS 6
797 struct mips_operand_array {
798   const struct mips_operand *operand[MAX_OPERANDS];
799 };
800 static struct mips_operand_array *mips_operands;
801 static struct mips_operand_array *mips16_operands;
802 static struct mips_operand_array *micromips_operands;
803
804 /* Nop instructions used by emit_nop.  */
805 static struct mips_cl_insn nop_insn;
806 static struct mips_cl_insn mips16_nop_insn;
807 static struct mips_cl_insn micromips_nop16_insn;
808 static struct mips_cl_insn micromips_nop32_insn;
809
810 /* The appropriate nop for the current mode.  */
811 #define NOP_INSN (mips_opts.mips16                                      \
812                   ? &mips16_nop_insn                                    \
813                   : (mips_opts.micromips                                \
814                      ? (mips_opts.insn32                                \
815                         ? &micromips_nop32_insn                         \
816                         : &micromips_nop16_insn)                        \
817                      : &nop_insn))
818
819 /* The size of NOP_INSN in bytes.  */
820 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
821                         || (mips_opts.micromips && !mips_opts.insn32))  \
822                        ? 2 : 4)
823
824 /* If this is set, it points to a frag holding nop instructions which
825    were inserted before the start of a noreorder section.  If those
826    nops turn out to be unnecessary, the size of the frag can be
827    decreased.  */
828 static fragS *prev_nop_frag;
829
830 /* The number of nop instructions we created in prev_nop_frag.  */
831 static int prev_nop_frag_holds;
832
833 /* The number of nop instructions that we know we need in
834    prev_nop_frag.  */
835 static int prev_nop_frag_required;
836
837 /* The number of instructions we've seen since prev_nop_frag.  */
838 static int prev_nop_frag_since;
839
840 /* Relocations against symbols are sometimes done in two parts, with a HI
841    relocation and a LO relocation.  Each relocation has only 16 bits of
842    space to store an addend.  This means that in order for the linker to
843    handle carries correctly, it must be able to locate both the HI and
844    the LO relocation.  This means that the relocations must appear in
845    order in the relocation table.
846
847    In order to implement this, we keep track of each unmatched HI
848    relocation.  We then sort them so that they immediately precede the
849    corresponding LO relocation.  */
850
851 struct mips_hi_fixup
852 {
853   /* Next HI fixup.  */
854   struct mips_hi_fixup *next;
855   /* This fixup.  */
856   fixS *fixp;
857   /* The section this fixup is in.  */
858   segT seg;
859 };
860
861 /* The list of unmatched HI relocs.  */
862
863 static struct mips_hi_fixup *mips_hi_fixup_list;
864
865 /* The frag containing the last explicit relocation operator.
866    Null if explicit relocations have not been used.  */
867
868 static fragS *prev_reloc_op_frag;
869
870 /* Map mips16 register numbers to normal MIPS register numbers.  */
871
872 static const unsigned int mips16_to_32_reg_map[] =
873 {
874   16, 17, 2, 3, 4, 5, 6, 7
875 };
876
877 /* Map microMIPS register numbers to normal MIPS register numbers.  */
878
879 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
880
881 /* The microMIPS registers with type h.  */
882 static const unsigned int micromips_to_32_reg_h_map1[] =
883 {
884   5, 5, 6, 4, 4, 4, 4, 4
885 };
886 static const unsigned int micromips_to_32_reg_h_map2[] =
887 {
888   6, 7, 7, 21, 22, 5, 6, 7
889 };
890
891 /* The microMIPS registers with type m.  */
892 static const unsigned int micromips_to_32_reg_m_map[] =
893 {
894   0, 17, 2, 3, 16, 18, 19, 20
895 };
896
897 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
898
899 /* Classifies the kind of instructions we're interested in when
900    implementing -mfix-vr4120.  */
901 enum fix_vr4120_class
902 {
903   FIX_VR4120_MACC,
904   FIX_VR4120_DMACC,
905   FIX_VR4120_MULT,
906   FIX_VR4120_DMULT,
907   FIX_VR4120_DIV,
908   FIX_VR4120_MTHILO,
909   NUM_FIX_VR4120_CLASSES
910 };
911
912 /* ...likewise -mfix-loongson2f-jump.  */
913 static bfd_boolean mips_fix_loongson2f_jump;
914
915 /* ...likewise -mfix-loongson2f-nop.  */
916 static bfd_boolean mips_fix_loongson2f_nop;
917
918 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
919 static bfd_boolean mips_fix_loongson2f;
920
921 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
922    there must be at least one other instruction between an instruction
923    of type X and an instruction of type Y.  */
924 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
925
926 /* True if -mfix-vr4120 is in force.  */
927 static int mips_fix_vr4120;
928
929 /* ...likewise -mfix-vr4130.  */
930 static int mips_fix_vr4130;
931
932 /* ...likewise -mfix-24k.  */
933 static int mips_fix_24k;
934
935 /* ...likewise -mfix-rm7000  */
936 static int mips_fix_rm7000;
937
938 /* ...likewise -mfix-cn63xxp1 */
939 static bfd_boolean mips_fix_cn63xxp1;
940
941 /* We don't relax branches by default, since this causes us to expand
942    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
943    fail to compute the offset before expanding the macro to the most
944    efficient expansion.  */
945
946 static int mips_relax_branch;
947
948 /* TRUE if checks are suppressed for invalid branches between ISA modes.
949    Needed for broken assembly produced by some GCC versions and some
950    sloppy code out there, where branches to data labels are present.  */
951 static bfd_boolean mips_ignore_branch_isa;
952 \f
953 /* The expansion of many macros depends on the type of symbol that
954    they refer to.  For example, when generating position-dependent code,
955    a macro that refers to a symbol may have two different expansions,
956    one which uses GP-relative addresses and one which uses absolute
957    addresses.  When generating SVR4-style PIC, a macro may have
958    different expansions for local and global symbols.
959
960    We handle these situations by generating both sequences and putting
961    them in variant frags.  In position-dependent code, the first sequence
962    will be the GP-relative one and the second sequence will be the
963    absolute one.  In SVR4 PIC, the first sequence will be for global
964    symbols and the second will be for local symbols.
965
966    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
967    SECOND are the lengths of the two sequences in bytes.  These fields
968    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
969    the subtype has the following flags:
970
971    RELAX_PIC
972         Set if generating PIC code.
973
974    RELAX_USE_SECOND
975         Set if it has been decided that we should use the second
976         sequence instead of the first.
977
978    RELAX_SECOND_LONGER
979         Set in the first variant frag if the macro's second implementation
980         is longer than its first.  This refers to the macro as a whole,
981         not an individual relaxation.
982
983    RELAX_NOMACRO
984         Set in the first variant frag if the macro appeared in a .set nomacro
985         block and if one alternative requires a warning but the other does not.
986
987    RELAX_DELAY_SLOT
988         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
989         delay slot.
990
991    RELAX_DELAY_SLOT_16BIT
992         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
993         16-bit instruction.
994
995    RELAX_DELAY_SLOT_SIZE_FIRST
996         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
997         the macro is of the wrong size for the branch delay slot.
998
999    RELAX_DELAY_SLOT_SIZE_SECOND
1000         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1001         the macro is of the wrong size for the branch delay slot.
1002
1003    The frag's "opcode" points to the first fixup for relaxable code.
1004
1005    Relaxable macros are generated using a sequence such as:
1006
1007       relax_start (SYMBOL);
1008       ... generate first expansion ...
1009       relax_switch ();
1010       ... generate second expansion ...
1011       relax_end ();
1012
1013    The code and fixups for the unwanted alternative are discarded
1014    by md_convert_frag.  */
1015 #define RELAX_ENCODE(FIRST, SECOND, PIC)                        \
1016   (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1017
1018 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1019 #define RELAX_SECOND(X) ((X) & 0xff)
1020 #define RELAX_PIC(X) (((X) & 0x10000) != 0)
1021 #define RELAX_USE_SECOND 0x20000
1022 #define RELAX_SECOND_LONGER 0x40000
1023 #define RELAX_NOMACRO 0x80000
1024 #define RELAX_DELAY_SLOT 0x100000
1025 #define RELAX_DELAY_SLOT_16BIT 0x200000
1026 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1027 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1028
1029 /* Branch without likely bit.  If label is out of range, we turn:
1030
1031         beq reg1, reg2, label
1032         delay slot
1033
1034    into
1035
1036         bne reg1, reg2, 0f
1037         nop
1038         j label
1039      0: delay slot
1040
1041    with the following opcode replacements:
1042
1043         beq <-> bne
1044         blez <-> bgtz
1045         bltz <-> bgez
1046         bc1f <-> bc1t
1047
1048         bltzal <-> bgezal  (with jal label instead of j label)
1049
1050    Even though keeping the delay slot instruction in the delay slot of
1051    the branch would be more efficient, it would be very tricky to do
1052    correctly, because we'd have to introduce a variable frag *after*
1053    the delay slot instruction, and expand that instead.  Let's do it
1054    the easy way for now, even if the branch-not-taken case now costs
1055    one additional instruction.  Out-of-range branches are not supposed
1056    to be common, anyway.
1057
1058    Branch likely.  If label is out of range, we turn:
1059
1060         beql reg1, reg2, label
1061         delay slot (annulled if branch not taken)
1062
1063    into
1064
1065         beql reg1, reg2, 1f
1066         nop
1067         beql $0, $0, 2f
1068         nop
1069      1: j[al] label
1070         delay slot (executed only if branch taken)
1071      2:
1072
1073    It would be possible to generate a shorter sequence by losing the
1074    likely bit, generating something like:
1075
1076         bne reg1, reg2, 0f
1077         nop
1078         j[al] label
1079         delay slot (executed only if branch taken)
1080      0:
1081
1082         beql -> bne
1083         bnel -> beq
1084         blezl -> bgtz
1085         bgtzl -> blez
1086         bltzl -> bgez
1087         bgezl -> bltz
1088         bc1fl -> bc1t
1089         bc1tl -> bc1f
1090
1091         bltzall -> bgezal  (with jal label instead of j label)
1092         bgezall -> bltzal  (ditto)
1093
1094
1095    but it's not clear that it would actually improve performance.  */
1096 #define RELAX_BRANCH_ENCODE(at, pic,                            \
1097                             uncond, likely, link, toofar)       \
1098   ((relax_substateT)                                            \
1099    (0xc0000000                                                  \
1100     | ((at) & 0x1f)                                             \
1101     | ((pic) ? 0x20 : 0)                                        \
1102     | ((toofar) ? 0x40 : 0)                                     \
1103     | ((link) ? 0x80 : 0)                                       \
1104     | ((likely) ? 0x100 : 0)                                    \
1105     | ((uncond) ? 0x200 : 0)))
1106 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1107 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1108 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1109 #define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1110 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1111 #define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1112 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1113
1114 /* For mips16 code, we use an entirely different form of relaxation.
1115    mips16 supports two versions of most instructions which take
1116    immediate values: a small one which takes some small value, and a
1117    larger one which takes a 16 bit value.  Since branches also follow
1118    this pattern, relaxing these values is required.
1119
1120    We can assemble both mips16 and normal MIPS code in a single
1121    object.  Therefore, we need to support this type of relaxation at
1122    the same time that we support the relaxation described above.  We
1123    use the high bit of the subtype field to distinguish these cases.
1124
1125    The information we store for this type of relaxation is the
1126    argument code found in the opcode file for this relocation, whether
1127    the user explicitly requested a small or extended form, and whether
1128    the relocation is in a jump or jal delay slot.  That tells us the
1129    size of the value, and how it should be stored.  We also store
1130    whether the fragment is considered to be extended or not.  We also
1131    store whether this is known to be a branch to a different section,
1132    whether we have tried to relax this frag yet, and whether we have
1133    ever extended a PC relative fragment because of a shift count.  */
1134 #define RELAX_MIPS16_ENCODE(type, e2, pic, sym32, nomacro,      \
1135                             small, ext,                         \
1136                             dslot, jal_dslot)                   \
1137   (0x80000000                                                   \
1138    | ((type) & 0xff)                                            \
1139    | ((e2) ? 0x100 : 0)                                         \
1140    | ((pic) ? 0x200 : 0)                                        \
1141    | ((sym32) ? 0x400 : 0)                                      \
1142    | ((nomacro) ? 0x800 : 0)                                    \
1143    | ((small) ? 0x1000 : 0)                                     \
1144    | ((ext) ? 0x2000 : 0)                                       \
1145    | ((dslot) ? 0x4000 : 0)                                     \
1146    | ((jal_dslot) ? 0x8000 : 0))
1147
1148 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1149 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1150 #define RELAX_MIPS16_E2(i) (((i) & 0x100) != 0)
1151 #define RELAX_MIPS16_PIC(i) (((i) & 0x200) != 0)
1152 #define RELAX_MIPS16_SYM32(i) (((i) & 0x400) != 0)
1153 #define RELAX_MIPS16_NOMACRO(i) (((i) & 0x800) != 0)
1154 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x1000) != 0)
1155 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x2000) != 0)
1156 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x4000) != 0)
1157 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x8000) != 0)
1158
1159 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x10000) != 0)
1160 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x10000)
1161 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x10000)
1162 #define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x20000) != 0)
1163 #define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x20000)
1164 #define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x20000)
1165 #define RELAX_MIPS16_MACRO(i) (((i) & 0x40000) != 0)
1166 #define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x40000)
1167 #define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x40000)
1168
1169 /* For microMIPS code, we use relaxation similar to one we use for
1170    MIPS16 code.  Some instructions that take immediate values support
1171    two encodings: a small one which takes some small value, and a
1172    larger one which takes a 16 bit value.  As some branches also follow
1173    this pattern, relaxing these values is required.
1174
1175    We can assemble both microMIPS and normal MIPS code in a single
1176    object.  Therefore, we need to support this type of relaxation at
1177    the same time that we support the relaxation described above.  We
1178    use one of the high bits of the subtype field to distinguish these
1179    cases.
1180
1181    The information we store for this type of relaxation is the argument
1182    code found in the opcode file for this relocation, the register
1183    selected as the assembler temporary, whether in the 32-bit
1184    instruction mode, whether the branch is unconditional, whether it is
1185    compact, whether there is no delay-slot instruction available to fill
1186    in, whether it stores the link address implicitly in $ra, whether
1187    relaxation of out-of-range 32-bit branches to a sequence of
1188    instructions is enabled, and whether the displacement of a branch is
1189    too large to fit as an immediate argument of a 16-bit and a 32-bit
1190    branch, respectively.  */
1191 #define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,           \
1192                                uncond, compact, link, nods,     \
1193                                relax32, toofar16, toofar32)     \
1194   (0x40000000                                                   \
1195    | ((type) & 0xff)                                            \
1196    | (((at) & 0x1f) << 8)                                       \
1197    | ((insn32) ? 0x2000 : 0)                                    \
1198    | ((pic) ? 0x4000 : 0)                                       \
1199    | ((uncond) ? 0x8000 : 0)                                    \
1200    | ((compact) ? 0x10000 : 0)                                  \
1201    | ((link) ? 0x20000 : 0)                                     \
1202    | ((nods) ? 0x40000 : 0)                                     \
1203    | ((relax32) ? 0x80000 : 0)                                  \
1204    | ((toofar16) ? 0x100000 : 0)                                \
1205    | ((toofar32) ? 0x200000 : 0))
1206 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1207 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1208 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1209 #define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1210 #define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1211 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1212 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1213 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1214 #define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1215 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1216
1217 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1218 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1219 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1220 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1221 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1222 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1223
1224 /* Sign-extend 16-bit value X.  */
1225 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1226
1227 /* Is the given value a sign-extended 32-bit value?  */
1228 #define IS_SEXT_32BIT_NUM(x)                                            \
1229   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1230    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1231
1232 /* Is the given value a sign-extended 16-bit value?  */
1233 #define IS_SEXT_16BIT_NUM(x)                                            \
1234   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1235    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1236
1237 /* Is the given value a sign-extended 12-bit value?  */
1238 #define IS_SEXT_12BIT_NUM(x)                                            \
1239   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1240
1241 /* Is the given value a sign-extended 9-bit value?  */
1242 #define IS_SEXT_9BIT_NUM(x)                                             \
1243   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1244
1245 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1246 #define IS_ZEXT_32BIT_NUM(x)                                            \
1247   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1248    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1249
1250 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1251    SHIFT places.  */
1252 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1253   (((STRUCT) >> (SHIFT)) & (MASK))
1254
1255 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1256 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1257   (!(MICROMIPS) \
1258    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1259    : EXTRACT_BITS ((INSN).insn_opcode, \
1260                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1261 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1262   EXTRACT_BITS ((INSN).insn_opcode, \
1263                 MIPS16OP_MASK_##FIELD, \
1264                 MIPS16OP_SH_##FIELD)
1265
1266 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1267 #define MIPS16_EXTEND (0xf000U << 16)
1268 \f
1269 /* Whether or not we are emitting a branch-likely macro.  */
1270 static bfd_boolean emit_branch_likely_macro = FALSE;
1271
1272 /* Global variables used when generating relaxable macros.  See the
1273    comment above RELAX_ENCODE for more details about how relaxation
1274    is used.  */
1275 static struct {
1276   /* 0 if we're not emitting a relaxable macro.
1277      1 if we're emitting the first of the two relaxation alternatives.
1278      2 if we're emitting the second alternative.  */
1279   int sequence;
1280
1281   /* The first relaxable fixup in the current frag.  (In other words,
1282      the first fixup that refers to relaxable code.)  */
1283   fixS *first_fixup;
1284
1285   /* sizes[0] says how many bytes of the first alternative are stored in
1286      the current frag.  Likewise sizes[1] for the second alternative.  */
1287   unsigned int sizes[2];
1288
1289   /* The symbol on which the choice of sequence depends.  */
1290   symbolS *symbol;
1291 } mips_relax;
1292 \f
1293 /* Global variables used to decide whether a macro needs a warning.  */
1294 static struct {
1295   /* True if the macro is in a branch delay slot.  */
1296   bfd_boolean delay_slot_p;
1297
1298   /* Set to the length in bytes required if the macro is in a delay slot
1299      that requires a specific length of instruction, otherwise zero.  */
1300   unsigned int delay_slot_length;
1301
1302   /* For relaxable macros, sizes[0] is the length of the first alternative
1303      in bytes and sizes[1] is the length of the second alternative.
1304      For non-relaxable macros, both elements give the length of the
1305      macro in bytes.  */
1306   unsigned int sizes[2];
1307
1308   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1309      instruction of the first alternative in bytes and first_insn_sizes[1]
1310      is the length of the first instruction of the second alternative.
1311      For non-relaxable macros, both elements give the length of the first
1312      instruction in bytes.
1313
1314      Set to zero if we haven't yet seen the first instruction.  */
1315   unsigned int first_insn_sizes[2];
1316
1317   /* For relaxable macros, insns[0] is the number of instructions for the
1318      first alternative and insns[1] is the number of instructions for the
1319      second alternative.
1320
1321      For non-relaxable macros, both elements give the number of
1322      instructions for the macro.  */
1323   unsigned int insns[2];
1324
1325   /* The first variant frag for this macro.  */
1326   fragS *first_frag;
1327 } mips_macro_warning;
1328 \f
1329 /* Prototypes for static functions.  */
1330
1331 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1332
1333 static void append_insn
1334   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1335    bfd_boolean expansionp);
1336 static void mips_no_prev_insn (void);
1337 static void macro_build (expressionS *, const char *, const char *, ...);
1338 static void mips16_macro_build
1339   (expressionS *, const char *, const char *, va_list *);
1340 static void load_register (int, expressionS *, int);
1341 static void macro_start (void);
1342 static void macro_end (void);
1343 static void macro (struct mips_cl_insn *ip, char *str);
1344 static void mips16_macro (struct mips_cl_insn * ip);
1345 static void mips_ip (char *str, struct mips_cl_insn * ip);
1346 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1347 static unsigned long mips16_immed_extend (offsetT, unsigned int);
1348 static void mips16_immed
1349   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1350    unsigned int, unsigned long *);
1351 static size_t my_getSmallExpression
1352   (expressionS *, bfd_reloc_code_real_type *, char *);
1353 static void my_getExpression (expressionS *, char *);
1354 static void s_align (int);
1355 static void s_change_sec (int);
1356 static void s_change_section (int);
1357 static void s_cons (int);
1358 static void s_float_cons (int);
1359 static void s_mips_globl (int);
1360 static void s_option (int);
1361 static void s_mipsset (int);
1362 static void s_abicalls (int);
1363 static void s_cpload (int);
1364 static void s_cpsetup (int);
1365 static void s_cplocal (int);
1366 static void s_cprestore (int);
1367 static void s_cpreturn (int);
1368 static void s_dtprelword (int);
1369 static void s_dtpreldword (int);
1370 static void s_tprelword (int);
1371 static void s_tpreldword (int);
1372 static void s_gpvalue (int);
1373 static void s_gpword (int);
1374 static void s_gpdword (int);
1375 static void s_ehword (int);
1376 static void s_cpadd (int);
1377 static void s_insn (int);
1378 static void s_nan (int);
1379 static void s_module (int);
1380 static void s_mips_ent (int);
1381 static void s_mips_end (int);
1382 static void s_mips_frame (int);
1383 static void s_mips_mask (int reg_type);
1384 static void s_mips_stab (int);
1385 static void s_mips_weakext (int);
1386 static void s_mips_file (int);
1387 static void s_mips_loc (int);
1388 static bfd_boolean pic_need_relax (symbolS *);
1389 static int relaxed_branch_length (fragS *, asection *, int);
1390 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1391 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1392 static void file_mips_check_options (void);
1393
1394 /* Table and functions used to map between CPU/ISA names, and
1395    ISA levels, and CPU numbers.  */
1396
1397 struct mips_cpu_info
1398 {
1399   const char *name;           /* CPU or ISA name.  */
1400   int flags;                  /* MIPS_CPU_* flags.  */
1401   int ase;                    /* Set of ASEs implemented by the CPU.  */
1402   int isa;                    /* ISA level.  */
1403   int cpu;                    /* CPU number (default CPU if ISA).  */
1404 };
1405
1406 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1407
1408 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1409 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1410 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1411 \f
1412 /* Command-line options.  */
1413 const char *md_shortopts = "O::g::G:";
1414
1415 enum options
1416   {
1417     OPTION_MARCH = OPTION_MD_BASE,
1418     OPTION_MTUNE,
1419     OPTION_MIPS1,
1420     OPTION_MIPS2,
1421     OPTION_MIPS3,
1422     OPTION_MIPS4,
1423     OPTION_MIPS5,
1424     OPTION_MIPS32,
1425     OPTION_MIPS64,
1426     OPTION_MIPS32R2,
1427     OPTION_MIPS32R3,
1428     OPTION_MIPS32R5,
1429     OPTION_MIPS32R6,
1430     OPTION_MIPS64R2,
1431     OPTION_MIPS64R3,
1432     OPTION_MIPS64R5,
1433     OPTION_MIPS64R6,
1434     OPTION_MIPS16,
1435     OPTION_NO_MIPS16,
1436     OPTION_MIPS3D,
1437     OPTION_NO_MIPS3D,
1438     OPTION_MDMX,
1439     OPTION_NO_MDMX,
1440     OPTION_DSP,
1441     OPTION_NO_DSP,
1442     OPTION_MT,
1443     OPTION_NO_MT,
1444     OPTION_VIRT,
1445     OPTION_NO_VIRT,
1446     OPTION_MSA,
1447     OPTION_NO_MSA,
1448     OPTION_SMARTMIPS,
1449     OPTION_NO_SMARTMIPS,
1450     OPTION_DSPR2,
1451     OPTION_NO_DSPR2,
1452     OPTION_DSPR3,
1453     OPTION_NO_DSPR3,
1454     OPTION_EVA,
1455     OPTION_NO_EVA,
1456     OPTION_XPA,
1457     OPTION_NO_XPA,
1458     OPTION_MICROMIPS,
1459     OPTION_NO_MICROMIPS,
1460     OPTION_MCU,
1461     OPTION_NO_MCU,
1462     OPTION_MIPS16E2,
1463     OPTION_NO_MIPS16E2,
1464     OPTION_CRC,
1465     OPTION_NO_CRC,
1466     OPTION_M4650,
1467     OPTION_NO_M4650,
1468     OPTION_M4010,
1469     OPTION_NO_M4010,
1470     OPTION_M4100,
1471     OPTION_NO_M4100,
1472     OPTION_M3900,
1473     OPTION_NO_M3900,
1474     OPTION_M7000_HILO_FIX,
1475     OPTION_MNO_7000_HILO_FIX,
1476     OPTION_FIX_24K,
1477     OPTION_NO_FIX_24K,
1478     OPTION_FIX_RM7000,
1479     OPTION_NO_FIX_RM7000,
1480     OPTION_FIX_LOONGSON2F_JUMP,
1481     OPTION_NO_FIX_LOONGSON2F_JUMP,
1482     OPTION_FIX_LOONGSON2F_NOP,
1483     OPTION_NO_FIX_LOONGSON2F_NOP,
1484     OPTION_FIX_VR4120,
1485     OPTION_NO_FIX_VR4120,
1486     OPTION_FIX_VR4130,
1487     OPTION_NO_FIX_VR4130,
1488     OPTION_FIX_CN63XXP1,
1489     OPTION_NO_FIX_CN63XXP1,
1490     OPTION_TRAP,
1491     OPTION_BREAK,
1492     OPTION_EB,
1493     OPTION_EL,
1494     OPTION_FP32,
1495     OPTION_GP32,
1496     OPTION_CONSTRUCT_FLOATS,
1497     OPTION_NO_CONSTRUCT_FLOATS,
1498     OPTION_FP64,
1499     OPTION_FPXX,
1500     OPTION_GP64,
1501     OPTION_RELAX_BRANCH,
1502     OPTION_NO_RELAX_BRANCH,
1503     OPTION_IGNORE_BRANCH_ISA,
1504     OPTION_NO_IGNORE_BRANCH_ISA,
1505     OPTION_INSN32,
1506     OPTION_NO_INSN32,
1507     OPTION_MSHARED,
1508     OPTION_MNO_SHARED,
1509     OPTION_MSYM32,
1510     OPTION_MNO_SYM32,
1511     OPTION_SOFT_FLOAT,
1512     OPTION_HARD_FLOAT,
1513     OPTION_SINGLE_FLOAT,
1514     OPTION_DOUBLE_FLOAT,
1515     OPTION_32,
1516     OPTION_CALL_SHARED,
1517     OPTION_CALL_NONPIC,
1518     OPTION_NON_SHARED,
1519     OPTION_XGOT,
1520     OPTION_MABI,
1521     OPTION_N32,
1522     OPTION_64,
1523     OPTION_MDEBUG,
1524     OPTION_NO_MDEBUG,
1525     OPTION_PDR,
1526     OPTION_NO_PDR,
1527     OPTION_MVXWORKS_PIC,
1528     OPTION_NAN,
1529     OPTION_ODD_SPREG,
1530     OPTION_NO_ODD_SPREG,
1531     OPTION_GINV,
1532     OPTION_NO_GINV,
1533     OPTION_LOONGSON_MMI,
1534     OPTION_NO_LOONGSON_MMI,
1535     OPTION_LOONGSON_CAM,
1536     OPTION_NO_LOONGSON_CAM,
1537     OPTION_LOONGSON_EXT,
1538     OPTION_NO_LOONGSON_EXT,
1539     OPTION_LOONGSON_EXT2,
1540     OPTION_NO_LOONGSON_EXT2,
1541     OPTION_END_OF_ENUM
1542   };
1543
1544 struct option md_longopts[] =
1545 {
1546   /* Options which specify architecture.  */
1547   {"march", required_argument, NULL, OPTION_MARCH},
1548   {"mtune", required_argument, NULL, OPTION_MTUNE},
1549   {"mips0", no_argument, NULL, OPTION_MIPS1},
1550   {"mips1", no_argument, NULL, OPTION_MIPS1},
1551   {"mips2", no_argument, NULL, OPTION_MIPS2},
1552   {"mips3", no_argument, NULL, OPTION_MIPS3},
1553   {"mips4", no_argument, NULL, OPTION_MIPS4},
1554   {"mips5", no_argument, NULL, OPTION_MIPS5},
1555   {"mips32", no_argument, NULL, OPTION_MIPS32},
1556   {"mips64", no_argument, NULL, OPTION_MIPS64},
1557   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1558   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1559   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1560   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1561   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1562   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1563   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1564   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1565
1566   /* Options which specify Application Specific Extensions (ASEs).  */
1567   {"mips16", no_argument, NULL, OPTION_MIPS16},
1568   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1569   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1570   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1571   {"mdmx", no_argument, NULL, OPTION_MDMX},
1572   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1573   {"mdsp", no_argument, NULL, OPTION_DSP},
1574   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1575   {"mmt", no_argument, NULL, OPTION_MT},
1576   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1577   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1578   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1579   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1580   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1581   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1582   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1583   {"meva", no_argument, NULL, OPTION_EVA},
1584   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1585   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1586   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1587   {"mmcu", no_argument, NULL, OPTION_MCU},
1588   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1589   {"mvirt", no_argument, NULL, OPTION_VIRT},
1590   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1591   {"mmsa", no_argument, NULL, OPTION_MSA},
1592   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1593   {"mxpa", no_argument, NULL, OPTION_XPA},
1594   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1595   {"mmips16e2", no_argument, NULL, OPTION_MIPS16E2},
1596   {"mno-mips16e2", no_argument, NULL, OPTION_NO_MIPS16E2},
1597   {"mcrc", no_argument, NULL, OPTION_CRC},
1598   {"mno-crc", no_argument, NULL, OPTION_NO_CRC},
1599   {"mginv", no_argument, NULL, OPTION_GINV},
1600   {"mno-ginv", no_argument, NULL, OPTION_NO_GINV},
1601   {"mloongson-mmi", no_argument, NULL, OPTION_LOONGSON_MMI},
1602   {"mno-loongson-mmi", no_argument, NULL, OPTION_NO_LOONGSON_MMI},
1603   {"mloongson-cam", no_argument, NULL, OPTION_LOONGSON_CAM},
1604   {"mno-loongson-cam", no_argument, NULL, OPTION_NO_LOONGSON_CAM},
1605   {"mloongson-ext", no_argument, NULL, OPTION_LOONGSON_EXT},
1606   {"mno-loongson-ext", no_argument, NULL, OPTION_NO_LOONGSON_EXT},
1607   {"mloongson-ext2", no_argument, NULL, OPTION_LOONGSON_EXT2},
1608   {"mno-loongson-ext2", no_argument, NULL, OPTION_NO_LOONGSON_EXT2},
1609
1610   /* Old-style architecture options.  Don't add more of these.  */
1611   {"m4650", no_argument, NULL, OPTION_M4650},
1612   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1613   {"m4010", no_argument, NULL, OPTION_M4010},
1614   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1615   {"m4100", no_argument, NULL, OPTION_M4100},
1616   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1617   {"m3900", no_argument, NULL, OPTION_M3900},
1618   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1619
1620   /* Options which enable bug fixes.  */
1621   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1622   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1623   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1624   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1625   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1626   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1627   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1628   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1629   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1630   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1631   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1632   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1633   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1634   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1635   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1636   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1637   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1638
1639   /* Miscellaneous options.  */
1640   {"trap", no_argument, NULL, OPTION_TRAP},
1641   {"no-break", no_argument, NULL, OPTION_TRAP},
1642   {"break", no_argument, NULL, OPTION_BREAK},
1643   {"no-trap", no_argument, NULL, OPTION_BREAK},
1644   {"EB", no_argument, NULL, OPTION_EB},
1645   {"EL", no_argument, NULL, OPTION_EL},
1646   {"mfp32", no_argument, NULL, OPTION_FP32},
1647   {"mgp32", no_argument, NULL, OPTION_GP32},
1648   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1649   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1650   {"mfp64", no_argument, NULL, OPTION_FP64},
1651   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1652   {"mgp64", no_argument, NULL, OPTION_GP64},
1653   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1654   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1655   {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1656   {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1657   {"minsn32", no_argument, NULL, OPTION_INSN32},
1658   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1659   {"mshared", no_argument, NULL, OPTION_MSHARED},
1660   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1661   {"msym32", no_argument, NULL, OPTION_MSYM32},
1662   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1663   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1664   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1665   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1666   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1667   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1668   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1669
1670   /* Strictly speaking this next option is ELF specific,
1671      but we allow it for other ports as well in order to
1672      make testing easier.  */
1673   {"32", no_argument, NULL, OPTION_32},
1674
1675   /* ELF-specific options.  */
1676   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1677   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1678   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1679   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1680   {"xgot", no_argument, NULL, OPTION_XGOT},
1681   {"mabi", required_argument, NULL, OPTION_MABI},
1682   {"n32", no_argument, NULL, OPTION_N32},
1683   {"64", no_argument, NULL, OPTION_64},
1684   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1685   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1686   {"mpdr", no_argument, NULL, OPTION_PDR},
1687   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1688   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1689   {"mnan", required_argument, NULL, OPTION_NAN},
1690
1691   {NULL, no_argument, NULL, 0}
1692 };
1693 size_t md_longopts_size = sizeof (md_longopts);
1694 \f
1695 /* Information about either an Application Specific Extension or an
1696    optional architecture feature that, for simplicity, we treat in the
1697    same way as an ASE.  */
1698 struct mips_ase
1699 {
1700   /* The name of the ASE, used in both the command-line and .set options.  */
1701   const char *name;
1702
1703   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1704      and 64-bit architectures, the flags here refer to the subset that
1705      is available on both.  */
1706   unsigned int flags;
1707
1708   /* The ASE_* flag used for instructions that are available on 64-bit
1709      architectures but that are not included in FLAGS.  */
1710   unsigned int flags64;
1711
1712   /* The command-line options that turn the ASE on and off.  */
1713   int option_on;
1714   int option_off;
1715
1716   /* The minimum required architecture revisions for MIPS32, MIPS64,
1717      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1718   int mips32_rev;
1719   int mips64_rev;
1720   int micromips32_rev;
1721   int micromips64_rev;
1722
1723   /* The architecture where the ASE was removed or -1 if the extension has not
1724      been removed.  */
1725   int rem_rev;
1726 };
1727
1728 /* A table of all supported ASEs.  */
1729 static const struct mips_ase mips_ases[] = {
1730   { "dsp", ASE_DSP, ASE_DSP64,
1731     OPTION_DSP, OPTION_NO_DSP,
1732     2, 2, 2, 2,
1733     -1 },
1734
1735   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1736     OPTION_DSPR2, OPTION_NO_DSPR2,
1737     2, 2, 2, 2,
1738     -1 },
1739
1740   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1741     OPTION_DSPR3, OPTION_NO_DSPR3,
1742     6, 6, -1, -1,
1743     -1 },
1744
1745   { "eva", ASE_EVA, 0,
1746     OPTION_EVA, OPTION_NO_EVA,
1747      2,  2,  2,  2,
1748     -1 },
1749
1750   { "mcu", ASE_MCU, 0,
1751     OPTION_MCU, OPTION_NO_MCU,
1752      2,  2,  2,  2,
1753     -1 },
1754
1755   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1756   { "mdmx", ASE_MDMX, 0,
1757     OPTION_MDMX, OPTION_NO_MDMX,
1758     -1, 1, -1, -1,
1759      6 },
1760
1761   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1762   { "mips3d", ASE_MIPS3D, 0,
1763     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1764     2, 1, -1, -1,
1765     6 },
1766
1767   { "mt", ASE_MT, 0,
1768     OPTION_MT, OPTION_NO_MT,
1769      2,  2, -1, -1,
1770     -1 },
1771
1772   { "smartmips", ASE_SMARTMIPS, 0,
1773     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1774     1, -1, -1, -1,
1775     6 },
1776
1777   { "virt", ASE_VIRT, ASE_VIRT64,
1778     OPTION_VIRT, OPTION_NO_VIRT,
1779      2,  2,  2,  2,
1780     -1 },
1781
1782   { "msa", ASE_MSA, ASE_MSA64,
1783     OPTION_MSA, OPTION_NO_MSA,
1784      2,  2,  2,  2,
1785     -1 },
1786
1787   { "xpa", ASE_XPA, 0,
1788     OPTION_XPA, OPTION_NO_XPA,
1789     2, 2, 2, 2,
1790     -1 },
1791
1792   { "mips16e2", ASE_MIPS16E2, 0,
1793     OPTION_MIPS16E2, OPTION_NO_MIPS16E2,
1794     2,  2, -1, -1,
1795     6 },
1796
1797   { "crc", ASE_CRC, ASE_CRC64,
1798     OPTION_CRC, OPTION_NO_CRC,
1799     6,  6, -1, -1,
1800     -1 },
1801
1802   { "ginv", ASE_GINV, 0,
1803     OPTION_GINV, OPTION_NO_GINV,
1804     6,  6, 6, 6,
1805     -1 },
1806
1807   { "loongson-mmi", ASE_LOONGSON_MMI, 0,
1808     OPTION_LOONGSON_MMI, OPTION_NO_LOONGSON_MMI,
1809     0, 0, -1, -1,
1810     -1 },
1811
1812   { "loongson-cam", ASE_LOONGSON_CAM, 0,
1813     OPTION_LOONGSON_CAM, OPTION_NO_LOONGSON_CAM,
1814     0, 0, -1, -1,
1815     -1 },
1816
1817   { "loongson-ext", ASE_LOONGSON_EXT, 0,
1818     OPTION_LOONGSON_EXT, OPTION_NO_LOONGSON_EXT,
1819     0, 0, -1, -1,
1820     -1 },
1821
1822   { "loongson-ext2", ASE_LOONGSON_EXT | ASE_LOONGSON_EXT2, 0,
1823     OPTION_LOONGSON_EXT2, OPTION_NO_LOONGSON_EXT2,
1824     0, 0, -1, -1,
1825     -1 },
1826 };
1827
1828 /* The set of ASEs that require -mfp64.  */
1829 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1830
1831 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1832 static const unsigned int mips_ase_groups[] = {
1833   ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 
1834   ASE_LOONGSON_EXT | ASE_LOONGSON_EXT2 
1835 };
1836 \f
1837 /* Pseudo-op table.
1838
1839    The following pseudo-ops from the Kane and Heinrich MIPS book
1840    should be defined here, but are currently unsupported: .alias,
1841    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1842
1843    The following pseudo-ops from the Kane and Heinrich MIPS book are
1844    specific to the type of debugging information being generated, and
1845    should be defined by the object format: .aent, .begin, .bend,
1846    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1847    .vreg.
1848
1849    The following pseudo-ops from the Kane and Heinrich MIPS book are
1850    not MIPS CPU specific, but are also not specific to the object file
1851    format.  This file is probably the best place to define them, but
1852    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1853
1854 static const pseudo_typeS mips_pseudo_table[] =
1855 {
1856   /* MIPS specific pseudo-ops.  */
1857   {"option", s_option, 0},
1858   {"set", s_mipsset, 0},
1859   {"rdata", s_change_sec, 'r'},
1860   {"sdata", s_change_sec, 's'},
1861   {"livereg", s_ignore, 0},
1862   {"abicalls", s_abicalls, 0},
1863   {"cpload", s_cpload, 0},
1864   {"cpsetup", s_cpsetup, 0},
1865   {"cplocal", s_cplocal, 0},
1866   {"cprestore", s_cprestore, 0},
1867   {"cpreturn", s_cpreturn, 0},
1868   {"dtprelword", s_dtprelword, 0},
1869   {"dtpreldword", s_dtpreldword, 0},
1870   {"tprelword", s_tprelword, 0},
1871   {"tpreldword", s_tpreldword, 0},
1872   {"gpvalue", s_gpvalue, 0},
1873   {"gpword", s_gpword, 0},
1874   {"gpdword", s_gpdword, 0},
1875   {"ehword", s_ehword, 0},
1876   {"cpadd", s_cpadd, 0},
1877   {"insn", s_insn, 0},
1878   {"nan", s_nan, 0},
1879   {"module", s_module, 0},
1880
1881   /* Relatively generic pseudo-ops that happen to be used on MIPS
1882      chips.  */
1883   {"asciiz", stringer, 8 + 1},
1884   {"bss", s_change_sec, 'b'},
1885   {"err", s_err, 0},
1886   {"half", s_cons, 1},
1887   {"dword", s_cons, 3},
1888   {"weakext", s_mips_weakext, 0},
1889   {"origin", s_org, 0},
1890   {"repeat", s_rept, 0},
1891
1892   /* For MIPS this is non-standard, but we define it for consistency.  */
1893   {"sbss", s_change_sec, 'B'},
1894
1895   /* These pseudo-ops are defined in read.c, but must be overridden
1896      here for one reason or another.  */
1897   {"align", s_align, 0},
1898   {"byte", s_cons, 0},
1899   {"data", s_change_sec, 'd'},
1900   {"double", s_float_cons, 'd'},
1901   {"float", s_float_cons, 'f'},
1902   {"globl", s_mips_globl, 0},
1903   {"global", s_mips_globl, 0},
1904   {"hword", s_cons, 1},
1905   {"int", s_cons, 2},
1906   {"long", s_cons, 2},
1907   {"octa", s_cons, 4},
1908   {"quad", s_cons, 3},
1909   {"section", s_change_section, 0},
1910   {"short", s_cons, 1},
1911   {"single", s_float_cons, 'f'},
1912   {"stabd", s_mips_stab, 'd'},
1913   {"stabn", s_mips_stab, 'n'},
1914   {"stabs", s_mips_stab, 's'},
1915   {"text", s_change_sec, 't'},
1916   {"word", s_cons, 2},
1917
1918   { "extern", ecoff_directive_extern, 0},
1919
1920   { NULL, NULL, 0 },
1921 };
1922
1923 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1924 {
1925   /* These pseudo-ops should be defined by the object file format.
1926      However, a.out doesn't support them, so we have versions here.  */
1927   {"aent", s_mips_ent, 1},
1928   {"bgnb", s_ignore, 0},
1929   {"end", s_mips_end, 0},
1930   {"endb", s_ignore, 0},
1931   {"ent", s_mips_ent, 0},
1932   {"file", s_mips_file, 0},
1933   {"fmask", s_mips_mask, 'F'},
1934   {"frame", s_mips_frame, 0},
1935   {"loc", s_mips_loc, 0},
1936   {"mask", s_mips_mask, 'R'},
1937   {"verstamp", s_ignore, 0},
1938   { NULL, NULL, 0 },
1939 };
1940
1941 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1942    purpose of the `.dc.a' internal pseudo-op.  */
1943
1944 int
1945 mips_address_bytes (void)
1946 {
1947   file_mips_check_options ();
1948   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1949 }
1950
1951 extern void pop_insert (const pseudo_typeS *);
1952
1953 void
1954 mips_pop_insert (void)
1955 {
1956   pop_insert (mips_pseudo_table);
1957   if (! ECOFF_DEBUGGING)
1958     pop_insert (mips_nonecoff_pseudo_table);
1959 }
1960 \f
1961 /* Symbols labelling the current insn.  */
1962
1963 struct insn_label_list
1964 {
1965   struct insn_label_list *next;
1966   symbolS *label;
1967 };
1968
1969 static struct insn_label_list *free_insn_labels;
1970 #define label_list tc_segment_info_data.labels
1971
1972 static void mips_clear_insn_labels (void);
1973 static void mips_mark_labels (void);
1974 static void mips_compressed_mark_labels (void);
1975
1976 static inline void
1977 mips_clear_insn_labels (void)
1978 {
1979   struct insn_label_list **pl;
1980   segment_info_type *si;
1981
1982   if (now_seg)
1983     {
1984       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1985         ;
1986
1987       si = seg_info (now_seg);
1988       *pl = si->label_list;
1989       si->label_list = NULL;
1990     }
1991 }
1992
1993 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1994
1995 static inline void
1996 mips_mark_labels (void)
1997 {
1998   if (HAVE_CODE_COMPRESSION)
1999     mips_compressed_mark_labels ();
2000 }
2001 \f
2002 static char *expr_end;
2003
2004 /* An expression in a macro instruction.  This is set by mips_ip and
2005    mips16_ip and when populated is always an O_constant.  */
2006
2007 static expressionS imm_expr;
2008
2009 /* The relocatable field in an instruction and the relocs associated
2010    with it.  These variables are used for instructions like LUI and
2011    JAL as well as true offsets.  They are also used for address
2012    operands in macros.  */
2013
2014 static expressionS offset_expr;
2015 static bfd_reloc_code_real_type offset_reloc[3]
2016   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2017
2018 /* This is set to the resulting size of the instruction to be produced
2019    by mips16_ip if an explicit extension is used or by mips_ip if an
2020    explicit size is supplied.  */
2021
2022 static unsigned int forced_insn_length;
2023
2024 /* True if we are assembling an instruction.  All dot symbols defined during
2025    this time should be treated as code labels.  */
2026
2027 static bfd_boolean mips_assembling_insn;
2028
2029 /* The pdr segment for per procedure frame/regmask info.  Not used for
2030    ECOFF debugging.  */
2031
2032 static segT pdr_seg;
2033
2034 /* The default target format to use.  */
2035
2036 #if defined (TE_FreeBSD)
2037 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
2038 #elif defined (TE_TMIPS)
2039 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
2040 #else
2041 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
2042 #endif
2043
2044 const char *
2045 mips_target_format (void)
2046 {
2047   switch (OUTPUT_FLAVOR)
2048     {
2049     case bfd_target_elf_flavour:
2050 #ifdef TE_VXWORKS
2051       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
2052         return (target_big_endian
2053                 ? "elf32-bigmips-vxworks"
2054                 : "elf32-littlemips-vxworks");
2055 #endif
2056       return (target_big_endian
2057               ? (HAVE_64BIT_OBJECTS
2058                  ? ELF_TARGET ("elf64-", "big")
2059                  : (HAVE_NEWABI
2060                     ? ELF_TARGET ("elf32-n", "big")
2061                     : ELF_TARGET ("elf32-", "big")))
2062               : (HAVE_64BIT_OBJECTS
2063                  ? ELF_TARGET ("elf64-", "little")
2064                  : (HAVE_NEWABI
2065                     ? ELF_TARGET ("elf32-n", "little")
2066                     : ELF_TARGET ("elf32-", "little"))));
2067     default:
2068       abort ();
2069       return NULL;
2070     }
2071 }
2072
2073 /* Return the ISA revision that is currently in use, or 0 if we are
2074    generating code for MIPS V or below.  */
2075
2076 static int
2077 mips_isa_rev (void)
2078 {
2079   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2080     return 2;
2081
2082   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2083     return 3;
2084
2085   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2086     return 5;
2087
2088   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2089     return 6;
2090
2091   /* microMIPS implies revision 2 or above.  */
2092   if (mips_opts.micromips)
2093     return 2;
2094
2095   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2096     return 1;
2097
2098   return 0;
2099 }
2100
2101 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2102
2103 static unsigned int
2104 mips_ase_mask (unsigned int flags)
2105 {
2106   unsigned int i;
2107
2108   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2109     if (flags & mips_ase_groups[i])
2110       flags |= mips_ase_groups[i];
2111   return flags;
2112 }
2113
2114 /* Check whether the current ISA supports ASE.  Issue a warning if
2115    appropriate.  */
2116
2117 static void
2118 mips_check_isa_supports_ase (const struct mips_ase *ase)
2119 {
2120   const char *base;
2121   int min_rev, size;
2122   static unsigned int warned_isa;
2123   static unsigned int warned_fp32;
2124
2125   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2126     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2127   else
2128     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2129   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2130       && (warned_isa & ase->flags) != ase->flags)
2131     {
2132       warned_isa |= ase->flags;
2133       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2134       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2135       if (min_rev < 0)
2136         as_warn (_("the %d-bit %s architecture does not support the"
2137                    " `%s' extension"), size, base, ase->name);
2138       else
2139         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2140                  ase->name, base, size, min_rev);
2141     }
2142   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2143            && (warned_isa & ase->flags) != ase->flags)
2144     {
2145       warned_isa |= ase->flags;
2146       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2147       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2148       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2149                ase->name, base, size, ase->rem_rev);
2150     }
2151
2152   if ((ase->flags & FP64_ASES)
2153       && mips_opts.fp != 64
2154       && (warned_fp32 & ase->flags) != ase->flags)
2155     {
2156       warned_fp32 |= ase->flags;
2157       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2158     }
2159 }
2160
2161 /* Check all enabled ASEs to see whether they are supported by the
2162    chosen architecture.  */
2163
2164 static void
2165 mips_check_isa_supports_ases (void)
2166 {
2167   unsigned int i, mask;
2168
2169   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2170     {
2171       mask = mips_ase_mask (mips_ases[i].flags);
2172       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2173         mips_check_isa_supports_ase (&mips_ases[i]);
2174     }
2175 }
2176
2177 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2178    that were affected.  */
2179
2180 static unsigned int
2181 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2182               bfd_boolean enabled_p)
2183 {
2184   unsigned int mask;
2185
2186   mask = mips_ase_mask (ase->flags);
2187   opts->ase &= ~mask;
2188
2189   /* Clear combination ASE flags, which need to be recalculated based on
2190      updated regular ASE settings.  */
2191   opts->ase &= ~(ASE_MIPS16E2_MT | ASE_XPA_VIRT);
2192
2193   if (enabled_p)
2194     opts->ase |= ase->flags;
2195
2196   /* The Virtualization ASE has eXtended Physical Addressing (XPA)
2197      instructions which are only valid when both ASEs are enabled.
2198      This sets the ASE_XPA_VIRT flag when both ASEs are present.  */
2199   if ((opts->ase & (ASE_XPA | ASE_VIRT)) == (ASE_XPA | ASE_VIRT))
2200     {
2201       opts->ase |= ASE_XPA_VIRT;
2202       mask |= ASE_XPA_VIRT;
2203     }
2204   if ((opts->ase & (ASE_MIPS16E2 | ASE_MT)) == (ASE_MIPS16E2 | ASE_MT))
2205     {
2206       opts->ase |= ASE_MIPS16E2_MT;
2207       mask |= ASE_MIPS16E2_MT;
2208     }
2209
2210   return mask;
2211 }
2212
2213 /* Return the ASE called NAME, or null if none.  */
2214
2215 static const struct mips_ase *
2216 mips_lookup_ase (const char *name)
2217 {
2218   unsigned int i;
2219
2220   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2221     if (strcmp (name, mips_ases[i].name) == 0)
2222       return &mips_ases[i];
2223   return NULL;
2224 }
2225
2226 /* Return the length of a microMIPS instruction in bytes.  If bits of
2227    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2228    otherwise it is a 32-bit instruction.  */
2229
2230 static inline unsigned int
2231 micromips_insn_length (const struct mips_opcode *mo)
2232 {
2233   return mips_opcode_32bit_p (mo) ? 4 : 2;
2234 }
2235
2236 /* Return the length of MIPS16 instruction OPCODE.  */
2237
2238 static inline unsigned int
2239 mips16_opcode_length (unsigned long opcode)
2240 {
2241   return (opcode >> 16) == 0 ? 2 : 4;
2242 }
2243
2244 /* Return the length of instruction INSN.  */
2245
2246 static inline unsigned int
2247 insn_length (const struct mips_cl_insn *insn)
2248 {
2249   if (mips_opts.micromips)
2250     return micromips_insn_length (insn->insn_mo);
2251   else if (mips_opts.mips16)
2252     return mips16_opcode_length (insn->insn_opcode);
2253   else
2254     return 4;
2255 }
2256
2257 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2258
2259 static void
2260 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2261 {
2262   size_t i;
2263
2264   insn->insn_mo = mo;
2265   insn->insn_opcode = mo->match;
2266   insn->frag = NULL;
2267   insn->where = 0;
2268   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2269     insn->fixp[i] = NULL;
2270   insn->fixed_p = (mips_opts.noreorder > 0);
2271   insn->noreorder_p = (mips_opts.noreorder > 0);
2272   insn->mips16_absolute_jump_p = 0;
2273   insn->complete_p = 0;
2274   insn->cleared_p = 0;
2275 }
2276
2277 /* Get a list of all the operands in INSN.  */
2278
2279 static const struct mips_operand_array *
2280 insn_operands (const struct mips_cl_insn *insn)
2281 {
2282   if (insn->insn_mo >= &mips_opcodes[0]
2283       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2284     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2285
2286   if (insn->insn_mo >= &mips16_opcodes[0]
2287       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2288     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2289
2290   if (insn->insn_mo >= &micromips_opcodes[0]
2291       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2292     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2293
2294   abort ();
2295 }
2296
2297 /* Get a description of operand OPNO of INSN.  */
2298
2299 static const struct mips_operand *
2300 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2301 {
2302   const struct mips_operand_array *operands;
2303
2304   operands = insn_operands (insn);
2305   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2306     abort ();
2307   return operands->operand[opno];
2308 }
2309
2310 /* Install UVAL as the value of OPERAND in INSN.  */
2311
2312 static inline void
2313 insn_insert_operand (struct mips_cl_insn *insn,
2314                      const struct mips_operand *operand, unsigned int uval)
2315 {
2316   if (mips_opts.mips16
2317       && operand->type == OP_INT && operand->lsb == 0
2318       && mips_opcode_32bit_p (insn->insn_mo))
2319     insn->insn_opcode |= mips16_immed_extend (uval, operand->size);
2320   else
2321     insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2322 }
2323
2324 /* Extract the value of OPERAND from INSN.  */
2325
2326 static inline unsigned
2327 insn_extract_operand (const struct mips_cl_insn *insn,
2328                       const struct mips_operand *operand)
2329 {
2330   return mips_extract_operand (operand, insn->insn_opcode);
2331 }
2332
2333 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2334
2335 static void
2336 mips_record_compressed_mode (void)
2337 {
2338   segment_info_type *si;
2339
2340   si = seg_info (now_seg);
2341   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2342     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2343   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2344     si->tc_segment_info_data.micromips = mips_opts.micromips;
2345 }
2346
2347 /* Read a standard MIPS instruction from BUF.  */
2348
2349 static unsigned long
2350 read_insn (char *buf)
2351 {
2352   if (target_big_endian)
2353     return bfd_getb32 ((bfd_byte *) buf);
2354   else
2355     return bfd_getl32 ((bfd_byte *) buf);
2356 }
2357
2358 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2359    the next byte.  */
2360
2361 static char *
2362 write_insn (char *buf, unsigned int insn)
2363 {
2364   md_number_to_chars (buf, insn, 4);
2365   return buf + 4;
2366 }
2367
2368 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2369    has length LENGTH.  */
2370
2371 static unsigned long
2372 read_compressed_insn (char *buf, unsigned int length)
2373 {
2374   unsigned long insn;
2375   unsigned int i;
2376
2377   insn = 0;
2378   for (i = 0; i < length; i += 2)
2379     {
2380       insn <<= 16;
2381       if (target_big_endian)
2382         insn |= bfd_getb16 ((char *) buf);
2383       else
2384         insn |= bfd_getl16 ((char *) buf);
2385       buf += 2;
2386     }
2387   return insn;
2388 }
2389
2390 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2391    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2392
2393 static char *
2394 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2395 {
2396   unsigned int i;
2397
2398   for (i = 0; i < length; i += 2)
2399     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2400   return buf + length;
2401 }
2402
2403 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2404
2405 static void
2406 install_insn (const struct mips_cl_insn *insn)
2407 {
2408   char *f = insn->frag->fr_literal + insn->where;
2409   if (HAVE_CODE_COMPRESSION)
2410     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2411   else
2412     write_insn (f, insn->insn_opcode);
2413   mips_record_compressed_mode ();
2414 }
2415
2416 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2417    and install the opcode in the new location.  */
2418
2419 static void
2420 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2421 {
2422   size_t i;
2423
2424   insn->frag = frag;
2425   insn->where = where;
2426   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2427     if (insn->fixp[i] != NULL)
2428       {
2429         insn->fixp[i]->fx_frag = frag;
2430         insn->fixp[i]->fx_where = where;
2431       }
2432   install_insn (insn);
2433 }
2434
2435 /* Add INSN to the end of the output.  */
2436
2437 static void
2438 add_fixed_insn (struct mips_cl_insn *insn)
2439 {
2440   char *f = frag_more (insn_length (insn));
2441   move_insn (insn, frag_now, f - frag_now->fr_literal);
2442 }
2443
2444 /* Start a variant frag and move INSN to the start of the variant part,
2445    marking it as fixed.  The other arguments are as for frag_var.  */
2446
2447 static void
2448 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2449                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2450 {
2451   frag_grow (max_chars);
2452   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2453   insn->fixed_p = 1;
2454   frag_var (rs_machine_dependent, max_chars, var,
2455             subtype, symbol, offset, NULL);
2456 }
2457
2458 /* Insert N copies of INSN into the history buffer, starting at
2459    position FIRST.  Neither FIRST nor N need to be clipped.  */
2460
2461 static void
2462 insert_into_history (unsigned int first, unsigned int n,
2463                      const struct mips_cl_insn *insn)
2464 {
2465   if (mips_relax.sequence != 2)
2466     {
2467       unsigned int i;
2468
2469       for (i = ARRAY_SIZE (history); i-- > first;)
2470         if (i >= first + n)
2471           history[i] = history[i - n];
2472         else
2473           history[i] = *insn;
2474     }
2475 }
2476
2477 /* Clear the error in insn_error.  */
2478
2479 static void
2480 clear_insn_error (void)
2481 {
2482   memset (&insn_error, 0, sizeof (insn_error));
2483 }
2484
2485 /* Possibly record error message MSG for the current instruction.
2486    If the error is about a particular argument, ARGNUM is the 1-based
2487    number of that argument, otherwise it is 0.  FORMAT is the format
2488    of MSG.  Return true if MSG was used, false if the current message
2489    was kept.  */
2490
2491 static bfd_boolean
2492 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2493                        const char *msg)
2494 {
2495   if (argnum == 0)
2496     {
2497       /* Give priority to errors against specific arguments, and to
2498          the first whole-instruction message.  */
2499       if (insn_error.msg)
2500         return FALSE;
2501     }
2502   else
2503     {
2504       /* Keep insn_error if it is against a later argument.  */
2505       if (argnum < insn_error.min_argnum)
2506         return FALSE;
2507
2508       /* If both errors are against the same argument but are different,
2509          give up on reporting a specific error for this argument.
2510          See the comment about mips_insn_error for details.  */
2511       if (argnum == insn_error.min_argnum
2512           && insn_error.msg
2513           && strcmp (insn_error.msg, msg) != 0)
2514         {
2515           insn_error.msg = 0;
2516           insn_error.min_argnum += 1;
2517           return FALSE;
2518         }
2519     }
2520   insn_error.min_argnum = argnum;
2521   insn_error.format = format;
2522   insn_error.msg = msg;
2523   return TRUE;
2524 }
2525
2526 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2527    as for set_insn_error_format.  */
2528
2529 static void
2530 set_insn_error (int argnum, const char *msg)
2531 {
2532   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2533 }
2534
2535 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2536    as for set_insn_error_format.  */
2537
2538 static void
2539 set_insn_error_i (int argnum, const char *msg, int i)
2540 {
2541   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2542     insn_error.u.i = i;
2543 }
2544
2545 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2546    are as for set_insn_error_format.  */
2547
2548 static void
2549 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2550 {
2551   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2552     {
2553       insn_error.u.ss[0] = s1;
2554       insn_error.u.ss[1] = s2;
2555     }
2556 }
2557
2558 /* Report the error in insn_error, which is against assembly code STR.  */
2559
2560 static void
2561 report_insn_error (const char *str)
2562 {
2563   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2564
2565   switch (insn_error.format)
2566     {
2567     case ERR_FMT_PLAIN:
2568       as_bad (msg, str);
2569       break;
2570
2571     case ERR_FMT_I:
2572       as_bad (msg, insn_error.u.i, str);
2573       break;
2574
2575     case ERR_FMT_SS:
2576       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2577       break;
2578     }
2579
2580   free ((char *) msg);
2581 }
2582
2583 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2584    the idea is to make it obvious at a glance that each errata is
2585    included.  */
2586
2587 static void
2588 init_vr4120_conflicts (void)
2589 {
2590 #define CONFLICT(FIRST, SECOND) \
2591     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2592
2593   /* Errata 21 - [D]DIV[U] after [D]MACC */
2594   CONFLICT (MACC, DIV);
2595   CONFLICT (DMACC, DIV);
2596
2597   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2598   CONFLICT (DMULT, DMULT);
2599   CONFLICT (DMULT, DMACC);
2600   CONFLICT (DMACC, DMULT);
2601   CONFLICT (DMACC, DMACC);
2602
2603   /* Errata 24 - MT{LO,HI} after [D]MACC */
2604   CONFLICT (MACC, MTHILO);
2605   CONFLICT (DMACC, MTHILO);
2606
2607   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2608      instruction is executed immediately after a MACC or DMACC
2609      instruction, the result of [either instruction] is incorrect."  */
2610   CONFLICT (MACC, MULT);
2611   CONFLICT (MACC, DMULT);
2612   CONFLICT (DMACC, MULT);
2613   CONFLICT (DMACC, DMULT);
2614
2615   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2616      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2617      DDIV or DDIVU instruction, the result of the MACC or
2618      DMACC instruction is incorrect.".  */
2619   CONFLICT (DMULT, MACC);
2620   CONFLICT (DMULT, DMACC);
2621   CONFLICT (DIV, MACC);
2622   CONFLICT (DIV, DMACC);
2623
2624 #undef CONFLICT
2625 }
2626
2627 struct regname {
2628   const char *name;
2629   unsigned int num;
2630 };
2631
2632 #define RNUM_MASK       0x00000ff
2633 #define RTYPE_MASK      0x0ffff00
2634 #define RTYPE_NUM       0x0000100
2635 #define RTYPE_FPU       0x0000200
2636 #define RTYPE_FCC       0x0000400
2637 #define RTYPE_VEC       0x0000800
2638 #define RTYPE_GP        0x0001000
2639 #define RTYPE_CP0       0x0002000
2640 #define RTYPE_PC        0x0004000
2641 #define RTYPE_ACC       0x0008000
2642 #define RTYPE_CCC       0x0010000
2643 #define RTYPE_VI        0x0020000
2644 #define RTYPE_VF        0x0040000
2645 #define RTYPE_R5900_I   0x0080000
2646 #define RTYPE_R5900_Q   0x0100000
2647 #define RTYPE_R5900_R   0x0200000
2648 #define RTYPE_R5900_ACC 0x0400000
2649 #define RTYPE_MSA       0x0800000
2650 #define RWARN           0x8000000
2651
2652 #define GENERIC_REGISTER_NUMBERS \
2653     {"$0",      RTYPE_NUM | 0},  \
2654     {"$1",      RTYPE_NUM | 1},  \
2655     {"$2",      RTYPE_NUM | 2},  \
2656     {"$3",      RTYPE_NUM | 3},  \
2657     {"$4",      RTYPE_NUM | 4},  \
2658     {"$5",      RTYPE_NUM | 5},  \
2659     {"$6",      RTYPE_NUM | 6},  \
2660     {"$7",      RTYPE_NUM | 7},  \
2661     {"$8",      RTYPE_NUM | 8},  \
2662     {"$9",      RTYPE_NUM | 9},  \
2663     {"$10",     RTYPE_NUM | 10}, \
2664     {"$11",     RTYPE_NUM | 11}, \
2665     {"$12",     RTYPE_NUM | 12}, \
2666     {"$13",     RTYPE_NUM | 13}, \
2667     {"$14",     RTYPE_NUM | 14}, \
2668     {"$15",     RTYPE_NUM | 15}, \
2669     {"$16",     RTYPE_NUM | 16}, \
2670     {"$17",     RTYPE_NUM | 17}, \
2671     {"$18",     RTYPE_NUM | 18}, \
2672     {"$19",     RTYPE_NUM | 19}, \
2673     {"$20",     RTYPE_NUM | 20}, \
2674     {"$21",     RTYPE_NUM | 21}, \
2675     {"$22",     RTYPE_NUM | 22}, \
2676     {"$23",     RTYPE_NUM | 23}, \
2677     {"$24",     RTYPE_NUM | 24}, \
2678     {"$25",     RTYPE_NUM | 25}, \
2679     {"$26",     RTYPE_NUM | 26}, \
2680     {"$27",     RTYPE_NUM | 27}, \
2681     {"$28",     RTYPE_NUM | 28}, \
2682     {"$29",     RTYPE_NUM | 29}, \
2683     {"$30",     RTYPE_NUM | 30}, \
2684     {"$31",     RTYPE_NUM | 31}
2685
2686 #define FPU_REGISTER_NAMES       \
2687     {"$f0",     RTYPE_FPU | 0},  \
2688     {"$f1",     RTYPE_FPU | 1},  \
2689     {"$f2",     RTYPE_FPU | 2},  \
2690     {"$f3",     RTYPE_FPU | 3},  \
2691     {"$f4",     RTYPE_FPU | 4},  \
2692     {"$f5",     RTYPE_FPU | 5},  \
2693     {"$f6",     RTYPE_FPU | 6},  \
2694     {"$f7",     RTYPE_FPU | 7},  \
2695     {"$f8",     RTYPE_FPU | 8},  \
2696     {"$f9",     RTYPE_FPU | 9},  \
2697     {"$f10",    RTYPE_FPU | 10}, \
2698     {"$f11",    RTYPE_FPU | 11}, \
2699     {"$f12",    RTYPE_FPU | 12}, \
2700     {"$f13",    RTYPE_FPU | 13}, \
2701     {"$f14",    RTYPE_FPU | 14}, \
2702     {"$f15",    RTYPE_FPU | 15}, \
2703     {"$f16",    RTYPE_FPU | 16}, \
2704     {"$f17",    RTYPE_FPU | 17}, \
2705     {"$f18",    RTYPE_FPU | 18}, \
2706     {"$f19",    RTYPE_FPU | 19}, \
2707     {"$f20",    RTYPE_FPU | 20}, \
2708     {"$f21",    RTYPE_FPU | 21}, \
2709     {"$f22",    RTYPE_FPU | 22}, \
2710     {"$f23",    RTYPE_FPU | 23}, \
2711     {"$f24",    RTYPE_FPU | 24}, \
2712     {"$f25",    RTYPE_FPU | 25}, \
2713     {"$f26",    RTYPE_FPU | 26}, \
2714     {"$f27",    RTYPE_FPU | 27}, \
2715     {"$f28",    RTYPE_FPU | 28}, \
2716     {"$f29",    RTYPE_FPU | 29}, \
2717     {"$f30",    RTYPE_FPU | 30}, \
2718     {"$f31",    RTYPE_FPU | 31}
2719
2720 #define FPU_CONDITION_CODE_NAMES \
2721     {"$fcc0",   RTYPE_FCC | 0},  \
2722     {"$fcc1",   RTYPE_FCC | 1},  \
2723     {"$fcc2",   RTYPE_FCC | 2},  \
2724     {"$fcc3",   RTYPE_FCC | 3},  \
2725     {"$fcc4",   RTYPE_FCC | 4},  \
2726     {"$fcc5",   RTYPE_FCC | 5},  \
2727     {"$fcc6",   RTYPE_FCC | 6},  \
2728     {"$fcc7",   RTYPE_FCC | 7}
2729
2730 #define COPROC_CONDITION_CODE_NAMES         \
2731     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2732     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2733     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2734     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2735     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2736     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2737     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2738     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2739
2740 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2741     {"$a4",     RTYPE_GP | 8},  \
2742     {"$a5",     RTYPE_GP | 9},  \
2743     {"$a6",     RTYPE_GP | 10}, \
2744     {"$a7",     RTYPE_GP | 11}, \
2745     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2746     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2747     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2748     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2749     {"$t0",     RTYPE_GP | 12}, \
2750     {"$t1",     RTYPE_GP | 13}, \
2751     {"$t2",     RTYPE_GP | 14}, \
2752     {"$t3",     RTYPE_GP | 15}
2753
2754 #define O32_SYMBOLIC_REGISTER_NAMES \
2755     {"$t0",     RTYPE_GP | 8},  \
2756     {"$t1",     RTYPE_GP | 9},  \
2757     {"$t2",     RTYPE_GP | 10}, \
2758     {"$t3",     RTYPE_GP | 11}, \
2759     {"$t4",     RTYPE_GP | 12}, \
2760     {"$t5",     RTYPE_GP | 13}, \
2761     {"$t6",     RTYPE_GP | 14}, \
2762     {"$t7",     RTYPE_GP | 15}, \
2763     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2764     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2765     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2766     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2767
2768 /* Remaining symbolic register names */
2769 #define SYMBOLIC_REGISTER_NAMES \
2770     {"$zero",   RTYPE_GP | 0},  \
2771     {"$at",     RTYPE_GP | 1},  \
2772     {"$AT",     RTYPE_GP | 1},  \
2773     {"$v0",     RTYPE_GP | 2},  \
2774     {"$v1",     RTYPE_GP | 3},  \
2775     {"$a0",     RTYPE_GP | 4},  \
2776     {"$a1",     RTYPE_GP | 5},  \
2777     {"$a2",     RTYPE_GP | 6},  \
2778     {"$a3",     RTYPE_GP | 7},  \
2779     {"$s0",     RTYPE_GP | 16}, \
2780     {"$s1",     RTYPE_GP | 17}, \
2781     {"$s2",     RTYPE_GP | 18}, \
2782     {"$s3",     RTYPE_GP | 19}, \
2783     {"$s4",     RTYPE_GP | 20}, \
2784     {"$s5",     RTYPE_GP | 21}, \
2785     {"$s6",     RTYPE_GP | 22}, \
2786     {"$s7",     RTYPE_GP | 23}, \
2787     {"$t8",     RTYPE_GP | 24}, \
2788     {"$t9",     RTYPE_GP | 25}, \
2789     {"$k0",     RTYPE_GP | 26}, \
2790     {"$kt0",    RTYPE_GP | 26}, \
2791     {"$k1",     RTYPE_GP | 27}, \
2792     {"$kt1",    RTYPE_GP | 27}, \
2793     {"$gp",     RTYPE_GP | 28}, \
2794     {"$sp",     RTYPE_GP | 29}, \
2795     {"$s8",     RTYPE_GP | 30}, \
2796     {"$fp",     RTYPE_GP | 30}, \
2797     {"$ra",     RTYPE_GP | 31}
2798
2799 #define MIPS16_SPECIAL_REGISTER_NAMES \
2800     {"$pc",     RTYPE_PC | 0}
2801
2802 #define MDMX_VECTOR_REGISTER_NAMES \
2803     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2804     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2805     {"$v2",     RTYPE_VEC | 2},  \
2806     {"$v3",     RTYPE_VEC | 3},  \
2807     {"$v4",     RTYPE_VEC | 4},  \
2808     {"$v5",     RTYPE_VEC | 5},  \
2809     {"$v6",     RTYPE_VEC | 6},  \
2810     {"$v7",     RTYPE_VEC | 7},  \
2811     {"$v8",     RTYPE_VEC | 8},  \
2812     {"$v9",     RTYPE_VEC | 9},  \
2813     {"$v10",    RTYPE_VEC | 10}, \
2814     {"$v11",    RTYPE_VEC | 11}, \
2815     {"$v12",    RTYPE_VEC | 12}, \
2816     {"$v13",    RTYPE_VEC | 13}, \
2817     {"$v14",    RTYPE_VEC | 14}, \
2818     {"$v15",    RTYPE_VEC | 15}, \
2819     {"$v16",    RTYPE_VEC | 16}, \
2820     {"$v17",    RTYPE_VEC | 17}, \
2821     {"$v18",    RTYPE_VEC | 18}, \
2822     {"$v19",    RTYPE_VEC | 19}, \
2823     {"$v20",    RTYPE_VEC | 20}, \
2824     {"$v21",    RTYPE_VEC | 21}, \
2825     {"$v22",    RTYPE_VEC | 22}, \
2826     {"$v23",    RTYPE_VEC | 23}, \
2827     {"$v24",    RTYPE_VEC | 24}, \
2828     {"$v25",    RTYPE_VEC | 25}, \
2829     {"$v26",    RTYPE_VEC | 26}, \
2830     {"$v27",    RTYPE_VEC | 27}, \
2831     {"$v28",    RTYPE_VEC | 28}, \
2832     {"$v29",    RTYPE_VEC | 29}, \
2833     {"$v30",    RTYPE_VEC | 30}, \
2834     {"$v31",    RTYPE_VEC | 31}
2835
2836 #define R5900_I_NAMES \
2837     {"$I",      RTYPE_R5900_I | 0}
2838
2839 #define R5900_Q_NAMES \
2840     {"$Q",      RTYPE_R5900_Q | 0}
2841
2842 #define R5900_R_NAMES \
2843     {"$R",      RTYPE_R5900_R | 0}
2844
2845 #define R5900_ACC_NAMES \
2846     {"$ACC",    RTYPE_R5900_ACC | 0 }
2847
2848 #define MIPS_DSP_ACCUMULATOR_NAMES \
2849     {"$ac0",    RTYPE_ACC | 0}, \
2850     {"$ac1",    RTYPE_ACC | 1}, \
2851     {"$ac2",    RTYPE_ACC | 2}, \
2852     {"$ac3",    RTYPE_ACC | 3}
2853
2854 static const struct regname reg_names[] = {
2855   GENERIC_REGISTER_NUMBERS,
2856   FPU_REGISTER_NAMES,
2857   FPU_CONDITION_CODE_NAMES,
2858   COPROC_CONDITION_CODE_NAMES,
2859
2860   /* The $txx registers depends on the abi,
2861      these will be added later into the symbol table from
2862      one of the tables below once mips_abi is set after
2863      parsing of arguments from the command line. */
2864   SYMBOLIC_REGISTER_NAMES,
2865
2866   MIPS16_SPECIAL_REGISTER_NAMES,
2867   MDMX_VECTOR_REGISTER_NAMES,
2868   R5900_I_NAMES,
2869   R5900_Q_NAMES,
2870   R5900_R_NAMES,
2871   R5900_ACC_NAMES,
2872   MIPS_DSP_ACCUMULATOR_NAMES,
2873   {0, 0}
2874 };
2875
2876 static const struct regname reg_names_o32[] = {
2877   O32_SYMBOLIC_REGISTER_NAMES,
2878   {0, 0}
2879 };
2880
2881 static const struct regname reg_names_n32n64[] = {
2882   N32N64_SYMBOLIC_REGISTER_NAMES,
2883   {0, 0}
2884 };
2885
2886 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2887    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2888    of these register symbols, return the associated vector register,
2889    otherwise return SYMVAL itself.  */
2890
2891 static unsigned int
2892 mips_prefer_vec_regno (unsigned int symval)
2893 {
2894   if ((symval & -2) == (RTYPE_GP | 2))
2895     return RTYPE_VEC | (symval & 1);
2896   return symval;
2897 }
2898
2899 /* Return true if string [S, E) is a valid register name, storing its
2900    symbol value in *SYMVAL_PTR if so.  */
2901
2902 static bfd_boolean
2903 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2904 {
2905   char save_c;
2906   symbolS *symbol;
2907
2908   /* Terminate name.  */
2909   save_c = *e;
2910   *e = '\0';
2911
2912   /* Look up the name.  */
2913   symbol = symbol_find (s);
2914   *e = save_c;
2915
2916   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2917     return FALSE;
2918
2919   *symval_ptr = S_GET_VALUE (symbol);
2920   return TRUE;
2921 }
2922
2923 /* Return true if the string at *SPTR is a valid register name.  Allow it
2924    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2925    is nonnull.
2926
2927    When returning true, move *SPTR past the register, store the
2928    register's symbol value in *SYMVAL_PTR and the channel mask in
2929    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2930    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2931    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2932
2933 static bfd_boolean
2934 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2935                      unsigned int *channels_ptr)
2936 {
2937   char *s, *e, *m;
2938   const char *q;
2939   unsigned int channels, symval, bit;
2940
2941   /* Find end of name.  */
2942   s = e = *sptr;
2943   if (is_name_beginner (*e))
2944     ++e;
2945   while (is_part_of_name (*e))
2946     ++e;
2947
2948   channels = 0;
2949   if (!mips_parse_register_1 (s, e, &symval))
2950     {
2951       if (!channels_ptr)
2952         return FALSE;
2953
2954       /* Eat characters from the end of the string that are valid
2955          channel suffixes.  The preceding register must be $ACC or
2956          end with a digit, so there is no ambiguity.  */
2957       bit = 1;
2958       m = e;
2959       for (q = "wzyx"; *q; q++, bit <<= 1)
2960         if (m > s && m[-1] == *q)
2961           {
2962             --m;
2963             channels |= bit;
2964           }
2965
2966       if (channels == 0
2967           || !mips_parse_register_1 (s, m, &symval)
2968           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2969         return FALSE;
2970     }
2971
2972   *sptr = e;
2973   *symval_ptr = symval;
2974   if (channels_ptr)
2975     *channels_ptr = channels;
2976   return TRUE;
2977 }
2978
2979 /* Check if SPTR points at a valid register specifier according to TYPES.
2980    If so, then return 1, advance S to consume the specifier and store
2981    the register's number in REGNOP, otherwise return 0.  */
2982
2983 static int
2984 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2985 {
2986   unsigned int regno;
2987
2988   if (mips_parse_register (s, &regno, NULL))
2989     {
2990       if (types & RTYPE_VEC)
2991         regno = mips_prefer_vec_regno (regno);
2992       if (regno & types)
2993         regno &= RNUM_MASK;
2994       else
2995         regno = ~0;
2996     }
2997   else
2998     {
2999       if (types & RWARN)
3000         as_warn (_("unrecognized register name `%s'"), *s);
3001       regno = ~0;
3002     }
3003   if (regnop)
3004     *regnop = regno;
3005   return regno <= RNUM_MASK;
3006 }
3007
3008 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
3009    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
3010
3011 static char *
3012 mips_parse_vu0_channels (char *s, unsigned int *channels)
3013 {
3014   unsigned int i;
3015
3016   *channels = 0;
3017   for (i = 0; i < 4; i++)
3018     if (*s == "xyzw"[i])
3019       {
3020         *channels |= 1 << (3 - i);
3021         ++s;
3022       }
3023   return s;
3024 }
3025
3026 /* Token types for parsed operand lists.  */
3027 enum mips_operand_token_type {
3028   /* A plain register, e.g. $f2.  */
3029   OT_REG,
3030
3031   /* A 4-bit XYZW channel mask.  */
3032   OT_CHANNELS,
3033
3034   /* A constant vector index, e.g. [1].  */
3035   OT_INTEGER_INDEX,
3036
3037   /* A register vector index, e.g. [$2].  */
3038   OT_REG_INDEX,
3039
3040   /* A continuous range of registers, e.g. $s0-$s4.  */
3041   OT_REG_RANGE,
3042
3043   /* A (possibly relocated) expression.  */
3044   OT_INTEGER,
3045
3046   /* A floating-point value.  */
3047   OT_FLOAT,
3048
3049   /* A single character.  This can be '(', ')' or ',', but '(' only appears
3050      before OT_REGs.  */
3051   OT_CHAR,
3052
3053   /* A doubled character, either "--" or "++".  */
3054   OT_DOUBLE_CHAR,
3055
3056   /* The end of the operand list.  */
3057   OT_END
3058 };
3059
3060 /* A parsed operand token.  */
3061 struct mips_operand_token
3062 {
3063   /* The type of token.  */
3064   enum mips_operand_token_type type;
3065   union
3066   {
3067     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
3068     unsigned int regno;
3069
3070     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
3071     unsigned int channels;
3072
3073     /* The integer value of an OT_INTEGER_INDEX.  */
3074     addressT index;
3075
3076     /* The two register symbol values involved in an OT_REG_RANGE.  */
3077     struct {
3078       unsigned int regno1;
3079       unsigned int regno2;
3080     } reg_range;
3081
3082     /* The value of an OT_INTEGER.  The value is represented as an
3083        expression and the relocation operators that were applied to
3084        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
3085        relocation operators were used.  */
3086     struct {
3087       expressionS value;
3088       bfd_reloc_code_real_type relocs[3];
3089     } integer;
3090
3091     /* The binary data for an OT_FLOAT constant, and the number of bytes
3092        in the constant.  */
3093     struct {
3094       unsigned char data[8];
3095       int length;
3096     } flt;
3097
3098     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3099     char ch;
3100   } u;
3101 };
3102
3103 /* An obstack used to construct lists of mips_operand_tokens.  */
3104 static struct obstack mips_operand_tokens;
3105
3106 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3107
3108 static void
3109 mips_add_token (struct mips_operand_token *token,
3110                 enum mips_operand_token_type type)
3111 {
3112   token->type = type;
3113   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3114 }
3115
3116 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
3117    and OT_REG tokens for them if so, and return a pointer to the first
3118    unconsumed character.  Return null otherwise.  */
3119
3120 static char *
3121 mips_parse_base_start (char *s)
3122 {
3123   struct mips_operand_token token;
3124   unsigned int regno, channels;
3125   bfd_boolean decrement_p;
3126
3127   if (*s != '(')
3128     return 0;
3129
3130   ++s;
3131   SKIP_SPACE_TABS (s);
3132
3133   /* Only match "--" as part of a base expression.  In other contexts "--X"
3134      is a double negative.  */
3135   decrement_p = (s[0] == '-' && s[1] == '-');
3136   if (decrement_p)
3137     {
3138       s += 2;
3139       SKIP_SPACE_TABS (s);
3140     }
3141
3142   /* Allow a channel specifier because that leads to better error messages
3143      than treating something like "$vf0x++" as an expression.  */
3144   if (!mips_parse_register (&s, &regno, &channels))
3145     return 0;
3146
3147   token.u.ch = '(';
3148   mips_add_token (&token, OT_CHAR);
3149
3150   if (decrement_p)
3151     {
3152       token.u.ch = '-';
3153       mips_add_token (&token, OT_DOUBLE_CHAR);
3154     }
3155
3156   token.u.regno = regno;
3157   mips_add_token (&token, OT_REG);
3158
3159   if (channels)
3160     {
3161       token.u.channels = channels;
3162       mips_add_token (&token, OT_CHANNELS);
3163     }
3164
3165   /* For consistency, only match "++" as part of base expressions too.  */
3166   SKIP_SPACE_TABS (s);
3167   if (s[0] == '+' && s[1] == '+')
3168     {
3169       s += 2;
3170       token.u.ch = '+';
3171       mips_add_token (&token, OT_DOUBLE_CHAR);
3172     }
3173
3174   return s;
3175 }
3176
3177 /* Parse one or more tokens from S.  Return a pointer to the first
3178    unconsumed character on success.  Return null if an error was found
3179    and store the error text in insn_error.  FLOAT_FORMAT is as for
3180    mips_parse_arguments.  */
3181
3182 static char *
3183 mips_parse_argument_token (char *s, char float_format)
3184 {
3185   char *end, *save_in;
3186   const char *err;
3187   unsigned int regno1, regno2, channels;
3188   struct mips_operand_token token;
3189
3190   /* First look for "($reg", since we want to treat that as an
3191      OT_CHAR and OT_REG rather than an expression.  */
3192   end = mips_parse_base_start (s);
3193   if (end)
3194     return end;
3195
3196   /* Handle other characters that end up as OT_CHARs.  */
3197   if (*s == ')' || *s == ',')
3198     {
3199       token.u.ch = *s;
3200       mips_add_token (&token, OT_CHAR);
3201       ++s;
3202       return s;
3203     }
3204
3205   /* Handle tokens that start with a register.  */
3206   if (mips_parse_register (&s, &regno1, &channels))
3207     {
3208       if (channels)
3209         {
3210           /* A register and a VU0 channel suffix.  */
3211           token.u.regno = regno1;
3212           mips_add_token (&token, OT_REG);
3213
3214           token.u.channels = channels;
3215           mips_add_token (&token, OT_CHANNELS);
3216           return s;
3217         }
3218
3219       SKIP_SPACE_TABS (s);
3220       if (*s == '-')
3221         {
3222           /* A register range.  */
3223           ++s;
3224           SKIP_SPACE_TABS (s);
3225           if (!mips_parse_register (&s, &regno2, NULL))
3226             {
3227               set_insn_error (0, _("invalid register range"));
3228               return 0;
3229             }
3230
3231           token.u.reg_range.regno1 = regno1;
3232           token.u.reg_range.regno2 = regno2;
3233           mips_add_token (&token, OT_REG_RANGE);
3234           return s;
3235         }
3236
3237       /* Add the register itself.  */
3238       token.u.regno = regno1;
3239       mips_add_token (&token, OT_REG);
3240
3241       /* Check for a vector index.  */
3242       if (*s == '[')
3243         {
3244           ++s;
3245           SKIP_SPACE_TABS (s);
3246           if (mips_parse_register (&s, &token.u.regno, NULL))
3247             mips_add_token (&token, OT_REG_INDEX);
3248           else
3249             {
3250               expressionS element;
3251
3252               my_getExpression (&element, s);
3253               if (element.X_op != O_constant)
3254                 {
3255                   set_insn_error (0, _("vector element must be constant"));
3256                   return 0;
3257                 }
3258               s = expr_end;
3259               token.u.index = element.X_add_number;
3260               mips_add_token (&token, OT_INTEGER_INDEX);
3261             }
3262           SKIP_SPACE_TABS (s);
3263           if (*s != ']')
3264             {
3265               set_insn_error (0, _("missing `]'"));
3266               return 0;
3267             }
3268           ++s;
3269         }
3270       return s;
3271     }
3272
3273   if (float_format)
3274     {
3275       /* First try to treat expressions as floats.  */
3276       save_in = input_line_pointer;
3277       input_line_pointer = s;
3278       err = md_atof (float_format, (char *) token.u.flt.data,
3279                      &token.u.flt.length);
3280       end = input_line_pointer;
3281       input_line_pointer = save_in;
3282       if (err && *err)
3283         {
3284           set_insn_error (0, err);
3285           return 0;
3286         }
3287       if (s != end)
3288         {
3289           mips_add_token (&token, OT_FLOAT);
3290           return end;
3291         }
3292     }
3293
3294   /* Treat everything else as an integer expression.  */
3295   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3296   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3297   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3298   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3299   s = expr_end;
3300   mips_add_token (&token, OT_INTEGER);
3301   return s;
3302 }
3303
3304 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3305    if expressions should be treated as 32-bit floating-point constants,
3306    'd' if they should be treated as 64-bit floating-point constants,
3307    or 0 if they should be treated as integer expressions (the usual case).
3308
3309    Return a list of tokens on success, otherwise return 0.  The caller
3310    must obstack_free the list after use.  */
3311
3312 static struct mips_operand_token *
3313 mips_parse_arguments (char *s, char float_format)
3314 {
3315   struct mips_operand_token token;
3316
3317   SKIP_SPACE_TABS (s);
3318   while (*s)
3319     {
3320       s = mips_parse_argument_token (s, float_format);
3321       if (!s)
3322         {
3323           obstack_free (&mips_operand_tokens,
3324                         obstack_finish (&mips_operand_tokens));
3325           return 0;
3326         }
3327       SKIP_SPACE_TABS (s);
3328     }
3329   mips_add_token (&token, OT_END);
3330   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3331 }
3332
3333 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3334    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3335
3336 static bfd_boolean
3337 is_opcode_valid (const struct mips_opcode *mo)
3338 {
3339   int isa = mips_opts.isa;
3340   int ase = mips_opts.ase;
3341   int fp_s, fp_d;
3342   unsigned int i;
3343
3344   if (ISA_HAS_64BIT_REGS (isa))
3345     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3346       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3347         ase |= mips_ases[i].flags64;
3348
3349   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3350     return FALSE;
3351
3352   /* Check whether the instruction or macro requires single-precision or
3353      double-precision floating-point support.  Note that this information is
3354      stored differently in the opcode table for insns and macros.  */
3355   if (mo->pinfo == INSN_MACRO)
3356     {
3357       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3358       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3359     }
3360   else
3361     {
3362       fp_s = mo->pinfo & FP_S;
3363       fp_d = mo->pinfo & FP_D;
3364     }
3365
3366   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3367     return FALSE;
3368
3369   if (fp_s && mips_opts.soft_float)
3370     return FALSE;
3371
3372   return TRUE;
3373 }
3374
3375 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3376    selected ISA and architecture.  */
3377
3378 static bfd_boolean
3379 is_opcode_valid_16 (const struct mips_opcode *mo)
3380 {
3381   int isa = mips_opts.isa;
3382   int ase = mips_opts.ase;
3383   unsigned int i;
3384
3385   if (ISA_HAS_64BIT_REGS (isa))
3386     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3387       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3388         ase |= mips_ases[i].flags64;
3389
3390   return opcode_is_member (mo, isa, ase, mips_opts.arch);
3391 }
3392
3393 /* Return TRUE if the size of the microMIPS opcode MO matches one
3394    explicitly requested.  Always TRUE in the standard MIPS mode.
3395    Use is_size_valid_16 for MIPS16 opcodes.  */
3396
3397 static bfd_boolean
3398 is_size_valid (const struct mips_opcode *mo)
3399 {
3400   if (!mips_opts.micromips)
3401     return TRUE;
3402
3403   if (mips_opts.insn32)
3404     {
3405       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3406         return FALSE;
3407       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3408         return FALSE;
3409     }
3410   if (!forced_insn_length)
3411     return TRUE;
3412   if (mo->pinfo == INSN_MACRO)
3413     return FALSE;
3414   return forced_insn_length == micromips_insn_length (mo);
3415 }
3416
3417 /* Return TRUE if the size of the MIPS16 opcode MO matches one
3418    explicitly requested.  */
3419
3420 static bfd_boolean
3421 is_size_valid_16 (const struct mips_opcode *mo)
3422 {
3423   if (!forced_insn_length)
3424     return TRUE;
3425   if (mo->pinfo == INSN_MACRO)
3426     return FALSE;
3427   if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3428     return FALSE;
3429   if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3430     return FALSE;
3431   return TRUE;
3432 }
3433
3434 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3435    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3436
3437    We don't accept macros in 16-bit delay slots to avoid a case where
3438    a macro expansion fails because it relies on a preceding 32-bit real
3439    instruction to have matched and does not handle the operands correctly.
3440    The only macros that may expand to 16-bit instructions are JAL that
3441    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3442    and BGT (that likewise cannot be placed in a delay slot) that decay to
3443    a NOP.  In all these cases the macros precede any corresponding real
3444    instruction definitions in the opcode table, so they will match in the
3445    second pass where the size of the delay slot is ignored and therefore
3446    produce correct code.  */
3447
3448 static bfd_boolean
3449 is_delay_slot_valid (const struct mips_opcode *mo)
3450 {
3451   if (!mips_opts.micromips)
3452     return TRUE;
3453
3454   if (mo->pinfo == INSN_MACRO)
3455     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3456   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3457       && micromips_insn_length (mo) != 4)
3458     return FALSE;
3459   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3460       && micromips_insn_length (mo) != 2)
3461     return FALSE;
3462
3463   return TRUE;
3464 }
3465
3466 /* For consistency checking, verify that all bits of OPCODE are specified
3467    either by the match/mask part of the instruction definition, or by the
3468    operand list.  Also build up a list of operands in OPERANDS.
3469
3470    INSN_BITS says which bits of the instruction are significant.
3471    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3472    provides the mips_operand description of each operand.  DECODE_OPERAND
3473    is null for MIPS16 instructions.  */
3474
3475 static int
3476 validate_mips_insn (const struct mips_opcode *opcode,
3477                     unsigned long insn_bits,
3478                     const struct mips_operand *(*decode_operand) (const char *),
3479                     struct mips_operand_array *operands)
3480 {
3481   const char *s;
3482   unsigned long used_bits, doubled, undefined, opno, mask;
3483   const struct mips_operand *operand;
3484
3485   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3486   if ((mask & opcode->match) != opcode->match)
3487     {
3488       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3489               opcode->name, opcode->args);
3490       return 0;
3491     }
3492   used_bits = 0;
3493   opno = 0;
3494   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3495     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3496   for (s = opcode->args; *s; ++s)
3497     switch (*s)
3498       {
3499       case ',':
3500       case '(':
3501       case ')':
3502         break;
3503
3504       case '#':
3505         s++;
3506         break;
3507
3508       default:
3509         if (!decode_operand)
3510           operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3511         else
3512           operand = decode_operand (s);
3513         if (!operand && opcode->pinfo != INSN_MACRO)
3514           {
3515             as_bad (_("internal: unknown operand type: %s %s"),
3516                     opcode->name, opcode->args);
3517             return 0;
3518           }
3519         gas_assert (opno < MAX_OPERANDS);
3520         operands->operand[opno] = operand;
3521         if (!decode_operand && operand
3522             && operand->type == OP_INT && operand->lsb == 0
3523             && mips_opcode_32bit_p (opcode))
3524           used_bits |= mips16_immed_extend (-1, operand->size);
3525         else if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3526           {
3527             used_bits = mips_insert_operand (operand, used_bits, -1);
3528             if (operand->type == OP_MDMX_IMM_REG)
3529               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3530                  has separate entries for each format.  */
3531               used_bits &= ~(1 << (operand->lsb + 5));
3532             if (operand->type == OP_ENTRY_EXIT_LIST)
3533               used_bits &= ~(mask & 0x700);
3534             /* interAptiv MR2 SAVE/RESTORE instructions have a discontiguous
3535                operand field that cannot be fully described with LSB/SIZE.  */
3536             if (operand->type == OP_SAVE_RESTORE_LIST && operand->lsb == 6)
3537               used_bits &= ~0x6000;
3538           }
3539         /* Skip prefix characters.  */
3540         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3541           ++s;
3542         opno += 1;
3543         break;
3544       }
3545   doubled = used_bits & mask & insn_bits;
3546   if (doubled)
3547     {
3548       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3549                 " %s %s"), doubled, opcode->name, opcode->args);
3550       return 0;
3551     }
3552   used_bits |= mask;
3553   undefined = ~used_bits & insn_bits;
3554   if (opcode->pinfo != INSN_MACRO && undefined)
3555     {
3556       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3557               undefined, opcode->name, opcode->args);
3558       return 0;
3559     }
3560   used_bits &= ~insn_bits;
3561   if (used_bits)
3562     {
3563       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3564               used_bits, opcode->name, opcode->args);
3565       return 0;
3566     }
3567   return 1;
3568 }
3569
3570 /* The MIPS16 version of validate_mips_insn.  */
3571
3572 static int
3573 validate_mips16_insn (const struct mips_opcode *opcode,
3574                       struct mips_operand_array *operands)
3575 {
3576   unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3577
3578   return validate_mips_insn (opcode, insn_bits, 0, operands);
3579 }
3580
3581 /* The microMIPS version of validate_mips_insn.  */
3582
3583 static int
3584 validate_micromips_insn (const struct mips_opcode *opc,
3585                          struct mips_operand_array *operands)
3586 {
3587   unsigned long insn_bits;
3588   unsigned long major;
3589   unsigned int length;
3590
3591   if (opc->pinfo == INSN_MACRO)
3592     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3593                                operands);
3594
3595   length = micromips_insn_length (opc);
3596   if (length != 2 && length != 4)
3597     {
3598       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3599                 "%s %s"), length, opc->name, opc->args);
3600       return 0;
3601     }
3602   major = opc->match >> (10 + 8 * (length - 2));
3603   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3604       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3605     {
3606       as_bad (_("internal error: bad microMIPS opcode "
3607                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3608       return 0;
3609     }
3610
3611   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3612   insn_bits = 1 << 4 * length;
3613   insn_bits <<= 4 * length;
3614   insn_bits -= 1;
3615   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3616                              operands);
3617 }
3618
3619 /* This function is called once, at assembler startup time.  It should set up
3620    all the tables, etc. that the MD part of the assembler will need.  */
3621
3622 void
3623 md_begin (void)
3624 {
3625   const char *retval = NULL;
3626   int i = 0;
3627   int broken = 0;
3628
3629   if (mips_pic != NO_PIC)
3630     {
3631       if (g_switch_seen && g_switch_value != 0)
3632         as_bad (_("-G may not be used in position-independent code"));
3633       g_switch_value = 0;
3634     }
3635   else if (mips_abicalls)
3636     {
3637       if (g_switch_seen && g_switch_value != 0)
3638         as_bad (_("-G may not be used with abicalls"));
3639       g_switch_value = 0;
3640     }
3641
3642   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3643     as_warn (_("could not set architecture and machine"));
3644
3645   op_hash = hash_new ();
3646
3647   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3648   for (i = 0; i < NUMOPCODES;)
3649     {
3650       const char *name = mips_opcodes[i].name;
3651
3652       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3653       if (retval != NULL)
3654         {
3655           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3656                    mips_opcodes[i].name, retval);
3657           /* Probably a memory allocation problem?  Give up now.  */
3658           as_fatal (_("broken assembler, no assembly attempted"));
3659         }
3660       do
3661         {
3662           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3663                                    decode_mips_operand, &mips_operands[i]))
3664             broken = 1;
3665           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3666             {
3667               create_insn (&nop_insn, mips_opcodes + i);
3668               if (mips_fix_loongson2f_nop)
3669                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3670               nop_insn.fixed_p = 1;
3671             }
3672           ++i;
3673         }
3674       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3675     }
3676
3677   mips16_op_hash = hash_new ();
3678   mips16_operands = XCNEWVEC (struct mips_operand_array,
3679                               bfd_mips16_num_opcodes);
3680
3681   i = 0;
3682   while (i < bfd_mips16_num_opcodes)
3683     {
3684       const char *name = mips16_opcodes[i].name;
3685
3686       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3687       if (retval != NULL)
3688         as_fatal (_("internal: can't hash `%s': %s"),
3689                   mips16_opcodes[i].name, retval);
3690       do
3691         {
3692           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3693             broken = 1;
3694           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3695             {
3696               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3697               mips16_nop_insn.fixed_p = 1;
3698             }
3699           ++i;
3700         }
3701       while (i < bfd_mips16_num_opcodes
3702              && strcmp (mips16_opcodes[i].name, name) == 0);
3703     }
3704
3705   micromips_op_hash = hash_new ();
3706   micromips_operands = XCNEWVEC (struct mips_operand_array,
3707                                  bfd_micromips_num_opcodes);
3708
3709   i = 0;
3710   while (i < bfd_micromips_num_opcodes)
3711     {
3712       const char *name = micromips_opcodes[i].name;
3713
3714       retval = hash_insert (micromips_op_hash, name,
3715                             (void *) &micromips_opcodes[i]);
3716       if (retval != NULL)
3717         as_fatal (_("internal: can't hash `%s': %s"),
3718                   micromips_opcodes[i].name, retval);
3719       do
3720         {
3721           struct mips_cl_insn *micromips_nop_insn;
3722
3723           if (!validate_micromips_insn (&micromips_opcodes[i],
3724                                         &micromips_operands[i]))
3725             broken = 1;
3726
3727           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3728             {
3729               if (micromips_insn_length (micromips_opcodes + i) == 2)
3730                 micromips_nop_insn = &micromips_nop16_insn;
3731               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3732                 micromips_nop_insn = &micromips_nop32_insn;
3733               else
3734                 continue;
3735
3736               if (micromips_nop_insn->insn_mo == NULL
3737                   && strcmp (name, "nop") == 0)
3738                 {
3739                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3740                   micromips_nop_insn->fixed_p = 1;
3741                 }
3742             }
3743         }
3744       while (++i < bfd_micromips_num_opcodes
3745              && strcmp (micromips_opcodes[i].name, name) == 0);
3746     }
3747
3748   if (broken)
3749     as_fatal (_("broken assembler, no assembly attempted"));
3750
3751   /* We add all the general register names to the symbol table.  This
3752      helps us detect invalid uses of them.  */
3753   for (i = 0; reg_names[i].name; i++)
3754     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3755                                      reg_names[i].num, /* & RNUM_MASK, */
3756                                      &zero_address_frag));
3757   if (HAVE_NEWABI)
3758     for (i = 0; reg_names_n32n64[i].name; i++)
3759       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3760                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3761                                        &zero_address_frag));
3762   else
3763     for (i = 0; reg_names_o32[i].name; i++)
3764       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3765                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3766                                        &zero_address_frag));
3767
3768   for (i = 0; i < 32; i++)
3769     {
3770       char regname[6];
3771
3772       /* R5900 VU0 floating-point register.  */
3773       sprintf (regname, "$vf%d", i);
3774       symbol_table_insert (symbol_new (regname, reg_section,
3775                                        RTYPE_VF | i, &zero_address_frag));
3776
3777       /* R5900 VU0 integer register.  */
3778       sprintf (regname, "$vi%d", i);
3779       symbol_table_insert (symbol_new (regname, reg_section,
3780                                        RTYPE_VI | i, &zero_address_frag));
3781
3782       /* MSA register.  */
3783       sprintf (regname, "$w%d", i);
3784       symbol_table_insert (symbol_new (regname, reg_section,
3785                                        RTYPE_MSA | i, &zero_address_frag));
3786     }
3787
3788   obstack_init (&mips_operand_tokens);
3789
3790   mips_no_prev_insn ();
3791
3792   mips_gprmask = 0;
3793   mips_cprmask[0] = 0;
3794   mips_cprmask[1] = 0;
3795   mips_cprmask[2] = 0;
3796   mips_cprmask[3] = 0;
3797
3798   /* set the default alignment for the text section (2**2) */
3799   record_alignment (text_section, 2);
3800
3801   bfd_set_gp_size (stdoutput, g_switch_value);
3802
3803   /* On a native system other than VxWorks, sections must be aligned
3804      to 16 byte boundaries.  When configured for an embedded ELF
3805      target, we don't bother.  */
3806   if (strncmp (TARGET_OS, "elf", 3) != 0
3807       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3808     {
3809       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3810       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3811       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3812     }
3813
3814   /* Create a .reginfo section for register masks and a .mdebug
3815      section for debugging information.  */
3816   {
3817     segT seg;
3818     subsegT subseg;
3819     flagword flags;
3820     segT sec;
3821
3822     seg = now_seg;
3823     subseg = now_subseg;
3824
3825     /* The ABI says this section should be loaded so that the
3826        running program can access it.  However, we don't load it
3827        if we are configured for an embedded target */
3828     flags = SEC_READONLY | SEC_DATA;
3829     if (strncmp (TARGET_OS, "elf", 3) != 0)
3830       flags |= SEC_ALLOC | SEC_LOAD;
3831
3832     if (mips_abi != N64_ABI)
3833       {
3834         sec = subseg_new (".reginfo", (subsegT) 0);
3835
3836         bfd_set_section_flags (stdoutput, sec, flags);
3837         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3838
3839         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3840       }
3841     else
3842       {
3843         /* The 64-bit ABI uses a .MIPS.options section rather than
3844            .reginfo section.  */
3845         sec = subseg_new (".MIPS.options", (subsegT) 0);
3846         bfd_set_section_flags (stdoutput, sec, flags);
3847         bfd_set_section_alignment (stdoutput, sec, 3);
3848
3849         /* Set up the option header.  */
3850         {
3851           Elf_Internal_Options opthdr;
3852           char *f;
3853
3854           opthdr.kind = ODK_REGINFO;
3855           opthdr.size = (sizeof (Elf_External_Options)
3856                          + sizeof (Elf64_External_RegInfo));
3857           opthdr.section = 0;
3858           opthdr.info = 0;
3859           f = frag_more (sizeof (Elf_External_Options));
3860           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3861                                          (Elf_External_Options *) f);
3862
3863           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3864         }
3865       }
3866
3867     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3868     bfd_set_section_flags (stdoutput, sec,
3869                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3870     bfd_set_section_alignment (stdoutput, sec, 3);
3871     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3872
3873     if (ECOFF_DEBUGGING)
3874       {
3875         sec = subseg_new (".mdebug", (subsegT) 0);
3876         (void) bfd_set_section_flags (stdoutput, sec,
3877                                       SEC_HAS_CONTENTS | SEC_READONLY);
3878         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3879       }
3880     else if (mips_flag_pdr)
3881       {
3882         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3883         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3884                                       SEC_READONLY | SEC_RELOC
3885                                       | SEC_DEBUGGING);
3886         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3887       }
3888
3889     subseg_set (seg, subseg);
3890   }
3891
3892   if (mips_fix_vr4120)
3893     init_vr4120_conflicts ();
3894 }
3895
3896 static inline void
3897 fpabi_incompatible_with (int fpabi, const char *what)
3898 {
3899   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3900            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3901 }
3902
3903 static inline void
3904 fpabi_requires (int fpabi, const char *what)
3905 {
3906   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3907            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3908 }
3909
3910 /* Check -mabi and register sizes against the specified FP ABI.  */
3911 static void
3912 check_fpabi (int fpabi)
3913 {
3914   switch (fpabi)
3915     {
3916     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3917       if (file_mips_opts.soft_float)
3918         fpabi_incompatible_with (fpabi, "softfloat");
3919       else if (file_mips_opts.single_float)
3920         fpabi_incompatible_with (fpabi, "singlefloat");
3921       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3922         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3923       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3924         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3925       break;
3926
3927     case Val_GNU_MIPS_ABI_FP_XX:
3928       if (mips_abi != O32_ABI)
3929         fpabi_requires (fpabi, "-mabi=32");
3930       else if (file_mips_opts.soft_float)
3931         fpabi_incompatible_with (fpabi, "softfloat");
3932       else if (file_mips_opts.single_float)
3933         fpabi_incompatible_with (fpabi, "singlefloat");
3934       else if (file_mips_opts.fp != 0)
3935         fpabi_requires (fpabi, "fp=xx");
3936       break;
3937
3938     case Val_GNU_MIPS_ABI_FP_64A:
3939     case Val_GNU_MIPS_ABI_FP_64:
3940       if (mips_abi != O32_ABI)
3941         fpabi_requires (fpabi, "-mabi=32");
3942       else if (file_mips_opts.soft_float)
3943         fpabi_incompatible_with (fpabi, "softfloat");
3944       else if (file_mips_opts.single_float)
3945         fpabi_incompatible_with (fpabi, "singlefloat");
3946       else if (file_mips_opts.fp != 64)
3947         fpabi_requires (fpabi, "fp=64");
3948       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3949         fpabi_incompatible_with (fpabi, "nooddspreg");
3950       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3951         fpabi_requires (fpabi, "nooddspreg");
3952       break;
3953
3954     case Val_GNU_MIPS_ABI_FP_SINGLE:
3955       if (file_mips_opts.soft_float)
3956         fpabi_incompatible_with (fpabi, "softfloat");
3957       else if (!file_mips_opts.single_float)
3958         fpabi_requires (fpabi, "singlefloat");
3959       break;
3960
3961     case Val_GNU_MIPS_ABI_FP_SOFT:
3962       if (!file_mips_opts.soft_float)
3963         fpabi_requires (fpabi, "softfloat");
3964       break;
3965
3966     case Val_GNU_MIPS_ABI_FP_OLD_64:
3967       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3968                Tag_GNU_MIPS_ABI_FP, fpabi);
3969       break;
3970
3971     case Val_GNU_MIPS_ABI_FP_NAN2008:
3972       /* Silently ignore compatibility value.  */
3973       break;
3974
3975     default:
3976       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3977                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3978       break;
3979     }
3980 }
3981
3982 /* Perform consistency checks on the current options.  */
3983
3984 static void
3985 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3986 {
3987   /* Check the size of integer registers agrees with the ABI and ISA.  */
3988   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3989     as_bad (_("`gp=64' used with a 32-bit processor"));
3990   else if (abi_checks
3991            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3992     as_bad (_("`gp=32' used with a 64-bit ABI"));
3993   else if (abi_checks
3994            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3995     as_bad (_("`gp=64' used with a 32-bit ABI"));
3996
3997   /* Check the size of the float registers agrees with the ABI and ISA.  */
3998   switch (opts->fp)
3999     {
4000     case 0:
4001       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
4002         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
4003       else if (opts->single_float == 1)
4004         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
4005       break;
4006     case 64:
4007       if (!ISA_HAS_64BIT_FPRS (opts->isa))
4008         as_bad (_("`fp=64' used with a 32-bit fpu"));
4009       else if (abi_checks
4010                && ABI_NEEDS_32BIT_REGS (mips_abi)
4011                && !ISA_HAS_MXHC1 (opts->isa))
4012         as_warn (_("`fp=64' used with a 32-bit ABI"));
4013       break;
4014     case 32:
4015       if (abi_checks
4016           && ABI_NEEDS_64BIT_REGS (mips_abi))
4017         as_warn (_("`fp=32' used with a 64-bit ABI"));
4018       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
4019         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
4020       break;
4021     default:
4022       as_bad (_("Unknown size of floating point registers"));
4023       break;
4024     }
4025
4026   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
4027     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
4028
4029   if (opts->micromips == 1 && opts->mips16 == 1)
4030     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
4031   else if (ISA_IS_R6 (opts->isa)
4032            && (opts->micromips == 1
4033                || opts->mips16 == 1))
4034     as_fatal (_("`%s' cannot be used with `%s'"),
4035               opts->micromips ? "micromips" : "mips16",
4036               mips_cpu_info_from_isa (opts->isa)->name);
4037
4038   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
4039     as_fatal (_("branch relaxation is not supported in `%s'"),
4040               mips_cpu_info_from_isa (opts->isa)->name);
4041 }
4042
4043 /* Perform consistency checks on the module level options exactly once.
4044    This is a deferred check that happens:
4045      at the first .set directive
4046      or, at the first pseudo op that generates code (inc .dc.a)
4047      or, at the first instruction
4048      or, at the end.  */
4049
4050 static void
4051 file_mips_check_options (void)
4052 {
4053   const struct mips_cpu_info *arch_info = 0;
4054
4055   if (file_mips_opts_checked)
4056     return;
4057
4058   /* The following code determines the register size.
4059      Similar code was added to GCC 3.3 (see override_options() in
4060      config/mips/mips.c).  The GAS and GCC code should be kept in sync
4061      as much as possible.  */
4062
4063   if (file_mips_opts.gp < 0)
4064     {
4065       /* Infer the integer register size from the ABI and processor.
4066          Restrict ourselves to 32-bit registers if that's all the
4067          processor has, or if the ABI cannot handle 64-bit registers.  */
4068       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
4069                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
4070                           ? 32 : 64;
4071     }
4072
4073   if (file_mips_opts.fp < 0)
4074     {
4075       /* No user specified float register size.
4076          ??? GAS treats single-float processors as though they had 64-bit
4077          float registers (although it complains when double-precision
4078          instructions are used).  As things stand, saying they have 32-bit
4079          registers would lead to spurious "register must be even" messages.
4080          So here we assume float registers are never smaller than the
4081          integer ones.  */
4082       if (file_mips_opts.gp == 64)
4083         /* 64-bit integer registers implies 64-bit float registers.  */
4084         file_mips_opts.fp = 64;
4085       else if ((file_mips_opts.ase & FP64_ASES)
4086                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
4087         /* Handle ASEs that require 64-bit float registers, if possible.  */
4088         file_mips_opts.fp = 64;
4089       else if (ISA_IS_R6 (mips_opts.isa))
4090         /* R6 implies 64-bit float registers.  */
4091         file_mips_opts.fp = 64;
4092       else
4093         /* 32-bit float registers.  */
4094         file_mips_opts.fp = 32;
4095     }
4096
4097   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
4098
4099   /* Disable operations on odd-numbered floating-point registers by default
4100      when using the FPXX ABI.  */
4101   if (file_mips_opts.oddspreg < 0)
4102     {
4103       if (file_mips_opts.fp == 0)
4104         file_mips_opts.oddspreg = 0;
4105       else
4106         file_mips_opts.oddspreg = 1;
4107     }
4108
4109   /* End of GCC-shared inference code.  */
4110
4111   /* This flag is set when we have a 64-bit capable CPU but use only
4112      32-bit wide registers.  Note that EABI does not use it.  */
4113   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4114       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4115           || mips_abi == O32_ABI))
4116     mips_32bitmode = 1;
4117
4118   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4119     as_bad (_("trap exception not supported at ISA 1"));
4120
4121   /* If the selected architecture includes support for ASEs, enable
4122      generation of code for them.  */
4123   if (file_mips_opts.mips16 == -1)
4124     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4125   if (file_mips_opts.micromips == -1)
4126     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4127                                 ? 1 : 0;
4128
4129   if (mips_nan2008 == -1)
4130     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4131   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4132     as_fatal (_("`%s' does not support legacy NaN"),
4133               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4134
4135   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4136      being selected implicitly.  */
4137   if (file_mips_opts.fp != 64)
4138     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4139
4140   /* If the user didn't explicitly select or deselect a particular ASE,
4141      use the default setting for the CPU.  */
4142   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
4143
4144   /* Set up the current options.  These may change throughout assembly.  */
4145   mips_opts = file_mips_opts;
4146
4147   mips_check_isa_supports_ases ();
4148   mips_check_options (&file_mips_opts, TRUE);
4149   file_mips_opts_checked = TRUE;
4150
4151   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4152     as_warn (_("could not set architecture and machine"));
4153 }
4154
4155 void
4156 md_assemble (char *str)
4157 {
4158   struct mips_cl_insn insn;
4159   bfd_reloc_code_real_type unused_reloc[3]
4160     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4161
4162   file_mips_check_options ();
4163
4164   imm_expr.X_op = O_absent;
4165   offset_expr.X_op = O_absent;
4166   offset_reloc[0] = BFD_RELOC_UNUSED;
4167   offset_reloc[1] = BFD_RELOC_UNUSED;
4168   offset_reloc[2] = BFD_RELOC_UNUSED;
4169
4170   mips_mark_labels ();
4171   mips_assembling_insn = TRUE;
4172   clear_insn_error ();
4173
4174   if (mips_opts.mips16)
4175     mips16_ip (str, &insn);
4176   else
4177     {
4178       mips_ip (str, &insn);
4179       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4180             str, insn.insn_opcode));
4181     }
4182
4183   if (insn_error.msg)
4184     report_insn_error (str);
4185   else if (insn.insn_mo->pinfo == INSN_MACRO)
4186     {
4187       macro_start ();
4188       if (mips_opts.mips16)
4189         mips16_macro (&insn);
4190       else
4191         macro (&insn, str);
4192       macro_end ();
4193     }
4194   else
4195     {
4196       if (offset_expr.X_op != O_absent)
4197         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4198       else
4199         append_insn (&insn, NULL, unused_reloc, FALSE);
4200     }
4201
4202   mips_assembling_insn = FALSE;
4203 }
4204
4205 /* Convenience functions for abstracting away the differences between
4206    MIPS16 and non-MIPS16 relocations.  */
4207
4208 static inline bfd_boolean
4209 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4210 {
4211   switch (reloc)
4212     {
4213     case BFD_RELOC_MIPS16_JMP:
4214     case BFD_RELOC_MIPS16_GPREL:
4215     case BFD_RELOC_MIPS16_GOT16:
4216     case BFD_RELOC_MIPS16_CALL16:
4217     case BFD_RELOC_MIPS16_HI16_S:
4218     case BFD_RELOC_MIPS16_HI16:
4219     case BFD_RELOC_MIPS16_LO16:
4220     case BFD_RELOC_MIPS16_16_PCREL_S1:
4221       return TRUE;
4222
4223     default:
4224       return FALSE;
4225     }
4226 }
4227
4228 static inline bfd_boolean
4229 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4230 {
4231   switch (reloc)
4232     {
4233     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4234     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4235     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4236     case BFD_RELOC_MICROMIPS_GPREL16:
4237     case BFD_RELOC_MICROMIPS_JMP:
4238     case BFD_RELOC_MICROMIPS_HI16:
4239     case BFD_RELOC_MICROMIPS_HI16_S:
4240     case BFD_RELOC_MICROMIPS_LO16:
4241     case BFD_RELOC_MICROMIPS_LITERAL:
4242     case BFD_RELOC_MICROMIPS_GOT16:
4243     case BFD_RELOC_MICROMIPS_CALL16:
4244     case BFD_RELOC_MICROMIPS_GOT_HI16:
4245     case BFD_RELOC_MICROMIPS_GOT_LO16:
4246     case BFD_RELOC_MICROMIPS_CALL_HI16:
4247     case BFD_RELOC_MICROMIPS_CALL_LO16:
4248     case BFD_RELOC_MICROMIPS_SUB:
4249     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4250     case BFD_RELOC_MICROMIPS_GOT_OFST:
4251     case BFD_RELOC_MICROMIPS_GOT_DISP:
4252     case BFD_RELOC_MICROMIPS_HIGHEST:
4253     case BFD_RELOC_MICROMIPS_HIGHER:
4254     case BFD_RELOC_MICROMIPS_SCN_DISP:
4255     case BFD_RELOC_MICROMIPS_JALR:
4256       return TRUE;
4257
4258     default:
4259       return FALSE;
4260     }
4261 }
4262
4263 static inline bfd_boolean
4264 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4265 {
4266   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4267 }
4268
4269 static inline bfd_boolean
4270 b_reloc_p (bfd_reloc_code_real_type reloc)
4271 {
4272   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4273           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4274           || reloc == BFD_RELOC_16_PCREL_S2
4275           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4276           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4277           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4278           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4279 }
4280
4281 static inline bfd_boolean
4282 got16_reloc_p (bfd_reloc_code_real_type reloc)
4283 {
4284   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4285           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4286 }
4287
4288 static inline bfd_boolean
4289 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4290 {
4291   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4292           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4293 }
4294
4295 static inline bfd_boolean
4296 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4297 {
4298   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4299           || reloc == BFD_RELOC_MICROMIPS_LO16);
4300 }
4301
4302 static inline bfd_boolean
4303 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4304 {
4305   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4306 }
4307
4308 static inline bfd_boolean
4309 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4310 {
4311   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4312           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4313 }
4314
4315 /* Return true if RELOC is a PC-relative relocation that does not have
4316    full address range.  */
4317
4318 static inline bfd_boolean
4319 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4320 {
4321   switch (reloc)
4322     {
4323     case BFD_RELOC_16_PCREL_S2:
4324     case BFD_RELOC_MIPS16_16_PCREL_S1:
4325     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4326     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4327     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4328     case BFD_RELOC_MIPS_21_PCREL_S2:
4329     case BFD_RELOC_MIPS_26_PCREL_S2:
4330     case BFD_RELOC_MIPS_18_PCREL_S3:
4331     case BFD_RELOC_MIPS_19_PCREL_S2:
4332       return TRUE;
4333
4334     case BFD_RELOC_32_PCREL:
4335     case BFD_RELOC_HI16_S_PCREL:
4336     case BFD_RELOC_LO16_PCREL:
4337       return HAVE_64BIT_ADDRESSES;
4338
4339     default:
4340       return FALSE;
4341     }
4342 }
4343
4344 /* Return true if the given relocation might need a matching %lo().
4345    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4346    need a matching %lo() when applied to local symbols.  */
4347
4348 static inline bfd_boolean
4349 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4350 {
4351   return (HAVE_IN_PLACE_ADDENDS
4352           && (hi16_reloc_p (reloc)
4353               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4354                  all GOT16 relocations evaluate to "G".  */
4355               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4356 }
4357
4358 /* Return the type of %lo() reloc needed by RELOC, given that
4359    reloc_needs_lo_p.  */
4360
4361 static inline bfd_reloc_code_real_type
4362 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4363 {
4364   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4365           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4366              : BFD_RELOC_LO16));
4367 }
4368
4369 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4370    relocation.  */
4371
4372 static inline bfd_boolean
4373 fixup_has_matching_lo_p (fixS *fixp)
4374 {
4375   return (fixp->fx_next != NULL
4376           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4377           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4378           && fixp->fx_offset == fixp->fx_next->fx_offset);
4379 }
4380
4381 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4382    says whether the labels refer to text or data.  */
4383
4384 static void
4385 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4386 {
4387   struct insn_label_list *l;
4388   valueT val;
4389
4390   for (l = labels; l != NULL; l = l->next)
4391     {
4392       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4393       symbol_set_frag (l->label, frag_now);
4394       val = (valueT) frag_now_fix ();
4395       /* MIPS16/microMIPS text labels are stored as odd.  */
4396       if (text_p && HAVE_CODE_COMPRESSION)
4397         ++val;
4398       S_SET_VALUE (l->label, val);
4399     }
4400 }
4401
4402 /* Move all labels in insn_labels to the current insertion point
4403    and treat them as text labels.  */
4404
4405 static void
4406 mips_move_text_labels (void)
4407 {
4408   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4409 }
4410
4411 /* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4412
4413 static bfd_boolean
4414 s_is_linkonce (symbolS *sym, segT from_seg)
4415 {
4416   bfd_boolean linkonce = FALSE;
4417   segT symseg = S_GET_SEGMENT (sym);
4418
4419   if (symseg != from_seg && !S_IS_LOCAL (sym))
4420     {
4421       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4422         linkonce = TRUE;
4423       /* The GNU toolchain uses an extension for ELF: a section
4424          beginning with the magic string .gnu.linkonce is a
4425          linkonce section.  */
4426       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4427                    sizeof ".gnu.linkonce" - 1) == 0)
4428         linkonce = TRUE;
4429     }
4430   return linkonce;
4431 }
4432
4433 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4434    linker to handle them specially, such as generating jalx instructions
4435    when needed.  We also make them odd for the duration of the assembly,
4436    in order to generate the right sort of code.  We will make them even
4437    in the adjust_symtab routine, while leaving them marked.  This is
4438    convenient for the debugger and the disassembler.  The linker knows
4439    to make them odd again.  */
4440
4441 static void
4442 mips_compressed_mark_label (symbolS *label)
4443 {
4444   gas_assert (HAVE_CODE_COMPRESSION);
4445
4446   if (mips_opts.mips16)
4447     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4448   else
4449     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4450   if ((S_GET_VALUE (label) & 1) == 0
4451       /* Don't adjust the address if the label is global or weak, or
4452          in a link-once section, since we'll be emitting symbol reloc
4453          references to it which will be patched up by the linker, and
4454          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4455       && !S_IS_WEAK (label)
4456       && !S_IS_EXTERNAL (label)
4457       && !s_is_linkonce (label, now_seg))
4458     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4459 }
4460
4461 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4462
4463 static void
4464 mips_compressed_mark_labels (void)
4465 {
4466   struct insn_label_list *l;
4467
4468   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4469     mips_compressed_mark_label (l->label);
4470 }
4471
4472 /* End the current frag.  Make it a variant frag and record the
4473    relaxation info.  */
4474
4475 static void
4476 relax_close_frag (void)
4477 {
4478   mips_macro_warning.first_frag = frag_now;
4479   frag_var (rs_machine_dependent, 0, 0,
4480             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4481                           mips_pic != NO_PIC),
4482             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4483
4484   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4485   mips_relax.first_fixup = 0;
4486 }
4487
4488 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4489    See the comment above RELAX_ENCODE for more details.  */
4490
4491 static void
4492 relax_start (symbolS *symbol)
4493 {
4494   gas_assert (mips_relax.sequence == 0);
4495   mips_relax.sequence = 1;
4496   mips_relax.symbol = symbol;
4497 }
4498
4499 /* Start generating the second version of a relaxable sequence.
4500    See the comment above RELAX_ENCODE for more details.  */
4501
4502 static void
4503 relax_switch (void)
4504 {
4505   gas_assert (mips_relax.sequence == 1);
4506   mips_relax.sequence = 2;
4507 }
4508
4509 /* End the current relaxable sequence.  */
4510
4511 static void
4512 relax_end (void)
4513 {
4514   gas_assert (mips_relax.sequence == 2);
4515   relax_close_frag ();
4516   mips_relax.sequence = 0;
4517 }
4518
4519 /* Return true if IP is a delayed branch or jump.  */
4520
4521 static inline bfd_boolean
4522 delayed_branch_p (const struct mips_cl_insn *ip)
4523 {
4524   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4525                                 | INSN_COND_BRANCH_DELAY
4526                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4527 }
4528
4529 /* Return true if IP is a compact branch or jump.  */
4530
4531 static inline bfd_boolean
4532 compact_branch_p (const struct mips_cl_insn *ip)
4533 {
4534   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4535                                  | INSN2_COND_BRANCH)) != 0;
4536 }
4537
4538 /* Return true if IP is an unconditional branch or jump.  */
4539
4540 static inline bfd_boolean
4541 uncond_branch_p (const struct mips_cl_insn *ip)
4542 {
4543   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4544           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4545 }
4546
4547 /* Return true if IP is a branch-likely instruction.  */
4548
4549 static inline bfd_boolean
4550 branch_likely_p (const struct mips_cl_insn *ip)
4551 {
4552   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4553 }
4554
4555 /* Return the type of nop that should be used to fill the delay slot
4556    of delayed branch IP.  */
4557
4558 static struct mips_cl_insn *
4559 get_delay_slot_nop (const struct mips_cl_insn *ip)
4560 {
4561   if (mips_opts.micromips
4562       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4563     return &micromips_nop32_insn;
4564   return NOP_INSN;
4565 }
4566
4567 /* Return a mask that has bit N set if OPCODE reads the register(s)
4568    in operand N.  */
4569
4570 static unsigned int
4571 insn_read_mask (const struct mips_opcode *opcode)
4572 {
4573   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4574 }
4575
4576 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4577    in operand N.  */
4578
4579 static unsigned int
4580 insn_write_mask (const struct mips_opcode *opcode)
4581 {
4582   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4583 }
4584
4585 /* Return a mask of the registers specified by operand OPERAND of INSN.
4586    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4587    is set.  */
4588
4589 static unsigned int
4590 operand_reg_mask (const struct mips_cl_insn *insn,
4591                   const struct mips_operand *operand,
4592                   unsigned int type_mask)
4593 {
4594   unsigned int uval, vsel;
4595
4596   switch (operand->type)
4597     {
4598     case OP_INT:
4599     case OP_MAPPED_INT:
4600     case OP_MSB:
4601     case OP_PCREL:
4602     case OP_PERF_REG:
4603     case OP_ADDIUSP_INT:
4604     case OP_ENTRY_EXIT_LIST:
4605     case OP_REPEAT_DEST_REG:
4606     case OP_REPEAT_PREV_REG:
4607     case OP_PC:
4608     case OP_VU0_SUFFIX:
4609     case OP_VU0_MATCH_SUFFIX:
4610     case OP_IMM_INDEX:
4611       abort ();
4612
4613     case OP_REG28:
4614       return 1 << 28;
4615
4616     case OP_REG:
4617     case OP_OPTIONAL_REG:
4618       {
4619         const struct mips_reg_operand *reg_op;
4620
4621         reg_op = (const struct mips_reg_operand *) operand;
4622         if (!(type_mask & (1 << reg_op->reg_type)))
4623           return 0;
4624         uval = insn_extract_operand (insn, operand);
4625         return 1 << mips_decode_reg_operand (reg_op, uval);
4626       }
4627
4628     case OP_REG_PAIR:
4629       {
4630         const struct mips_reg_pair_operand *pair_op;
4631
4632         pair_op = (const struct mips_reg_pair_operand *) operand;
4633         if (!(type_mask & (1 << pair_op->reg_type)))
4634           return 0;
4635         uval = insn_extract_operand (insn, operand);
4636         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4637       }
4638
4639     case OP_CLO_CLZ_DEST:
4640       if (!(type_mask & (1 << OP_REG_GP)))
4641         return 0;
4642       uval = insn_extract_operand (insn, operand);
4643       return (1 << (uval & 31)) | (1 << (uval >> 5));
4644
4645     case OP_SAME_RS_RT:
4646       if (!(type_mask & (1 << OP_REG_GP)))
4647         return 0;
4648       uval = insn_extract_operand (insn, operand);
4649       gas_assert ((uval & 31) == (uval >> 5));
4650       return 1 << (uval & 31);
4651
4652     case OP_CHECK_PREV:
4653     case OP_NON_ZERO_REG:
4654       if (!(type_mask & (1 << OP_REG_GP)))
4655         return 0;
4656       uval = insn_extract_operand (insn, operand);
4657       return 1 << (uval & 31);
4658
4659     case OP_LWM_SWM_LIST:
4660       abort ();
4661
4662     case OP_SAVE_RESTORE_LIST:
4663       abort ();
4664
4665     case OP_MDMX_IMM_REG:
4666       if (!(type_mask & (1 << OP_REG_VEC)))
4667         return 0;
4668       uval = insn_extract_operand (insn, operand);
4669       vsel = uval >> 5;
4670       if ((vsel & 0x18) == 0x18)
4671         return 0;
4672       return 1 << (uval & 31);
4673
4674     case OP_REG_INDEX:
4675       if (!(type_mask & (1 << OP_REG_GP)))
4676         return 0;
4677       return 1 << insn_extract_operand (insn, operand);
4678     }
4679   abort ();
4680 }
4681
4682 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4683    where bit N of OPNO_MASK is set if operand N should be included.
4684    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4685    is set.  */
4686
4687 static unsigned int
4688 insn_reg_mask (const struct mips_cl_insn *insn,
4689                unsigned int type_mask, unsigned int opno_mask)
4690 {
4691   unsigned int opno, reg_mask;
4692
4693   opno = 0;
4694   reg_mask = 0;
4695   while (opno_mask != 0)
4696     {
4697       if (opno_mask & 1)
4698         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4699       opno_mask >>= 1;
4700       opno += 1;
4701     }
4702   return reg_mask;
4703 }
4704
4705 /* Return the mask of core registers that IP reads.  */
4706
4707 static unsigned int
4708 gpr_read_mask (const struct mips_cl_insn *ip)
4709 {
4710   unsigned long pinfo, pinfo2;
4711   unsigned int mask;
4712
4713   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4714   pinfo = ip->insn_mo->pinfo;
4715   pinfo2 = ip->insn_mo->pinfo2;
4716   if (pinfo & INSN_UDI)
4717     {
4718       /* UDI instructions have traditionally been assumed to read RS
4719          and RT.  */
4720       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4721       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4722     }
4723   if (pinfo & INSN_READ_GPR_24)
4724     mask |= 1 << 24;
4725   if (pinfo2 & INSN2_READ_GPR_16)
4726     mask |= 1 << 16;
4727   if (pinfo2 & INSN2_READ_SP)
4728     mask |= 1 << SP;
4729   if (pinfo2 & INSN2_READ_GPR_31)
4730     mask |= 1 << 31;
4731   /* Don't include register 0.  */
4732   return mask & ~1;
4733 }
4734
4735 /* Return the mask of core registers that IP writes.  */
4736
4737 static unsigned int
4738 gpr_write_mask (const struct mips_cl_insn *ip)
4739 {
4740   unsigned long pinfo, pinfo2;
4741   unsigned int mask;
4742
4743   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4744   pinfo = ip->insn_mo->pinfo;
4745   pinfo2 = ip->insn_mo->pinfo2;
4746   if (pinfo & INSN_WRITE_GPR_24)
4747     mask |= 1 << 24;
4748   if (pinfo & INSN_WRITE_GPR_31)
4749     mask |= 1 << 31;
4750   if (pinfo & INSN_UDI)
4751     /* UDI instructions have traditionally been assumed to write to RD.  */
4752     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4753   if (pinfo2 & INSN2_WRITE_SP)
4754     mask |= 1 << SP;
4755   /* Don't include register 0.  */
4756   return mask & ~1;
4757 }
4758
4759 /* Return the mask of floating-point registers that IP reads.  */
4760
4761 static unsigned int
4762 fpr_read_mask (const struct mips_cl_insn *ip)
4763 {
4764   unsigned long pinfo;
4765   unsigned int mask;
4766
4767   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4768                              | (1 << OP_REG_MSA)),
4769                         insn_read_mask (ip->insn_mo));
4770   pinfo = ip->insn_mo->pinfo;
4771   /* Conservatively treat all operands to an FP_D instruction are doubles.
4772      (This is overly pessimistic for things like cvt.d.s.)  */
4773   if (FPR_SIZE != 64 && (pinfo & FP_D))
4774     mask |= mask << 1;
4775   return mask;
4776 }
4777
4778 /* Return the mask of floating-point registers that IP writes.  */
4779
4780 static unsigned int
4781 fpr_write_mask (const struct mips_cl_insn *ip)
4782 {
4783   unsigned long pinfo;
4784   unsigned int mask;
4785
4786   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4787                              | (1 << OP_REG_MSA)),
4788                         insn_write_mask (ip->insn_mo));
4789   pinfo = ip->insn_mo->pinfo;
4790   /* Conservatively treat all operands to an FP_D instruction are doubles.
4791      (This is overly pessimistic for things like cvt.s.d.)  */
4792   if (FPR_SIZE != 64 && (pinfo & FP_D))
4793     mask |= mask << 1;
4794   return mask;
4795 }
4796
4797 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4798    Check whether that is allowed.  */
4799
4800 static bfd_boolean
4801 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4802 {
4803   const char *s = insn->name;
4804   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4805                           || FPR_SIZE == 64)
4806                          && mips_opts.oddspreg;
4807
4808   if (insn->pinfo == INSN_MACRO)
4809     /* Let a macro pass, we'll catch it later when it is expanded.  */
4810     return TRUE;
4811
4812   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4813      otherwise it depends on oddspreg.  */
4814   if ((insn->pinfo & FP_S)
4815       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4816                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4817     return FPR_SIZE == 32 || oddspreg;
4818
4819   /* Allow odd registers for single-precision ops and double-precision if the
4820      floating-point registers are 64-bit wide.  */
4821   switch (insn->pinfo & (FP_S | FP_D))
4822     {
4823     case FP_S:
4824     case 0:
4825       return oddspreg;
4826     case FP_D:
4827       return FPR_SIZE == 64;
4828     default:
4829       break;
4830     }
4831
4832   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4833   s = strchr (insn->name, '.');
4834   if (s != NULL && opnum == 2)
4835     s = strchr (s + 1, '.');
4836   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4837     return oddspreg;
4838
4839   return FPR_SIZE == 64;
4840 }
4841
4842 /* Information about an instruction argument that we're trying to match.  */
4843 struct mips_arg_info
4844 {
4845   /* The instruction so far.  */
4846   struct mips_cl_insn *insn;
4847
4848   /* The first unconsumed operand token.  */
4849   struct mips_operand_token *token;
4850
4851   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4852   int opnum;
4853
4854   /* The 1-based argument number, for error reporting.  This does not
4855      count elided optional registers, etc..  */
4856   int argnum;
4857
4858   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4859   unsigned int last_regno;
4860
4861   /* If the first operand was an OP_REG, this is the register that it
4862      specified, otherwise it is ILLEGAL_REG.  */
4863   unsigned int dest_regno;
4864
4865   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4866      where it gives the lsb position.  */
4867   unsigned int last_op_int;
4868
4869   /* If true, match routines should assume that no later instruction
4870      alternative matches and should therefore be as accommodating as
4871      possible.  Match routines should not report errors if something
4872      is only invalid for !LAX_MATCH.  */
4873   bfd_boolean lax_match;
4874
4875   /* True if a reference to the current AT register was seen.  */
4876   bfd_boolean seen_at;
4877 };
4878
4879 /* Record that the argument is out of range.  */
4880
4881 static void
4882 match_out_of_range (struct mips_arg_info *arg)
4883 {
4884   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4885 }
4886
4887 /* Record that the argument isn't constant but needs to be.  */
4888
4889 static void
4890 match_not_constant (struct mips_arg_info *arg)
4891 {
4892   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4893                     arg->argnum);
4894 }
4895
4896 /* Try to match an OT_CHAR token for character CH.  Consume the token
4897    and return true on success, otherwise return false.  */
4898
4899 static bfd_boolean
4900 match_char (struct mips_arg_info *arg, char ch)
4901 {
4902   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4903     {
4904       ++arg->token;
4905       if (ch == ',')
4906         arg->argnum += 1;
4907       return TRUE;
4908     }
4909   return FALSE;
4910 }
4911
4912 /* Try to get an expression from the next tokens in ARG.  Consume the
4913    tokens and return true on success, storing the expression value in
4914    VALUE and relocation types in R.  */
4915
4916 static bfd_boolean
4917 match_expression (struct mips_arg_info *arg, expressionS *value,
4918                   bfd_reloc_code_real_type *r)
4919 {
4920   /* If the next token is a '(' that was parsed as being part of a base
4921      expression, assume we have an elided offset.  The later match will fail
4922      if this turns out to be wrong.  */
4923   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4924     {
4925       value->X_op = O_constant;
4926       value->X_add_number = 0;
4927       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4928       return TRUE;
4929     }
4930
4931   /* Reject register-based expressions such as "0+$2" and "(($2))".
4932      For plain registers the default error seems more appropriate.  */
4933   if (arg->token->type == OT_INTEGER
4934       && arg->token->u.integer.value.X_op == O_register)
4935     {
4936       set_insn_error (arg->argnum, _("register value used as expression"));
4937       return FALSE;
4938     }
4939
4940   if (arg->token->type == OT_INTEGER)
4941     {
4942       *value = arg->token->u.integer.value;
4943       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4944       ++arg->token;
4945       return TRUE;
4946     }
4947
4948   set_insn_error_i
4949     (arg->argnum, _("operand %d must be an immediate expression"),
4950      arg->argnum);
4951   return FALSE;
4952 }
4953
4954 /* Try to get a constant expression from the next tokens in ARG.  Consume
4955    the tokens and return true on success, storing the constant value
4956    in *VALUE.  */
4957
4958 static bfd_boolean
4959 match_const_int (struct mips_arg_info *arg, offsetT *value)
4960 {
4961   expressionS ex;
4962   bfd_reloc_code_real_type r[3];
4963
4964   if (!match_expression (arg, &ex, r))
4965     return FALSE;
4966
4967   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4968     *value = ex.X_add_number;
4969   else
4970     {
4971       if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_big)
4972         match_out_of_range (arg);
4973       else
4974         match_not_constant (arg);
4975       return FALSE;
4976     }
4977   return TRUE;
4978 }
4979
4980 /* Return the RTYPE_* flags for a register operand of type TYPE that
4981    appears in instruction OPCODE.  */
4982
4983 static unsigned int
4984 convert_reg_type (const struct mips_opcode *opcode,
4985                   enum mips_reg_operand_type type)
4986 {
4987   switch (type)
4988     {
4989     case OP_REG_GP:
4990       return RTYPE_NUM | RTYPE_GP;
4991
4992     case OP_REG_FP:
4993       /* Allow vector register names for MDMX if the instruction is a 64-bit
4994          FPR load, store or move (including moves to and from GPRs).  */
4995       if ((mips_opts.ase & ASE_MDMX)
4996           && (opcode->pinfo & FP_D)
4997           && (opcode->pinfo & (INSN_COPROC_MOVE
4998                                | INSN_COPROC_MEMORY_DELAY
4999                                | INSN_LOAD_COPROC
5000                                | INSN_LOAD_MEMORY
5001                                | INSN_STORE_MEMORY)))
5002         return RTYPE_FPU | RTYPE_VEC;
5003       return RTYPE_FPU;
5004
5005     case OP_REG_CCC:
5006       if (opcode->pinfo & (FP_D | FP_S))
5007         return RTYPE_CCC | RTYPE_FCC;
5008       return RTYPE_CCC;
5009
5010     case OP_REG_VEC:
5011       if (opcode->membership & INSN_5400)
5012         return RTYPE_FPU;
5013       return RTYPE_FPU | RTYPE_VEC;
5014
5015     case OP_REG_ACC:
5016       return RTYPE_ACC;
5017
5018     case OP_REG_COPRO:
5019       if (opcode->name[strlen (opcode->name) - 1] == '0')
5020         return RTYPE_NUM | RTYPE_CP0;
5021       return RTYPE_NUM;
5022
5023     case OP_REG_HW:
5024       return RTYPE_NUM;
5025
5026     case OP_REG_VI:
5027       return RTYPE_NUM | RTYPE_VI;
5028
5029     case OP_REG_VF:
5030       return RTYPE_NUM | RTYPE_VF;
5031
5032     case OP_REG_R5900_I:
5033       return RTYPE_R5900_I;
5034
5035     case OP_REG_R5900_Q:
5036       return RTYPE_R5900_Q;
5037
5038     case OP_REG_R5900_R:
5039       return RTYPE_R5900_R;
5040
5041     case OP_REG_R5900_ACC:
5042       return RTYPE_R5900_ACC;
5043
5044     case OP_REG_MSA:
5045       return RTYPE_MSA;
5046
5047     case OP_REG_MSA_CTRL:
5048       return RTYPE_NUM;
5049     }
5050   abort ();
5051 }
5052
5053 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
5054
5055 static void
5056 check_regno (struct mips_arg_info *arg,
5057              enum mips_reg_operand_type type, unsigned int regno)
5058 {
5059   if (AT && type == OP_REG_GP && regno == AT)
5060     arg->seen_at = TRUE;
5061
5062   if (type == OP_REG_FP
5063       && (regno & 1) != 0
5064       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
5065     {
5066       /* This was a warning prior to introducing O32 FPXX and FP64 support
5067          so maintain a warning for FP32 but raise an error for the new
5068          cases.  */
5069       if (FPR_SIZE == 32)
5070         as_warn (_("float register should be even, was %d"), regno);
5071       else
5072         as_bad (_("float register should be even, was %d"), regno);
5073     }
5074
5075   if (type == OP_REG_CCC)
5076     {
5077       const char *name;
5078       size_t length;
5079
5080       name = arg->insn->insn_mo->name;
5081       length = strlen (name);
5082       if ((regno & 1) != 0
5083           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
5084               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
5085         as_warn (_("condition code register should be even for %s, was %d"),
5086                  name, regno);
5087
5088       if ((regno & 3) != 0
5089           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
5090         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
5091                  name, regno);
5092     }
5093 }
5094
5095 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
5096    a register of type TYPE.  Return true on success, storing the register
5097    number in *REGNO and warning about any dubious uses.  */
5098
5099 static bfd_boolean
5100 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5101              unsigned int symval, unsigned int *regno)
5102 {
5103   if (type == OP_REG_VEC)
5104     symval = mips_prefer_vec_regno (symval);
5105   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
5106     return FALSE;
5107
5108   *regno = symval & RNUM_MASK;
5109   check_regno (arg, type, *regno);
5110   return TRUE;
5111 }
5112
5113 /* Try to interpret the next token in ARG as a register of type TYPE.
5114    Consume the token and return true on success, storing the register
5115    number in *REGNO.  Return false on failure.  */
5116
5117 static bfd_boolean
5118 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5119            unsigned int *regno)
5120 {
5121   if (arg->token->type == OT_REG
5122       && match_regno (arg, type, arg->token->u.regno, regno))
5123     {
5124       ++arg->token;
5125       return TRUE;
5126     }
5127   return FALSE;
5128 }
5129
5130 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
5131    Consume the token and return true on success, storing the register numbers
5132    in *REGNO1 and *REGNO2.  Return false on failure.  */
5133
5134 static bfd_boolean
5135 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5136                  unsigned int *regno1, unsigned int *regno2)
5137 {
5138   if (match_reg (arg, type, regno1))
5139     {
5140       *regno2 = *regno1;
5141       return TRUE;
5142     }
5143   if (arg->token->type == OT_REG_RANGE
5144       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5145       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5146       && *regno1 <= *regno2)
5147     {
5148       ++arg->token;
5149       return TRUE;
5150     }
5151   return FALSE;
5152 }
5153
5154 /* OP_INT matcher.  */
5155
5156 static bfd_boolean
5157 match_int_operand (struct mips_arg_info *arg,
5158                    const struct mips_operand *operand_base)
5159 {
5160   const struct mips_int_operand *operand;
5161   unsigned int uval;
5162   int min_val, max_val, factor;
5163   offsetT sval;
5164
5165   operand = (const struct mips_int_operand *) operand_base;
5166   factor = 1 << operand->shift;
5167   min_val = mips_int_operand_min (operand);
5168   max_val = mips_int_operand_max (operand);
5169
5170   if (operand_base->lsb == 0
5171       && operand_base->size == 16
5172       && operand->shift == 0
5173       && operand->bias == 0
5174       && (operand->max_val == 32767 || operand->max_val == 65535))
5175     {
5176       /* The operand can be relocated.  */
5177       if (!match_expression (arg, &offset_expr, offset_reloc))
5178         return FALSE;
5179
5180       if (offset_expr.X_op == O_big)
5181         {
5182           match_out_of_range (arg);
5183           return FALSE;
5184         }
5185
5186       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5187         /* Relocation operators were used.  Accept the argument and
5188            leave the relocation value in offset_expr and offset_relocs
5189            for the caller to process.  */
5190         return TRUE;
5191
5192       if (offset_expr.X_op != O_constant)
5193         {
5194           /* Accept non-constant operands if no later alternative matches,
5195              leaving it for the caller to process.  */
5196           if (!arg->lax_match)
5197             {
5198               match_not_constant (arg);
5199               return FALSE;
5200             }
5201           offset_reloc[0] = BFD_RELOC_LO16;
5202           return TRUE;
5203         }
5204
5205       /* Clear the global state; we're going to install the operand
5206          ourselves.  */
5207       sval = offset_expr.X_add_number;
5208       offset_expr.X_op = O_absent;
5209
5210       /* For compatibility with older assemblers, we accept
5211          0x8000-0xffff as signed 16-bit numbers when only
5212          signed numbers are allowed.  */
5213       if (sval > max_val)
5214         {
5215           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5216           if (!arg->lax_match && sval <= max_val)
5217             {
5218               match_out_of_range (arg);
5219               return FALSE;
5220             }
5221         }
5222     }
5223   else
5224     {
5225       if (!match_const_int (arg, &sval))
5226         return FALSE;
5227     }
5228
5229   arg->last_op_int = sval;
5230
5231   if (sval < min_val || sval > max_val || sval % factor)
5232     {
5233       match_out_of_range (arg);
5234       return FALSE;
5235     }
5236
5237   uval = (unsigned int) sval >> operand->shift;
5238   uval -= operand->bias;
5239
5240   /* Handle -mfix-cn63xxp1.  */
5241   if (arg->opnum == 1
5242       && mips_fix_cn63xxp1
5243       && !mips_opts.micromips
5244       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5245     switch (uval)
5246       {
5247       case 5:
5248       case 25:
5249       case 26:
5250       case 27:
5251       case 28:
5252       case 29:
5253       case 30:
5254       case 31:
5255         /* These are ok.  */
5256         break;
5257
5258       default:
5259         /* The rest must be changed to 28.  */
5260         uval = 28;
5261         break;
5262       }
5263
5264   insn_insert_operand (arg->insn, operand_base, uval);
5265   return TRUE;
5266 }
5267
5268 /* OP_MAPPED_INT matcher.  */
5269
5270 static bfd_boolean
5271 match_mapped_int_operand (struct mips_arg_info *arg,
5272                           const struct mips_operand *operand_base)
5273 {
5274   const struct mips_mapped_int_operand *operand;
5275   unsigned int uval, num_vals;
5276   offsetT sval;
5277
5278   operand = (const struct mips_mapped_int_operand *) operand_base;
5279   if (!match_const_int (arg, &sval))
5280     return FALSE;
5281
5282   num_vals = 1 << operand_base->size;
5283   for (uval = 0; uval < num_vals; uval++)
5284     if (operand->int_map[uval] == sval)
5285       break;
5286   if (uval == num_vals)
5287     {
5288       match_out_of_range (arg);
5289       return FALSE;
5290     }
5291
5292   insn_insert_operand (arg->insn, operand_base, uval);
5293   return TRUE;
5294 }
5295
5296 /* OP_MSB matcher.  */
5297
5298 static bfd_boolean
5299 match_msb_operand (struct mips_arg_info *arg,
5300                    const struct mips_operand *operand_base)
5301 {
5302   const struct mips_msb_operand *operand;
5303   int min_val, max_val, max_high;
5304   offsetT size, sval, high;
5305
5306   operand = (const struct mips_msb_operand *) operand_base;
5307   min_val = operand->bias;
5308   max_val = min_val + (1 << operand_base->size) - 1;
5309   max_high = operand->opsize;
5310
5311   if (!match_const_int (arg, &size))
5312     return FALSE;
5313
5314   high = size + arg->last_op_int;
5315   sval = operand->add_lsb ? high : size;
5316
5317   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5318     {
5319       match_out_of_range (arg);
5320       return FALSE;
5321     }
5322   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5323   return TRUE;
5324 }
5325
5326 /* OP_REG matcher.  */
5327
5328 static bfd_boolean
5329 match_reg_operand (struct mips_arg_info *arg,
5330                    const struct mips_operand *operand_base)
5331 {
5332   const struct mips_reg_operand *operand;
5333   unsigned int regno, uval, num_vals;
5334
5335   operand = (const struct mips_reg_operand *) operand_base;
5336   if (!match_reg (arg, operand->reg_type, &regno))
5337     return FALSE;
5338
5339   if (operand->reg_map)
5340     {
5341       num_vals = 1 << operand->root.size;
5342       for (uval = 0; uval < num_vals; uval++)
5343         if (operand->reg_map[uval] == regno)
5344           break;
5345       if (num_vals == uval)
5346         return FALSE;
5347     }
5348   else
5349     uval = regno;
5350
5351   arg->last_regno = regno;
5352   if (arg->opnum == 1)
5353     arg->dest_regno = regno;
5354   insn_insert_operand (arg->insn, operand_base, uval);
5355   return TRUE;
5356 }
5357
5358 /* OP_REG_PAIR matcher.  */
5359
5360 static bfd_boolean
5361 match_reg_pair_operand (struct mips_arg_info *arg,
5362                         const struct mips_operand *operand_base)
5363 {
5364   const struct mips_reg_pair_operand *operand;
5365   unsigned int regno1, regno2, uval, num_vals;
5366
5367   operand = (const struct mips_reg_pair_operand *) operand_base;
5368   if (!match_reg (arg, operand->reg_type, &regno1)
5369       || !match_char (arg, ',')
5370       || !match_reg (arg, operand->reg_type, &regno2))
5371     return FALSE;
5372
5373   num_vals = 1 << operand_base->size;
5374   for (uval = 0; uval < num_vals; uval++)
5375     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5376       break;
5377   if (uval == num_vals)
5378     return FALSE;
5379
5380   insn_insert_operand (arg->insn, operand_base, uval);
5381   return TRUE;
5382 }
5383
5384 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5385
5386 static bfd_boolean
5387 match_pcrel_operand (struct mips_arg_info *arg)
5388 {
5389   bfd_reloc_code_real_type r[3];
5390
5391   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5392 }
5393
5394 /* OP_PERF_REG matcher.  */
5395
5396 static bfd_boolean
5397 match_perf_reg_operand (struct mips_arg_info *arg,
5398                         const struct mips_operand *operand)
5399 {
5400   offsetT sval;
5401
5402   if (!match_const_int (arg, &sval))
5403     return FALSE;
5404
5405   if (sval != 0
5406       && (sval != 1
5407           || (mips_opts.arch == CPU_R5900
5408               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5409                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5410     {
5411       set_insn_error (arg->argnum, _("invalid performance register"));
5412       return FALSE;
5413     }
5414
5415   insn_insert_operand (arg->insn, operand, sval);
5416   return TRUE;
5417 }
5418
5419 /* OP_ADDIUSP matcher.  */
5420
5421 static bfd_boolean
5422 match_addiusp_operand (struct mips_arg_info *arg,
5423                        const struct mips_operand *operand)
5424 {
5425   offsetT sval;
5426   unsigned int uval;
5427
5428   if (!match_const_int (arg, &sval))
5429     return FALSE;
5430
5431   if (sval % 4)
5432     {
5433       match_out_of_range (arg);
5434       return FALSE;
5435     }
5436
5437   sval /= 4;
5438   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5439     {
5440       match_out_of_range (arg);
5441       return FALSE;
5442     }
5443
5444   uval = (unsigned int) sval;
5445   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5446   insn_insert_operand (arg->insn, operand, uval);
5447   return TRUE;
5448 }
5449
5450 /* OP_CLO_CLZ_DEST matcher.  */
5451
5452 static bfd_boolean
5453 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5454                             const struct mips_operand *operand)
5455 {
5456   unsigned int regno;
5457
5458   if (!match_reg (arg, OP_REG_GP, &regno))
5459     return FALSE;
5460
5461   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5462   return TRUE;
5463 }
5464
5465 /* OP_CHECK_PREV matcher.  */
5466
5467 static bfd_boolean
5468 match_check_prev_operand (struct mips_arg_info *arg,
5469                           const struct mips_operand *operand_base)
5470 {
5471   const struct mips_check_prev_operand *operand;
5472   unsigned int regno;
5473
5474   operand = (const struct mips_check_prev_operand *) operand_base;
5475
5476   if (!match_reg (arg, OP_REG_GP, &regno))
5477     return FALSE;
5478
5479   if (!operand->zero_ok && regno == 0)
5480     return FALSE;
5481
5482   if ((operand->less_than_ok && regno < arg->last_regno)
5483       || (operand->greater_than_ok && regno > arg->last_regno)
5484       || (operand->equal_ok && regno == arg->last_regno))
5485     {
5486       arg->last_regno = regno;
5487       insn_insert_operand (arg->insn, operand_base, regno);
5488       return TRUE;
5489     }
5490
5491   return FALSE;
5492 }
5493
5494 /* OP_SAME_RS_RT matcher.  */
5495
5496 static bfd_boolean
5497 match_same_rs_rt_operand (struct mips_arg_info *arg,
5498                           const struct mips_operand *operand)
5499 {
5500   unsigned int regno;
5501
5502   if (!match_reg (arg, OP_REG_GP, &regno))
5503     return FALSE;
5504
5505   if (regno == 0)
5506     {
5507       set_insn_error (arg->argnum, _("the source register must not be $0"));
5508       return FALSE;
5509     }
5510
5511   arg->last_regno = regno;
5512
5513   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5514   return TRUE;
5515 }
5516
5517 /* OP_LWM_SWM_LIST matcher.  */
5518
5519 static bfd_boolean
5520 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5521                             const struct mips_operand *operand)
5522 {
5523   unsigned int reglist, sregs, ra, regno1, regno2;
5524   struct mips_arg_info reset;
5525
5526   reglist = 0;
5527   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5528     return FALSE;
5529   do
5530     {
5531       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5532         {
5533           reglist |= 1 << FP;
5534           regno2 = S7;
5535         }
5536       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5537       reset = *arg;
5538     }
5539   while (match_char (arg, ',')
5540          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5541   *arg = reset;
5542
5543   if (operand->size == 2)
5544     {
5545       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5546
5547          s0, ra
5548          s0, s1, ra, s2, s3
5549          s0-s2, ra
5550
5551          and any permutations of these.  */
5552       if ((reglist & 0xfff1ffff) != 0x80010000)
5553         return FALSE;
5554
5555       sregs = (reglist >> 17) & 7;
5556       ra = 0;
5557     }
5558   else
5559     {
5560       /* The list must include at least one of ra and s0-sN,
5561          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5562          which are $23 and $30 respectively.)  E.g.:
5563
5564          ra
5565          s0
5566          ra, s0, s1, s2
5567          s0-s8
5568          s0-s5, ra
5569
5570          and any permutations of these.  */
5571       if ((reglist & 0x3f00ffff) != 0)
5572         return FALSE;
5573
5574       ra = (reglist >> 27) & 0x10;
5575       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5576     }
5577   sregs += 1;
5578   if ((sregs & -sregs) != sregs)
5579     return FALSE;
5580
5581   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5582   return TRUE;
5583 }
5584
5585 /* OP_ENTRY_EXIT_LIST matcher.  */
5586
5587 static unsigned int
5588 match_entry_exit_operand (struct mips_arg_info *arg,
5589                           const struct mips_operand *operand)
5590 {
5591   unsigned int mask;
5592   bfd_boolean is_exit;
5593
5594   /* The format is the same for both ENTRY and EXIT, but the constraints
5595      are different.  */
5596   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5597   mask = (is_exit ? 7 << 3 : 0);
5598   do
5599     {
5600       unsigned int regno1, regno2;
5601       bfd_boolean is_freg;
5602
5603       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5604         is_freg = FALSE;
5605       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5606         is_freg = TRUE;
5607       else
5608         return FALSE;
5609
5610       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5611         {
5612           mask &= ~(7 << 3);
5613           mask |= (5 + regno2) << 3;
5614         }
5615       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5616         mask |= (regno2 - 3) << 3;
5617       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5618         mask |= (regno2 - 15) << 1;
5619       else if (regno1 == RA && regno2 == RA)
5620         mask |= 1;
5621       else
5622         return FALSE;
5623     }
5624   while (match_char (arg, ','));
5625
5626   insn_insert_operand (arg->insn, operand, mask);
5627   return TRUE;
5628 }
5629
5630 /* Encode regular MIPS SAVE/RESTORE instruction operands according to
5631    the argument register mask AMASK, the number of static registers
5632    saved NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5633    respectively, and the frame size FRAME_SIZE.  */
5634
5635 static unsigned int
5636 mips_encode_save_restore (unsigned int amask, unsigned int nsreg,
5637                           unsigned int ra, unsigned int s0, unsigned int s1,
5638                           unsigned int frame_size)
5639 {
5640   return ((nsreg << 23) | ((frame_size & 0xf0) << 15) | (amask << 15)
5641           | (ra << 12) | (s0 << 11) | (s1 << 10) | ((frame_size & 0xf) << 6));
5642 }
5643
5644 /* Encode MIPS16 SAVE/RESTORE instruction operands according to the
5645    argument register mask AMASK, the number of static registers saved
5646    NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5647    respectively, and the frame size FRAME_SIZE.  */
5648
5649 static unsigned int
5650 mips16_encode_save_restore (unsigned int amask, unsigned int nsreg,
5651                             unsigned int ra, unsigned int s0, unsigned int s1,
5652                             unsigned int frame_size)
5653 {
5654   unsigned int args;
5655
5656   args = (ra << 6) | (s0 << 5) | (s1 << 4) | (frame_size & 0xf);
5657   if (nsreg || amask || frame_size == 0 || frame_size > 16)
5658     args |= (MIPS16_EXTEND | (nsreg << 24) | (amask << 16)
5659              | ((frame_size & 0xf0) << 16));
5660   return args;
5661 }
5662
5663 /* OP_SAVE_RESTORE_LIST matcher.  */
5664
5665 static bfd_boolean
5666 match_save_restore_list_operand (struct mips_arg_info *arg)
5667 {
5668   unsigned int opcode, args, statics, sregs;
5669   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5670   unsigned int arg_mask, ra, s0, s1;
5671   offsetT frame_size;
5672
5673   opcode = arg->insn->insn_opcode;
5674   frame_size = 0;
5675   num_frame_sizes = 0;
5676   args = 0;
5677   statics = 0;
5678   sregs = 0;
5679   ra = 0;
5680   s0 = 0;
5681   s1 = 0;
5682   do
5683     {
5684       unsigned int regno1, regno2;
5685
5686       if (arg->token->type == OT_INTEGER)
5687         {
5688           /* Handle the frame size.  */
5689           if (!match_const_int (arg, &frame_size))
5690             return FALSE;
5691           num_frame_sizes += 1;
5692         }
5693       else
5694         {
5695           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5696             return FALSE;
5697
5698           while (regno1 <= regno2)
5699             {
5700               if (regno1 >= 4 && regno1 <= 7)
5701                 {
5702                   if (num_frame_sizes == 0)
5703                     /* args $a0-$a3 */
5704                     args |= 1 << (regno1 - 4);
5705                   else
5706                     /* statics $a0-$a3 */
5707                     statics |= 1 << (regno1 - 4);
5708                 }
5709               else if (regno1 >= 16 && regno1 <= 23)
5710                 /* $s0-$s7 */
5711                 sregs |= 1 << (regno1 - 16);
5712               else if (regno1 == 30)
5713                 /* $s8 */
5714                 sregs |= 1 << 8;
5715               else if (regno1 == 31)
5716                 /* Add $ra to insn.  */
5717                 ra = 1;
5718               else
5719                 return FALSE;
5720               regno1 += 1;
5721               if (regno1 == 24)
5722                 regno1 = 30;
5723             }
5724         }
5725     }
5726   while (match_char (arg, ','));
5727
5728   /* Encode args/statics combination.  */
5729   if (args & statics)
5730     return FALSE;
5731   else if (args == 0xf)
5732     /* All $a0-$a3 are args.  */
5733     arg_mask = MIPS_SVRS_ALL_ARGS;
5734   else if (statics == 0xf)
5735     /* All $a0-$a3 are statics.  */
5736     arg_mask = MIPS_SVRS_ALL_STATICS;
5737   else
5738     {
5739       /* Count arg registers.  */
5740       num_args = 0;
5741       while (args & 0x1)
5742         {
5743           args >>= 1;
5744           num_args += 1;
5745         }
5746       if (args != 0)
5747         return FALSE;
5748
5749       /* Count static registers.  */
5750       num_statics = 0;
5751       while (statics & 0x8)
5752         {
5753           statics = (statics << 1) & 0xf;
5754           num_statics += 1;
5755         }
5756       if (statics != 0)
5757         return FALSE;
5758
5759       /* Encode args/statics.  */
5760       arg_mask = (num_args << 2) | num_statics;
5761     }
5762
5763   /* Encode $s0/$s1.  */
5764   if (sregs & (1 << 0))         /* $s0 */
5765     s0 = 1;
5766   if (sregs & (1 << 1))         /* $s1 */
5767     s1 = 1;
5768   sregs >>= 2;
5769
5770   /* Encode $s2-$s8. */
5771   num_sregs = 0;
5772   while (sregs & 1)
5773     {
5774       sregs >>= 1;
5775       num_sregs += 1;
5776     }
5777   if (sregs != 0)
5778     return FALSE;
5779
5780   /* Encode frame size.  */
5781   if (num_frame_sizes == 0)
5782     {
5783       set_insn_error (arg->argnum, _("missing frame size"));
5784       return FALSE;
5785     }
5786   if (num_frame_sizes > 1)
5787     {
5788       set_insn_error (arg->argnum, _("frame size specified twice"));
5789       return FALSE;
5790     }
5791   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5792     {
5793       set_insn_error (arg->argnum, _("invalid frame size"));
5794       return FALSE;
5795     }
5796   frame_size /= 8;
5797
5798   /* Finally build the instruction.  */
5799   if (mips_opts.mips16)
5800     opcode |= mips16_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5801                                           frame_size);
5802   else if (!mips_opts.micromips)
5803     opcode |= mips_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5804                                         frame_size);
5805   else
5806     abort ();
5807
5808   arg->insn->insn_opcode = opcode;
5809   return TRUE;
5810 }
5811
5812 /* OP_MDMX_IMM_REG matcher.  */
5813
5814 static bfd_boolean
5815 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5816                             const struct mips_operand *operand)
5817 {
5818   unsigned int regno, uval;
5819   bfd_boolean is_qh;
5820   const struct mips_opcode *opcode;
5821
5822   /* The mips_opcode records whether this is an octobyte or quadhalf
5823      instruction.  Start out with that bit in place.  */
5824   opcode = arg->insn->insn_mo;
5825   uval = mips_extract_operand (operand, opcode->match);
5826   is_qh = (uval != 0);
5827
5828   if (arg->token->type == OT_REG)
5829     {
5830       if ((opcode->membership & INSN_5400)
5831           && strcmp (opcode->name, "rzu.ob") == 0)
5832         {
5833           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5834                             arg->argnum);
5835           return FALSE;
5836         }
5837
5838       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5839         return FALSE;
5840       ++arg->token;
5841
5842       /* Check whether this is a vector register or a broadcast of
5843          a single element.  */
5844       if (arg->token->type == OT_INTEGER_INDEX)
5845         {
5846           if (arg->token->u.index > (is_qh ? 3 : 7))
5847             {
5848               set_insn_error (arg->argnum, _("invalid element selector"));
5849               return FALSE;
5850             }
5851           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5852           ++arg->token;
5853         }
5854       else
5855         {
5856           /* A full vector.  */
5857           if ((opcode->membership & INSN_5400)
5858               && (strcmp (opcode->name, "sll.ob") == 0
5859                   || strcmp (opcode->name, "srl.ob") == 0))
5860             {
5861               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5862                                 arg->argnum);
5863               return FALSE;
5864             }
5865
5866           if (is_qh)
5867             uval |= MDMX_FMTSEL_VEC_QH << 5;
5868           else
5869             uval |= MDMX_FMTSEL_VEC_OB << 5;
5870         }
5871       uval |= regno;
5872     }
5873   else
5874     {
5875       offsetT sval;
5876
5877       if (!match_const_int (arg, &sval))
5878         return FALSE;
5879       if (sval < 0 || sval > 31)
5880         {
5881           match_out_of_range (arg);
5882           return FALSE;
5883         }
5884       uval |= (sval & 31);
5885       if (is_qh)
5886         uval |= MDMX_FMTSEL_IMM_QH << 5;
5887       else
5888         uval |= MDMX_FMTSEL_IMM_OB << 5;
5889     }
5890   insn_insert_operand (arg->insn, operand, uval);
5891   return TRUE;
5892 }
5893
5894 /* OP_IMM_INDEX matcher.  */
5895
5896 static bfd_boolean
5897 match_imm_index_operand (struct mips_arg_info *arg,
5898                          const struct mips_operand *operand)
5899 {
5900   unsigned int max_val;
5901
5902   if (arg->token->type != OT_INTEGER_INDEX)
5903     return FALSE;
5904
5905   max_val = (1 << operand->size) - 1;
5906   if (arg->token->u.index > max_val)
5907     {
5908       match_out_of_range (arg);
5909       return FALSE;
5910     }
5911   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5912   ++arg->token;
5913   return TRUE;
5914 }
5915
5916 /* OP_REG_INDEX matcher.  */
5917
5918 static bfd_boolean
5919 match_reg_index_operand (struct mips_arg_info *arg,
5920                          const struct mips_operand *operand)
5921 {
5922   unsigned int regno;
5923
5924   if (arg->token->type != OT_REG_INDEX)
5925     return FALSE;
5926
5927   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5928     return FALSE;
5929
5930   insn_insert_operand (arg->insn, operand, regno);
5931   ++arg->token;
5932   return TRUE;
5933 }
5934
5935 /* OP_PC matcher.  */
5936
5937 static bfd_boolean
5938 match_pc_operand (struct mips_arg_info *arg)
5939 {
5940   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5941     {
5942       ++arg->token;
5943       return TRUE;
5944     }
5945   return FALSE;
5946 }
5947
5948 /* OP_REG28 matcher.  */
5949
5950 static bfd_boolean
5951 match_reg28_operand (struct mips_arg_info *arg)
5952 {
5953   unsigned int regno;
5954
5955   if (arg->token->type == OT_REG
5956       && match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno)
5957       && regno == GP)
5958     {
5959       ++arg->token;
5960       return TRUE;
5961     }
5962   return FALSE;
5963 }
5964
5965 /* OP_NON_ZERO_REG matcher.  */
5966
5967 static bfd_boolean
5968 match_non_zero_reg_operand (struct mips_arg_info *arg,
5969                             const struct mips_operand *operand)
5970 {
5971   unsigned int regno;
5972
5973   if (!match_reg (arg, OP_REG_GP, &regno))
5974     return FALSE;
5975
5976   if (regno == 0)
5977     return FALSE;
5978
5979   arg->last_regno = regno;
5980   insn_insert_operand (arg->insn, operand, regno);
5981   return TRUE;
5982 }
5983
5984 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5985    register that we need to match.  */
5986
5987 static bfd_boolean
5988 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5989 {
5990   unsigned int regno;
5991
5992   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5993 }
5994
5995 /* Try to match a floating-point constant from ARG for LI.S or LI.D.
5996    LENGTH is the length of the value in bytes (4 for float, 8 for double)
5997    and USING_GPRS says whether the destination is a GPR rather than an FPR.
5998
5999    Return the constant in IMM and OFFSET as follows:
6000
6001    - If the constant should be loaded via memory, set IMM to O_absent and
6002      OFFSET to the memory address.
6003
6004    - Otherwise, if the constant should be loaded into two 32-bit registers,
6005      set IMM to the O_constant to load into the high register and OFFSET
6006      to the corresponding value for the low register.
6007
6008    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
6009
6010    These constants only appear as the last operand in an instruction,
6011    and every instruction that accepts them in any variant accepts them
6012    in all variants.  This means we don't have to worry about backing out
6013    any changes if the instruction does not match.  We just match
6014    unconditionally and report an error if the constant is invalid.  */
6015
6016 static bfd_boolean
6017 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
6018                       expressionS *offset, int length, bfd_boolean using_gprs)
6019 {
6020   char *p;
6021   segT seg, new_seg;
6022   subsegT subseg;
6023   const char *newname;
6024   unsigned char *data;
6025
6026   /* Where the constant is placed is based on how the MIPS assembler
6027      does things:
6028
6029      length == 4 && using_gprs  -- immediate value only
6030      length == 8 && using_gprs  -- .rdata or immediate value
6031      length == 4 && !using_gprs -- .lit4 or immediate value
6032      length == 8 && !using_gprs -- .lit8 or immediate value
6033
6034      The .lit4 and .lit8 sections are only used if permitted by the
6035      -G argument.  */
6036   if (arg->token->type != OT_FLOAT)
6037     {
6038       set_insn_error (arg->argnum, _("floating-point expression required"));
6039       return FALSE;
6040     }
6041
6042   gas_assert (arg->token->u.flt.length == length);
6043   data = arg->token->u.flt.data;
6044   ++arg->token;
6045
6046   /* Handle 32-bit constants for which an immediate value is best.  */
6047   if (length == 4
6048       && (using_gprs
6049           || g_switch_value < 4
6050           || (data[0] == 0 && data[1] == 0)
6051           || (data[2] == 0 && data[3] == 0)))
6052     {
6053       imm->X_op = O_constant;
6054       if (!target_big_endian)
6055         imm->X_add_number = bfd_getl32 (data);
6056       else
6057         imm->X_add_number = bfd_getb32 (data);
6058       offset->X_op = O_absent;
6059       return TRUE;
6060     }
6061
6062   /* Handle 64-bit constants for which an immediate value is best.  */
6063   if (length == 8
6064       && !mips_disable_float_construction
6065       /* Constants can only be constructed in GPRs and copied to FPRs if the
6066          GPRs are at least as wide as the FPRs or MTHC1 is available.
6067          Unlike most tests for 32-bit floating-point registers this check
6068          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
6069          permit 64-bit moves without MXHC1.
6070          Force the constant into memory otherwise.  */
6071       && (using_gprs
6072           || GPR_SIZE == 64
6073           || ISA_HAS_MXHC1 (mips_opts.isa)
6074           || FPR_SIZE == 32)
6075       && ((data[0] == 0 && data[1] == 0)
6076           || (data[2] == 0 && data[3] == 0))
6077       && ((data[4] == 0 && data[5] == 0)
6078           || (data[6] == 0 && data[7] == 0)))
6079     {
6080       /* The value is simple enough to load with a couple of instructions.
6081          If using 32-bit registers, set IMM to the high order 32 bits and
6082          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
6083          64 bit constant.  */
6084       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
6085         {
6086           imm->X_op = O_constant;
6087           offset->X_op = O_constant;
6088           if (!target_big_endian)
6089             {
6090               imm->X_add_number = bfd_getl32 (data + 4);
6091               offset->X_add_number = bfd_getl32 (data);
6092             }
6093           else
6094             {
6095               imm->X_add_number = bfd_getb32 (data);
6096               offset->X_add_number = bfd_getb32 (data + 4);
6097             }
6098           if (offset->X_add_number == 0)
6099             offset->X_op = O_absent;
6100         }
6101       else
6102         {
6103           imm->X_op = O_constant;
6104           if (!target_big_endian)
6105             imm->X_add_number = bfd_getl64 (data);
6106           else
6107             imm->X_add_number = bfd_getb64 (data);
6108           offset->X_op = O_absent;
6109         }
6110       return TRUE;
6111     }
6112
6113   /* Switch to the right section.  */
6114   seg = now_seg;
6115   subseg = now_subseg;
6116   if (length == 4)
6117     {
6118       gas_assert (!using_gprs && g_switch_value >= 4);
6119       newname = ".lit4";
6120     }
6121   else
6122     {
6123       if (using_gprs || g_switch_value < 8)
6124         newname = RDATA_SECTION_NAME;
6125       else
6126         newname = ".lit8";
6127     }
6128
6129   new_seg = subseg_new (newname, (subsegT) 0);
6130   bfd_set_section_flags (stdoutput, new_seg,
6131                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
6132   frag_align (length == 4 ? 2 : 3, 0, 0);
6133   if (strncmp (TARGET_OS, "elf", 3) != 0)
6134     record_alignment (new_seg, 4);
6135   else
6136     record_alignment (new_seg, length == 4 ? 2 : 3);
6137   if (seg == now_seg)
6138     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
6139
6140   /* Set the argument to the current address in the section.  */
6141   imm->X_op = O_absent;
6142   offset->X_op = O_symbol;
6143   offset->X_add_symbol = symbol_temp_new_now ();
6144   offset->X_add_number = 0;
6145
6146   /* Put the floating point number into the section.  */
6147   p = frag_more (length);
6148   memcpy (p, data, length);
6149
6150   /* Switch back to the original section.  */
6151   subseg_set (seg, subseg);
6152   return TRUE;
6153 }
6154
6155 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
6156    them.  */
6157
6158 static bfd_boolean
6159 match_vu0_suffix_operand (struct mips_arg_info *arg,
6160                           const struct mips_operand *operand,
6161                           bfd_boolean match_p)
6162 {
6163   unsigned int uval;
6164
6165   /* The operand can be an XYZW mask or a single 2-bit channel index
6166      (with X being 0).  */
6167   gas_assert (operand->size == 2 || operand->size == 4);
6168
6169   /* The suffix can be omitted when it is already part of the opcode.  */
6170   if (arg->token->type != OT_CHANNELS)
6171     return match_p;
6172
6173   uval = arg->token->u.channels;
6174   if (operand->size == 2)
6175     {
6176       /* Check that a single bit is set and convert it into a 2-bit index.  */
6177       if ((uval & -uval) != uval)
6178         return FALSE;
6179       uval = 4 - ffs (uval);
6180     }
6181
6182   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6183     return FALSE;
6184
6185   ++arg->token;
6186   if (!match_p)
6187     insn_insert_operand (arg->insn, operand, uval);
6188   return TRUE;
6189 }
6190
6191 /* Try to match a token from ARG against OPERAND.  Consume the token
6192    and return true on success, otherwise return false.  */
6193
6194 static bfd_boolean
6195 match_operand (struct mips_arg_info *arg,
6196                const struct mips_operand *operand)
6197 {
6198   switch (operand->type)
6199     {
6200     case OP_INT:
6201       return match_int_operand (arg, operand);
6202
6203     case OP_MAPPED_INT:
6204       return match_mapped_int_operand (arg, operand);
6205
6206     case OP_MSB:
6207       return match_msb_operand (arg, operand);
6208
6209     case OP_REG:
6210     case OP_OPTIONAL_REG:
6211       return match_reg_operand (arg, operand);
6212
6213     case OP_REG_PAIR:
6214       return match_reg_pair_operand (arg, operand);
6215
6216     case OP_PCREL:
6217       return match_pcrel_operand (arg);
6218
6219     case OP_PERF_REG:
6220       return match_perf_reg_operand (arg, operand);
6221
6222     case OP_ADDIUSP_INT:
6223       return match_addiusp_operand (arg, operand);
6224
6225     case OP_CLO_CLZ_DEST:
6226       return match_clo_clz_dest_operand (arg, operand);
6227
6228     case OP_LWM_SWM_LIST:
6229       return match_lwm_swm_list_operand (arg, operand);
6230
6231     case OP_ENTRY_EXIT_LIST:
6232       return match_entry_exit_operand (arg, operand);
6233
6234     case OP_SAVE_RESTORE_LIST:
6235       return match_save_restore_list_operand (arg);
6236
6237     case OP_MDMX_IMM_REG:
6238       return match_mdmx_imm_reg_operand (arg, operand);
6239
6240     case OP_REPEAT_DEST_REG:
6241       return match_tied_reg_operand (arg, arg->dest_regno);
6242
6243     case OP_REPEAT_PREV_REG:
6244       return match_tied_reg_operand (arg, arg->last_regno);
6245
6246     case OP_PC:
6247       return match_pc_operand (arg);
6248
6249     case OP_REG28:
6250       return match_reg28_operand (arg);
6251
6252     case OP_VU0_SUFFIX:
6253       return match_vu0_suffix_operand (arg, operand, FALSE);
6254
6255     case OP_VU0_MATCH_SUFFIX:
6256       return match_vu0_suffix_operand (arg, operand, TRUE);
6257
6258     case OP_IMM_INDEX:
6259       return match_imm_index_operand (arg, operand);
6260
6261     case OP_REG_INDEX:
6262       return match_reg_index_operand (arg, operand);
6263
6264     case OP_SAME_RS_RT:
6265       return match_same_rs_rt_operand (arg, operand);
6266
6267     case OP_CHECK_PREV:
6268       return match_check_prev_operand (arg, operand);
6269
6270     case OP_NON_ZERO_REG:
6271       return match_non_zero_reg_operand (arg, operand);
6272     }
6273   abort ();
6274 }
6275
6276 /* ARG is the state after successfully matching an instruction.
6277    Issue any queued-up warnings.  */
6278
6279 static void
6280 check_completed_insn (struct mips_arg_info *arg)
6281 {
6282   if (arg->seen_at)
6283     {
6284       if (AT == ATREG)
6285         as_warn (_("used $at without \".set noat\""));
6286       else
6287         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6288     }
6289 }
6290
6291 /* Return true if modifying general-purpose register REG needs a delay.  */
6292
6293 static bfd_boolean
6294 reg_needs_delay (unsigned int reg)
6295 {
6296   unsigned long prev_pinfo;
6297
6298   prev_pinfo = history[0].insn_mo->pinfo;
6299   if (!mips_opts.noreorder
6300       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6301           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6302       && (gpr_write_mask (&history[0]) & (1 << reg)))
6303     return TRUE;
6304
6305   return FALSE;
6306 }
6307
6308 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6309    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6310    by VR4120 errata.  */
6311
6312 static unsigned int
6313 classify_vr4120_insn (const char *name)
6314 {
6315   if (strncmp (name, "macc", 4) == 0)
6316     return FIX_VR4120_MACC;
6317   if (strncmp (name, "dmacc", 5) == 0)
6318     return FIX_VR4120_DMACC;
6319   if (strncmp (name, "mult", 4) == 0)
6320     return FIX_VR4120_MULT;
6321   if (strncmp (name, "dmult", 5) == 0)
6322     return FIX_VR4120_DMULT;
6323   if (strstr (name, "div"))
6324     return FIX_VR4120_DIV;
6325   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6326     return FIX_VR4120_MTHILO;
6327   return NUM_FIX_VR4120_CLASSES;
6328 }
6329
6330 #define INSN_ERET       0x42000018
6331 #define INSN_DERET      0x4200001f
6332 #define INSN_DMULT      0x1c
6333 #define INSN_DMULTU     0x1d
6334
6335 /* Return the number of instructions that must separate INSN1 and INSN2,
6336    where INSN1 is the earlier instruction.  Return the worst-case value
6337    for any INSN2 if INSN2 is null.  */
6338
6339 static unsigned int
6340 insns_between (const struct mips_cl_insn *insn1,
6341                const struct mips_cl_insn *insn2)
6342 {
6343   unsigned long pinfo1, pinfo2;
6344   unsigned int mask;
6345
6346   /* If INFO2 is null, pessimistically assume that all flags are set for
6347      the second instruction.  */
6348   pinfo1 = insn1->insn_mo->pinfo;
6349   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6350
6351   /* For most targets, write-after-read dependencies on the HI and LO
6352      registers must be separated by at least two instructions.  */
6353   if (!hilo_interlocks)
6354     {
6355       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6356         return 2;
6357       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6358         return 2;
6359     }
6360
6361   /* If we're working around r7000 errata, there must be two instructions
6362      between an mfhi or mflo and any instruction that uses the result.  */
6363   if (mips_7000_hilo_fix
6364       && !mips_opts.micromips
6365       && MF_HILO_INSN (pinfo1)
6366       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6367     return 2;
6368
6369   /* If we're working around 24K errata, one instruction is required
6370      if an ERET or DERET is followed by a branch instruction.  */
6371   if (mips_fix_24k && !mips_opts.micromips)
6372     {
6373       if (insn1->insn_opcode == INSN_ERET
6374           || insn1->insn_opcode == INSN_DERET)
6375         {
6376           if (insn2 == NULL
6377               || insn2->insn_opcode == INSN_ERET
6378               || insn2->insn_opcode == INSN_DERET
6379               || delayed_branch_p (insn2))
6380             return 1;
6381         }
6382     }
6383
6384   /* If we're working around PMC RM7000 errata, there must be three
6385      nops between a dmult and a load instruction.  */
6386   if (mips_fix_rm7000 && !mips_opts.micromips)
6387     {
6388       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6389           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6390         {
6391           if (pinfo2 & INSN_LOAD_MEMORY)
6392            return 3;
6393         }
6394     }
6395
6396   /* If working around VR4120 errata, check for combinations that need
6397      a single intervening instruction.  */
6398   if (mips_fix_vr4120 && !mips_opts.micromips)
6399     {
6400       unsigned int class1, class2;
6401
6402       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6403       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6404         {
6405           if (insn2 == NULL)
6406             return 1;
6407           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6408           if (vr4120_conflicts[class1] & (1 << class2))
6409             return 1;
6410         }
6411     }
6412
6413   if (!HAVE_CODE_COMPRESSION)
6414     {
6415       /* Check for GPR or coprocessor load delays.  All such delays
6416          are on the RT register.  */
6417       /* Itbl support may require additional care here.  */
6418       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6419           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6420         {
6421           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6422             return 1;
6423         }
6424
6425       /* Check for generic coprocessor hazards.
6426
6427          This case is not handled very well.  There is no special
6428          knowledge of CP0 handling, and the coprocessors other than
6429          the floating point unit are not distinguished at all.  */
6430       /* Itbl support may require additional care here. FIXME!
6431          Need to modify this to include knowledge about
6432          user specified delays!  */
6433       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6434                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6435         {
6436           /* Handle cases where INSN1 writes to a known general coprocessor
6437              register.  There must be a one instruction delay before INSN2
6438              if INSN2 reads that register, otherwise no delay is needed.  */
6439           mask = fpr_write_mask (insn1);
6440           if (mask != 0)
6441             {
6442               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6443                 return 1;
6444             }
6445           else
6446             {
6447               /* Read-after-write dependencies on the control registers
6448                  require a two-instruction gap.  */
6449               if ((pinfo1 & INSN_WRITE_COND_CODE)
6450                   && (pinfo2 & INSN_READ_COND_CODE))
6451                 return 2;
6452
6453               /* We don't know exactly what INSN1 does.  If INSN2 is
6454                  also a coprocessor instruction, assume there must be
6455                  a one instruction gap.  */
6456               if (pinfo2 & INSN_COP)
6457                 return 1;
6458             }
6459         }
6460
6461       /* Check for read-after-write dependencies on the coprocessor
6462          control registers in cases where INSN1 does not need a general
6463          coprocessor delay.  This means that INSN1 is a floating point
6464          comparison instruction.  */
6465       /* Itbl support may require additional care here.  */
6466       else if (!cop_interlocks
6467                && (pinfo1 & INSN_WRITE_COND_CODE)
6468                && (pinfo2 & INSN_READ_COND_CODE))
6469         return 1;
6470     }
6471
6472   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6473      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6474      and pause.  */
6475   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6476       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6477           || (insn2 && delayed_branch_p (insn2))))
6478     return 1;
6479
6480   return 0;
6481 }
6482
6483 /* Return the number of nops that would be needed to work around the
6484    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6485    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6486    that are contained within the first IGNORE instructions of HIST.  */
6487
6488 static int
6489 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6490                  const struct mips_cl_insn *insn)
6491 {
6492   int i, j;
6493   unsigned int mask;
6494
6495   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6496      are not affected by the errata.  */
6497   if (insn != 0
6498       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6499           || strcmp (insn->insn_mo->name, "mtlo") == 0
6500           || strcmp (insn->insn_mo->name, "mthi") == 0))
6501     return 0;
6502
6503   /* Search for the first MFLO or MFHI.  */
6504   for (i = 0; i < MAX_VR4130_NOPS; i++)
6505     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6506       {
6507         /* Extract the destination register.  */
6508         mask = gpr_write_mask (&hist[i]);
6509
6510         /* No nops are needed if INSN reads that register.  */
6511         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6512           return 0;
6513
6514         /* ...or if any of the intervening instructions do.  */
6515         for (j = 0; j < i; j++)
6516           if (gpr_read_mask (&hist[j]) & mask)
6517             return 0;
6518
6519         if (i >= ignore)
6520           return MAX_VR4130_NOPS - i;
6521       }
6522   return 0;
6523 }
6524
6525 #define BASE_REG_EQ(INSN1, INSN2)       \
6526   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6527       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6528
6529 /* Return the minimum alignment for this store instruction.  */
6530
6531 static int
6532 fix_24k_align_to (const struct mips_opcode *mo)
6533 {
6534   if (strcmp (mo->name, "sh") == 0)
6535     return 2;
6536
6537   if (strcmp (mo->name, "swc1") == 0
6538       || strcmp (mo->name, "swc2") == 0
6539       || strcmp (mo->name, "sw") == 0
6540       || strcmp (mo->name, "sc") == 0
6541       || strcmp (mo->name, "s.s") == 0)
6542     return 4;
6543
6544   if (strcmp (mo->name, "sdc1") == 0
6545       || strcmp (mo->name, "sdc2") == 0
6546       || strcmp (mo->name, "s.d") == 0)
6547     return 8;
6548
6549   /* sb, swl, swr */
6550   return 1;
6551 }
6552
6553 struct fix_24k_store_info
6554   {
6555     /* Immediate offset, if any, for this store instruction.  */
6556     short off;
6557     /* Alignment required by this store instruction.  */
6558     int align_to;
6559     /* True for register offsets.  */
6560     int register_offset;
6561   };
6562
6563 /* Comparison function used by qsort.  */
6564
6565 static int
6566 fix_24k_sort (const void *a, const void *b)
6567 {
6568   const struct fix_24k_store_info *pos1 = a;
6569   const struct fix_24k_store_info *pos2 = b;
6570
6571   return (pos1->off - pos2->off);
6572 }
6573
6574 /* INSN is a store instruction.  Try to record the store information
6575    in STINFO.  Return false if the information isn't known.  */
6576
6577 static bfd_boolean
6578 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6579                            const struct mips_cl_insn *insn)
6580 {
6581   /* The instruction must have a known offset.  */
6582   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6583     return FALSE;
6584
6585   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6586   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6587   return TRUE;
6588 }
6589
6590 /* Return the number of nops that would be needed to work around the 24k
6591    "lost data on stores during refill" errata if instruction INSN
6592    immediately followed the 2 instructions described by HIST.
6593    Ignore hazards that are contained within the first IGNORE
6594    instructions of HIST.
6595
6596    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6597    for the data cache refills and store data. The following describes
6598    the scenario where the store data could be lost.
6599
6600    * A data cache miss, due to either a load or a store, causing fill
6601      data to be supplied by the memory subsystem
6602    * The first three doublewords of fill data are returned and written
6603      into the cache
6604    * A sequence of four stores occurs in consecutive cycles around the
6605      final doubleword of the fill:
6606    * Store A
6607    * Store B
6608    * Store C
6609    * Zero, One or more instructions
6610    * Store D
6611
6612    The four stores A-D must be to different doublewords of the line that
6613    is being filled. The fourth instruction in the sequence above permits
6614    the fill of the final doubleword to be transferred from the FSB into
6615    the cache. In the sequence above, the stores may be either integer
6616    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6617    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6618    different doublewords on the line. If the floating point unit is
6619    running in 1:2 mode, it is not possible to create the sequence above
6620    using only floating point store instructions.
6621
6622    In this case, the cache line being filled is incorrectly marked
6623    invalid, thereby losing the data from any store to the line that
6624    occurs between the original miss and the completion of the five
6625    cycle sequence shown above.
6626
6627    The workarounds are:
6628
6629    * Run the data cache in write-through mode.
6630    * Insert a non-store instruction between
6631      Store A and Store B or Store B and Store C.  */
6632
6633 static int
6634 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6635               const struct mips_cl_insn *insn)
6636 {
6637   struct fix_24k_store_info pos[3];
6638   int align, i, base_offset;
6639
6640   if (ignore >= 2)
6641     return 0;
6642
6643   /* If the previous instruction wasn't a store, there's nothing to
6644      worry about.  */
6645   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6646     return 0;
6647
6648   /* If the instructions after the previous one are unknown, we have
6649      to assume the worst.  */
6650   if (!insn)
6651     return 1;
6652
6653   /* Check whether we are dealing with three consecutive stores.  */
6654   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6655       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6656     return 0;
6657
6658   /* If we don't know the relationship between the store addresses,
6659      assume the worst.  */
6660   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6661       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6662     return 1;
6663
6664   if (!fix_24k_record_store_info (&pos[0], insn)
6665       || !fix_24k_record_store_info (&pos[1], &hist[0])
6666       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6667     return 1;
6668
6669   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6670
6671   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6672      X bytes and such that the base register + X is known to be aligned
6673      to align bytes.  */
6674
6675   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6676     align = 8;
6677   else
6678     {
6679       align = pos[0].align_to;
6680       base_offset = pos[0].off;
6681       for (i = 1; i < 3; i++)
6682         if (align < pos[i].align_to)
6683           {
6684             align = pos[i].align_to;
6685             base_offset = pos[i].off;
6686           }
6687       for (i = 0; i < 3; i++)
6688         pos[i].off -= base_offset;
6689     }
6690
6691   pos[0].off &= ~align + 1;
6692   pos[1].off &= ~align + 1;
6693   pos[2].off &= ~align + 1;
6694
6695   /* If any two stores write to the same chunk, they also write to the
6696      same doubleword.  The offsets are still sorted at this point.  */
6697   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6698     return 0;
6699
6700   /* A range of at least 9 bytes is needed for the stores to be in
6701      non-overlapping doublewords.  */
6702   if (pos[2].off - pos[0].off <= 8)
6703     return 0;
6704
6705   if (pos[2].off - pos[1].off >= 24
6706       || pos[1].off - pos[0].off >= 24
6707       || pos[2].off - pos[0].off >= 32)
6708     return 0;
6709
6710   return 1;
6711 }
6712
6713 /* Return the number of nops that would be needed if instruction INSN
6714    immediately followed the MAX_NOPS instructions given by HIST,
6715    where HIST[0] is the most recent instruction.  Ignore hazards
6716    between INSN and the first IGNORE instructions in HIST.
6717
6718    If INSN is null, return the worse-case number of nops for any
6719    instruction.  */
6720
6721 static int
6722 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6723                const struct mips_cl_insn *insn)
6724 {
6725   int i, nops, tmp_nops;
6726
6727   nops = 0;
6728   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6729     {
6730       tmp_nops = insns_between (hist + i, insn) - i;
6731       if (tmp_nops > nops)
6732         nops = tmp_nops;
6733     }
6734
6735   if (mips_fix_vr4130 && !mips_opts.micromips)
6736     {
6737       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6738       if (tmp_nops > nops)
6739         nops = tmp_nops;
6740     }
6741
6742   if (mips_fix_24k && !mips_opts.micromips)
6743     {
6744       tmp_nops = nops_for_24k (ignore, hist, insn);
6745       if (tmp_nops > nops)
6746         nops = tmp_nops;
6747     }
6748
6749   return nops;
6750 }
6751
6752 /* The variable arguments provide NUM_INSNS extra instructions that
6753    might be added to HIST.  Return the largest number of nops that
6754    would be needed after the extended sequence, ignoring hazards
6755    in the first IGNORE instructions.  */
6756
6757 static int
6758 nops_for_sequence (int num_insns, int ignore,
6759                    const struct mips_cl_insn *hist, ...)
6760 {
6761   va_list args;
6762   struct mips_cl_insn buffer[MAX_NOPS];
6763   struct mips_cl_insn *cursor;
6764   int nops;
6765
6766   va_start (args, hist);
6767   cursor = buffer + num_insns;
6768   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6769   while (cursor > buffer)
6770     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6771
6772   nops = nops_for_insn (ignore, buffer, NULL);
6773   va_end (args);
6774   return nops;
6775 }
6776
6777 /* Like nops_for_insn, but if INSN is a branch, take into account the
6778    worst-case delay for the branch target.  */
6779
6780 static int
6781 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6782                          const struct mips_cl_insn *insn)
6783 {
6784   int nops, tmp_nops;
6785
6786   nops = nops_for_insn (ignore, hist, insn);
6787   if (delayed_branch_p (insn))
6788     {
6789       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6790                                     hist, insn, get_delay_slot_nop (insn));
6791       if (tmp_nops > nops)
6792         nops = tmp_nops;
6793     }
6794   else if (compact_branch_p (insn))
6795     {
6796       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6797       if (tmp_nops > nops)
6798         nops = tmp_nops;
6799     }
6800   return nops;
6801 }
6802
6803 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6804
6805 static void
6806 fix_loongson2f_nop (struct mips_cl_insn * ip)
6807 {
6808   gas_assert (!HAVE_CODE_COMPRESSION);
6809   if (strcmp (ip->insn_mo->name, "nop") == 0)
6810     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6811 }
6812
6813 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6814                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6815
6816 static void
6817 fix_loongson2f_jump (struct mips_cl_insn * ip)
6818 {
6819   gas_assert (!HAVE_CODE_COMPRESSION);
6820   if (strcmp (ip->insn_mo->name, "j") == 0
6821       || strcmp (ip->insn_mo->name, "jr") == 0
6822       || strcmp (ip->insn_mo->name, "jalr") == 0)
6823     {
6824       int sreg;
6825       expressionS ep;
6826
6827       if (! mips_opts.at)
6828         return;
6829
6830       sreg = EXTRACT_OPERAND (0, RS, *ip);
6831       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6832         return;
6833
6834       ep.X_op = O_constant;
6835       ep.X_add_number = 0xcfff0000;
6836       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6837       ep.X_add_number = 0xffff;
6838       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6839       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6840     }
6841 }
6842
6843 static void
6844 fix_loongson2f (struct mips_cl_insn * ip)
6845 {
6846   if (mips_fix_loongson2f_nop)
6847     fix_loongson2f_nop (ip);
6848
6849   if (mips_fix_loongson2f_jump)
6850     fix_loongson2f_jump (ip);
6851 }
6852
6853 /* IP is a branch that has a delay slot, and we need to fill it
6854    automatically.   Return true if we can do that by swapping IP
6855    with the previous instruction.
6856    ADDRESS_EXPR is an operand of the instruction to be used with
6857    RELOC_TYPE.  */
6858
6859 static bfd_boolean
6860 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6861                    bfd_reloc_code_real_type *reloc_type)
6862 {
6863   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6864   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6865   unsigned int fpr_read, prev_fpr_write;
6866
6867   /* -O2 and above is required for this optimization.  */
6868   if (mips_optimize < 2)
6869     return FALSE;
6870
6871   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6872   if (mips_opts.nomove)
6873     return FALSE;
6874
6875   /* We can't swap if the previous instruction's position is fixed.  */
6876   if (history[0].fixed_p)
6877     return FALSE;
6878
6879   /* If the previous previous insn was in a .set noreorder, we can't
6880      swap.  Actually, the MIPS assembler will swap in this situation.
6881      However, gcc configured -with-gnu-as will generate code like
6882
6883         .set    noreorder
6884         lw      $4,XXX
6885         .set    reorder
6886         INSN
6887         bne     $4,$0,foo
6888
6889      in which we can not swap the bne and INSN.  If gcc is not configured
6890      -with-gnu-as, it does not output the .set pseudo-ops.  */
6891   if (history[1].noreorder_p)
6892     return FALSE;
6893
6894   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6895      This means that the previous instruction was a 4-byte one anyhow.  */
6896   if (mips_opts.mips16 && history[0].fixp[0])
6897     return FALSE;
6898
6899   /* If the branch is itself the target of a branch, we can not swap.
6900      We cheat on this; all we check for is whether there is a label on
6901      this instruction.  If there are any branches to anything other than
6902      a label, users must use .set noreorder.  */
6903   if (seg_info (now_seg)->label_list)
6904     return FALSE;
6905
6906   /* If the previous instruction is in a variant frag other than this
6907      branch's one, we cannot do the swap.  This does not apply to
6908      MIPS16 code, which uses variant frags for different purposes.  */
6909   if (!mips_opts.mips16
6910       && history[0].frag
6911       && history[0].frag->fr_type == rs_machine_dependent)
6912     return FALSE;
6913
6914   /* We do not swap with instructions that cannot architecturally
6915      be placed in a branch delay slot, such as SYNC or ERET.  We
6916      also refrain from swapping with a trap instruction, since it
6917      complicates trap handlers to have the trap instruction be in
6918      a delay slot.  */
6919   prev_pinfo = history[0].insn_mo->pinfo;
6920   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6921     return FALSE;
6922
6923   /* Check for conflicts between the branch and the instructions
6924      before the candidate delay slot.  */
6925   if (nops_for_insn (0, history + 1, ip) > 0)
6926     return FALSE;
6927
6928   /* Check for conflicts between the swapped sequence and the
6929      target of the branch.  */
6930   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6931     return FALSE;
6932
6933   /* If the branch reads a register that the previous
6934      instruction sets, we can not swap.  */
6935   gpr_read = gpr_read_mask (ip);
6936   prev_gpr_write = gpr_write_mask (&history[0]);
6937   if (gpr_read & prev_gpr_write)
6938     return FALSE;
6939
6940   fpr_read = fpr_read_mask (ip);
6941   prev_fpr_write = fpr_write_mask (&history[0]);
6942   if (fpr_read & prev_fpr_write)
6943     return FALSE;
6944
6945   /* If the branch writes a register that the previous
6946      instruction sets, we can not swap.  */
6947   gpr_write = gpr_write_mask (ip);
6948   if (gpr_write & prev_gpr_write)
6949     return FALSE;
6950
6951   /* If the branch writes a register that the previous
6952      instruction reads, we can not swap.  */
6953   prev_gpr_read = gpr_read_mask (&history[0]);
6954   if (gpr_write & prev_gpr_read)
6955     return FALSE;
6956
6957   /* If one instruction sets a condition code and the
6958      other one uses a condition code, we can not swap.  */
6959   pinfo = ip->insn_mo->pinfo;
6960   if ((pinfo & INSN_READ_COND_CODE)
6961       && (prev_pinfo & INSN_WRITE_COND_CODE))
6962     return FALSE;
6963   if ((pinfo & INSN_WRITE_COND_CODE)
6964       && (prev_pinfo & INSN_READ_COND_CODE))
6965     return FALSE;
6966
6967   /* If the previous instruction uses the PC, we can not swap.  */
6968   prev_pinfo2 = history[0].insn_mo->pinfo2;
6969   if (prev_pinfo2 & INSN2_READ_PC)
6970     return FALSE;
6971
6972   /* If the previous instruction has an incorrect size for a fixed
6973      branch delay slot in microMIPS mode, we cannot swap.  */
6974   pinfo2 = ip->insn_mo->pinfo2;
6975   if (mips_opts.micromips
6976       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6977       && insn_length (history) != 2)
6978     return FALSE;
6979   if (mips_opts.micromips
6980       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6981       && insn_length (history) != 4)
6982     return FALSE;
6983
6984   /* On R5900 short loops need to be fixed by inserting a nop in
6985      the branch delay slots.
6986      A short loop can be terminated too early.  */
6987   if (mips_opts.arch == CPU_R5900
6988       /* Check if instruction has a parameter, ignore "j $31". */
6989       && (address_expr != NULL)
6990       /* Parameter must be 16 bit. */
6991       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6992       /* Branch to same segment. */
6993       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6994       /* Branch to same code fragment. */
6995       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6996       /* Can only calculate branch offset if value is known. */
6997       && symbol_constant_p (address_expr->X_add_symbol)
6998       /* Check if branch is really conditional. */
6999       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
7000         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
7001         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
7002     {
7003       int distance;
7004       /* Check if loop is shorter than 6 instructions including
7005          branch and delay slot.  */
7006       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
7007       if (distance <= 20)
7008         {
7009           int i;
7010           int rv;
7011
7012           rv = FALSE;
7013           /* When the loop includes branches or jumps,
7014              it is not a short loop. */
7015           for (i = 0; i < (distance / 4); i++)
7016             {
7017               if ((history[i].cleared_p)
7018                   || delayed_branch_p (&history[i]))
7019                 {
7020                   rv = TRUE;
7021                   break;
7022                 }
7023             }
7024           if (!rv)
7025             {
7026               /* Insert nop after branch to fix short loop. */
7027               return FALSE;
7028             }
7029         }
7030     }
7031
7032   return TRUE;
7033 }
7034
7035 /* Decide how we should add IP to the instruction stream.
7036    ADDRESS_EXPR is an operand of the instruction to be used with
7037    RELOC_TYPE.  */
7038
7039 static enum append_method
7040 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
7041                    bfd_reloc_code_real_type *reloc_type)
7042 {
7043   /* The relaxed version of a macro sequence must be inherently
7044      hazard-free.  */
7045   if (mips_relax.sequence == 2)
7046     return APPEND_ADD;
7047
7048   /* We must not dabble with instructions in a ".set noreorder" block.  */
7049   if (mips_opts.noreorder)
7050     return APPEND_ADD;
7051
7052   /* Otherwise, it's our responsibility to fill branch delay slots.  */
7053   if (delayed_branch_p (ip))
7054     {
7055       if (!branch_likely_p (ip)
7056           && can_swap_branch_p (ip, address_expr, reloc_type))
7057         return APPEND_SWAP;
7058
7059       if (mips_opts.mips16
7060           && ISA_SUPPORTS_MIPS16E
7061           && gpr_read_mask (ip) != 0)
7062         return APPEND_ADD_COMPACT;
7063
7064       if (mips_opts.micromips
7065           && ((ip->insn_opcode & 0xffe0) == 0x4580
7066               || (!forced_insn_length
7067                   && ((ip->insn_opcode & 0xfc00) == 0xcc00
7068                       || (ip->insn_opcode & 0xdc00) == 0x8c00))
7069               || (ip->insn_opcode & 0xdfe00000) == 0x94000000
7070               || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
7071         return APPEND_ADD_COMPACT;
7072
7073       return APPEND_ADD_WITH_NOP;
7074     }
7075
7076   return APPEND_ADD;
7077 }
7078
7079 /* IP is an instruction whose opcode we have just changed, END points
7080    to the end of the opcode table processed.  Point IP->insn_mo to the
7081    new opcode's definition.  */
7082
7083 static void
7084 find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
7085 {
7086   const struct mips_opcode *mo;
7087
7088   for (mo = ip->insn_mo; mo < end; mo++)
7089     if (mo->pinfo != INSN_MACRO
7090         && (ip->insn_opcode & mo->mask) == mo->match)
7091       {
7092         ip->insn_mo = mo;
7093         return;
7094       }
7095   abort ();
7096 }
7097
7098 /* IP is a MIPS16 instruction whose opcode we have just changed.
7099    Point IP->insn_mo to the new opcode's definition.  */
7100
7101 static void
7102 find_altered_mips16_opcode (struct mips_cl_insn *ip)
7103 {
7104   find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
7105 }
7106
7107 /* IP is a microMIPS instruction whose opcode we have just changed.
7108    Point IP->insn_mo to the new opcode's definition.  */
7109
7110 static void
7111 find_altered_micromips_opcode (struct mips_cl_insn *ip)
7112 {
7113   find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
7114 }
7115
7116 /* For microMIPS macros, we need to generate a local number label
7117    as the target of branches.  */
7118 #define MICROMIPS_LABEL_CHAR            '\037'
7119 static unsigned long micromips_target_label;
7120 static char micromips_target_name[32];
7121
7122 static char *
7123 micromips_label_name (void)
7124 {
7125   char *p = micromips_target_name;
7126   char symbol_name_temporary[24];
7127   unsigned long l;
7128   int i;
7129
7130   if (*p)
7131     return p;
7132
7133   i = 0;
7134   l = micromips_target_label;
7135 #ifdef LOCAL_LABEL_PREFIX
7136   *p++ = LOCAL_LABEL_PREFIX;
7137 #endif
7138   *p++ = 'L';
7139   *p++ = MICROMIPS_LABEL_CHAR;
7140   do
7141     {
7142       symbol_name_temporary[i++] = l % 10 + '0';
7143       l /= 10;
7144     }
7145   while (l != 0);
7146   while (i > 0)
7147     *p++ = symbol_name_temporary[--i];
7148   *p = '\0';
7149
7150   return micromips_target_name;
7151 }
7152
7153 static void
7154 micromips_label_expr (expressionS *label_expr)
7155 {
7156   label_expr->X_op = O_symbol;
7157   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
7158   label_expr->X_add_number = 0;
7159 }
7160
7161 static void
7162 micromips_label_inc (void)
7163 {
7164   micromips_target_label++;
7165   *micromips_target_name = '\0';
7166 }
7167
7168 static void
7169 micromips_add_label (void)
7170 {
7171   symbolS *s;
7172
7173   s = colon (micromips_label_name ());
7174   micromips_label_inc ();
7175   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
7176 }
7177
7178 /* If assembling microMIPS code, then return the microMIPS reloc
7179    corresponding to the requested one if any.  Otherwise return
7180    the reloc unchanged.  */
7181
7182 static bfd_reloc_code_real_type
7183 micromips_map_reloc (bfd_reloc_code_real_type reloc)
7184 {
7185   static const bfd_reloc_code_real_type relocs[][2] =
7186     {
7187       /* Keep sorted incrementally by the left-hand key.  */
7188       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7189       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7190       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7191       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7192       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7193       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7194       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7195       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7196       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7197       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7198       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7199       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7200       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7201       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7202       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7203       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7204       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7205       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7206       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7207       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7208       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7209       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7210       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7211       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7212       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7213       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7214       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7215     };
7216   bfd_reloc_code_real_type r;
7217   size_t i;
7218
7219   if (!mips_opts.micromips)
7220     return reloc;
7221   for (i = 0; i < ARRAY_SIZE (relocs); i++)
7222     {
7223       r = relocs[i][0];
7224       if (r > reloc)
7225         return reloc;
7226       if (r == reloc)
7227         return relocs[i][1];
7228     }
7229   return reloc;
7230 }
7231
7232 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7233    Return true on success, storing the resolved value in RESULT.  */
7234
7235 static bfd_boolean
7236 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7237                  offsetT *result)
7238 {
7239   switch (reloc)
7240     {
7241     case BFD_RELOC_MIPS_HIGHEST:
7242     case BFD_RELOC_MICROMIPS_HIGHEST:
7243       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7244       return TRUE;
7245
7246     case BFD_RELOC_MIPS_HIGHER:
7247     case BFD_RELOC_MICROMIPS_HIGHER:
7248       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7249       return TRUE;
7250
7251     case BFD_RELOC_HI16_S:
7252     case BFD_RELOC_HI16_S_PCREL:
7253     case BFD_RELOC_MICROMIPS_HI16_S:
7254     case BFD_RELOC_MIPS16_HI16_S:
7255       *result = ((operand + 0x8000) >> 16) & 0xffff;
7256       return TRUE;
7257
7258     case BFD_RELOC_HI16:
7259     case BFD_RELOC_MICROMIPS_HI16:
7260     case BFD_RELOC_MIPS16_HI16:
7261       *result = (operand >> 16) & 0xffff;
7262       return TRUE;
7263
7264     case BFD_RELOC_LO16:
7265     case BFD_RELOC_LO16_PCREL:
7266     case BFD_RELOC_MICROMIPS_LO16:
7267     case BFD_RELOC_MIPS16_LO16:
7268       *result = operand & 0xffff;
7269       return TRUE;
7270
7271     case BFD_RELOC_UNUSED:
7272       *result = operand;
7273       return TRUE;
7274
7275     default:
7276       return FALSE;
7277     }
7278 }
7279
7280 /* Output an instruction.  IP is the instruction information.
7281    ADDRESS_EXPR is an operand of the instruction to be used with
7282    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7283    a macro expansion.  */
7284
7285 static void
7286 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7287              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7288 {
7289   unsigned long prev_pinfo2, pinfo;
7290   bfd_boolean relaxed_branch = FALSE;
7291   enum append_method method;
7292   bfd_boolean relax32;
7293   int branch_disp;
7294
7295   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7296     fix_loongson2f (ip);
7297
7298   file_ase_mips16 |= mips_opts.mips16;
7299   file_ase_micromips |= mips_opts.micromips;
7300
7301   prev_pinfo2 = history[0].insn_mo->pinfo2;
7302   pinfo = ip->insn_mo->pinfo;
7303
7304   /* Don't raise alarm about `nods' frags as they'll fill in the right
7305      kind of nop in relaxation if required.  */
7306   if (mips_opts.micromips
7307       && !expansionp
7308       && !(history[0].frag
7309            && history[0].frag->fr_type == rs_machine_dependent
7310            && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7311            && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7312       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7313            && micromips_insn_length (ip->insn_mo) != 2)
7314           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7315               && micromips_insn_length (ip->insn_mo) != 4)))
7316     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7317              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7318
7319   if (address_expr == NULL)
7320     ip->complete_p = 1;
7321   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7322            && reloc_type[1] == BFD_RELOC_UNUSED
7323            && reloc_type[2] == BFD_RELOC_UNUSED
7324            && address_expr->X_op == O_constant)
7325     {
7326       switch (*reloc_type)
7327         {
7328         case BFD_RELOC_MIPS_JMP:
7329           {
7330             int shift;
7331
7332             /* Shift is 2, unusually, for microMIPS JALX.  */
7333             shift = (mips_opts.micromips
7334                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7335             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7336               as_bad (_("jump to misaligned address (0x%lx)"),
7337                       (unsigned long) address_expr->X_add_number);
7338             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7339                                 & 0x3ffffff);
7340             ip->complete_p = 1;
7341           }
7342           break;
7343
7344         case BFD_RELOC_MIPS16_JMP:
7345           if ((address_expr->X_add_number & 3) != 0)
7346             as_bad (_("jump to misaligned address (0x%lx)"),
7347                     (unsigned long) address_expr->X_add_number);
7348           ip->insn_opcode |=
7349             (((address_expr->X_add_number & 0x7c0000) << 3)
7350                | ((address_expr->X_add_number & 0xf800000) >> 7)
7351                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7352           ip->complete_p = 1;
7353           break;
7354
7355         case BFD_RELOC_16_PCREL_S2:
7356           {
7357             int shift;
7358
7359             shift = mips_opts.micromips ? 1 : 2;
7360             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7361               as_bad (_("branch to misaligned address (0x%lx)"),
7362                       (unsigned long) address_expr->X_add_number);
7363             if (!mips_relax_branch)
7364               {
7365                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7366                     & ~((1 << (shift + 16)) - 1))
7367                   as_bad (_("branch address range overflow (0x%lx)"),
7368                           (unsigned long) address_expr->X_add_number);
7369                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7370                                     & 0xffff);
7371               }
7372           }
7373           break;
7374
7375         case BFD_RELOC_MIPS_21_PCREL_S2:
7376           {
7377             int shift;
7378
7379             shift = 2;
7380             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7381               as_bad (_("branch to misaligned address (0x%lx)"),
7382                       (unsigned long) address_expr->X_add_number);
7383             if ((address_expr->X_add_number + (1 << (shift + 20)))
7384                 & ~((1 << (shift + 21)) - 1))
7385               as_bad (_("branch address range overflow (0x%lx)"),
7386                       (unsigned long) address_expr->X_add_number);
7387             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7388                                 & 0x1fffff);
7389           }
7390           break;
7391
7392         case BFD_RELOC_MIPS_26_PCREL_S2:
7393           {
7394             int shift;
7395
7396             shift = 2;
7397             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7398               as_bad (_("branch to misaligned address (0x%lx)"),
7399                       (unsigned long) address_expr->X_add_number);
7400             if ((address_expr->X_add_number + (1 << (shift + 25)))
7401                 & ~((1 << (shift + 26)) - 1))
7402               as_bad (_("branch address range overflow (0x%lx)"),
7403                       (unsigned long) address_expr->X_add_number);
7404             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7405                                 & 0x3ffffff);
7406           }
7407           break;
7408
7409         default:
7410           {
7411             offsetT value;
7412
7413             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7414                                  &value))
7415               {
7416                 ip->insn_opcode |= value & 0xffff;
7417                 ip->complete_p = 1;
7418               }
7419           }
7420           break;
7421         }
7422     }
7423
7424   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7425     {
7426       /* There are a lot of optimizations we could do that we don't.
7427          In particular, we do not, in general, reorder instructions.
7428          If you use gcc with optimization, it will reorder
7429          instructions and generally do much more optimization then we
7430          do here; repeating all that work in the assembler would only
7431          benefit hand written assembly code, and does not seem worth
7432          it.  */
7433       int nops = (mips_optimize == 0
7434                   ? nops_for_insn (0, history, NULL)
7435                   : nops_for_insn_or_target (0, history, ip));
7436       if (nops > 0)
7437         {
7438           fragS *old_frag;
7439           unsigned long old_frag_offset;
7440           int i;
7441
7442           old_frag = frag_now;
7443           old_frag_offset = frag_now_fix ();
7444
7445           for (i = 0; i < nops; i++)
7446             add_fixed_insn (NOP_INSN);
7447           insert_into_history (0, nops, NOP_INSN);
7448
7449           if (listing)
7450             {
7451               listing_prev_line ();
7452               /* We may be at the start of a variant frag.  In case we
7453                  are, make sure there is enough space for the frag
7454                  after the frags created by listing_prev_line.  The
7455                  argument to frag_grow here must be at least as large
7456                  as the argument to all other calls to frag_grow in
7457                  this file.  We don't have to worry about being in the
7458                  middle of a variant frag, because the variants insert
7459                  all needed nop instructions themselves.  */
7460               frag_grow (40);
7461             }
7462
7463           mips_move_text_labels ();
7464
7465 #ifndef NO_ECOFF_DEBUGGING
7466           if (ECOFF_DEBUGGING)
7467             ecoff_fix_loc (old_frag, old_frag_offset);
7468 #endif
7469         }
7470     }
7471   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7472     {
7473       int nops;
7474
7475       /* Work out how many nops in prev_nop_frag are needed by IP,
7476          ignoring hazards generated by the first prev_nop_frag_since
7477          instructions.  */
7478       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7479       gas_assert (nops <= prev_nop_frag_holds);
7480
7481       /* Enforce NOPS as a minimum.  */
7482       if (nops > prev_nop_frag_required)
7483         prev_nop_frag_required = nops;
7484
7485       if (prev_nop_frag_holds == prev_nop_frag_required)
7486         {
7487           /* Settle for the current number of nops.  Update the history
7488              accordingly (for the benefit of any future .set reorder code).  */
7489           prev_nop_frag = NULL;
7490           insert_into_history (prev_nop_frag_since,
7491                                prev_nop_frag_holds, NOP_INSN);
7492         }
7493       else
7494         {
7495           /* Allow this instruction to replace one of the nops that was
7496              tentatively added to prev_nop_frag.  */
7497           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7498           prev_nop_frag_holds--;
7499           prev_nop_frag_since++;
7500         }
7501     }
7502
7503   method = get_append_method (ip, address_expr, reloc_type);
7504   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7505
7506   dwarf2_emit_insn (0);
7507   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7508      so "move" the instruction address accordingly.
7509
7510      Also, it doesn't seem appropriate for the assembler to reorder .loc
7511      entries.  If this instruction is a branch that we are going to swap
7512      with the previous instruction, the two instructions should be
7513      treated as a unit, and the debug information for both instructions
7514      should refer to the start of the branch sequence.  Using the
7515      current position is certainly wrong when swapping a 32-bit branch
7516      and a 16-bit delay slot, since the current position would then be
7517      in the middle of a branch.  */
7518   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7519
7520   relax32 = (mips_relax_branch
7521              /* Don't try branch relaxation within .set nomacro, or within
7522                 .set noat if we use $at for PIC computations.  If it turns
7523                 out that the branch was out-of-range, we'll get an error.  */
7524              && !mips_opts.warn_about_macros
7525              && (mips_opts.at || mips_pic == NO_PIC)
7526              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7527                 as they have no complementing branches.  */
7528              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7529
7530   if (!HAVE_CODE_COMPRESSION
7531       && address_expr
7532       && relax32
7533       && *reloc_type == BFD_RELOC_16_PCREL_S2
7534       && delayed_branch_p (ip))
7535     {
7536       relaxed_branch = TRUE;
7537       add_relaxed_insn (ip, (relaxed_branch_length
7538                              (NULL, NULL,
7539                               uncond_branch_p (ip) ? -1
7540                               : branch_likely_p (ip) ? 1
7541                               : 0)), 4,
7542                         RELAX_BRANCH_ENCODE
7543                         (AT, mips_pic != NO_PIC,
7544                          uncond_branch_p (ip),
7545                          branch_likely_p (ip),
7546                          pinfo & INSN_WRITE_GPR_31,
7547                          0),
7548                         address_expr->X_add_symbol,
7549                         address_expr->X_add_number);
7550       *reloc_type = BFD_RELOC_UNUSED;
7551     }
7552   else if (mips_opts.micromips
7553            && address_expr
7554            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7555                || *reloc_type > BFD_RELOC_UNUSED)
7556            && (delayed_branch_p (ip) || compact_branch_p (ip))
7557            /* Don't try branch relaxation when users specify
7558               16-bit/32-bit instructions.  */
7559            && !forced_insn_length)
7560     {
7561       bfd_boolean relax16 = (method != APPEND_ADD_COMPACT
7562                              && *reloc_type > BFD_RELOC_UNUSED);
7563       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7564       int uncond = uncond_branch_p (ip) ? -1 : 0;
7565       int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7566       int nods = method == APPEND_ADD_WITH_NOP;
7567       int al = pinfo & INSN_WRITE_GPR_31;
7568       int length32 = nods ? 8 : 4;
7569
7570       gas_assert (address_expr != NULL);
7571       gas_assert (!mips_relax.sequence);
7572
7573       relaxed_branch = TRUE;
7574       if (nods)
7575         method = APPEND_ADD;
7576       if (relax32)
7577         length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7578       add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7579                         RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7580                                                 mips_pic != NO_PIC,
7581                                                 uncond, compact, al, nods,
7582                                                 relax32, 0, 0),
7583                         address_expr->X_add_symbol,
7584                         address_expr->X_add_number);
7585       *reloc_type = BFD_RELOC_UNUSED;
7586     }
7587   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7588     {
7589       bfd_boolean require_unextended;
7590       bfd_boolean require_extended;
7591       symbolS *symbol;
7592       offsetT offset;
7593
7594       if (forced_insn_length != 0)
7595         {
7596           require_unextended = forced_insn_length == 2;
7597           require_extended = forced_insn_length == 4;
7598         }
7599       else
7600         {
7601           require_unextended = (mips_opts.noautoextend
7602                                 && !mips_opcode_32bit_p (ip->insn_mo));
7603           require_extended = 0;
7604         }
7605
7606       /* We need to set up a variant frag.  */
7607       gas_assert (address_expr != NULL);
7608       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7609          symbol created by `make_expr_symbol' may not get a necessary
7610          external relocation produced.  */
7611       if (address_expr->X_op == O_symbol)
7612         {
7613           symbol = address_expr->X_add_symbol;
7614           offset = address_expr->X_add_number;
7615         }
7616       else
7617         {
7618           symbol = make_expr_symbol (address_expr);
7619           symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7620           offset = 0;
7621         }
7622       add_relaxed_insn (ip, 12, 0,
7623                         RELAX_MIPS16_ENCODE
7624                         (*reloc_type - BFD_RELOC_UNUSED,
7625                          mips_opts.ase & ASE_MIPS16E2,
7626                          mips_pic != NO_PIC,
7627                          HAVE_32BIT_SYMBOLS,
7628                          mips_opts.warn_about_macros,
7629                          require_unextended, require_extended,
7630                          delayed_branch_p (&history[0]),
7631                          history[0].mips16_absolute_jump_p),
7632                         symbol, offset);
7633     }
7634   else if (mips_opts.mips16 && insn_length (ip) == 2)
7635     {
7636       if (!delayed_branch_p (ip))
7637         /* Make sure there is enough room to swap this instruction with
7638            a following jump instruction.  */
7639         frag_grow (6);
7640       add_fixed_insn (ip);
7641     }
7642   else
7643     {
7644       if (mips_opts.mips16
7645           && mips_opts.noreorder
7646           && delayed_branch_p (&history[0]))
7647         as_warn (_("extended instruction in delay slot"));
7648
7649       if (mips_relax.sequence)
7650         {
7651           /* If we've reached the end of this frag, turn it into a variant
7652              frag and record the information for the instructions we've
7653              written so far.  */
7654           if (frag_room () < 4)
7655             relax_close_frag ();
7656           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7657         }
7658
7659       if (mips_relax.sequence != 2)
7660         {
7661           if (mips_macro_warning.first_insn_sizes[0] == 0)
7662             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7663           mips_macro_warning.sizes[0] += insn_length (ip);
7664           mips_macro_warning.insns[0]++;
7665         }
7666       if (mips_relax.sequence != 1)
7667         {
7668           if (mips_macro_warning.first_insn_sizes[1] == 0)
7669             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7670           mips_macro_warning.sizes[1] += insn_length (ip);
7671           mips_macro_warning.insns[1]++;
7672         }
7673
7674       if (mips_opts.mips16)
7675         {
7676           ip->fixed_p = 1;
7677           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7678         }
7679       add_fixed_insn (ip);
7680     }
7681
7682   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7683     {
7684       bfd_reloc_code_real_type final_type[3];
7685       reloc_howto_type *howto0;
7686       reloc_howto_type *howto;
7687       int i;
7688
7689       /* Perform any necessary conversion to microMIPS relocations
7690          and find out how many relocations there actually are.  */
7691       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7692         final_type[i] = micromips_map_reloc (reloc_type[i]);
7693
7694       /* In a compound relocation, it is the final (outermost)
7695          operator that determines the relocated field.  */
7696       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7697       if (!howto)
7698         abort ();
7699
7700       if (i > 1)
7701         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7702       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7703                                  bfd_get_reloc_size (howto),
7704                                  address_expr,
7705                                  howto0 && howto0->pc_relative,
7706                                  final_type[0]);
7707       /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7708       ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7709
7710       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7711       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7712         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7713
7714       /* These relocations can have an addend that won't fit in
7715          4 octets for 64bit assembly.  */
7716       if (GPR_SIZE == 64
7717           && ! howto->partial_inplace
7718           && (reloc_type[0] == BFD_RELOC_16
7719               || reloc_type[0] == BFD_RELOC_32
7720               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7721               || reloc_type[0] == BFD_RELOC_GPREL16
7722               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7723               || reloc_type[0] == BFD_RELOC_GPREL32
7724               || reloc_type[0] == BFD_RELOC_64
7725               || reloc_type[0] == BFD_RELOC_CTOR
7726               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7727               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7728               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7729               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7730               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7731               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7732               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7733               || hi16_reloc_p (reloc_type[0])
7734               || lo16_reloc_p (reloc_type[0])))
7735         ip->fixp[0]->fx_no_overflow = 1;
7736
7737       /* These relocations can have an addend that won't fit in 2 octets.  */
7738       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7739           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7740         ip->fixp[0]->fx_no_overflow = 1;
7741
7742       if (mips_relax.sequence)
7743         {
7744           if (mips_relax.first_fixup == 0)
7745             mips_relax.first_fixup = ip->fixp[0];
7746         }
7747       else if (reloc_needs_lo_p (*reloc_type))
7748         {
7749           struct mips_hi_fixup *hi_fixup;
7750
7751           /* Reuse the last entry if it already has a matching %lo.  */
7752           hi_fixup = mips_hi_fixup_list;
7753           if (hi_fixup == 0
7754               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7755             {
7756               hi_fixup = XNEW (struct mips_hi_fixup);
7757               hi_fixup->next = mips_hi_fixup_list;
7758               mips_hi_fixup_list = hi_fixup;
7759             }
7760           hi_fixup->fixp = ip->fixp[0];
7761           hi_fixup->seg = now_seg;
7762         }
7763
7764       /* Add fixups for the second and third relocations, if given.
7765          Note that the ABI allows the second relocation to be
7766          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7767          moment we only use RSS_UNDEF, but we could add support
7768          for the others if it ever becomes necessary.  */
7769       for (i = 1; i < 3; i++)
7770         if (reloc_type[i] != BFD_RELOC_UNUSED)
7771           {
7772             ip->fixp[i] = fix_new (ip->frag, ip->where,
7773                                    ip->fixp[0]->fx_size, NULL, 0,
7774                                    FALSE, final_type[i]);
7775
7776             /* Use fx_tcbit to mark compound relocs.  */
7777             ip->fixp[0]->fx_tcbit = 1;
7778             ip->fixp[i]->fx_tcbit = 1;
7779           }
7780     }
7781
7782   /* Update the register mask information.  */
7783   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7784   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7785
7786   switch (method)
7787     {
7788     case APPEND_ADD:
7789       insert_into_history (0, 1, ip);
7790       break;
7791
7792     case APPEND_ADD_WITH_NOP:
7793       {
7794         struct mips_cl_insn *nop;
7795
7796         insert_into_history (0, 1, ip);
7797         nop = get_delay_slot_nop (ip);
7798         add_fixed_insn (nop);
7799         insert_into_history (0, 1, nop);
7800         if (mips_relax.sequence)
7801           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7802       }
7803       break;
7804
7805     case APPEND_ADD_COMPACT:
7806       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7807       if (mips_opts.mips16)
7808         {
7809           ip->insn_opcode |= 0x0080;
7810           find_altered_mips16_opcode (ip);
7811         }
7812       /* Convert microMIPS instructions.  */
7813       else if (mips_opts.micromips)
7814         {
7815           /* jr16->jrc */
7816           if ((ip->insn_opcode & 0xffe0) == 0x4580)
7817             ip->insn_opcode |= 0x0020;
7818           /* b16->bc */
7819           else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
7820             ip->insn_opcode = 0x40e00000;
7821           /* beqz16->beqzc, bnez16->bnezc */
7822           else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
7823             {
7824               unsigned long regno;
7825
7826               regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
7827               regno &= MICROMIPSOP_MASK_MD;
7828               regno = micromips_to_32_reg_d_map[regno];
7829               ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
7830                                  | (regno << MICROMIPSOP_SH_RS)
7831                                  | 0x40a00000) ^ 0x00400000;
7832             }
7833           /* beqz->beqzc, bnez->bnezc */
7834           else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
7835             ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
7836                                | ((ip->insn_opcode >> 7) & 0x00400000)
7837                                | 0x40a00000) ^ 0x00400000;
7838           /* beq $0->beqzc, bne $0->bnezc */
7839           else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
7840             ip->insn_opcode = (((ip->insn_opcode >>
7841                                  (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
7842                                 & (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
7843                                | ((ip->insn_opcode >> 7) & 0x00400000)
7844                                | 0x40a00000) ^ 0x00400000;
7845           else
7846             abort ();
7847           find_altered_micromips_opcode (ip);
7848         }
7849       else
7850         abort ();
7851       install_insn (ip);
7852       insert_into_history (0, 1, ip);
7853       break;
7854
7855     case APPEND_SWAP:
7856       {
7857         struct mips_cl_insn delay = history[0];
7858
7859         if (relaxed_branch || delay.frag != ip->frag)
7860           {
7861             /* Add the delay slot instruction to the end of the
7862                current frag and shrink the fixed part of the
7863                original frag.  If the branch occupies the tail of
7864                the latter, move it backwards to cover the gap.  */
7865             delay.frag->fr_fix -= branch_disp;
7866             if (delay.frag == ip->frag)
7867               move_insn (ip, ip->frag, ip->where - branch_disp);
7868             add_fixed_insn (&delay);
7869           }
7870         else
7871           {
7872             /* If this is not a relaxed branch and we are in the
7873                same frag, then just swap the instructions.  */
7874             move_insn (ip, delay.frag, delay.where);
7875             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7876           }
7877         history[0] = *ip;
7878         delay.fixed_p = 1;
7879         insert_into_history (0, 1, &delay);
7880       }
7881       break;
7882     }
7883
7884   /* If we have just completed an unconditional branch, clear the history.  */
7885   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7886       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7887     {
7888       unsigned int i;
7889
7890       mips_no_prev_insn ();
7891
7892       for (i = 0; i < ARRAY_SIZE (history); i++)
7893         history[i].cleared_p = 1;
7894     }
7895
7896   /* We need to emit a label at the end of branch-likely macros.  */
7897   if (emit_branch_likely_macro)
7898     {
7899       emit_branch_likely_macro = FALSE;
7900       micromips_add_label ();
7901     }
7902
7903   /* We just output an insn, so the next one doesn't have a label.  */
7904   mips_clear_insn_labels ();
7905 }
7906
7907 /* Forget that there was any previous instruction or label.
7908    When BRANCH is true, the branch history is also flushed.  */
7909
7910 static void
7911 mips_no_prev_insn (void)
7912 {
7913   prev_nop_frag = NULL;
7914   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7915   mips_clear_insn_labels ();
7916 }
7917
7918 /* This function must be called before we emit something other than
7919    instructions.  It is like mips_no_prev_insn except that it inserts
7920    any NOPS that might be needed by previous instructions.  */
7921
7922 void
7923 mips_emit_delays (void)
7924 {
7925   if (! mips_opts.noreorder)
7926     {
7927       int nops = nops_for_insn (0, history, NULL);
7928       if (nops > 0)
7929         {
7930           while (nops-- > 0)
7931             add_fixed_insn (NOP_INSN);
7932           mips_move_text_labels ();
7933         }
7934     }
7935   mips_no_prev_insn ();
7936 }
7937
7938 /* Start a (possibly nested) noreorder block.  */
7939
7940 static void
7941 start_noreorder (void)
7942 {
7943   if (mips_opts.noreorder == 0)
7944     {
7945       unsigned int i;
7946       int nops;
7947
7948       /* None of the instructions before the .set noreorder can be moved.  */
7949       for (i = 0; i < ARRAY_SIZE (history); i++)
7950         history[i].fixed_p = 1;
7951
7952       /* Insert any nops that might be needed between the .set noreorder
7953          block and the previous instructions.  We will later remove any
7954          nops that turn out not to be needed.  */
7955       nops = nops_for_insn (0, history, NULL);
7956       if (nops > 0)
7957         {
7958           if (mips_optimize != 0)
7959             {
7960               /* Record the frag which holds the nop instructions, so
7961                  that we can remove them if we don't need them.  */
7962               frag_grow (nops * NOP_INSN_SIZE);
7963               prev_nop_frag = frag_now;
7964               prev_nop_frag_holds = nops;
7965               prev_nop_frag_required = 0;
7966               prev_nop_frag_since = 0;
7967             }
7968
7969           for (; nops > 0; --nops)
7970             add_fixed_insn (NOP_INSN);
7971
7972           /* Move on to a new frag, so that it is safe to simply
7973              decrease the size of prev_nop_frag.  */
7974           frag_wane (frag_now);
7975           frag_new (0);
7976           mips_move_text_labels ();
7977         }
7978       mips_mark_labels ();
7979       mips_clear_insn_labels ();
7980     }
7981   mips_opts.noreorder++;
7982   mips_any_noreorder = 1;
7983 }
7984
7985 /* End a nested noreorder block.  */
7986
7987 static void
7988 end_noreorder (void)
7989 {
7990   mips_opts.noreorder--;
7991   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7992     {
7993       /* Commit to inserting prev_nop_frag_required nops and go back to
7994          handling nop insertion the .set reorder way.  */
7995       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7996                                 * NOP_INSN_SIZE);
7997       insert_into_history (prev_nop_frag_since,
7998                            prev_nop_frag_required, NOP_INSN);
7999       prev_nop_frag = NULL;
8000     }
8001 }
8002
8003 /* Sign-extend 32-bit mode constants that have bit 31 set and all
8004    higher bits unset.  */
8005
8006 static void
8007 normalize_constant_expr (expressionS *ex)
8008 {
8009   if (ex->X_op == O_constant
8010       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8011     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8012                         - 0x80000000);
8013 }
8014
8015 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
8016    all higher bits unset.  */
8017
8018 static void
8019 normalize_address_expr (expressionS *ex)
8020 {
8021   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
8022         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
8023       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8024     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8025                         - 0x80000000);
8026 }
8027
8028 /* Try to match TOKENS against OPCODE, storing the result in INSN.
8029    Return true if the match was successful.
8030
8031    OPCODE_EXTRA is a value that should be ORed into the opcode
8032    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
8033    there are more alternatives after OPCODE and SOFT_MATCH is
8034    as for mips_arg_info.  */
8035
8036 static bfd_boolean
8037 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8038             struct mips_operand_token *tokens, unsigned int opcode_extra,
8039             bfd_boolean lax_match, bfd_boolean complete_p)
8040 {
8041   const char *args;
8042   struct mips_arg_info arg;
8043   const struct mips_operand *operand;
8044   char c;
8045
8046   imm_expr.X_op = O_absent;
8047   offset_expr.X_op = O_absent;
8048   offset_reloc[0] = BFD_RELOC_UNUSED;
8049   offset_reloc[1] = BFD_RELOC_UNUSED;
8050   offset_reloc[2] = BFD_RELOC_UNUSED;
8051
8052   create_insn (insn, opcode);
8053   /* When no opcode suffix is specified, assume ".xyzw". */
8054   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
8055     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
8056   else
8057     insn->insn_opcode |= opcode_extra;
8058   memset (&arg, 0, sizeof (arg));
8059   arg.insn = insn;
8060   arg.token = tokens;
8061   arg.argnum = 1;
8062   arg.last_regno = ILLEGAL_REG;
8063   arg.dest_regno = ILLEGAL_REG;
8064   arg.lax_match = lax_match;
8065   for (args = opcode->args;; ++args)
8066     {
8067       if (arg.token->type == OT_END)
8068         {
8069           /* Handle unary instructions in which only one operand is given.
8070              The source is then the same as the destination.  */
8071           if (arg.opnum == 1 && *args == ',')
8072             {
8073               operand = (mips_opts.micromips
8074                          ? decode_micromips_operand (args + 1)
8075                          : decode_mips_operand (args + 1));
8076               if (operand && mips_optional_operand_p (operand))
8077                 {
8078                   arg.token = tokens;
8079                   arg.argnum = 1;
8080                   continue;
8081                 }
8082             }
8083
8084           /* Treat elided base registers as $0.  */
8085           if (strcmp (args, "(b)") == 0)
8086             args += 3;
8087
8088           if (args[0] == '+')
8089             switch (args[1])
8090               {
8091               case 'K':
8092               case 'N':
8093                 /* The register suffix is optional. */
8094                 args += 2;
8095                 break;
8096               }
8097
8098           /* Fail the match if there were too few operands.  */
8099           if (*args)
8100             return FALSE;
8101
8102           /* Successful match.  */
8103           if (!complete_p)
8104             return TRUE;
8105           clear_insn_error ();
8106           if (arg.dest_regno == arg.last_regno
8107               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
8108             {
8109               if (arg.opnum == 2)
8110                 set_insn_error
8111                   (0, _("source and destination must be different"));
8112               else if (arg.last_regno == 31)
8113                 set_insn_error
8114                   (0, _("a destination register must be supplied"));
8115             }
8116           else if (arg.last_regno == 31
8117                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
8118                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
8119             set_insn_error (0, _("the source register must not be $31"));
8120           check_completed_insn (&arg);
8121           return TRUE;
8122         }
8123
8124       /* Fail the match if the line has too many operands.   */
8125       if (*args == 0)
8126         return FALSE;
8127
8128       /* Handle characters that need to match exactly.  */
8129       if (*args == '(' || *args == ')' || *args == ',')
8130         {
8131           if (match_char (&arg, *args))
8132             continue;
8133           return FALSE;
8134         }
8135       if (*args == '#')
8136         {
8137           ++args;
8138           if (arg.token->type == OT_DOUBLE_CHAR
8139               && arg.token->u.ch == *args)
8140             {
8141               ++arg.token;
8142               continue;
8143             }
8144           return FALSE;
8145         }
8146
8147       /* Handle special macro operands.  Work out the properties of
8148          other operands.  */
8149       arg.opnum += 1;
8150       switch (*args)
8151         {
8152         case '-':
8153           switch (args[1])
8154             {
8155             case 'A':
8156               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
8157               break;
8158
8159             case 'B':
8160               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
8161               break;
8162             }
8163           break;
8164
8165         case '+':
8166           switch (args[1])
8167             {
8168             case 'i':
8169               *offset_reloc = BFD_RELOC_MIPS_JMP;
8170               break;
8171
8172             case '\'':
8173               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
8174               break;
8175
8176             case '\"':
8177               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
8178               break;
8179             }
8180           break;
8181
8182         case 'I':
8183           if (!match_const_int (&arg, &imm_expr.X_add_number))
8184             return FALSE;
8185           imm_expr.X_op = O_constant;
8186           if (GPR_SIZE == 32)
8187             normalize_constant_expr (&imm_expr);
8188           continue;
8189
8190         case 'A':
8191           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8192             {
8193               /* Assume that the offset has been elided and that what
8194                  we saw was a base register.  The match will fail later
8195                  if that assumption turns out to be wrong.  */
8196               offset_expr.X_op = O_constant;
8197               offset_expr.X_add_number = 0;
8198             }
8199           else
8200             {
8201               if (!match_expression (&arg, &offset_expr, offset_reloc))
8202                 return FALSE;
8203               normalize_address_expr (&offset_expr);
8204             }
8205           continue;
8206
8207         case 'F':
8208           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8209                                      8, TRUE))
8210             return FALSE;
8211           continue;
8212
8213         case 'L':
8214           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8215                                      8, FALSE))
8216             return FALSE;
8217           continue;
8218
8219         case 'f':
8220           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8221                                      4, TRUE))
8222             return FALSE;
8223           continue;
8224
8225         case 'l':
8226           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8227                                      4, FALSE))
8228             return FALSE;
8229           continue;
8230
8231         case 'p':
8232           *offset_reloc = BFD_RELOC_16_PCREL_S2;
8233           break;
8234
8235         case 'a':
8236           *offset_reloc = BFD_RELOC_MIPS_JMP;
8237           break;
8238
8239         case 'm':
8240           gas_assert (mips_opts.micromips);
8241           c = args[1];
8242           switch (c)
8243             {
8244             case 'D':
8245             case 'E':
8246               if (!forced_insn_length)
8247                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
8248               else if (c == 'D')
8249                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8250               else
8251                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8252               break;
8253             }
8254           break;
8255         }
8256
8257       operand = (mips_opts.micromips
8258                  ? decode_micromips_operand (args)
8259                  : decode_mips_operand (args));
8260       if (!operand)
8261         abort ();
8262
8263       /* Skip prefixes.  */
8264       if (*args == '+' || *args == 'm' || *args == '-')
8265         args++;
8266
8267       if (mips_optional_operand_p (operand)
8268           && args[1] == ','
8269           && (arg.token[0].type != OT_REG
8270               || arg.token[1].type == OT_END))
8271         {
8272           /* Assume that the register has been elided and is the
8273              same as the first operand.  */
8274           arg.token = tokens;
8275           arg.argnum = 1;
8276         }
8277
8278       if (!match_operand (&arg, operand))
8279         return FALSE;
8280     }
8281 }
8282
8283 /* Like match_insn, but for MIPS16.  */
8284
8285 static bfd_boolean
8286 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8287                    struct mips_operand_token *tokens)
8288 {
8289   const char *args;
8290   const struct mips_operand *operand;
8291   const struct mips_operand *ext_operand;
8292   bfd_boolean pcrel = FALSE;
8293   int required_insn_length;
8294   struct mips_arg_info arg;
8295   int relax_char;
8296
8297   if (forced_insn_length)
8298     required_insn_length = forced_insn_length;
8299   else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8300     required_insn_length = 2;
8301   else
8302     required_insn_length = 0;
8303
8304   create_insn (insn, opcode);
8305   imm_expr.X_op = O_absent;
8306   offset_expr.X_op = O_absent;
8307   offset_reloc[0] = BFD_RELOC_UNUSED;
8308   offset_reloc[1] = BFD_RELOC_UNUSED;
8309   offset_reloc[2] = BFD_RELOC_UNUSED;
8310   relax_char = 0;
8311
8312   memset (&arg, 0, sizeof (arg));
8313   arg.insn = insn;
8314   arg.token = tokens;
8315   arg.argnum = 1;
8316   arg.last_regno = ILLEGAL_REG;
8317   arg.dest_regno = ILLEGAL_REG;
8318   relax_char = 0;
8319   for (args = opcode->args;; ++args)
8320     {
8321       int c;
8322
8323       if (arg.token->type == OT_END)
8324         {
8325           offsetT value;
8326
8327           /* Handle unary instructions in which only one operand is given.
8328              The source is then the same as the destination.  */
8329           if (arg.opnum == 1 && *args == ',')
8330             {
8331               operand = decode_mips16_operand (args[1], FALSE);
8332               if (operand && mips_optional_operand_p (operand))
8333                 {
8334                   arg.token = tokens;
8335                   arg.argnum = 1;
8336                   continue;
8337                 }
8338             }
8339
8340           /* Fail the match if there were too few operands.  */
8341           if (*args)
8342             return FALSE;
8343
8344           /* Successful match.  Stuff the immediate value in now, if
8345              we can.  */
8346           clear_insn_error ();
8347           if (opcode->pinfo == INSN_MACRO)
8348             {
8349               gas_assert (relax_char == 0 || relax_char == 'p');
8350               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8351             }
8352           else if (relax_char
8353                    && offset_expr.X_op == O_constant
8354                    && !pcrel
8355                    && calculate_reloc (*offset_reloc,
8356                                        offset_expr.X_add_number,
8357                                        &value))
8358             {
8359               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8360                             required_insn_length, &insn->insn_opcode);
8361               offset_expr.X_op = O_absent;
8362               *offset_reloc = BFD_RELOC_UNUSED;
8363             }
8364           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8365             {
8366               if (required_insn_length == 2)
8367                 set_insn_error (0, _("invalid unextended operand value"));
8368               else if (!mips_opcode_32bit_p (opcode))
8369                 {
8370                   forced_insn_length = 4;
8371                   insn->insn_opcode |= MIPS16_EXTEND;
8372                 }
8373             }
8374           else if (relax_char)
8375             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8376
8377           check_completed_insn (&arg);
8378           return TRUE;
8379         }
8380
8381       /* Fail the match if the line has too many operands.   */
8382       if (*args == 0)
8383         return FALSE;
8384
8385       /* Handle characters that need to match exactly.  */
8386       if (*args == '(' || *args == ')' || *args == ',')
8387         {
8388           if (match_char (&arg, *args))
8389             continue;
8390           return FALSE;
8391         }
8392
8393       arg.opnum += 1;
8394       c = *args;
8395       switch (c)
8396         {
8397         case 'p':
8398         case 'q':
8399         case 'A':
8400         case 'B':
8401         case 'E':
8402         case 'V':
8403         case 'u':
8404           relax_char = c;
8405           break;
8406
8407         case 'I':
8408           if (!match_const_int (&arg, &imm_expr.X_add_number))
8409             return FALSE;
8410           imm_expr.X_op = O_constant;
8411           if (GPR_SIZE == 32)
8412             normalize_constant_expr (&imm_expr);
8413           continue;
8414
8415         case 'a':
8416         case 'i':
8417           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8418           break;
8419         }
8420
8421       operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8422       if (!operand)
8423         abort ();
8424
8425       if (operand->type == OP_PCREL)
8426         pcrel = TRUE;
8427       else
8428         {
8429           ext_operand = decode_mips16_operand (c, TRUE);
8430           if (operand != ext_operand)
8431             {
8432               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8433                 {
8434                   offset_expr.X_op = O_constant;
8435                   offset_expr.X_add_number = 0;
8436                   relax_char = c;
8437                   continue;
8438                 }
8439
8440               if (!match_expression (&arg, &offset_expr, offset_reloc))
8441                 return FALSE;
8442
8443               /* '8' is used for SLTI(U) and has traditionally not
8444                  been allowed to take relocation operators.  */
8445               if (offset_reloc[0] != BFD_RELOC_UNUSED
8446                   && (ext_operand->size != 16 || c == '8'))
8447                 {
8448                   match_not_constant (&arg);
8449                   return FALSE;
8450                 }
8451
8452               if (offset_expr.X_op == O_big)
8453                 {
8454                   match_out_of_range (&arg);
8455                   return FALSE;
8456                 }
8457
8458               relax_char = c;
8459               continue;
8460             }
8461         }
8462
8463       if (mips_optional_operand_p (operand)
8464           && args[1] == ','
8465           && (arg.token[0].type != OT_REG
8466               || arg.token[1].type == OT_END))
8467         {
8468           /* Assume that the register has been elided and is the
8469              same as the first operand.  */
8470           arg.token = tokens;
8471           arg.argnum = 1;
8472         }
8473
8474       if (!match_operand (&arg, operand))
8475         return FALSE;
8476     }
8477 }
8478
8479 /* Record that the current instruction is invalid for the current ISA.  */
8480
8481 static void
8482 match_invalid_for_isa (void)
8483 {
8484   set_insn_error_ss
8485     (0, _("opcode not supported on this processor: %s (%s)"),
8486      mips_cpu_info_from_arch (mips_opts.arch)->name,
8487      mips_cpu_info_from_isa (mips_opts.isa)->name);
8488 }
8489
8490 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8491    Return true if a definite match or failure was found, storing any match
8492    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8493    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8494    tried and failed to match under normal conditions and now want to try a
8495    more relaxed match.  */
8496
8497 static bfd_boolean
8498 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8499              const struct mips_opcode *past, struct mips_operand_token *tokens,
8500              int opcode_extra, bfd_boolean lax_match)
8501 {
8502   const struct mips_opcode *opcode;
8503   const struct mips_opcode *invalid_delay_slot;
8504   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8505
8506   /* Search for a match, ignoring alternatives that don't satisfy the
8507      current ISA or forced_length.  */
8508   invalid_delay_slot = 0;
8509   seen_valid_for_isa = FALSE;
8510   seen_valid_for_size = FALSE;
8511   opcode = first;
8512   do
8513     {
8514       gas_assert (strcmp (opcode->name, first->name) == 0);
8515       if (is_opcode_valid (opcode))
8516         {
8517           seen_valid_for_isa = TRUE;
8518           if (is_size_valid (opcode))
8519             {
8520               bfd_boolean delay_slot_ok;
8521
8522               seen_valid_for_size = TRUE;
8523               delay_slot_ok = is_delay_slot_valid (opcode);
8524               if (match_insn (insn, opcode, tokens, opcode_extra,
8525                               lax_match, delay_slot_ok))
8526                 {
8527                   if (!delay_slot_ok)
8528                     {
8529                       if (!invalid_delay_slot)
8530                         invalid_delay_slot = opcode;
8531                     }
8532                   else
8533                     return TRUE;
8534                 }
8535             }
8536         }
8537       ++opcode;
8538     }
8539   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8540
8541   /* If the only matches we found had the wrong length for the delay slot,
8542      pick the first such match.  We'll issue an appropriate warning later.  */
8543   if (invalid_delay_slot)
8544     {
8545       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8546                       lax_match, TRUE))
8547         return TRUE;
8548       abort ();
8549     }
8550
8551   /* Handle the case where we didn't try to match an instruction because
8552      all the alternatives were incompatible with the current ISA.  */
8553   if (!seen_valid_for_isa)
8554     {
8555       match_invalid_for_isa ();
8556       return TRUE;
8557     }
8558
8559   /* Handle the case where we didn't try to match an instruction because
8560      all the alternatives were of the wrong size.  */
8561   if (!seen_valid_for_size)
8562     {
8563       if (mips_opts.insn32)
8564         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8565       else
8566         set_insn_error_i
8567           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8568            8 * forced_insn_length);
8569       return TRUE;
8570     }
8571
8572   return FALSE;
8573 }
8574
8575 /* Like match_insns, but for MIPS16.  */
8576
8577 static bfd_boolean
8578 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8579                     struct mips_operand_token *tokens)
8580 {
8581   const struct mips_opcode *opcode;
8582   bfd_boolean seen_valid_for_isa;
8583   bfd_boolean seen_valid_for_size;
8584
8585   /* Search for a match, ignoring alternatives that don't satisfy the
8586      current ISA.  There are no separate entries for extended forms so
8587      we deal with forced_length later.  */
8588   seen_valid_for_isa = FALSE;
8589   seen_valid_for_size = FALSE;
8590   opcode = first;
8591   do
8592     {
8593       gas_assert (strcmp (opcode->name, first->name) == 0);
8594       if (is_opcode_valid_16 (opcode))
8595         {
8596           seen_valid_for_isa = TRUE;
8597           if (is_size_valid_16 (opcode))
8598             {
8599               seen_valid_for_size = TRUE;
8600               if (match_mips16_insn (insn, opcode, tokens))
8601                 return TRUE;
8602             }
8603         }
8604       ++opcode;
8605     }
8606   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8607          && strcmp (opcode->name, first->name) == 0);
8608
8609   /* Handle the case where we didn't try to match an instruction because
8610      all the alternatives were incompatible with the current ISA.  */
8611   if (!seen_valid_for_isa)
8612     {
8613       match_invalid_for_isa ();
8614       return TRUE;
8615     }
8616
8617   /* Handle the case where we didn't try to match an instruction because
8618      all the alternatives were of the wrong size.  */
8619   if (!seen_valid_for_size)
8620     {
8621       if (forced_insn_length == 2)
8622         set_insn_error
8623           (0, _("unrecognized unextended version of MIPS16 opcode"));
8624       else
8625         set_insn_error
8626           (0, _("unrecognized extended version of MIPS16 opcode"));
8627       return TRUE;
8628     }
8629
8630   return FALSE;
8631 }
8632
8633 /* Set up global variables for the start of a new macro.  */
8634
8635 static void
8636 macro_start (void)
8637 {
8638   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8639   memset (&mips_macro_warning.first_insn_sizes, 0,
8640           sizeof (mips_macro_warning.first_insn_sizes));
8641   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8642   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8643                                      && delayed_branch_p (&history[0]));
8644   if (history[0].frag
8645       && history[0].frag->fr_type == rs_machine_dependent
8646       && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8647       && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8648     mips_macro_warning.delay_slot_length = 0;
8649   else
8650     switch (history[0].insn_mo->pinfo2
8651             & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8652       {
8653       case INSN2_BRANCH_DELAY_32BIT:
8654         mips_macro_warning.delay_slot_length = 4;
8655         break;
8656       case INSN2_BRANCH_DELAY_16BIT:
8657         mips_macro_warning.delay_slot_length = 2;
8658         break;
8659       default:
8660         mips_macro_warning.delay_slot_length = 0;
8661         break;
8662       }
8663   mips_macro_warning.first_frag = NULL;
8664 }
8665
8666 /* Given that a macro is longer than one instruction or of the wrong size,
8667    return the appropriate warning for it.  Return null if no warning is
8668    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8669    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8670    and RELAX_NOMACRO.  */
8671
8672 static const char *
8673 macro_warning (relax_substateT subtype)
8674 {
8675   if (subtype & RELAX_DELAY_SLOT)
8676     return _("macro instruction expanded into multiple instructions"
8677              " in a branch delay slot");
8678   else if (subtype & RELAX_NOMACRO)
8679     return _("macro instruction expanded into multiple instructions");
8680   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8681                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8682     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8683             ? _("macro instruction expanded into a wrong size instruction"
8684                 " in a 16-bit branch delay slot")
8685             : _("macro instruction expanded into a wrong size instruction"
8686                 " in a 32-bit branch delay slot"));
8687   else
8688     return 0;
8689 }
8690
8691 /* Finish up a macro.  Emit warnings as appropriate.  */
8692
8693 static void
8694 macro_end (void)
8695 {
8696   /* Relaxation warning flags.  */
8697   relax_substateT subtype = 0;
8698
8699   /* Check delay slot size requirements.  */
8700   if (mips_macro_warning.delay_slot_length == 2)
8701     subtype |= RELAX_DELAY_SLOT_16BIT;
8702   if (mips_macro_warning.delay_slot_length != 0)
8703     {
8704       if (mips_macro_warning.delay_slot_length
8705           != mips_macro_warning.first_insn_sizes[0])
8706         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8707       if (mips_macro_warning.delay_slot_length
8708           != mips_macro_warning.first_insn_sizes[1])
8709         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8710     }
8711
8712   /* Check instruction count requirements.  */
8713   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8714     {
8715       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8716         subtype |= RELAX_SECOND_LONGER;
8717       if (mips_opts.warn_about_macros)
8718         subtype |= RELAX_NOMACRO;
8719       if (mips_macro_warning.delay_slot_p)
8720         subtype |= RELAX_DELAY_SLOT;
8721     }
8722
8723   /* If both alternatives fail to fill a delay slot correctly,
8724      emit the warning now.  */
8725   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8726       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8727     {
8728       relax_substateT s;
8729       const char *msg;
8730
8731       s = subtype & (RELAX_DELAY_SLOT_16BIT
8732                      | RELAX_DELAY_SLOT_SIZE_FIRST
8733                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8734       msg = macro_warning (s);
8735       if (msg != NULL)
8736         as_warn ("%s", msg);
8737       subtype &= ~s;
8738     }
8739
8740   /* If both implementations are longer than 1 instruction, then emit the
8741      warning now.  */
8742   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8743     {
8744       relax_substateT s;
8745       const char *msg;
8746
8747       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8748       msg = macro_warning (s);
8749       if (msg != NULL)
8750         as_warn ("%s", msg);
8751       subtype &= ~s;
8752     }
8753
8754   /* If any flags still set, then one implementation might need a warning
8755      and the other either will need one of a different kind or none at all.
8756      Pass any remaining flags over to relaxation.  */
8757   if (mips_macro_warning.first_frag != NULL)
8758     mips_macro_warning.first_frag->fr_subtype |= subtype;
8759 }
8760
8761 /* Instruction operand formats used in macros that vary between
8762    standard MIPS and microMIPS code.  */
8763
8764 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8765 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8766 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8767 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8768 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8769 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8770 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8771 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8772
8773 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8774 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8775                                              : cop12_fmt[mips_opts.micromips])
8776 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8777 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8778 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8779 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8780                                              : mem12_fmt[mips_opts.micromips])
8781 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8782 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8783 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8784
8785 /* Read a macro's relocation codes from *ARGS and store them in *R.
8786    The first argument in *ARGS will be either the code for a single
8787    relocation or -1 followed by the three codes that make up a
8788    composite relocation.  */
8789
8790 static void
8791 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8792 {
8793   int i, next;
8794
8795   next = va_arg (*args, int);
8796   if (next >= 0)
8797     r[0] = (bfd_reloc_code_real_type) next;
8798   else
8799     {
8800       for (i = 0; i < 3; i++)
8801         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8802       /* This function is only used for 16-bit relocation fields.
8803          To make the macro code simpler, treat an unrelocated value
8804          in the same way as BFD_RELOC_LO16.  */
8805       if (r[0] == BFD_RELOC_UNUSED)
8806         r[0] = BFD_RELOC_LO16;
8807     }
8808 }
8809
8810 /* Build an instruction created by a macro expansion.  This is passed
8811    a pointer to the count of instructions created so far, an
8812    expression, the name of the instruction to build, an operand format
8813    string, and corresponding arguments.  */
8814
8815 static void
8816 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8817 {
8818   const struct mips_opcode *mo = NULL;
8819   bfd_reloc_code_real_type r[3];
8820   const struct mips_opcode *amo;
8821   const struct mips_operand *operand;
8822   struct hash_control *hash;
8823   struct mips_cl_insn insn;
8824   va_list args;
8825   unsigned int uval;
8826
8827   va_start (args, fmt);
8828
8829   if (mips_opts.mips16)
8830     {
8831       mips16_macro_build (ep, name, fmt, &args);
8832       va_end (args);
8833       return;
8834     }
8835
8836   r[0] = BFD_RELOC_UNUSED;
8837   r[1] = BFD_RELOC_UNUSED;
8838   r[2] = BFD_RELOC_UNUSED;
8839   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8840   amo = (struct mips_opcode *) hash_find (hash, name);
8841   gas_assert (amo);
8842   gas_assert (strcmp (name, amo->name) == 0);
8843
8844   do
8845     {
8846       /* Search until we get a match for NAME.  It is assumed here that
8847          macros will never generate MDMX, MIPS-3D, or MT instructions.
8848          We try to match an instruction that fulfills the branch delay
8849          slot instruction length requirement (if any) of the previous
8850          instruction.  While doing this we record the first instruction
8851          seen that matches all the other conditions and use it anyway
8852          if the requirement cannot be met; we will issue an appropriate
8853          warning later on.  */
8854       if (strcmp (fmt, amo->args) == 0
8855           && amo->pinfo != INSN_MACRO
8856           && is_opcode_valid (amo)
8857           && is_size_valid (amo))
8858         {
8859           if (is_delay_slot_valid (amo))
8860             {
8861               mo = amo;
8862               break;
8863             }
8864           else if (!mo)
8865             mo = amo;
8866         }
8867
8868       ++amo;
8869       gas_assert (amo->name);
8870     }
8871   while (strcmp (name, amo->name) == 0);
8872
8873   gas_assert (mo);
8874   create_insn (&insn, mo);
8875   for (; *fmt; ++fmt)
8876     {
8877       switch (*fmt)
8878         {
8879         case ',':
8880         case '(':
8881         case ')':
8882         case 'z':
8883           break;
8884
8885         case 'i':
8886         case 'j':
8887           macro_read_relocs (&args, r);
8888           gas_assert (*r == BFD_RELOC_GPREL16
8889                       || *r == BFD_RELOC_MIPS_HIGHER
8890                       || *r == BFD_RELOC_HI16_S
8891                       || *r == BFD_RELOC_LO16
8892                       || *r == BFD_RELOC_MIPS_GOT_OFST
8893                       || (mips_opts.micromips
8894                           && (*r == BFD_RELOC_16
8895                               || *r == BFD_RELOC_MIPS_GOT16
8896                               || *r == BFD_RELOC_MIPS_CALL16
8897                               || *r == BFD_RELOC_MIPS_GOT_HI16
8898                               || *r == BFD_RELOC_MIPS_GOT_LO16
8899                               || *r == BFD_RELOC_MIPS_CALL_HI16
8900                               || *r == BFD_RELOC_MIPS_CALL_LO16
8901                               || *r == BFD_RELOC_MIPS_SUB
8902                               || *r == BFD_RELOC_MIPS_GOT_PAGE
8903                               || *r == BFD_RELOC_MIPS_HIGHEST
8904                               || *r == BFD_RELOC_MIPS_GOT_DISP
8905                               || *r == BFD_RELOC_MIPS_TLS_GD
8906                               || *r == BFD_RELOC_MIPS_TLS_LDM
8907                               || *r == BFD_RELOC_MIPS_TLS_DTPREL_HI16
8908                               || *r == BFD_RELOC_MIPS_TLS_DTPREL_LO16
8909                               || *r == BFD_RELOC_MIPS_TLS_GOTTPREL
8910                               || *r == BFD_RELOC_MIPS_TLS_TPREL_HI16
8911                               || *r == BFD_RELOC_MIPS_TLS_TPREL_LO16)));
8912           break;
8913
8914         case 'o':
8915           macro_read_relocs (&args, r);
8916           break;
8917
8918         case 'u':
8919           macro_read_relocs (&args, r);
8920           gas_assert (ep != NULL
8921                       && (ep->X_op == O_constant
8922                           || (ep->X_op == O_symbol
8923                               && (*r == BFD_RELOC_MIPS_HIGHEST
8924                                   || *r == BFD_RELOC_HI16_S
8925                                   || *r == BFD_RELOC_HI16
8926                                   || *r == BFD_RELOC_GPREL16
8927                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8928                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8929           break;
8930
8931         case 'p':
8932           gas_assert (ep != NULL);
8933
8934           /*
8935            * This allows macro() to pass an immediate expression for
8936            * creating short branches without creating a symbol.
8937            *
8938            * We don't allow branch relaxation for these branches, as
8939            * they should only appear in ".set nomacro" anyway.
8940            */
8941           if (ep->X_op == O_constant)
8942             {
8943               /* For microMIPS we always use relocations for branches.
8944                  So we should not resolve immediate values.  */
8945               gas_assert (!mips_opts.micromips);
8946
8947               if ((ep->X_add_number & 3) != 0)
8948                 as_bad (_("branch to misaligned address (0x%lx)"),
8949                         (unsigned long) ep->X_add_number);
8950               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8951                 as_bad (_("branch address range overflow (0x%lx)"),
8952                         (unsigned long) ep->X_add_number);
8953               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8954               ep = NULL;
8955             }
8956           else
8957             *r = BFD_RELOC_16_PCREL_S2;
8958           break;
8959
8960         case 'a':
8961           gas_assert (ep != NULL);
8962           *r = BFD_RELOC_MIPS_JMP;
8963           break;
8964
8965         default:
8966           operand = (mips_opts.micromips
8967                      ? decode_micromips_operand (fmt)
8968                      : decode_mips_operand (fmt));
8969           if (!operand)
8970             abort ();
8971
8972           uval = va_arg (args, int);
8973           if (operand->type == OP_CLO_CLZ_DEST)
8974             uval |= (uval << 5);
8975           insn_insert_operand (&insn, operand, uval);
8976
8977           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8978             ++fmt;
8979           break;
8980         }
8981     }
8982   va_end (args);
8983   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8984
8985   append_insn (&insn, ep, r, TRUE);
8986 }
8987
8988 static void
8989 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8990                     va_list *args)
8991 {
8992   struct mips_opcode *mo;
8993   struct mips_cl_insn insn;
8994   const struct mips_operand *operand;
8995   bfd_reloc_code_real_type r[3]
8996     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8997
8998   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8999   gas_assert (mo);
9000   gas_assert (strcmp (name, mo->name) == 0);
9001
9002   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
9003     {
9004       ++mo;
9005       gas_assert (mo->name);
9006       gas_assert (strcmp (name, mo->name) == 0);
9007     }
9008
9009   create_insn (&insn, mo);
9010   for (; *fmt; ++fmt)
9011     {
9012       int c;
9013
9014       c = *fmt;
9015       switch (c)
9016         {
9017         case ',':
9018         case '(':
9019         case ')':
9020           break;
9021
9022         case '.':
9023         case 'S':
9024         case 'P':
9025         case 'R':
9026           break;
9027
9028         case '<':
9029         case '5':
9030         case 'F':
9031         case 'H':
9032         case 'W':
9033         case 'D':
9034         case 'j':
9035         case '8':
9036         case 'V':
9037         case 'C':
9038         case 'U':
9039         case 'k':
9040         case 'K':
9041         case 'p':
9042         case 'q':
9043           {
9044             offsetT value;
9045
9046             gas_assert (ep != NULL);
9047
9048             if (ep->X_op != O_constant)
9049               *r = (int) BFD_RELOC_UNUSED + c;
9050             else if (calculate_reloc (*r, ep->X_add_number, &value))
9051               {
9052                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
9053                 ep = NULL;
9054                 *r = BFD_RELOC_UNUSED;
9055               }
9056           }
9057           break;
9058
9059         default:
9060           operand = decode_mips16_operand (c, FALSE);
9061           if (!operand)
9062             abort ();
9063
9064           insn_insert_operand (&insn, operand, va_arg (*args, int));
9065           break;
9066         }
9067     }
9068
9069   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
9070
9071   append_insn (&insn, ep, r, TRUE);
9072 }
9073
9074 /*
9075  * Generate a "jalr" instruction with a relocation hint to the called
9076  * function.  This occurs in NewABI PIC code.
9077  */
9078 static void
9079 macro_build_jalr (expressionS *ep, int cprestore)
9080 {
9081   static const bfd_reloc_code_real_type jalr_relocs[2]
9082     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
9083   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
9084   const char *jalr;
9085   char *f = NULL;
9086
9087   if (MIPS_JALR_HINT_P (ep))
9088     {
9089       frag_grow (8);
9090       f = frag_more (0);
9091     }
9092   if (mips_opts.micromips)
9093     {
9094       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
9095               ? "jalr" : "jalrs");
9096       if (MIPS_JALR_HINT_P (ep)
9097           || mips_opts.insn32
9098           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9099         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
9100       else
9101         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
9102     }
9103   else
9104     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
9105   if (MIPS_JALR_HINT_P (ep))
9106     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
9107 }
9108
9109 /*
9110  * Generate a "lui" instruction.
9111  */
9112 static void
9113 macro_build_lui (expressionS *ep, int regnum)
9114 {
9115   gas_assert (! mips_opts.mips16);
9116
9117   if (ep->X_op != O_constant)
9118     {
9119       gas_assert (ep->X_op == O_symbol);
9120       /* _gp_disp is a special case, used from s_cpload.
9121          __gnu_local_gp is used if mips_no_shared.  */
9122       gas_assert (mips_pic == NO_PIC
9123               || (! HAVE_NEWABI
9124                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
9125               || (! mips_in_shared
9126                   && strcmp (S_GET_NAME (ep->X_add_symbol),
9127                              "__gnu_local_gp") == 0));
9128     }
9129
9130   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
9131 }
9132
9133 /* Generate a sequence of instructions to do a load or store from a constant
9134    offset off of a base register (breg) into/from a target register (treg),
9135    using AT if necessary.  */
9136 static void
9137 macro_build_ldst_constoffset (expressionS *ep, const char *op,
9138                               int treg, int breg, int dbl)
9139 {
9140   gas_assert (ep->X_op == O_constant);
9141
9142   /* Sign-extending 32-bit constants makes their handling easier.  */
9143   if (!dbl)
9144     normalize_constant_expr (ep);
9145
9146   /* Right now, this routine can only handle signed 32-bit constants.  */
9147   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
9148     as_warn (_("operand overflow"));
9149
9150   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
9151     {
9152       /* Signed 16-bit offset will fit in the op.  Easy!  */
9153       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
9154     }
9155   else
9156     {
9157       /* 32-bit offset, need multiple instructions and AT, like:
9158            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
9159            addu     $tempreg,$tempreg,$breg
9160            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
9161          to handle the complete offset.  */
9162       macro_build_lui (ep, AT);
9163       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
9164       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
9165
9166       if (!mips_opts.at)
9167         as_bad (_("macro used $at after \".set noat\""));
9168     }
9169 }
9170
9171 /*                      set_at()
9172  * Generates code to set the $at register to true (one)
9173  * if reg is less than the immediate expression.
9174  */
9175 static void
9176 set_at (int reg, int unsignedp)
9177 {
9178   if (imm_expr.X_add_number >= -0x8000
9179       && imm_expr.X_add_number < 0x8000)
9180     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
9181                  AT, reg, BFD_RELOC_LO16);
9182   else
9183     {
9184       load_register (AT, &imm_expr, GPR_SIZE == 64);
9185       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
9186     }
9187 }
9188
9189 /* Count the leading zeroes by performing a binary chop. This is a
9190    bulky bit of source, but performance is a LOT better for the
9191    majority of values than a simple loop to count the bits:
9192        for (lcnt = 0; (lcnt < 32); lcnt++)
9193          if ((v) & (1 << (31 - lcnt)))
9194            break;
9195   However it is not code size friendly, and the gain will drop a bit
9196   on certain cached systems.
9197 */
9198 #define COUNT_TOP_ZEROES(v)             \
9199   (((v) & ~0xffff) == 0                 \
9200    ? ((v) & ~0xff) == 0                 \
9201      ? ((v) & ~0xf) == 0                \
9202        ? ((v) & ~0x3) == 0              \
9203          ? ((v) & ~0x1) == 0            \
9204            ? !(v)                       \
9205              ? 32                       \
9206              : 31                       \
9207            : 30                         \
9208          : ((v) & ~0x7) == 0            \
9209            ? 29                         \
9210            : 28                         \
9211        : ((v) & ~0x3f) == 0             \
9212          ? ((v) & ~0x1f) == 0           \
9213            ? 27                         \
9214            : 26                         \
9215          : ((v) & ~0x7f) == 0           \
9216            ? 25                         \
9217            : 24                         \
9218      : ((v) & ~0xfff) == 0              \
9219        ? ((v) & ~0x3ff) == 0            \
9220          ? ((v) & ~0x1ff) == 0          \
9221            ? 23                         \
9222            : 22                         \
9223          : ((v) & ~0x7ff) == 0          \
9224            ? 21                         \
9225            : 20                         \
9226        : ((v) & ~0x3fff) == 0           \
9227          ? ((v) & ~0x1fff) == 0         \
9228            ? 19                         \
9229            : 18                         \
9230          : ((v) & ~0x7fff) == 0         \
9231            ? 17                         \
9232            : 16                         \
9233    : ((v) & ~0xffffff) == 0             \
9234      ? ((v) & ~0xfffff) == 0            \
9235        ? ((v) & ~0x3ffff) == 0          \
9236          ? ((v) & ~0x1ffff) == 0        \
9237            ? 15                         \
9238            : 14                         \
9239          : ((v) & ~0x7ffff) == 0        \
9240            ? 13                         \
9241            : 12                         \
9242        : ((v) & ~0x3fffff) == 0         \
9243          ? ((v) & ~0x1fffff) == 0       \
9244            ? 11                         \
9245            : 10                         \
9246          : ((v) & ~0x7fffff) == 0       \
9247            ? 9                          \
9248            : 8                          \
9249      : ((v) & ~0xfffffff) == 0          \
9250        ? ((v) & ~0x3ffffff) == 0        \
9251          ? ((v) & ~0x1ffffff) == 0      \
9252            ? 7                          \
9253            : 6                          \
9254          : ((v) & ~0x7ffffff) == 0      \
9255            ? 5                          \
9256            : 4                          \
9257        : ((v) & ~0x3fffffff) == 0       \
9258          ? ((v) & ~0x1fffffff) == 0     \
9259            ? 3                          \
9260            : 2                          \
9261          : ((v) & ~0x7fffffff) == 0     \
9262            ? 1                          \
9263            : 0)
9264
9265 /*                      load_register()
9266  *  This routine generates the least number of instructions necessary to load
9267  *  an absolute expression value into a register.
9268  */
9269 static void
9270 load_register (int reg, expressionS *ep, int dbl)
9271 {
9272   int freg;
9273   expressionS hi32, lo32;
9274
9275   if (ep->X_op != O_big)
9276     {
9277       gas_assert (ep->X_op == O_constant);
9278
9279       /* Sign-extending 32-bit constants makes their handling easier.  */
9280       if (!dbl)
9281         normalize_constant_expr (ep);
9282
9283       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9284         {
9285           /* We can handle 16 bit signed values with an addiu to
9286              $zero.  No need to ever use daddiu here, since $zero and
9287              the result are always correct in 32 bit mode.  */
9288           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9289           return;
9290         }
9291       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9292         {
9293           /* We can handle 16 bit unsigned values with an ori to
9294              $zero.  */
9295           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9296           return;
9297         }
9298       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9299         {
9300           /* 32 bit values require an lui.  */
9301           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9302           if ((ep->X_add_number & 0xffff) != 0)
9303             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9304           return;
9305         }
9306     }
9307
9308   /* The value is larger than 32 bits.  */
9309
9310   if (!dbl || GPR_SIZE == 32)
9311     {
9312       char value[32];
9313
9314       sprintf_vma (value, ep->X_add_number);
9315       as_bad (_("number (0x%s) larger than 32 bits"), value);
9316       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9317       return;
9318     }
9319
9320   if (ep->X_op != O_big)
9321     {
9322       hi32 = *ep;
9323       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9324       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9325       hi32.X_add_number &= 0xffffffff;
9326       lo32 = *ep;
9327       lo32.X_add_number &= 0xffffffff;
9328     }
9329   else
9330     {
9331       gas_assert (ep->X_add_number > 2);
9332       if (ep->X_add_number == 3)
9333         generic_bignum[3] = 0;
9334       else if (ep->X_add_number > 4)
9335         as_bad (_("number larger than 64 bits"));
9336       lo32.X_op = O_constant;
9337       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9338       hi32.X_op = O_constant;
9339       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9340     }
9341
9342   if (hi32.X_add_number == 0)
9343     freg = 0;
9344   else
9345     {
9346       int shift, bit;
9347       unsigned long hi, lo;
9348
9349       if (hi32.X_add_number == (offsetT) 0xffffffff)
9350         {
9351           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9352             {
9353               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9354               return;
9355             }
9356           if (lo32.X_add_number & 0x80000000)
9357             {
9358               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9359               if (lo32.X_add_number & 0xffff)
9360                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9361               return;
9362             }
9363         }
9364
9365       /* Check for 16bit shifted constant.  We know that hi32 is
9366          non-zero, so start the mask on the first bit of the hi32
9367          value.  */
9368       shift = 17;
9369       do
9370         {
9371           unsigned long himask, lomask;
9372
9373           if (shift < 32)
9374             {
9375               himask = 0xffff >> (32 - shift);
9376               lomask = (0xffff << shift) & 0xffffffff;
9377             }
9378           else
9379             {
9380               himask = 0xffff << (shift - 32);
9381               lomask = 0;
9382             }
9383           if ((hi32.X_add_number & ~(offsetT) himask) == 0
9384               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9385             {
9386               expressionS tmp;
9387
9388               tmp.X_op = O_constant;
9389               if (shift < 32)
9390                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9391                                     | (lo32.X_add_number >> shift));
9392               else
9393                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9394               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9395               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9396                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9397               return;
9398             }
9399           ++shift;
9400         }
9401       while (shift <= (64 - 16));
9402
9403       /* Find the bit number of the lowest one bit, and store the
9404          shifted value in hi/lo.  */
9405       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9406       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9407       if (lo != 0)
9408         {
9409           bit = 0;
9410           while ((lo & 1) == 0)
9411             {
9412               lo >>= 1;
9413               ++bit;
9414             }
9415           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9416           hi >>= bit;
9417         }
9418       else
9419         {
9420           bit = 32;
9421           while ((hi & 1) == 0)
9422             {
9423               hi >>= 1;
9424               ++bit;
9425             }
9426           lo = hi;
9427           hi = 0;
9428         }
9429
9430       /* Optimize if the shifted value is a (power of 2) - 1.  */
9431       if ((hi == 0 && ((lo + 1) & lo) == 0)
9432           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9433         {
9434           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9435           if (shift != 0)
9436             {
9437               expressionS tmp;
9438
9439               /* This instruction will set the register to be all
9440                  ones.  */
9441               tmp.X_op = O_constant;
9442               tmp.X_add_number = (offsetT) -1;
9443               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9444               if (bit != 0)
9445                 {
9446                   bit += shift;
9447                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9448                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9449                 }
9450               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9451                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9452               return;
9453             }
9454         }
9455
9456       /* Sign extend hi32 before calling load_register, because we can
9457          generally get better code when we load a sign extended value.  */
9458       if ((hi32.X_add_number & 0x80000000) != 0)
9459         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9460       load_register (reg, &hi32, 0);
9461       freg = reg;
9462     }
9463   if ((lo32.X_add_number & 0xffff0000) == 0)
9464     {
9465       if (freg != 0)
9466         {
9467           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9468           freg = reg;
9469         }
9470     }
9471   else
9472     {
9473       expressionS mid16;
9474
9475       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9476         {
9477           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9478           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9479           return;
9480         }
9481
9482       if (freg != 0)
9483         {
9484           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9485           freg = reg;
9486         }
9487       mid16 = lo32;
9488       mid16.X_add_number >>= 16;
9489       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9490       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9491       freg = reg;
9492     }
9493   if ((lo32.X_add_number & 0xffff) != 0)
9494     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9495 }
9496
9497 static inline void
9498 load_delay_nop (void)
9499 {
9500   if (!gpr_interlocks)
9501     macro_build (NULL, "nop", "");
9502 }
9503
9504 /* Load an address into a register.  */
9505
9506 static void
9507 load_address (int reg, expressionS *ep, int *used_at)
9508 {
9509   if (ep->X_op != O_constant
9510       && ep->X_op != O_symbol)
9511     {
9512       as_bad (_("expression too complex"));
9513       ep->X_op = O_constant;
9514     }
9515
9516   if (ep->X_op == O_constant)
9517     {
9518       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9519       return;
9520     }
9521
9522   if (mips_pic == NO_PIC)
9523     {
9524       /* If this is a reference to a GP relative symbol, we want
9525            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9526          Otherwise we want
9527            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9528            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9529          If we have an addend, we always use the latter form.
9530
9531          With 64bit address space and a usable $at we want
9532            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9533            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9534            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9535            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9536            dsll32       $reg,0
9537            daddu        $reg,$reg,$at
9538
9539          If $at is already in use, we use a path which is suboptimal
9540          on superscalar processors.
9541            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9542            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9543            dsll         $reg,16
9544            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9545            dsll         $reg,16
9546            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9547
9548          For GP relative symbols in 64bit address space we can use
9549          the same sequence as in 32bit address space.  */
9550       if (HAVE_64BIT_SYMBOLS)
9551         {
9552           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9553               && !nopic_need_relax (ep->X_add_symbol, 1))
9554             {
9555               relax_start (ep->X_add_symbol);
9556               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9557                            mips_gp_register, BFD_RELOC_GPREL16);
9558               relax_switch ();
9559             }
9560
9561           if (*used_at == 0 && mips_opts.at)
9562             {
9563               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9564               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9565               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9566                            BFD_RELOC_MIPS_HIGHER);
9567               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9568               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9569               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9570               *used_at = 1;
9571             }
9572           else
9573             {
9574               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9575               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9576                            BFD_RELOC_MIPS_HIGHER);
9577               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9578               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9579               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9580               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9581             }
9582
9583           if (mips_relax.sequence)
9584             relax_end ();
9585         }
9586       else
9587         {
9588           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9589               && !nopic_need_relax (ep->X_add_symbol, 1))
9590             {
9591               relax_start (ep->X_add_symbol);
9592               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9593                            mips_gp_register, BFD_RELOC_GPREL16);
9594               relax_switch ();
9595             }
9596           macro_build_lui (ep, reg);
9597           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9598                        reg, reg, BFD_RELOC_LO16);
9599           if (mips_relax.sequence)
9600             relax_end ();
9601         }
9602     }
9603   else if (!mips_big_got)
9604     {
9605       expressionS ex;
9606
9607       /* If this is a reference to an external symbol, we want
9608            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9609          Otherwise we want
9610            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9611            nop
9612            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9613          If there is a constant, it must be added in after.
9614
9615          If we have NewABI, we want
9616            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9617          unless we're referencing a global symbol with a non-zero
9618          offset, in which case cst must be added separately.  */
9619       if (HAVE_NEWABI)
9620         {
9621           if (ep->X_add_number)
9622             {
9623               ex.X_add_number = ep->X_add_number;
9624               ep->X_add_number = 0;
9625               relax_start (ep->X_add_symbol);
9626               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9627                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9628               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9629                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9630               ex.X_op = O_constant;
9631               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9632                            reg, reg, BFD_RELOC_LO16);
9633               ep->X_add_number = ex.X_add_number;
9634               relax_switch ();
9635             }
9636           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9637                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9638           if (mips_relax.sequence)
9639             relax_end ();
9640         }
9641       else
9642         {
9643           ex.X_add_number = ep->X_add_number;
9644           ep->X_add_number = 0;
9645           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9646                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9647           load_delay_nop ();
9648           relax_start (ep->X_add_symbol);
9649           relax_switch ();
9650           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9651                        BFD_RELOC_LO16);
9652           relax_end ();
9653
9654           if (ex.X_add_number != 0)
9655             {
9656               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9657                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9658               ex.X_op = O_constant;
9659               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9660                            reg, reg, BFD_RELOC_LO16);
9661             }
9662         }
9663     }
9664   else if (mips_big_got)
9665     {
9666       expressionS ex;
9667
9668       /* This is the large GOT case.  If this is a reference to an
9669          external symbol, we want
9670            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9671            addu         $reg,$reg,$gp
9672            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9673
9674          Otherwise, for a reference to a local symbol in old ABI, we want
9675            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9676            nop
9677            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9678          If there is a constant, it must be added in after.
9679
9680          In the NewABI, for local symbols, with or without offsets, we want:
9681            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9682            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9683       */
9684       if (HAVE_NEWABI)
9685         {
9686           ex.X_add_number = ep->X_add_number;
9687           ep->X_add_number = 0;
9688           relax_start (ep->X_add_symbol);
9689           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9690           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9691                        reg, reg, mips_gp_register);
9692           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9693                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9694           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9695             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9696           else if (ex.X_add_number)
9697             {
9698               ex.X_op = O_constant;
9699               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9700                            BFD_RELOC_LO16);
9701             }
9702
9703           ep->X_add_number = ex.X_add_number;
9704           relax_switch ();
9705           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9706                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9707           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9708                        BFD_RELOC_MIPS_GOT_OFST);
9709           relax_end ();
9710         }
9711       else
9712         {
9713           ex.X_add_number = ep->X_add_number;
9714           ep->X_add_number = 0;
9715           relax_start (ep->X_add_symbol);
9716           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9717           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9718                        reg, reg, mips_gp_register);
9719           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9720                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9721           relax_switch ();
9722           if (reg_needs_delay (mips_gp_register))
9723             {
9724               /* We need a nop before loading from $gp.  This special
9725                  check is required because the lui which starts the main
9726                  instruction stream does not refer to $gp, and so will not
9727                  insert the nop which may be required.  */
9728               macro_build (NULL, "nop", "");
9729             }
9730           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9731                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9732           load_delay_nop ();
9733           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9734                        BFD_RELOC_LO16);
9735           relax_end ();
9736
9737           if (ex.X_add_number != 0)
9738             {
9739               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9740                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9741               ex.X_op = O_constant;
9742               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9743                            BFD_RELOC_LO16);
9744             }
9745         }
9746     }
9747   else
9748     abort ();
9749
9750   if (!mips_opts.at && *used_at == 1)
9751     as_bad (_("macro used $at after \".set noat\""));
9752 }
9753
9754 /* Move the contents of register SOURCE into register DEST.  */
9755
9756 static void
9757 move_register (int dest, int source)
9758 {
9759   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9760      instruction specifically requires a 32-bit one.  */
9761   if (mips_opts.micromips
9762       && !mips_opts.insn32
9763       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9764     macro_build (NULL, "move", "mp,mj", dest, source);
9765   else
9766     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9767 }
9768
9769 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9770    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9771    The two alternatives are:
9772
9773    Global symbol                Local symbol
9774    -------------                ------------
9775    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9776    ...                          ...
9777    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9778
9779    load_got_offset emits the first instruction and add_got_offset
9780    emits the second for a 16-bit offset or add_got_offset_hilo emits
9781    a sequence to add a 32-bit offset using a scratch register.  */
9782
9783 static void
9784 load_got_offset (int dest, expressionS *local)
9785 {
9786   expressionS global;
9787
9788   global = *local;
9789   global.X_add_number = 0;
9790
9791   relax_start (local->X_add_symbol);
9792   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9793                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9794   relax_switch ();
9795   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9796                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9797   relax_end ();
9798 }
9799
9800 static void
9801 add_got_offset (int dest, expressionS *local)
9802 {
9803   expressionS global;
9804
9805   global.X_op = O_constant;
9806   global.X_op_symbol = NULL;
9807   global.X_add_symbol = NULL;
9808   global.X_add_number = local->X_add_number;
9809
9810   relax_start (local->X_add_symbol);
9811   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9812                dest, dest, BFD_RELOC_LO16);
9813   relax_switch ();
9814   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9815   relax_end ();
9816 }
9817
9818 static void
9819 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9820 {
9821   expressionS global;
9822   int hold_mips_optimize;
9823
9824   global.X_op = O_constant;
9825   global.X_op_symbol = NULL;
9826   global.X_add_symbol = NULL;
9827   global.X_add_number = local->X_add_number;
9828
9829   relax_start (local->X_add_symbol);
9830   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9831   relax_switch ();
9832   /* Set mips_optimize around the lui instruction to avoid
9833      inserting an unnecessary nop after the lw.  */
9834   hold_mips_optimize = mips_optimize;
9835   mips_optimize = 2;
9836   macro_build_lui (&global, tmp);
9837   mips_optimize = hold_mips_optimize;
9838   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9839   relax_end ();
9840
9841   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9842 }
9843
9844 /* Emit a sequence of instructions to emulate a branch likely operation.
9845    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9846    is its complementing branch with the original condition negated.
9847    CALL is set if the original branch specified the link operation.
9848    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9849
9850    Code like this is produced in the noreorder mode:
9851
9852         BRNEG   <args>, 1f
9853          nop
9854         b       <sym>
9855          delay slot (executed only if branch taken)
9856     1:
9857
9858    or, if CALL is set:
9859
9860         BRNEG   <args>, 1f
9861          nop
9862         bal     <sym>
9863          delay slot (executed only if branch taken)
9864     1:
9865
9866    In the reorder mode the delay slot would be filled with a nop anyway,
9867    so code produced is simply:
9868
9869         BR      <args>, <sym>
9870          nop
9871
9872    This function is used when producing code for the microMIPS ASE that
9873    does not implement branch likely instructions in hardware.  */
9874
9875 static void
9876 macro_build_branch_likely (const char *br, const char *brneg,
9877                            int call, expressionS *ep, const char *fmt,
9878                            unsigned int sreg, unsigned int treg)
9879 {
9880   int noreorder = mips_opts.noreorder;
9881   expressionS expr1;
9882
9883   gas_assert (mips_opts.micromips);
9884   start_noreorder ();
9885   if (noreorder)
9886     {
9887       micromips_label_expr (&expr1);
9888       macro_build (&expr1, brneg, fmt, sreg, treg);
9889       macro_build (NULL, "nop", "");
9890       macro_build (ep, call ? "bal" : "b", "p");
9891
9892       /* Set to true so that append_insn adds a label.  */
9893       emit_branch_likely_macro = TRUE;
9894     }
9895   else
9896     {
9897       macro_build (ep, br, fmt, sreg, treg);
9898       macro_build (NULL, "nop", "");
9899     }
9900   end_noreorder ();
9901 }
9902
9903 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9904    the condition code tested.  EP specifies the branch target.  */
9905
9906 static void
9907 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9908 {
9909   const int call = 0;
9910   const char *brneg;
9911   const char *br;
9912
9913   switch (type)
9914     {
9915     case M_BC1FL:
9916       br = "bc1f";
9917       brneg = "bc1t";
9918       break;
9919     case M_BC1TL:
9920       br = "bc1t";
9921       brneg = "bc1f";
9922       break;
9923     case M_BC2FL:
9924       br = "bc2f";
9925       brneg = "bc2t";
9926       break;
9927     case M_BC2TL:
9928       br = "bc2t";
9929       brneg = "bc2f";
9930       break;
9931     default:
9932       abort ();
9933     }
9934   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9935 }
9936
9937 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9938    the register tested.  EP specifies the branch target.  */
9939
9940 static void
9941 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9942 {
9943   const char *brneg = NULL;
9944   const char *br;
9945   int call = 0;
9946
9947   switch (type)
9948     {
9949     case M_BGEZ:
9950       br = "bgez";
9951       break;
9952     case M_BGEZL:
9953       br = mips_opts.micromips ? "bgez" : "bgezl";
9954       brneg = "bltz";
9955       break;
9956     case M_BGEZALL:
9957       gas_assert (mips_opts.micromips);
9958       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9959       brneg = "bltz";
9960       call = 1;
9961       break;
9962     case M_BGTZ:
9963       br = "bgtz";
9964       break;
9965     case M_BGTZL:
9966       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9967       brneg = "blez";
9968       break;
9969     case M_BLEZ:
9970       br = "blez";
9971       break;
9972     case M_BLEZL:
9973       br = mips_opts.micromips ? "blez" : "blezl";
9974       brneg = "bgtz";
9975       break;
9976     case M_BLTZ:
9977       br = "bltz";
9978       break;
9979     case M_BLTZL:
9980       br = mips_opts.micromips ? "bltz" : "bltzl";
9981       brneg = "bgez";
9982       break;
9983     case M_BLTZALL:
9984       gas_assert (mips_opts.micromips);
9985       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9986       brneg = "bgez";
9987       call = 1;
9988       break;
9989     default:
9990       abort ();
9991     }
9992   if (mips_opts.micromips && brneg)
9993     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9994   else
9995     macro_build (ep, br, "s,p", sreg);
9996 }
9997
9998 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9999    TREG as the registers tested.  EP specifies the branch target.  */
10000
10001 static void
10002 macro_build_branch_rsrt (int type, expressionS *ep,
10003                          unsigned int sreg, unsigned int treg)
10004 {
10005   const char *brneg = NULL;
10006   const int call = 0;
10007   const char *br;
10008
10009   switch (type)
10010     {
10011     case M_BEQ:
10012     case M_BEQ_I:
10013       br = "beq";
10014       break;
10015     case M_BEQL:
10016     case M_BEQL_I:
10017       br = mips_opts.micromips ? "beq" : "beql";
10018       brneg = "bne";
10019       break;
10020     case M_BNE:
10021     case M_BNE_I:
10022       br = "bne";
10023       break;
10024     case M_BNEL:
10025     case M_BNEL_I:
10026       br = mips_opts.micromips ? "bne" : "bnel";
10027       brneg = "beq";
10028       break;
10029     default:
10030       abort ();
10031     }
10032   if (mips_opts.micromips && brneg)
10033     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
10034   else
10035     macro_build (ep, br, "s,t,p", sreg, treg);
10036 }
10037
10038 /* Return the high part that should be loaded in order to make the low
10039    part of VALUE accessible using an offset of OFFBITS bits.  */
10040
10041 static offsetT
10042 offset_high_part (offsetT value, unsigned int offbits)
10043 {
10044   offsetT bias;
10045   addressT low_mask;
10046
10047   if (offbits == 0)
10048     return value;
10049   bias = 1 << (offbits - 1);
10050   low_mask = bias * 2 - 1;
10051   return (value + bias) & ~low_mask;
10052 }
10053
10054 /* Return true if the value stored in offset_expr and offset_reloc
10055    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
10056    amount that the caller wants to add without inducing overflow
10057    and ALIGN is the known alignment of the value in bytes.  */
10058
10059 static bfd_boolean
10060 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
10061 {
10062   if (offbits == 16)
10063     {
10064       /* Accept any relocation operator if overflow isn't a concern.  */
10065       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
10066         return TRUE;
10067
10068       /* These relocations are guaranteed not to overflow in correct links.  */
10069       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
10070           || gprel16_reloc_p (*offset_reloc))
10071         return TRUE;
10072     }
10073   if (offset_expr.X_op == O_constant
10074       && offset_high_part (offset_expr.X_add_number, offbits) == 0
10075       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
10076     return TRUE;
10077   return FALSE;
10078 }
10079
10080 /*
10081  *                      Build macros
10082  *   This routine implements the seemingly endless macro or synthesized
10083  * instructions and addressing modes in the mips assembly language. Many
10084  * of these macros are simple and are similar to each other. These could
10085  * probably be handled by some kind of table or grammar approach instead of
10086  * this verbose method. Others are not simple macros but are more like
10087  * optimizing code generation.
10088  *   One interesting optimization is when several store macros appear
10089  * consecutively that would load AT with the upper half of the same address.
10090  * The ensuing load upper instructions are omitted. This implies some kind
10091  * of global optimization. We currently only optimize within a single macro.
10092  *   For many of the load and store macros if the address is specified as a
10093  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
10094  * first load register 'at' with zero and use it as the base register. The
10095  * mips assembler simply uses register $zero. Just one tiny optimization
10096  * we're missing.
10097  */
10098 static void
10099 macro (struct mips_cl_insn *ip, char *str)
10100 {
10101   const struct mips_operand_array *operands;
10102   unsigned int breg, i;
10103   unsigned int tempreg;
10104   int mask;
10105   int used_at = 0;
10106   expressionS label_expr;
10107   expressionS expr1;
10108   expressionS *ep;
10109   const char *s;
10110   const char *s2;
10111   const char *fmt;
10112   int likely = 0;
10113   int coproc = 0;
10114   int offbits = 16;
10115   int call = 0;
10116   int jals = 0;
10117   int dbl = 0;
10118   int imm = 0;
10119   int ust = 0;
10120   int lp = 0;
10121   bfd_boolean large_offset;
10122   int off;
10123   int hold_mips_optimize;
10124   unsigned int align;
10125   unsigned int op[MAX_OPERANDS];
10126
10127   gas_assert (! mips_opts.mips16);
10128
10129   operands = insn_operands (ip);
10130   for (i = 0; i < MAX_OPERANDS; i++)
10131     if (operands->operand[i])
10132       op[i] = insn_extract_operand (ip, operands->operand[i]);
10133     else
10134       op[i] = -1;
10135
10136   mask = ip->insn_mo->mask;
10137
10138   label_expr.X_op = O_constant;
10139   label_expr.X_op_symbol = NULL;
10140   label_expr.X_add_symbol = NULL;
10141   label_expr.X_add_number = 0;
10142
10143   expr1.X_op = O_constant;
10144   expr1.X_op_symbol = NULL;
10145   expr1.X_add_symbol = NULL;
10146   expr1.X_add_number = 1;
10147   align = 1;
10148
10149   switch (mask)
10150     {
10151     case M_DABS:
10152       dbl = 1;
10153       /* Fall through.  */
10154     case M_ABS:
10155       /*    bgez    $a0,1f
10156             move    v0,$a0
10157             sub     v0,$zero,$a0
10158          1:
10159        */
10160
10161       start_noreorder ();
10162
10163       if (mips_opts.micromips)
10164         micromips_label_expr (&label_expr);
10165       else
10166         label_expr.X_add_number = 8;
10167       macro_build (&label_expr, "bgez", "s,p", op[1]);
10168       if (op[0] == op[1])
10169         macro_build (NULL, "nop", "");
10170       else
10171         move_register (op[0], op[1]);
10172       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
10173       if (mips_opts.micromips)
10174         micromips_add_label ();
10175
10176       end_noreorder ();
10177       break;
10178
10179     case M_ADD_I:
10180       s = "addi";
10181       s2 = "add";
10182       goto do_addi;
10183     case M_ADDU_I:
10184       s = "addiu";
10185       s2 = "addu";
10186       goto do_addi;
10187     case M_DADD_I:
10188       dbl = 1;
10189       s = "daddi";
10190       s2 = "dadd";
10191       if (!mips_opts.micromips)
10192         goto do_addi;
10193       if (imm_expr.X_add_number >= -0x200
10194           && imm_expr.X_add_number < 0x200)
10195         {
10196           macro_build (NULL, s, "t,r,.", op[0], op[1],
10197                        (int) imm_expr.X_add_number);
10198           break;
10199         }
10200       goto do_addi_i;
10201     case M_DADDU_I:
10202       dbl = 1;
10203       s = "daddiu";
10204       s2 = "daddu";
10205     do_addi:
10206       if (imm_expr.X_add_number >= -0x8000
10207           && imm_expr.X_add_number < 0x8000)
10208         {
10209           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
10210           break;
10211         }
10212     do_addi_i:
10213       used_at = 1;
10214       load_register (AT, &imm_expr, dbl);
10215       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10216       break;
10217
10218     case M_AND_I:
10219       s = "andi";
10220       s2 = "and";
10221       goto do_bit;
10222     case M_OR_I:
10223       s = "ori";
10224       s2 = "or";
10225       goto do_bit;
10226     case M_NOR_I:
10227       s = "";
10228       s2 = "nor";
10229       goto do_bit;
10230     case M_XOR_I:
10231       s = "xori";
10232       s2 = "xor";
10233     do_bit:
10234       if (imm_expr.X_add_number >= 0
10235           && imm_expr.X_add_number < 0x10000)
10236         {
10237           if (mask != M_NOR_I)
10238             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10239           else
10240             {
10241               macro_build (&imm_expr, "ori", "t,r,i",
10242                            op[0], op[1], BFD_RELOC_LO16);
10243               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10244             }
10245           break;
10246         }
10247
10248       used_at = 1;
10249       load_register (AT, &imm_expr, GPR_SIZE == 64);
10250       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10251       break;
10252
10253     case M_BALIGN:
10254       switch (imm_expr.X_add_number)
10255         {
10256         case 0:
10257           macro_build (NULL, "nop", "");
10258           break;
10259         case 2:
10260           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10261           break;
10262         case 1:
10263         case 3:
10264           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10265                        (int) imm_expr.X_add_number);
10266           break;
10267         default:
10268           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10269                   (unsigned long) imm_expr.X_add_number);
10270           break;
10271         }
10272       break;
10273
10274     case M_BC1FL:
10275     case M_BC1TL:
10276     case M_BC2FL:
10277     case M_BC2TL:
10278       gas_assert (mips_opts.micromips);
10279       macro_build_branch_ccl (mask, &offset_expr,
10280                               EXTRACT_OPERAND (1, BCC, *ip));
10281       break;
10282
10283     case M_BEQ_I:
10284     case M_BEQL_I:
10285     case M_BNE_I:
10286     case M_BNEL_I:
10287       if (imm_expr.X_add_number == 0)
10288         op[1] = 0;
10289       else
10290         {
10291           op[1] = AT;
10292           used_at = 1;
10293           load_register (op[1], &imm_expr, GPR_SIZE == 64);
10294         }
10295       /* Fall through.  */
10296     case M_BEQL:
10297     case M_BNEL:
10298       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10299       break;
10300
10301     case M_BGEL:
10302       likely = 1;
10303       /* Fall through.  */
10304     case M_BGE:
10305       if (op[1] == 0)
10306         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10307       else if (op[0] == 0)
10308         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10309       else
10310         {
10311           used_at = 1;
10312           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10313           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10314                                    &offset_expr, AT, ZERO);
10315         }
10316       break;
10317
10318     case M_BGEZL:
10319     case M_BGEZALL:
10320     case M_BGTZL:
10321     case M_BLEZL:
10322     case M_BLTZL:
10323     case M_BLTZALL:
10324       macro_build_branch_rs (mask, &offset_expr, op[0]);
10325       break;
10326
10327     case M_BGTL_I:
10328       likely = 1;
10329       /* Fall through.  */
10330     case M_BGT_I:
10331       /* Check for > max integer.  */
10332       if (imm_expr.X_add_number >= GPR_SMAX)
10333         {
10334         do_false:
10335           /* Result is always false.  */
10336           if (! likely)
10337             macro_build (NULL, "nop", "");
10338           else
10339             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10340           break;
10341         }
10342       ++imm_expr.X_add_number;
10343       /* FALLTHROUGH */
10344     case M_BGE_I:
10345     case M_BGEL_I:
10346       if (mask == M_BGEL_I)
10347         likely = 1;
10348       if (imm_expr.X_add_number == 0)
10349         {
10350           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10351                                  &offset_expr, op[0]);
10352           break;
10353         }
10354       if (imm_expr.X_add_number == 1)
10355         {
10356           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10357                                  &offset_expr, op[0]);
10358           break;
10359         }
10360       if (imm_expr.X_add_number <= GPR_SMIN)
10361         {
10362         do_true:
10363           /* result is always true */
10364           as_warn (_("branch %s is always true"), ip->insn_mo->name);
10365           macro_build (&offset_expr, "b", "p");
10366           break;
10367         }
10368       used_at = 1;
10369       set_at (op[0], 0);
10370       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10371                                &offset_expr, AT, ZERO);
10372       break;
10373
10374     case M_BGEUL:
10375       likely = 1;
10376       /* Fall through.  */
10377     case M_BGEU:
10378       if (op[1] == 0)
10379         goto do_true;
10380       else if (op[0] == 0)
10381         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10382                                  &offset_expr, ZERO, op[1]);
10383       else
10384         {
10385           used_at = 1;
10386           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10387           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10388                                    &offset_expr, AT, ZERO);
10389         }
10390       break;
10391
10392     case M_BGTUL_I:
10393       likely = 1;
10394       /* Fall through.  */
10395     case M_BGTU_I:
10396       if (op[0] == 0
10397           || (GPR_SIZE == 32
10398               && imm_expr.X_add_number == -1))
10399         goto do_false;
10400       ++imm_expr.X_add_number;
10401       /* FALLTHROUGH */
10402     case M_BGEU_I:
10403     case M_BGEUL_I:
10404       if (mask == M_BGEUL_I)
10405         likely = 1;
10406       if (imm_expr.X_add_number == 0)
10407         goto do_true;
10408       else if (imm_expr.X_add_number == 1)
10409         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10410                                  &offset_expr, op[0], ZERO);
10411       else
10412         {
10413           used_at = 1;
10414           set_at (op[0], 1);
10415           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10416                                    &offset_expr, AT, ZERO);
10417         }
10418       break;
10419
10420     case M_BGTL:
10421       likely = 1;
10422       /* Fall through.  */
10423     case M_BGT:
10424       if (op[1] == 0)
10425         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10426       else if (op[0] == 0)
10427         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10428       else
10429         {
10430           used_at = 1;
10431           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10432           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10433                                    &offset_expr, AT, ZERO);
10434         }
10435       break;
10436
10437     case M_BGTUL:
10438       likely = 1;
10439       /* Fall through.  */
10440     case M_BGTU:
10441       if (op[1] == 0)
10442         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10443                                  &offset_expr, op[0], ZERO);
10444       else if (op[0] == 0)
10445         goto do_false;
10446       else
10447         {
10448           used_at = 1;
10449           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10450           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10451                                    &offset_expr, AT, ZERO);
10452         }
10453       break;
10454
10455     case M_BLEL:
10456       likely = 1;
10457       /* Fall through.  */
10458     case M_BLE:
10459       if (op[1] == 0)
10460         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10461       else if (op[0] == 0)
10462         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10463       else
10464         {
10465           used_at = 1;
10466           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10467           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10468                                    &offset_expr, AT, ZERO);
10469         }
10470       break;
10471
10472     case M_BLEL_I:
10473       likely = 1;
10474       /* Fall through.  */
10475     case M_BLE_I:
10476       if (imm_expr.X_add_number >= GPR_SMAX)
10477         goto do_true;
10478       ++imm_expr.X_add_number;
10479       /* FALLTHROUGH */
10480     case M_BLT_I:
10481     case M_BLTL_I:
10482       if (mask == M_BLTL_I)
10483         likely = 1;
10484       if (imm_expr.X_add_number == 0)
10485         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10486       else if (imm_expr.X_add_number == 1)
10487         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10488       else
10489         {
10490           used_at = 1;
10491           set_at (op[0], 0);
10492           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10493                                    &offset_expr, AT, ZERO);
10494         }
10495       break;
10496
10497     case M_BLEUL:
10498       likely = 1;
10499       /* Fall through.  */
10500     case M_BLEU:
10501       if (op[1] == 0)
10502         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10503                                  &offset_expr, op[0], ZERO);
10504       else if (op[0] == 0)
10505         goto do_true;
10506       else
10507         {
10508           used_at = 1;
10509           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10510           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10511                                    &offset_expr, AT, ZERO);
10512         }
10513       break;
10514
10515     case M_BLEUL_I:
10516       likely = 1;
10517       /* Fall through.  */
10518     case M_BLEU_I:
10519       if (op[0] == 0
10520           || (GPR_SIZE == 32
10521               && imm_expr.X_add_number == -1))
10522         goto do_true;
10523       ++imm_expr.X_add_number;
10524       /* FALLTHROUGH */
10525     case M_BLTU_I:
10526     case M_BLTUL_I:
10527       if (mask == M_BLTUL_I)
10528         likely = 1;
10529       if (imm_expr.X_add_number == 0)
10530         goto do_false;
10531       else if (imm_expr.X_add_number == 1)
10532         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10533                                  &offset_expr, op[0], ZERO);
10534       else
10535         {
10536           used_at = 1;
10537           set_at (op[0], 1);
10538           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10539                                    &offset_expr, AT, ZERO);
10540         }
10541       break;
10542
10543     case M_BLTL:
10544       likely = 1;
10545       /* Fall through.  */
10546     case M_BLT:
10547       if (op[1] == 0)
10548         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10549       else if (op[0] == 0)
10550         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10551       else
10552         {
10553           used_at = 1;
10554           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10555           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10556                                    &offset_expr, AT, ZERO);
10557         }
10558       break;
10559
10560     case M_BLTUL:
10561       likely = 1;
10562       /* Fall through.  */
10563     case M_BLTU:
10564       if (op[1] == 0)
10565         goto do_false;
10566       else if (op[0] == 0)
10567         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10568                                  &offset_expr, ZERO, op[1]);
10569       else
10570         {
10571           used_at = 1;
10572           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10573           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10574                                    &offset_expr, AT, ZERO);
10575         }
10576       break;
10577
10578     case M_DDIV_3:
10579       dbl = 1;
10580       /* Fall through.  */
10581     case M_DIV_3:
10582       s = "mflo";
10583       goto do_div3;
10584     case M_DREM_3:
10585       dbl = 1;
10586       /* Fall through.  */
10587     case M_REM_3:
10588       s = "mfhi";
10589     do_div3:
10590       if (op[2] == 0)
10591         {
10592           as_warn (_("divide by zero"));
10593           if (mips_trap)
10594             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10595           else
10596             macro_build (NULL, "break", BRK_FMT, 7);
10597           break;
10598         }
10599
10600       start_noreorder ();
10601       if (mips_trap)
10602         {
10603           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10604           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10605         }
10606       else
10607         {
10608           if (mips_opts.micromips)
10609             micromips_label_expr (&label_expr);
10610           else
10611             label_expr.X_add_number = 8;
10612           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10613           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10614           macro_build (NULL, "break", BRK_FMT, 7);
10615           if (mips_opts.micromips)
10616             micromips_add_label ();
10617         }
10618       expr1.X_add_number = -1;
10619       used_at = 1;
10620       load_register (AT, &expr1, dbl);
10621       if (mips_opts.micromips)
10622         micromips_label_expr (&label_expr);
10623       else
10624         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10625       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10626       if (dbl)
10627         {
10628           expr1.X_add_number = 1;
10629           load_register (AT, &expr1, dbl);
10630           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10631         }
10632       else
10633         {
10634           expr1.X_add_number = 0x80000000;
10635           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10636         }
10637       if (mips_trap)
10638         {
10639           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10640           /* We want to close the noreorder block as soon as possible, so
10641              that later insns are available for delay slot filling.  */
10642           end_noreorder ();
10643         }
10644       else
10645         {
10646           if (mips_opts.micromips)
10647             micromips_label_expr (&label_expr);
10648           else
10649             label_expr.X_add_number = 8;
10650           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10651           macro_build (NULL, "nop", "");
10652
10653           /* We want to close the noreorder block as soon as possible, so
10654              that later insns are available for delay slot filling.  */
10655           end_noreorder ();
10656
10657           macro_build (NULL, "break", BRK_FMT, 6);
10658         }
10659       if (mips_opts.micromips)
10660         micromips_add_label ();
10661       macro_build (NULL, s, MFHL_FMT, op[0]);
10662       break;
10663
10664     case M_DIV_3I:
10665       s = "div";
10666       s2 = "mflo";
10667       goto do_divi;
10668     case M_DIVU_3I:
10669       s = "divu";
10670       s2 = "mflo";
10671       goto do_divi;
10672     case M_REM_3I:
10673       s = "div";
10674       s2 = "mfhi";
10675       goto do_divi;
10676     case M_REMU_3I:
10677       s = "divu";
10678       s2 = "mfhi";
10679       goto do_divi;
10680     case M_DDIV_3I:
10681       dbl = 1;
10682       s = "ddiv";
10683       s2 = "mflo";
10684       goto do_divi;
10685     case M_DDIVU_3I:
10686       dbl = 1;
10687       s = "ddivu";
10688       s2 = "mflo";
10689       goto do_divi;
10690     case M_DREM_3I:
10691       dbl = 1;
10692       s = "ddiv";
10693       s2 = "mfhi";
10694       goto do_divi;
10695     case M_DREMU_3I:
10696       dbl = 1;
10697       s = "ddivu";
10698       s2 = "mfhi";
10699     do_divi:
10700       if (imm_expr.X_add_number == 0)
10701         {
10702           as_warn (_("divide by zero"));
10703           if (mips_trap)
10704             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10705           else
10706             macro_build (NULL, "break", BRK_FMT, 7);
10707           break;
10708         }
10709       if (imm_expr.X_add_number == 1)
10710         {
10711           if (strcmp (s2, "mflo") == 0)
10712             move_register (op[0], op[1]);
10713           else
10714             move_register (op[0], ZERO);
10715           break;
10716         }
10717       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10718         {
10719           if (strcmp (s2, "mflo") == 0)
10720             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10721           else
10722             move_register (op[0], ZERO);
10723           break;
10724         }
10725
10726       used_at = 1;
10727       load_register (AT, &imm_expr, dbl);
10728       macro_build (NULL, s, "z,s,t", op[1], AT);
10729       macro_build (NULL, s2, MFHL_FMT, op[0]);
10730       break;
10731
10732     case M_DIVU_3:
10733       s = "divu";
10734       s2 = "mflo";
10735       goto do_divu3;
10736     case M_REMU_3:
10737       s = "divu";
10738       s2 = "mfhi";
10739       goto do_divu3;
10740     case M_DDIVU_3:
10741       s = "ddivu";
10742       s2 = "mflo";
10743       goto do_divu3;
10744     case M_DREMU_3:
10745       s = "ddivu";
10746       s2 = "mfhi";
10747     do_divu3:
10748       start_noreorder ();
10749       if (mips_trap)
10750         {
10751           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10752           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10753           /* We want to close the noreorder block as soon as possible, so
10754              that later insns are available for delay slot filling.  */
10755           end_noreorder ();
10756         }
10757       else
10758         {
10759           if (mips_opts.micromips)
10760             micromips_label_expr (&label_expr);
10761           else
10762             label_expr.X_add_number = 8;
10763           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10764           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10765
10766           /* We want to close the noreorder block as soon as possible, so
10767              that later insns are available for delay slot filling.  */
10768           end_noreorder ();
10769           macro_build (NULL, "break", BRK_FMT, 7);
10770           if (mips_opts.micromips)
10771             micromips_add_label ();
10772         }
10773       macro_build (NULL, s2, MFHL_FMT, op[0]);
10774       break;
10775
10776     case M_DLCA_AB:
10777       dbl = 1;
10778       /* Fall through.  */
10779     case M_LCA_AB:
10780       call = 1;
10781       goto do_la;
10782     case M_DLA_AB:
10783       dbl = 1;
10784       /* Fall through.  */
10785     case M_LA_AB:
10786     do_la:
10787       /* Load the address of a symbol into a register.  If breg is not
10788          zero, we then add a base register to it.  */
10789
10790       breg = op[2];
10791       if (dbl && GPR_SIZE == 32)
10792         as_warn (_("dla used to load 32-bit register; recommend using la "
10793                    "instead"));
10794
10795       if (!dbl && HAVE_64BIT_OBJECTS)
10796         as_warn (_("la used to load 64-bit address; recommend using dla "
10797                    "instead"));
10798
10799       if (small_offset_p (0, align, 16))
10800         {
10801           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10802                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10803           break;
10804         }
10805
10806       if (mips_opts.at && (op[0] == breg))
10807         {
10808           tempreg = AT;
10809           used_at = 1;
10810         }
10811       else
10812         tempreg = op[0];
10813
10814       if (offset_expr.X_op != O_symbol
10815           && offset_expr.X_op != O_constant)
10816         {
10817           as_bad (_("expression too complex"));
10818           offset_expr.X_op = O_constant;
10819         }
10820
10821       if (offset_expr.X_op == O_constant)
10822         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10823       else if (mips_pic == NO_PIC)
10824         {
10825           /* If this is a reference to a GP relative symbol, we want
10826                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10827              Otherwise we want
10828                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10829                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10830              If we have a constant, we need two instructions anyhow,
10831              so we may as well always use the latter form.
10832
10833              With 64bit address space and a usable $at we want
10834                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10835                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10836                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10837                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10838                dsll32   $tempreg,0
10839                daddu    $tempreg,$tempreg,$at
10840
10841              If $at is already in use, we use a path which is suboptimal
10842              on superscalar processors.
10843                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10844                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10845                dsll     $tempreg,16
10846                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10847                dsll     $tempreg,16
10848                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10849
10850              For GP relative symbols in 64bit address space we can use
10851              the same sequence as in 32bit address space.  */
10852           if (HAVE_64BIT_SYMBOLS)
10853             {
10854               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10855                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10856                 {
10857                   relax_start (offset_expr.X_add_symbol);
10858                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10859                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10860                   relax_switch ();
10861                 }
10862
10863               if (used_at == 0 && mips_opts.at)
10864                 {
10865                   macro_build (&offset_expr, "lui", LUI_FMT,
10866                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10867                   macro_build (&offset_expr, "lui", LUI_FMT,
10868                                AT, BFD_RELOC_HI16_S);
10869                   macro_build (&offset_expr, "daddiu", "t,r,j",
10870                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10871                   macro_build (&offset_expr, "daddiu", "t,r,j",
10872                                AT, AT, BFD_RELOC_LO16);
10873                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10874                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10875                   used_at = 1;
10876                 }
10877               else
10878                 {
10879                   macro_build (&offset_expr, "lui", LUI_FMT,
10880                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10881                   macro_build (&offset_expr, "daddiu", "t,r,j",
10882                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10883                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10884                   macro_build (&offset_expr, "daddiu", "t,r,j",
10885                                tempreg, tempreg, BFD_RELOC_HI16_S);
10886                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10887                   macro_build (&offset_expr, "daddiu", "t,r,j",
10888                                tempreg, tempreg, BFD_RELOC_LO16);
10889                 }
10890
10891               if (mips_relax.sequence)
10892                 relax_end ();
10893             }
10894           else
10895             {
10896               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10897                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10898                 {
10899                   relax_start (offset_expr.X_add_symbol);
10900                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10901                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10902                   relax_switch ();
10903                 }
10904               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10905                 as_bad (_("offset too large"));
10906               macro_build_lui (&offset_expr, tempreg);
10907               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10908                            tempreg, tempreg, BFD_RELOC_LO16);
10909               if (mips_relax.sequence)
10910                 relax_end ();
10911             }
10912         }
10913       else if (!mips_big_got && !HAVE_NEWABI)
10914         {
10915           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10916
10917           /* If this is a reference to an external symbol, and there
10918              is no constant, we want
10919                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10920              or for lca or if tempreg is PIC_CALL_REG
10921                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10922              For a local symbol, we want
10923                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10924                nop
10925                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10926
10927              If we have a small constant, and this is a reference to
10928              an external symbol, we want
10929                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10930                nop
10931                addiu    $tempreg,$tempreg,<constant>
10932              For a local symbol, we want the same instruction
10933              sequence, but we output a BFD_RELOC_LO16 reloc on the
10934              addiu instruction.
10935
10936              If we have a large constant, and this is a reference to
10937              an external symbol, we want
10938                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10939                lui      $at,<hiconstant>
10940                addiu    $at,$at,<loconstant>
10941                addu     $tempreg,$tempreg,$at
10942              For a local symbol, we want the same instruction
10943              sequence, but we output a BFD_RELOC_LO16 reloc on the
10944              addiu instruction.
10945            */
10946
10947           if (offset_expr.X_add_number == 0)
10948             {
10949               if (mips_pic == SVR4_PIC
10950                   && breg == 0
10951                   && (call || tempreg == PIC_CALL_REG))
10952                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10953
10954               relax_start (offset_expr.X_add_symbol);
10955               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10956                            lw_reloc_type, mips_gp_register);
10957               if (breg != 0)
10958                 {
10959                   /* We're going to put in an addu instruction using
10960                      tempreg, so we may as well insert the nop right
10961                      now.  */
10962                   load_delay_nop ();
10963                 }
10964               relax_switch ();
10965               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10966                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10967               load_delay_nop ();
10968               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10969                            tempreg, tempreg, BFD_RELOC_LO16);
10970               relax_end ();
10971               /* FIXME: If breg == 0, and the next instruction uses
10972                  $tempreg, then if this variant case is used an extra
10973                  nop will be generated.  */
10974             }
10975           else if (offset_expr.X_add_number >= -0x8000
10976                    && offset_expr.X_add_number < 0x8000)
10977             {
10978               load_got_offset (tempreg, &offset_expr);
10979               load_delay_nop ();
10980               add_got_offset (tempreg, &offset_expr);
10981             }
10982           else
10983             {
10984               expr1.X_add_number = offset_expr.X_add_number;
10985               offset_expr.X_add_number =
10986                 SEXT_16BIT (offset_expr.X_add_number);
10987               load_got_offset (tempreg, &offset_expr);
10988               offset_expr.X_add_number = expr1.X_add_number;
10989               /* If we are going to add in a base register, and the
10990                  target register and the base register are the same,
10991                  then we are using AT as a temporary register.  Since
10992                  we want to load the constant into AT, we add our
10993                  current AT (from the global offset table) and the
10994                  register into the register now, and pretend we were
10995                  not using a base register.  */
10996               if (breg == op[0])
10997                 {
10998                   load_delay_nop ();
10999                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11000                                op[0], AT, breg);
11001                   breg = 0;
11002                   tempreg = op[0];
11003                 }
11004               add_got_offset_hilo (tempreg, &offset_expr, AT);
11005               used_at = 1;
11006             }
11007         }
11008       else if (!mips_big_got && HAVE_NEWABI)
11009         {
11010           int add_breg_early = 0;
11011
11012           /* If this is a reference to an external, and there is no
11013              constant, or local symbol (*), with or without a
11014              constant, we want
11015                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11016              or for lca or if tempreg is PIC_CALL_REG
11017                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
11018
11019              If we have a small constant, and this is a reference to
11020              an external symbol, we want
11021                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11022                addiu    $tempreg,$tempreg,<constant>
11023
11024              If we have a large constant, and this is a reference to
11025              an external symbol, we want
11026                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
11027                lui      $at,<hiconstant>
11028                addiu    $at,$at,<loconstant>
11029                addu     $tempreg,$tempreg,$at
11030
11031              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
11032              local symbols, even though it introduces an additional
11033              instruction.  */
11034
11035           if (offset_expr.X_add_number)
11036             {
11037               expr1.X_add_number = offset_expr.X_add_number;
11038               offset_expr.X_add_number = 0;
11039
11040               relax_start (offset_expr.X_add_symbol);
11041               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11042                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11043
11044               if (expr1.X_add_number >= -0x8000
11045                   && expr1.X_add_number < 0x8000)
11046                 {
11047                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11048                                tempreg, tempreg, BFD_RELOC_LO16);
11049                 }
11050               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11051                 {
11052                   unsigned int dreg;
11053
11054                   /* If we are going to add in a base register, and the
11055                      target register and the base register are the same,
11056                      then we are using AT as a temporary register.  Since
11057                      we want to load the constant into AT, we add our
11058                      current AT (from the global offset table) and the
11059                      register into the register now, and pretend we were
11060                      not using a base register.  */
11061                   if (breg != op[0])
11062                     dreg = tempreg;
11063                   else
11064                     {
11065                       gas_assert (tempreg == AT);
11066                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11067                                    op[0], AT, breg);
11068                       dreg = op[0];
11069                       add_breg_early = 1;
11070                     }
11071
11072                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11073                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11074                                dreg, dreg, AT);
11075
11076                   used_at = 1;
11077                 }
11078               else
11079                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11080
11081               relax_switch ();
11082               offset_expr.X_add_number = expr1.X_add_number;
11083
11084               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11085                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11086               if (add_breg_early)
11087                 {
11088                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11089                                op[0], tempreg, breg);
11090                   breg = 0;
11091                   tempreg = op[0];
11092                 }
11093               relax_end ();
11094             }
11095           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
11096             {
11097               relax_start (offset_expr.X_add_symbol);
11098               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11099                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
11100               relax_switch ();
11101               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11102                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11103               relax_end ();
11104             }
11105           else
11106             {
11107               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11108                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11109             }
11110         }
11111       else if (mips_big_got && !HAVE_NEWABI)
11112         {
11113           int gpdelay;
11114           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11115           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11116           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11117
11118           /* This is the large GOT case.  If this is a reference to an
11119              external symbol, and there is no constant, we want
11120                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11121                addu     $tempreg,$tempreg,$gp
11122                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11123              or for lca or if tempreg is PIC_CALL_REG
11124                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11125                addu     $tempreg,$tempreg,$gp
11126                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11127              For a local symbol, we want
11128                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11129                nop
11130                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11131
11132              If we have a small constant, and this is a reference to
11133              an external symbol, we want
11134                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11135                addu     $tempreg,$tempreg,$gp
11136                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11137                nop
11138                addiu    $tempreg,$tempreg,<constant>
11139              For a local symbol, we want
11140                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11141                nop
11142                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
11143
11144              If we have a large constant, and this is a reference to
11145              an external symbol, we want
11146                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11147                addu     $tempreg,$tempreg,$gp
11148                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11149                lui      $at,<hiconstant>
11150                addiu    $at,$at,<loconstant>
11151                addu     $tempreg,$tempreg,$at
11152              For a local symbol, we want
11153                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11154                lui      $at,<hiconstant>
11155                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
11156                addu     $tempreg,$tempreg,$at
11157           */
11158
11159           expr1.X_add_number = offset_expr.X_add_number;
11160           offset_expr.X_add_number = 0;
11161           relax_start (offset_expr.X_add_symbol);
11162           gpdelay = reg_needs_delay (mips_gp_register);
11163           if (expr1.X_add_number == 0 && breg == 0
11164               && (call || tempreg == PIC_CALL_REG))
11165             {
11166               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11167               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11168             }
11169           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11170           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11171                        tempreg, tempreg, mips_gp_register);
11172           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11173                        tempreg, lw_reloc_type, tempreg);
11174           if (expr1.X_add_number == 0)
11175             {
11176               if (breg != 0)
11177                 {
11178                   /* We're going to put in an addu instruction using
11179                      tempreg, so we may as well insert the nop right
11180                      now.  */
11181                   load_delay_nop ();
11182                 }
11183             }
11184           else if (expr1.X_add_number >= -0x8000
11185                    && expr1.X_add_number < 0x8000)
11186             {
11187               load_delay_nop ();
11188               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11189                            tempreg, tempreg, BFD_RELOC_LO16);
11190             }
11191           else
11192             {
11193               unsigned int dreg;
11194
11195               /* If we are going to add in a base register, and the
11196                  target register and the base register are the same,
11197                  then we are using AT as a temporary register.  Since
11198                  we want to load the constant into AT, we add our
11199                  current AT (from the global offset table) and the
11200                  register into the register now, and pretend we were
11201                  not using a base register.  */
11202               if (breg != op[0])
11203                 dreg = tempreg;
11204               else
11205                 {
11206                   gas_assert (tempreg == AT);
11207                   load_delay_nop ();
11208                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11209                                op[0], AT, breg);
11210                   dreg = op[0];
11211                 }
11212
11213               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11214               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11215
11216               used_at = 1;
11217             }
11218           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11219           relax_switch ();
11220
11221           if (gpdelay)
11222             {
11223               /* This is needed because this instruction uses $gp, but
11224                  the first instruction on the main stream does not.  */
11225               macro_build (NULL, "nop", "");
11226             }
11227
11228           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11229                        local_reloc_type, mips_gp_register);
11230           if (expr1.X_add_number >= -0x8000
11231               && expr1.X_add_number < 0x8000)
11232             {
11233               load_delay_nop ();
11234               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11235                            tempreg, tempreg, BFD_RELOC_LO16);
11236               /* FIXME: If add_number is 0, and there was no base
11237                  register, the external symbol case ended with a load,
11238                  so if the symbol turns out to not be external, and
11239                  the next instruction uses tempreg, an unnecessary nop
11240                  will be inserted.  */
11241             }
11242           else
11243             {
11244               if (breg == op[0])
11245                 {
11246                   /* We must add in the base register now, as in the
11247                      external symbol case.  */
11248                   gas_assert (tempreg == AT);
11249                   load_delay_nop ();
11250                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11251                                op[0], AT, breg);
11252                   tempreg = op[0];
11253                   /* We set breg to 0 because we have arranged to add
11254                      it in in both cases.  */
11255                   breg = 0;
11256                 }
11257
11258               macro_build_lui (&expr1, AT);
11259               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11260                            AT, AT, BFD_RELOC_LO16);
11261               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11262                            tempreg, tempreg, AT);
11263               used_at = 1;
11264             }
11265           relax_end ();
11266         }
11267       else if (mips_big_got && HAVE_NEWABI)
11268         {
11269           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11270           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11271           int add_breg_early = 0;
11272
11273           /* This is the large GOT case.  If this is a reference to an
11274              external symbol, and there is no constant, we want
11275                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11276                add      $tempreg,$tempreg,$gp
11277                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11278              or for lca or if tempreg is PIC_CALL_REG
11279                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11280                add      $tempreg,$tempreg,$gp
11281                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11282
11283              If we have a small constant, and this is a reference to
11284              an external symbol, we want
11285                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11286                add      $tempreg,$tempreg,$gp
11287                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11288                addi     $tempreg,$tempreg,<constant>
11289
11290              If we have a large constant, and this is a reference to
11291              an external symbol, we want
11292                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11293                addu     $tempreg,$tempreg,$gp
11294                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11295                lui      $at,<hiconstant>
11296                addi     $at,$at,<loconstant>
11297                add      $tempreg,$tempreg,$at
11298
11299              If we have NewABI, and we know it's a local symbol, we want
11300                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
11301                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
11302              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11303
11304           relax_start (offset_expr.X_add_symbol);
11305
11306           expr1.X_add_number = offset_expr.X_add_number;
11307           offset_expr.X_add_number = 0;
11308
11309           if (expr1.X_add_number == 0 && breg == 0
11310               && (call || tempreg == PIC_CALL_REG))
11311             {
11312               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11313               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11314             }
11315           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11316           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11317                        tempreg, tempreg, mips_gp_register);
11318           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11319                        tempreg, lw_reloc_type, tempreg);
11320
11321           if (expr1.X_add_number == 0)
11322             ;
11323           else if (expr1.X_add_number >= -0x8000
11324                    && expr1.X_add_number < 0x8000)
11325             {
11326               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11327                            tempreg, tempreg, BFD_RELOC_LO16);
11328             }
11329           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11330             {
11331               unsigned int dreg;
11332
11333               /* If we are going to add in a base register, and the
11334                  target register and the base register are the same,
11335                  then we are using AT as a temporary register.  Since
11336                  we want to load the constant into AT, we add our
11337                  current AT (from the global offset table) and the
11338                  register into the register now, and pretend we were
11339                  not using a base register.  */
11340               if (breg != op[0])
11341                 dreg = tempreg;
11342               else
11343                 {
11344                   gas_assert (tempreg == AT);
11345                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11346                                op[0], AT, breg);
11347                   dreg = op[0];
11348                   add_breg_early = 1;
11349                 }
11350
11351               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11352               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11353
11354               used_at = 1;
11355             }
11356           else
11357             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11358
11359           relax_switch ();
11360           offset_expr.X_add_number = expr1.X_add_number;
11361           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11362                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11363           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11364                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
11365           if (add_breg_early)
11366             {
11367               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11368                            op[0], tempreg, breg);
11369               breg = 0;
11370               tempreg = op[0];
11371             }
11372           relax_end ();
11373         }
11374       else
11375         abort ();
11376
11377       if (breg != 0)
11378         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11379       break;
11380
11381     case M_MSGSND:
11382       gas_assert (!mips_opts.micromips);
11383       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11384       break;
11385
11386     case M_MSGLD:
11387       gas_assert (!mips_opts.micromips);
11388       macro_build (NULL, "c2", "C", 0x02);
11389       break;
11390
11391     case M_MSGLD_T:
11392       gas_assert (!mips_opts.micromips);
11393       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11394       break;
11395
11396     case M_MSGWAIT:
11397       gas_assert (!mips_opts.micromips);
11398       macro_build (NULL, "c2", "C", 3);
11399       break;
11400
11401     case M_MSGWAIT_T:
11402       gas_assert (!mips_opts.micromips);
11403       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11404       break;
11405
11406     case M_J_A:
11407       /* The j instruction may not be used in PIC code, since it
11408          requires an absolute address.  We convert it to a b
11409          instruction.  */
11410       if (mips_pic == NO_PIC)
11411         macro_build (&offset_expr, "j", "a");
11412       else
11413         macro_build (&offset_expr, "b", "p");
11414       break;
11415
11416       /* The jal instructions must be handled as macros because when
11417          generating PIC code they expand to multi-instruction
11418          sequences.  Normally they are simple instructions.  */
11419     case M_JALS_1:
11420       op[1] = op[0];
11421       op[0] = RA;
11422       /* Fall through.  */
11423     case M_JALS_2:
11424       gas_assert (mips_opts.micromips);
11425       if (mips_opts.insn32)
11426         {
11427           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11428           break;
11429         }
11430       jals = 1;
11431       goto jal;
11432     case M_JAL_1:
11433       op[1] = op[0];
11434       op[0] = RA;
11435       /* Fall through.  */
11436     case M_JAL_2:
11437     jal:
11438       if (mips_pic == NO_PIC)
11439         {
11440           s = jals ? "jalrs" : "jalr";
11441           if (mips_opts.micromips
11442               && !mips_opts.insn32
11443               && op[0] == RA
11444               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11445             macro_build (NULL, s, "mj", op[1]);
11446           else
11447             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11448         }
11449       else
11450         {
11451           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11452                            && mips_cprestore_offset >= 0);
11453
11454           if (op[1] != PIC_CALL_REG)
11455             as_warn (_("MIPS PIC call to register other than $25"));
11456
11457           s = ((mips_opts.micromips
11458                 && !mips_opts.insn32
11459                 && (!mips_opts.noreorder || cprestore))
11460                ? "jalrs" : "jalr");
11461           if (mips_opts.micromips
11462               && !mips_opts.insn32
11463               && op[0] == RA
11464               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11465             macro_build (NULL, s, "mj", op[1]);
11466           else
11467             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11468           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11469             {
11470               if (mips_cprestore_offset < 0)
11471                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11472               else
11473                 {
11474                   if (!mips_frame_reg_valid)
11475                     {
11476                       as_warn (_("no .frame pseudo-op used in PIC code"));
11477                       /* Quiet this warning.  */
11478                       mips_frame_reg_valid = 1;
11479                     }
11480                   if (!mips_cprestore_valid)
11481                     {
11482                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11483                       /* Quiet this warning.  */
11484                       mips_cprestore_valid = 1;
11485                     }
11486                   if (mips_opts.noreorder)
11487                     macro_build (NULL, "nop", "");
11488                   expr1.X_add_number = mips_cprestore_offset;
11489                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11490                                                 mips_gp_register,
11491                                                 mips_frame_reg,
11492                                                 HAVE_64BIT_ADDRESSES);
11493                 }
11494             }
11495         }
11496
11497       break;
11498
11499     case M_JALS_A:
11500       gas_assert (mips_opts.micromips);
11501       if (mips_opts.insn32)
11502         {
11503           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11504           break;
11505         }
11506       jals = 1;
11507       /* Fall through.  */
11508     case M_JAL_A:
11509       if (mips_pic == NO_PIC)
11510         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11511       else if (mips_pic == SVR4_PIC)
11512         {
11513           /* If this is a reference to an external symbol, and we are
11514              using a small GOT, we want
11515                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11516                nop
11517                jalr     $ra,$25
11518                nop
11519                lw       $gp,cprestore($sp)
11520              The cprestore value is set using the .cprestore
11521              pseudo-op.  If we are using a big GOT, we want
11522                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11523                addu     $25,$25,$gp
11524                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11525                nop
11526                jalr     $ra,$25
11527                nop
11528                lw       $gp,cprestore($sp)
11529              If the symbol is not external, we want
11530                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11531                nop
11532                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11533                jalr     $ra,$25
11534                nop
11535                lw $gp,cprestore($sp)
11536
11537              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11538              sequences above, minus nops, unless the symbol is local,
11539              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11540              GOT_DISP.  */
11541           if (HAVE_NEWABI)
11542             {
11543               if (!mips_big_got)
11544                 {
11545                   relax_start (offset_expr.X_add_symbol);
11546                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11547                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11548                                mips_gp_register);
11549                   relax_switch ();
11550                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11551                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11552                                mips_gp_register);
11553                   relax_end ();
11554                 }
11555               else
11556                 {
11557                   relax_start (offset_expr.X_add_symbol);
11558                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11559                                BFD_RELOC_MIPS_CALL_HI16);
11560                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11561                                PIC_CALL_REG, mips_gp_register);
11562                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11563                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11564                                PIC_CALL_REG);
11565                   relax_switch ();
11566                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11567                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11568                                mips_gp_register);
11569                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11570                                PIC_CALL_REG, PIC_CALL_REG,
11571                                BFD_RELOC_MIPS_GOT_OFST);
11572                   relax_end ();
11573                 }
11574
11575               macro_build_jalr (&offset_expr, 0);
11576             }
11577           else
11578             {
11579               relax_start (offset_expr.X_add_symbol);
11580               if (!mips_big_got)
11581                 {
11582                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11583                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11584                                mips_gp_register);
11585                   load_delay_nop ();
11586                   relax_switch ();
11587                 }
11588               else
11589                 {
11590                   int gpdelay;
11591
11592                   gpdelay = reg_needs_delay (mips_gp_register);
11593                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11594                                BFD_RELOC_MIPS_CALL_HI16);
11595                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11596                                PIC_CALL_REG, mips_gp_register);
11597                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11598                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11599                                PIC_CALL_REG);
11600                   load_delay_nop ();
11601                   relax_switch ();
11602                   if (gpdelay)
11603                     macro_build (NULL, "nop", "");
11604                 }
11605               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11606                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11607                            mips_gp_register);
11608               load_delay_nop ();
11609               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11610                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11611               relax_end ();
11612               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11613
11614               if (mips_cprestore_offset < 0)
11615                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11616               else
11617                 {
11618                   if (!mips_frame_reg_valid)
11619                     {
11620                       as_warn (_("no .frame pseudo-op used in PIC code"));
11621                       /* Quiet this warning.  */
11622                       mips_frame_reg_valid = 1;
11623                     }
11624                   if (!mips_cprestore_valid)
11625                     {
11626                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11627                       /* Quiet this warning.  */
11628                       mips_cprestore_valid = 1;
11629                     }
11630                   if (mips_opts.noreorder)
11631                     macro_build (NULL, "nop", "");
11632                   expr1.X_add_number = mips_cprestore_offset;
11633                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11634                                                 mips_gp_register,
11635                                                 mips_frame_reg,
11636                                                 HAVE_64BIT_ADDRESSES);
11637                 }
11638             }
11639         }
11640       else if (mips_pic == VXWORKS_PIC)
11641         as_bad (_("non-PIC jump used in PIC library"));
11642       else
11643         abort ();
11644
11645       break;
11646
11647     case M_LBUE_AB:
11648       s = "lbue";
11649       fmt = "t,+j(b)";
11650       offbits = 9;
11651       goto ld_st;
11652     case M_LHUE_AB:
11653       s = "lhue";
11654       fmt = "t,+j(b)";
11655       offbits = 9;
11656       goto ld_st;
11657     case M_LBE_AB:
11658       s = "lbe";
11659       fmt = "t,+j(b)";
11660       offbits = 9;
11661       goto ld_st;
11662     case M_LHE_AB:
11663       s = "lhe";
11664       fmt = "t,+j(b)";
11665       offbits = 9;
11666       goto ld_st;
11667     case M_LLE_AB:
11668       s = "lle";
11669       fmt = "t,+j(b)";
11670       offbits = 9;
11671       goto ld_st;
11672     case M_LWE_AB:
11673       s = "lwe";
11674       fmt = "t,+j(b)";
11675       offbits = 9;
11676       goto ld_st;
11677     case M_LWLE_AB:
11678       s = "lwle";
11679       fmt = "t,+j(b)";
11680       offbits = 9;
11681       goto ld_st;
11682     case M_LWRE_AB:
11683       s = "lwre";
11684       fmt = "t,+j(b)";
11685       offbits = 9;
11686       goto ld_st;
11687     case M_SBE_AB:
11688       s = "sbe";
11689       fmt = "t,+j(b)";
11690       offbits = 9;
11691       goto ld_st;
11692     case M_SCE_AB:
11693       s = "sce";
11694       fmt = "t,+j(b)";
11695       offbits = 9;
11696       goto ld_st;
11697     case M_SHE_AB:
11698       s = "she";
11699       fmt = "t,+j(b)";
11700       offbits = 9;
11701       goto ld_st;
11702     case M_SWE_AB:
11703       s = "swe";
11704       fmt = "t,+j(b)";
11705       offbits = 9;
11706       goto ld_st;
11707     case M_SWLE_AB:
11708       s = "swle";
11709       fmt = "t,+j(b)";
11710       offbits = 9;
11711       goto ld_st;
11712     case M_SWRE_AB:
11713       s = "swre";
11714       fmt = "t,+j(b)";
11715       offbits = 9;
11716       goto ld_st;
11717     case M_ACLR_AB:
11718       s = "aclr";
11719       fmt = "\\,~(b)";
11720       offbits = 12;
11721       goto ld_st;
11722     case M_ASET_AB:
11723       s = "aset";
11724       fmt = "\\,~(b)";
11725       offbits = 12;
11726       goto ld_st;
11727     case M_LB_AB:
11728       s = "lb";
11729       fmt = "t,o(b)";
11730       goto ld;
11731     case M_LBU_AB:
11732       s = "lbu";
11733       fmt = "t,o(b)";
11734       goto ld;
11735     case M_LH_AB:
11736       s = "lh";
11737       fmt = "t,o(b)";
11738       goto ld;
11739     case M_LHU_AB:
11740       s = "lhu";
11741       fmt = "t,o(b)";
11742       goto ld;
11743     case M_LW_AB:
11744       s = "lw";
11745       fmt = "t,o(b)";
11746       goto ld;
11747     case M_LWC0_AB:
11748       gas_assert (!mips_opts.micromips);
11749       s = "lwc0";
11750       fmt = "E,o(b)";
11751       /* Itbl support may require additional care here.  */
11752       coproc = 1;
11753       goto ld_st;
11754     case M_LWC1_AB:
11755       s = "lwc1";
11756       fmt = "T,o(b)";
11757       /* Itbl support may require additional care here.  */
11758       coproc = 1;
11759       goto ld_st;
11760     case M_LWC2_AB:
11761       s = "lwc2";
11762       fmt = COP12_FMT;
11763       offbits = (mips_opts.micromips ? 12
11764                  : ISA_IS_R6 (mips_opts.isa) ? 11
11765                  : 16);
11766       /* Itbl support may require additional care here.  */
11767       coproc = 1;
11768       goto ld_st;
11769     case M_LWC3_AB:
11770       gas_assert (!mips_opts.micromips);
11771       s = "lwc3";
11772       fmt = "E,o(b)";
11773       /* Itbl support may require additional care here.  */
11774       coproc = 1;
11775       goto ld_st;
11776     case M_LWL_AB:
11777       s = "lwl";
11778       fmt = MEM12_FMT;
11779       offbits = (mips_opts.micromips ? 12 : 16);
11780       goto ld_st;
11781     case M_LWR_AB:
11782       s = "lwr";
11783       fmt = MEM12_FMT;
11784       offbits = (mips_opts.micromips ? 12 : 16);
11785       goto ld_st;
11786     case M_LDC1_AB:
11787       s = "ldc1";
11788       fmt = "T,o(b)";
11789       /* Itbl support may require additional care here.  */
11790       coproc = 1;
11791       goto ld_st;
11792     case M_LDC2_AB:
11793       s = "ldc2";
11794       fmt = COP12_FMT;
11795       offbits = (mips_opts.micromips ? 12
11796                  : ISA_IS_R6 (mips_opts.isa) ? 11
11797                  : 16);
11798       /* Itbl support may require additional care here.  */
11799       coproc = 1;
11800       goto ld_st;
11801     case M_LQC2_AB:
11802       s = "lqc2";
11803       fmt = "+7,o(b)";
11804       /* Itbl support may require additional care here.  */
11805       coproc = 1;
11806       goto ld_st;
11807     case M_LDC3_AB:
11808       s = "ldc3";
11809       fmt = "E,o(b)";
11810       /* Itbl support may require additional care here.  */
11811       coproc = 1;
11812       goto ld_st;
11813     case M_LDL_AB:
11814       s = "ldl";
11815       fmt = MEM12_FMT;
11816       offbits = (mips_opts.micromips ? 12 : 16);
11817       goto ld_st;
11818     case M_LDR_AB:
11819       s = "ldr";
11820       fmt = MEM12_FMT;
11821       offbits = (mips_opts.micromips ? 12 : 16);
11822       goto ld_st;
11823     case M_LL_AB:
11824       s = "ll";
11825       fmt = LL_SC_FMT;
11826       offbits = (mips_opts.micromips ? 12
11827                  : ISA_IS_R6 (mips_opts.isa) ? 9
11828                  : 16);
11829       goto ld;
11830     case M_LLD_AB:
11831       s = "lld";
11832       fmt = LL_SC_FMT;
11833       offbits = (mips_opts.micromips ? 12
11834                  : ISA_IS_R6 (mips_opts.isa) ? 9
11835                  : 16);
11836       goto ld;
11837     case M_LWU_AB:
11838       s = "lwu";
11839       fmt = MEM12_FMT;
11840       offbits = (mips_opts.micromips ? 12 : 16);
11841       goto ld;
11842     case M_LWP_AB:
11843       gas_assert (mips_opts.micromips);
11844       s = "lwp";
11845       fmt = "t,~(b)";
11846       offbits = 12;
11847       lp = 1;
11848       goto ld;
11849     case M_LDP_AB:
11850       gas_assert (mips_opts.micromips);
11851       s = "ldp";
11852       fmt = "t,~(b)";
11853       offbits = 12;
11854       lp = 1;
11855       goto ld;
11856     case M_LWM_AB:
11857       gas_assert (mips_opts.micromips);
11858       s = "lwm";
11859       fmt = "n,~(b)";
11860       offbits = 12;
11861       goto ld_st;
11862     case M_LDM_AB:
11863       gas_assert (mips_opts.micromips);
11864       s = "ldm";
11865       fmt = "n,~(b)";
11866       offbits = 12;
11867       goto ld_st;
11868
11869     ld:
11870       /* We don't want to use $0 as tempreg.  */
11871       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11872         goto ld_st;
11873       else
11874         tempreg = op[0] + lp;
11875       goto ld_noat;
11876
11877     case M_SB_AB:
11878       s = "sb";
11879       fmt = "t,o(b)";
11880       goto ld_st;
11881     case M_SH_AB:
11882       s = "sh";
11883       fmt = "t,o(b)";
11884       goto ld_st;
11885     case M_SW_AB:
11886       s = "sw";
11887       fmt = "t,o(b)";
11888       goto ld_st;
11889     case M_SWC0_AB:
11890       gas_assert (!mips_opts.micromips);
11891       s = "swc0";
11892       fmt = "E,o(b)";
11893       /* Itbl support may require additional care here.  */
11894       coproc = 1;
11895       goto ld_st;
11896     case M_SWC1_AB:
11897       s = "swc1";
11898       fmt = "T,o(b)";
11899       /* Itbl support may require additional care here.  */
11900       coproc = 1;
11901       goto ld_st;
11902     case M_SWC2_AB:
11903       s = "swc2";
11904       fmt = COP12_FMT;
11905       offbits = (mips_opts.micromips ? 12
11906                  : ISA_IS_R6 (mips_opts.isa) ? 11
11907                  : 16);
11908       /* Itbl support may require additional care here.  */
11909       coproc = 1;
11910       goto ld_st;
11911     case M_SWC3_AB:
11912       gas_assert (!mips_opts.micromips);
11913       s = "swc3";
11914       fmt = "E,o(b)";
11915       /* Itbl support may require additional care here.  */
11916       coproc = 1;
11917       goto ld_st;
11918     case M_SWL_AB:
11919       s = "swl";
11920       fmt = MEM12_FMT;
11921       offbits = (mips_opts.micromips ? 12 : 16);
11922       goto ld_st;
11923     case M_SWR_AB:
11924       s = "swr";
11925       fmt = MEM12_FMT;
11926       offbits = (mips_opts.micromips ? 12 : 16);
11927       goto ld_st;
11928     case M_SC_AB:
11929       s = "sc";
11930       fmt = LL_SC_FMT;
11931       offbits = (mips_opts.micromips ? 12
11932                  : ISA_IS_R6 (mips_opts.isa) ? 9
11933                  : 16);
11934       goto ld_st;
11935     case M_SCD_AB:
11936       s = "scd";
11937       fmt = LL_SC_FMT;
11938       offbits = (mips_opts.micromips ? 12
11939                  : ISA_IS_R6 (mips_opts.isa) ? 9
11940                  : 16);
11941       goto ld_st;
11942     case M_CACHE_AB:
11943       s = "cache";
11944       fmt = (mips_opts.micromips ? "k,~(b)"
11945              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11946              : "k,o(b)");
11947       offbits = (mips_opts.micromips ? 12
11948                  : ISA_IS_R6 (mips_opts.isa) ? 9
11949                  : 16);
11950       goto ld_st;
11951     case M_CACHEE_AB:
11952       s = "cachee";
11953       fmt = "k,+j(b)";
11954       offbits = 9;
11955       goto ld_st;
11956     case M_PREF_AB:
11957       s = "pref";
11958       fmt = (mips_opts.micromips ? "k,~(b)"
11959              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11960              : "k,o(b)");
11961       offbits = (mips_opts.micromips ? 12
11962                  : ISA_IS_R6 (mips_opts.isa) ? 9
11963                  : 16);
11964       goto ld_st;
11965     case M_PREFE_AB:
11966       s = "prefe";
11967       fmt = "k,+j(b)";
11968       offbits = 9;
11969       goto ld_st;
11970     case M_SDC1_AB:
11971       s = "sdc1";
11972       fmt = "T,o(b)";
11973       coproc = 1;
11974       /* Itbl support may require additional care here.  */
11975       goto ld_st;
11976     case M_SDC2_AB:
11977       s = "sdc2";
11978       fmt = COP12_FMT;
11979       offbits = (mips_opts.micromips ? 12
11980                  : ISA_IS_R6 (mips_opts.isa) ? 11
11981                  : 16);
11982       /* Itbl support may require additional care here.  */
11983       coproc = 1;
11984       goto ld_st;
11985     case M_SQC2_AB:
11986       s = "sqc2";
11987       fmt = "+7,o(b)";
11988       /* Itbl support may require additional care here.  */
11989       coproc = 1;
11990       goto ld_st;
11991     case M_SDC3_AB:
11992       gas_assert (!mips_opts.micromips);
11993       s = "sdc3";
11994       fmt = "E,o(b)";
11995       /* Itbl support may require additional care here.  */
11996       coproc = 1;
11997       goto ld_st;
11998     case M_SDL_AB:
11999       s = "sdl";
12000       fmt = MEM12_FMT;
12001       offbits = (mips_opts.micromips ? 12 : 16);
12002       goto ld_st;
12003     case M_SDR_AB:
12004       s = "sdr";
12005       fmt = MEM12_FMT;
12006       offbits = (mips_opts.micromips ? 12 : 16);
12007       goto ld_st;
12008     case M_SWP_AB:
12009       gas_assert (mips_opts.micromips);
12010       s = "swp";
12011       fmt = "t,~(b)";
12012       offbits = 12;
12013       goto ld_st;
12014     case M_SDP_AB:
12015       gas_assert (mips_opts.micromips);
12016       s = "sdp";
12017       fmt = "t,~(b)";
12018       offbits = 12;
12019       goto ld_st;
12020     case M_SWM_AB:
12021       gas_assert (mips_opts.micromips);
12022       s = "swm";
12023       fmt = "n,~(b)";
12024       offbits = 12;
12025       goto ld_st;
12026     case M_SDM_AB:
12027       gas_assert (mips_opts.micromips);
12028       s = "sdm";
12029       fmt = "n,~(b)";
12030       offbits = 12;
12031
12032     ld_st:
12033       tempreg = AT;
12034     ld_noat:
12035       breg = op[2];
12036       if (small_offset_p (0, align, 16))
12037         {
12038           /* The first case exists for M_LD_AB and M_SD_AB, which are
12039              macros for o32 but which should act like normal instructions
12040              otherwise.  */
12041           if (offbits == 16)
12042             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
12043                          offset_reloc[1], offset_reloc[2], breg);
12044           else if (small_offset_p (0, align, offbits))
12045             {
12046               if (offbits == 0)
12047                 macro_build (NULL, s, fmt, op[0], breg);
12048               else
12049                 macro_build (NULL, s, fmt, op[0],
12050                              (int) offset_expr.X_add_number, breg);
12051             }
12052           else
12053             {
12054               if (tempreg == AT)
12055                 used_at = 1;
12056               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
12057                            tempreg, breg, -1, offset_reloc[0],
12058                            offset_reloc[1], offset_reloc[2]);
12059               if (offbits == 0)
12060                 macro_build (NULL, s, fmt, op[0], tempreg);
12061               else
12062                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
12063             }
12064           break;
12065         }
12066
12067       if (tempreg == AT)
12068         used_at = 1;
12069
12070       if (offset_expr.X_op != O_constant
12071           && offset_expr.X_op != O_symbol)
12072         {
12073           as_bad (_("expression too complex"));
12074           offset_expr.X_op = O_constant;
12075         }
12076
12077       if (HAVE_32BIT_ADDRESSES
12078           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12079         {
12080           char value [32];
12081
12082           sprintf_vma (value, offset_expr.X_add_number);
12083           as_bad (_("number (0x%s) larger than 32 bits"), value);
12084         }
12085
12086       /* A constant expression in PIC code can be handled just as it
12087          is in non PIC code.  */
12088       if (offset_expr.X_op == O_constant)
12089         {
12090           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
12091                                                  offbits == 0 ? 16 : offbits);
12092           offset_expr.X_add_number -= expr1.X_add_number;
12093
12094           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
12095           if (breg != 0)
12096             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12097                          tempreg, tempreg, breg);
12098           if (offbits == 0)
12099             {
12100               if (offset_expr.X_add_number != 0)
12101                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
12102                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
12103               macro_build (NULL, s, fmt, op[0], tempreg);
12104             }
12105           else if (offbits == 16)
12106             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12107           else
12108             macro_build (NULL, s, fmt, op[0],
12109                          (int) offset_expr.X_add_number, tempreg);
12110         }
12111       else if (offbits != 16)
12112         {
12113           /* The offset field is too narrow to be used for a low-part
12114              relocation, so load the whole address into the auxiliary
12115              register.  */
12116           load_address (tempreg, &offset_expr, &used_at);
12117           if (breg != 0)
12118             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12119                          tempreg, tempreg, breg);
12120           if (offbits == 0)
12121             macro_build (NULL, s, fmt, op[0], tempreg);
12122           else
12123             macro_build (NULL, s, fmt, op[0], 0, tempreg);
12124         }
12125       else if (mips_pic == NO_PIC)
12126         {
12127           /* If this is a reference to a GP relative symbol, and there
12128              is no base register, we want
12129                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12130              Otherwise, if there is no base register, we want
12131                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12132                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12133              If we have a constant, we need two instructions anyhow,
12134              so we always use the latter form.
12135
12136              If we have a base register, and this is a reference to a
12137              GP relative symbol, we want
12138                addu     $tempreg,$breg,$gp
12139                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
12140              Otherwise we want
12141                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12142                addu     $tempreg,$tempreg,$breg
12143                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12144              With a constant we always use the latter case.
12145
12146              With 64bit address space and no base register and $at usable,
12147              we want
12148                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12149                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12150                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12151                dsll32   $tempreg,0
12152                daddu    $tempreg,$at
12153                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12154              If we have a base register, we want
12155                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12156                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12157                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12158                daddu    $at,$breg
12159                dsll32   $tempreg,0
12160                daddu    $tempreg,$at
12161                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12162
12163              Without $at we can't generate the optimal path for superscalar
12164              processors here since this would require two temporary registers.
12165                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12166                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12167                dsll     $tempreg,16
12168                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12169                dsll     $tempreg,16
12170                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12171              If we have a base register, we want
12172                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12173                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12174                dsll     $tempreg,16
12175                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12176                dsll     $tempreg,16
12177                daddu    $tempreg,$tempreg,$breg
12178                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12179
12180              For GP relative symbols in 64bit address space we can use
12181              the same sequence as in 32bit address space.  */
12182           if (HAVE_64BIT_SYMBOLS)
12183             {
12184               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12185                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12186                 {
12187                   relax_start (offset_expr.X_add_symbol);
12188                   if (breg == 0)
12189                     {
12190                       macro_build (&offset_expr, s, fmt, op[0],
12191                                    BFD_RELOC_GPREL16, mips_gp_register);
12192                     }
12193                   else
12194                     {
12195                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12196                                    tempreg, breg, mips_gp_register);
12197                       macro_build (&offset_expr, s, fmt, op[0],
12198                                    BFD_RELOC_GPREL16, tempreg);
12199                     }
12200                   relax_switch ();
12201                 }
12202
12203               if (used_at == 0 && mips_opts.at)
12204                 {
12205                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12206                                BFD_RELOC_MIPS_HIGHEST);
12207                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
12208                                BFD_RELOC_HI16_S);
12209                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12210                                tempreg, BFD_RELOC_MIPS_HIGHER);
12211                   if (breg != 0)
12212                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12213                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12214                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12215                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12216                                tempreg);
12217                   used_at = 1;
12218                 }
12219               else
12220                 {
12221                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12222                                BFD_RELOC_MIPS_HIGHEST);
12223                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12224                                tempreg, BFD_RELOC_MIPS_HIGHER);
12225                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12226                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12227                                tempreg, BFD_RELOC_HI16_S);
12228                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12229                   if (breg != 0)
12230                     macro_build (NULL, "daddu", "d,v,t",
12231                                  tempreg, tempreg, breg);
12232                   macro_build (&offset_expr, s, fmt, op[0],
12233                                BFD_RELOC_LO16, tempreg);
12234                 }
12235
12236               if (mips_relax.sequence)
12237                 relax_end ();
12238               break;
12239             }
12240
12241           if (breg == 0)
12242             {
12243               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12244                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12245                 {
12246                   relax_start (offset_expr.X_add_symbol);
12247                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12248                                mips_gp_register);
12249                   relax_switch ();
12250                 }
12251               macro_build_lui (&offset_expr, tempreg);
12252               macro_build (&offset_expr, s, fmt, op[0],
12253                            BFD_RELOC_LO16, tempreg);
12254               if (mips_relax.sequence)
12255                 relax_end ();
12256             }
12257           else
12258             {
12259               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12260                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12261                 {
12262                   relax_start (offset_expr.X_add_symbol);
12263                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12264                                tempreg, breg, mips_gp_register);
12265                   macro_build (&offset_expr, s, fmt, op[0],
12266                                BFD_RELOC_GPREL16, tempreg);
12267                   relax_switch ();
12268                 }
12269               macro_build_lui (&offset_expr, tempreg);
12270               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12271                            tempreg, tempreg, breg);
12272               macro_build (&offset_expr, s, fmt, op[0],
12273                            BFD_RELOC_LO16, tempreg);
12274               if (mips_relax.sequence)
12275                 relax_end ();
12276             }
12277         }
12278       else if (!mips_big_got)
12279         {
12280           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12281
12282           /* If this is a reference to an external symbol, we want
12283                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12284                nop
12285                <op>     op[0],0($tempreg)
12286              Otherwise we want
12287                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12288                nop
12289                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12290                <op>     op[0],0($tempreg)
12291
12292              For NewABI, we want
12293                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12294                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12295
12296              If there is a base register, we add it to $tempreg before
12297              the <op>.  If there is a constant, we stick it in the
12298              <op> instruction.  We don't handle constants larger than
12299              16 bits, because we have no way to load the upper 16 bits
12300              (actually, we could handle them for the subset of cases
12301              in which we are not using $at).  */
12302           gas_assert (offset_expr.X_op == O_symbol);
12303           if (HAVE_NEWABI)
12304             {
12305               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12306                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12307               if (breg != 0)
12308                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12309                              tempreg, tempreg, breg);
12310               macro_build (&offset_expr, s, fmt, op[0],
12311                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
12312               break;
12313             }
12314           expr1.X_add_number = offset_expr.X_add_number;
12315           offset_expr.X_add_number = 0;
12316           if (expr1.X_add_number < -0x8000
12317               || expr1.X_add_number >= 0x8000)
12318             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12319           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12320                        lw_reloc_type, mips_gp_register);
12321           load_delay_nop ();
12322           relax_start (offset_expr.X_add_symbol);
12323           relax_switch ();
12324           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12325                        tempreg, BFD_RELOC_LO16);
12326           relax_end ();
12327           if (breg != 0)
12328             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12329                          tempreg, tempreg, breg);
12330           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12331         }
12332       else if (mips_big_got && !HAVE_NEWABI)
12333         {
12334           int gpdelay;
12335
12336           /* If this is a reference to an external symbol, we want
12337                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12338                addu     $tempreg,$tempreg,$gp
12339                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12340                <op>     op[0],0($tempreg)
12341              Otherwise we want
12342                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12343                nop
12344                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12345                <op>     op[0],0($tempreg)
12346              If there is a base register, we add it to $tempreg before
12347              the <op>.  If there is a constant, we stick it in the
12348              <op> instruction.  We don't handle constants larger than
12349              16 bits, because we have no way to load the upper 16 bits
12350              (actually, we could handle them for the subset of cases
12351              in which we are not using $at).  */
12352           gas_assert (offset_expr.X_op == O_symbol);
12353           expr1.X_add_number = offset_expr.X_add_number;
12354           offset_expr.X_add_number = 0;
12355           if (expr1.X_add_number < -0x8000
12356               || expr1.X_add_number >= 0x8000)
12357             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12358           gpdelay = reg_needs_delay (mips_gp_register);
12359           relax_start (offset_expr.X_add_symbol);
12360           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12361                        BFD_RELOC_MIPS_GOT_HI16);
12362           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12363                        mips_gp_register);
12364           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12365                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12366           relax_switch ();
12367           if (gpdelay)
12368             macro_build (NULL, "nop", "");
12369           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12370                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12371           load_delay_nop ();
12372           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12373                        tempreg, BFD_RELOC_LO16);
12374           relax_end ();
12375
12376           if (breg != 0)
12377             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12378                          tempreg, tempreg, breg);
12379           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12380         }
12381       else if (mips_big_got && HAVE_NEWABI)
12382         {
12383           /* If this is a reference to an external symbol, we want
12384                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12385                add      $tempreg,$tempreg,$gp
12386                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12387                <op>     op[0],<ofst>($tempreg)
12388              Otherwise, for local symbols, we want:
12389                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12390                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12391           gas_assert (offset_expr.X_op == O_symbol);
12392           expr1.X_add_number = offset_expr.X_add_number;
12393           offset_expr.X_add_number = 0;
12394           if (expr1.X_add_number < -0x8000
12395               || expr1.X_add_number >= 0x8000)
12396             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12397           relax_start (offset_expr.X_add_symbol);
12398           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12399                        BFD_RELOC_MIPS_GOT_HI16);
12400           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12401                        mips_gp_register);
12402           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12403                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12404           if (breg != 0)
12405             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12406                          tempreg, tempreg, breg);
12407           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12408
12409           relax_switch ();
12410           offset_expr.X_add_number = expr1.X_add_number;
12411           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12412                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12413           if (breg != 0)
12414             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12415                          tempreg, tempreg, breg);
12416           macro_build (&offset_expr, s, fmt, op[0],
12417                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12418           relax_end ();
12419         }
12420       else
12421         abort ();
12422
12423       break;
12424
12425     case M_JRADDIUSP:
12426       gas_assert (mips_opts.micromips);
12427       gas_assert (mips_opts.insn32);
12428       start_noreorder ();
12429       macro_build (NULL, "jr", "s", RA);
12430       expr1.X_add_number = op[0] << 2;
12431       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12432       end_noreorder ();
12433       break;
12434
12435     case M_JRC:
12436       gas_assert (mips_opts.micromips);
12437       gas_assert (mips_opts.insn32);
12438       macro_build (NULL, "jr", "s", op[0]);
12439       if (mips_opts.noreorder)
12440         macro_build (NULL, "nop", "");
12441       break;
12442
12443     case M_LI:
12444     case M_LI_S:
12445       load_register (op[0], &imm_expr, 0);
12446       break;
12447
12448     case M_DLI:
12449       load_register (op[0], &imm_expr, 1);
12450       break;
12451
12452     case M_LI_SS:
12453       if (imm_expr.X_op == O_constant)
12454         {
12455           used_at = 1;
12456           load_register (AT, &imm_expr, 0);
12457           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12458           break;
12459         }
12460       else
12461         {
12462           gas_assert (imm_expr.X_op == O_absent
12463                       && offset_expr.X_op == O_symbol
12464                       && strcmp (segment_name (S_GET_SEGMENT
12465                                                (offset_expr.X_add_symbol)),
12466                                  ".lit4") == 0
12467                       && offset_expr.X_add_number == 0);
12468           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12469                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12470           break;
12471         }
12472
12473     case M_LI_D:
12474       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12475          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12476          order 32 bits of the value and the low order 32 bits are either
12477          zero or in OFFSET_EXPR.  */
12478       if (imm_expr.X_op == O_constant)
12479         {
12480           if (GPR_SIZE == 64)
12481             load_register (op[0], &imm_expr, 1);
12482           else
12483             {
12484               int hreg, lreg;
12485
12486               if (target_big_endian)
12487                 {
12488                   hreg = op[0];
12489                   lreg = op[0] + 1;
12490                 }
12491               else
12492                 {
12493                   hreg = op[0] + 1;
12494                   lreg = op[0];
12495                 }
12496
12497               if (hreg <= 31)
12498                 load_register (hreg, &imm_expr, 0);
12499               if (lreg <= 31)
12500                 {
12501                   if (offset_expr.X_op == O_absent)
12502                     move_register (lreg, 0);
12503                   else
12504                     {
12505                       gas_assert (offset_expr.X_op == O_constant);
12506                       load_register (lreg, &offset_expr, 0);
12507                     }
12508                 }
12509             }
12510           break;
12511         }
12512       gas_assert (imm_expr.X_op == O_absent);
12513
12514       /* We know that sym is in the .rdata section.  First we get the
12515          upper 16 bits of the address.  */
12516       if (mips_pic == NO_PIC)
12517         {
12518           macro_build_lui (&offset_expr, AT);
12519           used_at = 1;
12520         }
12521       else
12522         {
12523           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12524                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12525           used_at = 1;
12526         }
12527
12528       /* Now we load the register(s).  */
12529       if (GPR_SIZE == 64)
12530         {
12531           used_at = 1;
12532           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12533                        BFD_RELOC_LO16, AT);
12534         }
12535       else
12536         {
12537           used_at = 1;
12538           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12539                        BFD_RELOC_LO16, AT);
12540           if (op[0] != RA)
12541             {
12542               /* FIXME: How in the world do we deal with the possible
12543                  overflow here?  */
12544               offset_expr.X_add_number += 4;
12545               macro_build (&offset_expr, "lw", "t,o(b)",
12546                            op[0] + 1, BFD_RELOC_LO16, AT);
12547             }
12548         }
12549       break;
12550
12551     case M_LI_DD:
12552       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12553          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12554          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12555          the value and the low order 32 bits are either zero or in
12556          OFFSET_EXPR.  */
12557       if (imm_expr.X_op == O_constant)
12558         {
12559           used_at = 1;
12560           load_register (AT, &imm_expr, FPR_SIZE == 64);
12561           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12562             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12563           else
12564             {
12565               if (ISA_HAS_MXHC1 (mips_opts.isa))
12566                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12567               else if (FPR_SIZE != 32)
12568                 as_bad (_("Unable to generate `%s' compliant code "
12569                           "without mthc1"),
12570                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12571               else
12572                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12573               if (offset_expr.X_op == O_absent)
12574                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12575               else
12576                 {
12577                   gas_assert (offset_expr.X_op == O_constant);
12578                   load_register (AT, &offset_expr, 0);
12579                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12580                 }
12581             }
12582           break;
12583         }
12584
12585       gas_assert (imm_expr.X_op == O_absent
12586                   && offset_expr.X_op == O_symbol
12587                   && offset_expr.X_add_number == 0);
12588       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12589       if (strcmp (s, ".lit8") == 0)
12590         {
12591           op[2] = mips_gp_register;
12592           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12593           offset_reloc[1] = BFD_RELOC_UNUSED;
12594           offset_reloc[2] = BFD_RELOC_UNUSED;
12595         }
12596       else
12597         {
12598           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12599           used_at = 1;
12600           if (mips_pic != NO_PIC)
12601             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12602                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12603           else
12604             {
12605               /* FIXME: This won't work for a 64 bit address.  */
12606               macro_build_lui (&offset_expr, AT);
12607             }
12608
12609           op[2] = AT;
12610           offset_reloc[0] = BFD_RELOC_LO16;
12611           offset_reloc[1] = BFD_RELOC_UNUSED;
12612           offset_reloc[2] = BFD_RELOC_UNUSED;
12613         }
12614       align = 8;
12615       /* Fall through */
12616
12617     case M_L_DAB:
12618       /*
12619        * The MIPS assembler seems to check for X_add_number not
12620        * being double aligned and generating:
12621        *        lui     at,%hi(foo+1)
12622        *        addu    at,at,v1
12623        *        addiu   at,at,%lo(foo+1)
12624        *        lwc1    f2,0(at)
12625        *        lwc1    f3,4(at)
12626        * But, the resulting address is the same after relocation so why
12627        * generate the extra instruction?
12628        */
12629       /* Itbl support may require additional care here.  */
12630       coproc = 1;
12631       fmt = "T,o(b)";
12632       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12633         {
12634           s = "ldc1";
12635           goto ld_st;
12636         }
12637       s = "lwc1";
12638       goto ldd_std;
12639
12640     case M_S_DAB:
12641       gas_assert (!mips_opts.micromips);
12642       /* Itbl support may require additional care here.  */
12643       coproc = 1;
12644       fmt = "T,o(b)";
12645       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12646         {
12647           s = "sdc1";
12648           goto ld_st;
12649         }
12650       s = "swc1";
12651       goto ldd_std;
12652
12653     case M_LQ_AB:
12654       fmt = "t,o(b)";
12655       s = "lq";
12656       goto ld;
12657
12658     case M_SQ_AB:
12659       fmt = "t,o(b)";
12660       s = "sq";
12661       goto ld_st;
12662
12663     case M_LD_AB:
12664       fmt = "t,o(b)";
12665       if (GPR_SIZE == 64)
12666         {
12667           s = "ld";
12668           goto ld;
12669         }
12670       s = "lw";
12671       goto ldd_std;
12672
12673     case M_SD_AB:
12674       fmt = "t,o(b)";
12675       if (GPR_SIZE == 64)
12676         {
12677           s = "sd";
12678           goto ld_st;
12679         }
12680       s = "sw";
12681
12682     ldd_std:
12683       /* Even on a big endian machine $fn comes before $fn+1.  We have
12684          to adjust when loading from memory.  We set coproc if we must
12685          load $fn+1 first.  */
12686       /* Itbl support may require additional care here.  */
12687       if (!target_big_endian)
12688         coproc = 0;
12689
12690       breg = op[2];
12691       if (small_offset_p (0, align, 16))
12692         {
12693           ep = &offset_expr;
12694           if (!small_offset_p (4, align, 16))
12695             {
12696               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12697                            -1, offset_reloc[0], offset_reloc[1],
12698                            offset_reloc[2]);
12699               expr1.X_add_number = 0;
12700               ep = &expr1;
12701               breg = AT;
12702               used_at = 1;
12703               offset_reloc[0] = BFD_RELOC_LO16;
12704               offset_reloc[1] = BFD_RELOC_UNUSED;
12705               offset_reloc[2] = BFD_RELOC_UNUSED;
12706             }
12707           if (strcmp (s, "lw") == 0 && op[0] == breg)
12708             {
12709               ep->X_add_number += 4;
12710               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12711                            offset_reloc[1], offset_reloc[2], breg);
12712               ep->X_add_number -= 4;
12713               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12714                            offset_reloc[1], offset_reloc[2], breg);
12715             }
12716           else
12717             {
12718               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12719                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12720                            breg);
12721               ep->X_add_number += 4;
12722               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12723                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12724                            breg);
12725             }
12726           break;
12727         }
12728
12729       if (offset_expr.X_op != O_symbol
12730           && offset_expr.X_op != O_constant)
12731         {
12732           as_bad (_("expression too complex"));
12733           offset_expr.X_op = O_constant;
12734         }
12735
12736       if (HAVE_32BIT_ADDRESSES
12737           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12738         {
12739           char value [32];
12740
12741           sprintf_vma (value, offset_expr.X_add_number);
12742           as_bad (_("number (0x%s) larger than 32 bits"), value);
12743         }
12744
12745       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12746         {
12747           /* If this is a reference to a GP relative symbol, we want
12748                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12749                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12750              If we have a base register, we use this
12751                addu     $at,$breg,$gp
12752                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12753                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12754              If this is not a GP relative symbol, we want
12755                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12756                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12757                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12758              If there is a base register, we add it to $at after the
12759              lui instruction.  If there is a constant, we always use
12760              the last case.  */
12761           if (offset_expr.X_op == O_symbol
12762               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12763               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12764             {
12765               relax_start (offset_expr.X_add_symbol);
12766               if (breg == 0)
12767                 {
12768                   tempreg = mips_gp_register;
12769                 }
12770               else
12771                 {
12772                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12773                                AT, breg, mips_gp_register);
12774                   tempreg = AT;
12775                   used_at = 1;
12776                 }
12777
12778               /* Itbl support may require additional care here.  */
12779               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12780                            BFD_RELOC_GPREL16, tempreg);
12781               offset_expr.X_add_number += 4;
12782
12783               /* Set mips_optimize to 2 to avoid inserting an
12784                  undesired nop.  */
12785               hold_mips_optimize = mips_optimize;
12786               mips_optimize = 2;
12787               /* Itbl support may require additional care here.  */
12788               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12789                            BFD_RELOC_GPREL16, tempreg);
12790               mips_optimize = hold_mips_optimize;
12791
12792               relax_switch ();
12793
12794               offset_expr.X_add_number -= 4;
12795             }
12796           used_at = 1;
12797           if (offset_high_part (offset_expr.X_add_number, 16)
12798               != offset_high_part (offset_expr.X_add_number + 4, 16))
12799             {
12800               load_address (AT, &offset_expr, &used_at);
12801               offset_expr.X_op = O_constant;
12802               offset_expr.X_add_number = 0;
12803             }
12804           else
12805             macro_build_lui (&offset_expr, AT);
12806           if (breg != 0)
12807             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12808           /* Itbl support may require additional care here.  */
12809           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12810                        BFD_RELOC_LO16, AT);
12811           /* FIXME: How do we handle overflow here?  */
12812           offset_expr.X_add_number += 4;
12813           /* Itbl support may require additional care here.  */
12814           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12815                        BFD_RELOC_LO16, AT);
12816           if (mips_relax.sequence)
12817             relax_end ();
12818         }
12819       else if (!mips_big_got)
12820         {
12821           /* If this is a reference to an external symbol, we want
12822                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12823                nop
12824                <op>     op[0],0($at)
12825                <op>     op[0]+1,4($at)
12826              Otherwise we want
12827                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12828                nop
12829                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12830                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12831              If there is a base register we add it to $at before the
12832              lwc1 instructions.  If there is a constant we include it
12833              in the lwc1 instructions.  */
12834           used_at = 1;
12835           expr1.X_add_number = offset_expr.X_add_number;
12836           if (expr1.X_add_number < -0x8000
12837               || expr1.X_add_number >= 0x8000 - 4)
12838             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12839           load_got_offset (AT, &offset_expr);
12840           load_delay_nop ();
12841           if (breg != 0)
12842             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12843
12844           /* Set mips_optimize to 2 to avoid inserting an undesired
12845              nop.  */
12846           hold_mips_optimize = mips_optimize;
12847           mips_optimize = 2;
12848
12849           /* Itbl support may require additional care here.  */
12850           relax_start (offset_expr.X_add_symbol);
12851           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12852                        BFD_RELOC_LO16, AT);
12853           expr1.X_add_number += 4;
12854           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12855                        BFD_RELOC_LO16, AT);
12856           relax_switch ();
12857           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12858                        BFD_RELOC_LO16, AT);
12859           offset_expr.X_add_number += 4;
12860           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12861                        BFD_RELOC_LO16, AT);
12862           relax_end ();
12863
12864           mips_optimize = hold_mips_optimize;
12865         }
12866       else if (mips_big_got)
12867         {
12868           int gpdelay;
12869
12870           /* If this is a reference to an external symbol, we want
12871                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12872                addu     $at,$at,$gp
12873                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12874                nop
12875                <op>     op[0],0($at)
12876                <op>     op[0]+1,4($at)
12877              Otherwise we want
12878                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12879                nop
12880                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12881                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12882              If there is a base register we add it to $at before the
12883              lwc1 instructions.  If there is a constant we include it
12884              in the lwc1 instructions.  */
12885           used_at = 1;
12886           expr1.X_add_number = offset_expr.X_add_number;
12887           offset_expr.X_add_number = 0;
12888           if (expr1.X_add_number < -0x8000
12889               || expr1.X_add_number >= 0x8000 - 4)
12890             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12891           gpdelay = reg_needs_delay (mips_gp_register);
12892           relax_start (offset_expr.X_add_symbol);
12893           macro_build (&offset_expr, "lui", LUI_FMT,
12894                        AT, BFD_RELOC_MIPS_GOT_HI16);
12895           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12896                        AT, AT, mips_gp_register);
12897           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12898                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12899           load_delay_nop ();
12900           if (breg != 0)
12901             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12902           /* Itbl support may require additional care here.  */
12903           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12904                        BFD_RELOC_LO16, AT);
12905           expr1.X_add_number += 4;
12906
12907           /* Set mips_optimize to 2 to avoid inserting an undesired
12908              nop.  */
12909           hold_mips_optimize = mips_optimize;
12910           mips_optimize = 2;
12911           /* Itbl support may require additional care here.  */
12912           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12913                        BFD_RELOC_LO16, AT);
12914           mips_optimize = hold_mips_optimize;
12915           expr1.X_add_number -= 4;
12916
12917           relax_switch ();
12918           offset_expr.X_add_number = expr1.X_add_number;
12919           if (gpdelay)
12920             macro_build (NULL, "nop", "");
12921           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12922                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12923           load_delay_nop ();
12924           if (breg != 0)
12925             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12926           /* Itbl support may require additional care here.  */
12927           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12928                        BFD_RELOC_LO16, AT);
12929           offset_expr.X_add_number += 4;
12930
12931           /* Set mips_optimize to 2 to avoid inserting an undesired
12932              nop.  */
12933           hold_mips_optimize = mips_optimize;
12934           mips_optimize = 2;
12935           /* Itbl support may require additional care here.  */
12936           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12937                        BFD_RELOC_LO16, AT);
12938           mips_optimize = hold_mips_optimize;
12939           relax_end ();
12940         }
12941       else
12942         abort ();
12943
12944       break;
12945
12946     case M_SAA_AB:
12947       s = "saa";
12948       goto saa_saad;
12949     case M_SAAD_AB:
12950       s = "saad";
12951     saa_saad:
12952       gas_assert (!mips_opts.micromips);
12953       offbits = 0;
12954       fmt = "t,(b)";
12955       goto ld_st;
12956
12957    /* New code added to support COPZ instructions.
12958       This code builds table entries out of the macros in mip_opcodes.
12959       R4000 uses interlocks to handle coproc delays.
12960       Other chips (like the R3000) require nops to be inserted for delays.
12961
12962       FIXME: Currently, we require that the user handle delays.
12963       In order to fill delay slots for non-interlocked chips,
12964       we must have a way to specify delays based on the coprocessor.
12965       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12966       What are the side-effects of the cop instruction?
12967       What cache support might we have and what are its effects?
12968       Both coprocessor & memory require delays. how long???
12969       What registers are read/set/modified?
12970
12971       If an itbl is provided to interpret cop instructions,
12972       this knowledge can be encoded in the itbl spec.  */
12973
12974     case M_COP0:
12975       s = "c0";
12976       goto copz;
12977     case M_COP1:
12978       s = "c1";
12979       goto copz;
12980     case M_COP2:
12981       s = "c2";
12982       goto copz;
12983     case M_COP3:
12984       s = "c3";
12985     copz:
12986       gas_assert (!mips_opts.micromips);
12987       /* For now we just do C (same as Cz).  The parameter will be
12988          stored in insn_opcode by mips_ip.  */
12989       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12990       break;
12991
12992     case M_MOVE:
12993       move_register (op[0], op[1]);
12994       break;
12995
12996     case M_MOVEP:
12997       gas_assert (mips_opts.micromips);
12998       gas_assert (mips_opts.insn32);
12999       move_register (micromips_to_32_reg_h_map1[op[0]],
13000                      micromips_to_32_reg_m_map[op[1]]);
13001       move_register (micromips_to_32_reg_h_map2[op[0]],
13002                      micromips_to_32_reg_n_map[op[2]]);
13003       break;
13004
13005     case M_DMUL:
13006       dbl = 1;
13007       /* Fall through.  */
13008     case M_MUL:
13009       if (mips_opts.arch == CPU_R5900)
13010         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
13011                      op[2]);
13012       else
13013         {
13014           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
13015           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13016         }
13017       break;
13018
13019     case M_DMUL_I:
13020       dbl = 1;
13021       /* Fall through.  */
13022     case M_MUL_I:
13023       /* The MIPS assembler some times generates shifts and adds.  I'm
13024          not trying to be that fancy. GCC should do this for us
13025          anyway.  */
13026       used_at = 1;
13027       load_register (AT, &imm_expr, dbl);
13028       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
13029       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13030       break;
13031
13032     case M_DMULO_I:
13033       dbl = 1;
13034       /* Fall through.  */
13035     case M_MULO_I:
13036       imm = 1;
13037       goto do_mulo;
13038
13039     case M_DMULO:
13040       dbl = 1;
13041       /* Fall through.  */
13042     case M_MULO:
13043     do_mulo:
13044       start_noreorder ();
13045       used_at = 1;
13046       if (imm)
13047         load_register (AT, &imm_expr, dbl);
13048       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
13049                    op[1], imm ? AT : op[2]);
13050       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13051       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
13052       macro_build (NULL, "mfhi", MFHL_FMT, AT);
13053       if (mips_trap)
13054         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
13055       else
13056         {
13057           if (mips_opts.micromips)
13058             micromips_label_expr (&label_expr);
13059           else
13060             label_expr.X_add_number = 8;
13061           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
13062           macro_build (NULL, "nop", "");
13063           macro_build (NULL, "break", BRK_FMT, 6);
13064           if (mips_opts.micromips)
13065             micromips_add_label ();
13066         }
13067       end_noreorder ();
13068       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13069       break;
13070
13071     case M_DMULOU_I:
13072       dbl = 1;
13073       /* Fall through.  */
13074     case M_MULOU_I:
13075       imm = 1;
13076       goto do_mulou;
13077
13078     case M_DMULOU:
13079       dbl = 1;
13080       /* Fall through.  */
13081     case M_MULOU:
13082     do_mulou:
13083       start_noreorder ();
13084       used_at = 1;
13085       if (imm)
13086         load_register (AT, &imm_expr, dbl);
13087       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
13088                    op[1], imm ? AT : op[2]);
13089       macro_build (NULL, "mfhi", MFHL_FMT, AT);
13090       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13091       if (mips_trap)
13092         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
13093       else
13094         {
13095           if (mips_opts.micromips)
13096             micromips_label_expr (&label_expr);
13097           else
13098             label_expr.X_add_number = 8;
13099           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
13100           macro_build (NULL, "nop", "");
13101           macro_build (NULL, "break", BRK_FMT, 6);
13102           if (mips_opts.micromips)
13103             micromips_add_label ();
13104         }
13105       end_noreorder ();
13106       break;
13107
13108     case M_DROL:
13109       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13110         {
13111           if (op[0] == op[1])
13112             {
13113               tempreg = AT;
13114               used_at = 1;
13115             }
13116           else
13117             tempreg = op[0];
13118           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
13119           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
13120           break;
13121         }
13122       used_at = 1;
13123       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13124       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
13125       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
13126       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13127       break;
13128
13129     case M_ROL:
13130       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13131         {
13132           if (op[0] == op[1])
13133             {
13134               tempreg = AT;
13135               used_at = 1;
13136             }
13137           else
13138             tempreg = op[0];
13139           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
13140           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
13141           break;
13142         }
13143       used_at = 1;
13144       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13145       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
13146       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
13147       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13148       break;
13149
13150     case M_DROL_I:
13151       {
13152         unsigned int rot;
13153         const char *l;
13154         const char *rr;
13155
13156         rot = imm_expr.X_add_number & 0x3f;
13157         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13158           {
13159             rot = (64 - rot) & 0x3f;
13160             if (rot >= 32)
13161               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13162             else
13163               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13164             break;
13165           }
13166         if (rot == 0)
13167           {
13168             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13169             break;
13170           }
13171         l = (rot < 0x20) ? "dsll" : "dsll32";
13172         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
13173         rot &= 0x1f;
13174         used_at = 1;
13175         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
13176         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13177         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13178       }
13179       break;
13180
13181     case M_ROL_I:
13182       {
13183         unsigned int rot;
13184
13185         rot = imm_expr.X_add_number & 0x1f;
13186         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13187           {
13188             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
13189                          (32 - rot) & 0x1f);
13190             break;
13191           }
13192         if (rot == 0)
13193           {
13194             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13195             break;
13196           }
13197         used_at = 1;
13198         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
13199         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13200         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13201       }
13202       break;
13203
13204     case M_DROR:
13205       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13206         {
13207           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
13208           break;
13209         }
13210       used_at = 1;
13211       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13212       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13213       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13214       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13215       break;
13216
13217     case M_ROR:
13218       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13219         {
13220           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13221           break;
13222         }
13223       used_at = 1;
13224       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13225       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13226       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13227       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13228       break;
13229
13230     case M_DROR_I:
13231       {
13232         unsigned int rot;
13233         const char *l;
13234         const char *rr;
13235
13236         rot = imm_expr.X_add_number & 0x3f;
13237         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13238           {
13239             if (rot >= 32)
13240               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13241             else
13242               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13243             break;
13244           }
13245         if (rot == 0)
13246           {
13247             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13248             break;
13249           }
13250         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13251         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13252         rot &= 0x1f;
13253         used_at = 1;
13254         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13255         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13256         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13257       }
13258       break;
13259
13260     case M_ROR_I:
13261       {
13262         unsigned int rot;
13263
13264         rot = imm_expr.X_add_number & 0x1f;
13265         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13266           {
13267             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13268             break;
13269           }
13270         if (rot == 0)
13271           {
13272             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13273             break;
13274           }
13275         used_at = 1;
13276         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13277         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13278         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13279       }
13280       break;
13281
13282     case M_SEQ:
13283       if (op[1] == 0)
13284         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13285       else if (op[2] == 0)
13286         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13287       else
13288         {
13289           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13290           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13291         }
13292       break;
13293
13294     case M_SEQ_I:
13295       if (imm_expr.X_add_number == 0)
13296         {
13297           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13298           break;
13299         }
13300       if (op[1] == 0)
13301         {
13302           as_warn (_("instruction %s: result is always false"),
13303                    ip->insn_mo->name);
13304           move_register (op[0], 0);
13305           break;
13306         }
13307       if (CPU_HAS_SEQ (mips_opts.arch)
13308           && -512 <= imm_expr.X_add_number
13309           && imm_expr.X_add_number < 512)
13310         {
13311           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13312                        (int) imm_expr.X_add_number);
13313           break;
13314         }
13315       if (imm_expr.X_add_number >= 0
13316           && imm_expr.X_add_number < 0x10000)
13317         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13318       else if (imm_expr.X_add_number > -0x8000
13319                && imm_expr.X_add_number < 0)
13320         {
13321           imm_expr.X_add_number = -imm_expr.X_add_number;
13322           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13323                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13324         }
13325       else if (CPU_HAS_SEQ (mips_opts.arch))
13326         {
13327           used_at = 1;
13328           load_register (AT, &imm_expr, GPR_SIZE == 64);
13329           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13330           break;
13331         }
13332       else
13333         {
13334           load_register (AT, &imm_expr, GPR_SIZE == 64);
13335           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13336           used_at = 1;
13337         }
13338       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13339       break;
13340
13341     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
13342       s = "slt";
13343       goto sge;
13344     case M_SGEU:
13345       s = "sltu";
13346     sge:
13347       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13348       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13349       break;
13350
13351     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
13352     case M_SGEU_I:
13353       if (imm_expr.X_add_number >= -0x8000
13354           && imm_expr.X_add_number < 0x8000)
13355         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13356                      op[0], op[1], BFD_RELOC_LO16);
13357       else
13358         {
13359           load_register (AT, &imm_expr, GPR_SIZE == 64);
13360           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13361                        op[0], op[1], AT);
13362           used_at = 1;
13363         }
13364       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13365       break;
13366
13367     case M_SGT:         /* X > Y  <==>  Y < X */
13368       s = "slt";
13369       goto sgt;
13370     case M_SGTU:
13371       s = "sltu";
13372     sgt:
13373       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13374       break;
13375
13376     case M_SGT_I:       /* X > I  <==>  I < X */
13377       s = "slt";
13378       goto sgti;
13379     case M_SGTU_I:
13380       s = "sltu";
13381     sgti:
13382       used_at = 1;
13383       load_register (AT, &imm_expr, GPR_SIZE == 64);
13384       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13385       break;
13386
13387     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
13388       s = "slt";
13389       goto sle;
13390     case M_SLEU:
13391       s = "sltu";
13392     sle:
13393       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13394       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13395       break;
13396
13397     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
13398       s = "slt";
13399       goto slei;
13400     case M_SLEU_I:
13401       s = "sltu";
13402     slei:
13403       used_at = 1;
13404       load_register (AT, &imm_expr, GPR_SIZE == 64);
13405       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13406       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13407       break;
13408
13409     case M_SLT_I:
13410       if (imm_expr.X_add_number >= -0x8000
13411           && imm_expr.X_add_number < 0x8000)
13412         {
13413           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13414                        BFD_RELOC_LO16);
13415           break;
13416         }
13417       used_at = 1;
13418       load_register (AT, &imm_expr, GPR_SIZE == 64);
13419       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13420       break;
13421
13422     case M_SLTU_I:
13423       if (imm_expr.X_add_number >= -0x8000
13424           && imm_expr.X_add_number < 0x8000)
13425         {
13426           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13427                        BFD_RELOC_LO16);
13428           break;
13429         }
13430       used_at = 1;
13431       load_register (AT, &imm_expr, GPR_SIZE == 64);
13432       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13433       break;
13434
13435     case M_SNE:
13436       if (op[1] == 0)
13437         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13438       else if (op[2] == 0)
13439         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13440       else
13441         {
13442           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13443           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13444         }
13445       break;
13446
13447     case M_SNE_I:
13448       if (imm_expr.X_add_number == 0)
13449         {
13450           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13451           break;
13452         }
13453       if (op[1] == 0)
13454         {
13455           as_warn (_("instruction %s: result is always true"),
13456                    ip->insn_mo->name);
13457           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13458                        op[0], 0, BFD_RELOC_LO16);
13459           break;
13460         }
13461       if (CPU_HAS_SEQ (mips_opts.arch)
13462           && -512 <= imm_expr.X_add_number
13463           && imm_expr.X_add_number < 512)
13464         {
13465           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13466                        (int) imm_expr.X_add_number);
13467           break;
13468         }
13469       if (imm_expr.X_add_number >= 0
13470           && imm_expr.X_add_number < 0x10000)
13471         {
13472           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13473                        BFD_RELOC_LO16);
13474         }
13475       else if (imm_expr.X_add_number > -0x8000
13476                && imm_expr.X_add_number < 0)
13477         {
13478           imm_expr.X_add_number = -imm_expr.X_add_number;
13479           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13480                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13481         }
13482       else if (CPU_HAS_SEQ (mips_opts.arch))
13483         {
13484           used_at = 1;
13485           load_register (AT, &imm_expr, GPR_SIZE == 64);
13486           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13487           break;
13488         }
13489       else
13490         {
13491           load_register (AT, &imm_expr, GPR_SIZE == 64);
13492           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13493           used_at = 1;
13494         }
13495       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13496       break;
13497
13498     case M_SUB_I:
13499       s = "addi";
13500       s2 = "sub";
13501       goto do_subi;
13502     case M_SUBU_I:
13503       s = "addiu";
13504       s2 = "subu";
13505       goto do_subi;
13506     case M_DSUB_I:
13507       dbl = 1;
13508       s = "daddi";
13509       s2 = "dsub";
13510       if (!mips_opts.micromips)
13511         goto do_subi;
13512       if (imm_expr.X_add_number > -0x200
13513           && imm_expr.X_add_number <= 0x200)
13514         {
13515           macro_build (NULL, s, "t,r,.", op[0], op[1],
13516                        (int) -imm_expr.X_add_number);
13517           break;
13518         }
13519       goto do_subi_i;
13520     case M_DSUBU_I:
13521       dbl = 1;
13522       s = "daddiu";
13523       s2 = "dsubu";
13524     do_subi:
13525       if (imm_expr.X_add_number > -0x8000
13526           && imm_expr.X_add_number <= 0x8000)
13527         {
13528           imm_expr.X_add_number = -imm_expr.X_add_number;
13529           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13530           break;
13531         }
13532     do_subi_i:
13533       used_at = 1;
13534       load_register (AT, &imm_expr, dbl);
13535       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13536       break;
13537
13538     case M_TEQ_I:
13539       s = "teq";
13540       goto trap;
13541     case M_TGE_I:
13542       s = "tge";
13543       goto trap;
13544     case M_TGEU_I:
13545       s = "tgeu";
13546       goto trap;
13547     case M_TLT_I:
13548       s = "tlt";
13549       goto trap;
13550     case M_TLTU_I:
13551       s = "tltu";
13552       goto trap;
13553     case M_TNE_I:
13554       s = "tne";
13555     trap:
13556       used_at = 1;
13557       load_register (AT, &imm_expr, GPR_SIZE == 64);
13558       macro_build (NULL, s, "s,t", op[0], AT);
13559       break;
13560
13561     case M_TRUNCWS:
13562     case M_TRUNCWD:
13563       gas_assert (!mips_opts.micromips);
13564       gas_assert (mips_opts.isa == ISA_MIPS1);
13565       used_at = 1;
13566
13567       /*
13568        * Is the double cfc1 instruction a bug in the mips assembler;
13569        * or is there a reason for it?
13570        */
13571       start_noreorder ();
13572       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13573       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13574       macro_build (NULL, "nop", "");
13575       expr1.X_add_number = 3;
13576       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13577       expr1.X_add_number = 2;
13578       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13579       macro_build (NULL, "ctc1", "t,G", AT, RA);
13580       macro_build (NULL, "nop", "");
13581       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13582                    op[0], op[1]);
13583       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13584       macro_build (NULL, "nop", "");
13585       end_noreorder ();
13586       break;
13587
13588     case M_ULH_AB:
13589       s = "lb";
13590       s2 = "lbu";
13591       off = 1;
13592       goto uld_st;
13593     case M_ULHU_AB:
13594       s = "lbu";
13595       s2 = "lbu";
13596       off = 1;
13597       goto uld_st;
13598     case M_ULW_AB:
13599       s = "lwl";
13600       s2 = "lwr";
13601       offbits = (mips_opts.micromips ? 12 : 16);
13602       off = 3;
13603       goto uld_st;
13604     case M_ULD_AB:
13605       s = "ldl";
13606       s2 = "ldr";
13607       offbits = (mips_opts.micromips ? 12 : 16);
13608       off = 7;
13609       goto uld_st;
13610     case M_USH_AB:
13611       s = "sb";
13612       s2 = "sb";
13613       off = 1;
13614       ust = 1;
13615       goto uld_st;
13616     case M_USW_AB:
13617       s = "swl";
13618       s2 = "swr";
13619       offbits = (mips_opts.micromips ? 12 : 16);
13620       off = 3;
13621       ust = 1;
13622       goto uld_st;
13623     case M_USD_AB:
13624       s = "sdl";
13625       s2 = "sdr";
13626       offbits = (mips_opts.micromips ? 12 : 16);
13627       off = 7;
13628       ust = 1;
13629
13630     uld_st:
13631       breg = op[2];
13632       large_offset = !small_offset_p (off, align, offbits);
13633       ep = &offset_expr;
13634       expr1.X_add_number = 0;
13635       if (large_offset)
13636         {
13637           used_at = 1;
13638           tempreg = AT;
13639           if (small_offset_p (0, align, 16))
13640             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13641                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13642           else
13643             {
13644               load_address (tempreg, ep, &used_at);
13645               if (breg != 0)
13646                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13647                              tempreg, tempreg, breg);
13648             }
13649           offset_reloc[0] = BFD_RELOC_LO16;
13650           offset_reloc[1] = BFD_RELOC_UNUSED;
13651           offset_reloc[2] = BFD_RELOC_UNUSED;
13652           breg = tempreg;
13653           tempreg = op[0];
13654           ep = &expr1;
13655         }
13656       else if (!ust && op[0] == breg)
13657         {
13658           used_at = 1;
13659           tempreg = AT;
13660         }
13661       else
13662         tempreg = op[0];
13663
13664       if (off == 1)
13665         goto ulh_sh;
13666
13667       if (!target_big_endian)
13668         ep->X_add_number += off;
13669       if (offbits == 12)
13670         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13671       else
13672         macro_build (ep, s, "t,o(b)", tempreg, -1,
13673                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13674
13675       if (!target_big_endian)
13676         ep->X_add_number -= off;
13677       else
13678         ep->X_add_number += off;
13679       if (offbits == 12)
13680         macro_build (NULL, s2, "t,~(b)",
13681                      tempreg, (int) ep->X_add_number, breg);
13682       else
13683         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13684                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13685
13686       /* If necessary, move the result in tempreg to the final destination.  */
13687       if (!ust && op[0] != tempreg)
13688         {
13689           /* Protect second load's delay slot.  */
13690           load_delay_nop ();
13691           move_register (op[0], tempreg);
13692         }
13693       break;
13694
13695     ulh_sh:
13696       used_at = 1;
13697       if (target_big_endian == ust)
13698         ep->X_add_number += off;
13699       tempreg = ust || large_offset ? op[0] : AT;
13700       macro_build (ep, s, "t,o(b)", tempreg, -1,
13701                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13702
13703       /* For halfword transfers we need a temporary register to shuffle
13704          bytes.  Unfortunately for M_USH_A we have none available before
13705          the next store as AT holds the base address.  We deal with this
13706          case by clobbering TREG and then restoring it as with ULH.  */
13707       tempreg = ust == large_offset ? op[0] : AT;
13708       if (ust)
13709         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13710
13711       if (target_big_endian == ust)
13712         ep->X_add_number -= off;
13713       else
13714         ep->X_add_number += off;
13715       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13716                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13717
13718       /* For M_USH_A re-retrieve the LSB.  */
13719       if (ust && large_offset)
13720         {
13721           if (target_big_endian)
13722             ep->X_add_number += off;
13723           else
13724             ep->X_add_number -= off;
13725           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13726                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13727         }
13728       /* For ULH and M_USH_A OR the LSB in.  */
13729       if (!ust || large_offset)
13730         {
13731           tempreg = !large_offset ? AT : op[0];
13732           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13733           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13734         }
13735       break;
13736
13737     default:
13738       /* FIXME: Check if this is one of the itbl macros, since they
13739          are added dynamically.  */
13740       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13741       break;
13742     }
13743   if (!mips_opts.at && used_at)
13744     as_bad (_("macro used $at after \".set noat\""));
13745 }
13746
13747 /* Implement macros in mips16 mode.  */
13748
13749 static void
13750 mips16_macro (struct mips_cl_insn *ip)
13751 {
13752   const struct mips_operand_array *operands;
13753   int mask;
13754   int tmp;
13755   expressionS expr1;
13756   int dbl;
13757   const char *s, *s2, *s3;
13758   unsigned int op[MAX_OPERANDS];
13759   unsigned int i;
13760
13761   mask = ip->insn_mo->mask;
13762
13763   operands = insn_operands (ip);
13764   for (i = 0; i < MAX_OPERANDS; i++)
13765     if (operands->operand[i])
13766       op[i] = insn_extract_operand (ip, operands->operand[i]);
13767     else
13768       op[i] = -1;
13769
13770   expr1.X_op = O_constant;
13771   expr1.X_op_symbol = NULL;
13772   expr1.X_add_symbol = NULL;
13773   expr1.X_add_number = 1;
13774
13775   dbl = 0;
13776
13777   switch (mask)
13778     {
13779     default:
13780       abort ();
13781
13782     case M_DDIV_3:
13783       dbl = 1;
13784       /* Fall through.  */
13785     case M_DIV_3:
13786       s = "mflo";
13787       goto do_div3;
13788     case M_DREM_3:
13789       dbl = 1;
13790       /* Fall through.  */
13791     case M_REM_3:
13792       s = "mfhi";
13793     do_div3:
13794       start_noreorder ();
13795       macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
13796       expr1.X_add_number = 2;
13797       macro_build (&expr1, "bnez", "x,p", op[2]);
13798       macro_build (NULL, "break", "6", 7);
13799
13800       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13801          since that causes an overflow.  We should do that as well,
13802          but I don't see how to do the comparisons without a temporary
13803          register.  */
13804       end_noreorder ();
13805       macro_build (NULL, s, "x", op[0]);
13806       break;
13807
13808     case M_DIVU_3:
13809       s = "divu";
13810       s2 = "mflo";
13811       goto do_divu3;
13812     case M_REMU_3:
13813       s = "divu";
13814       s2 = "mfhi";
13815       goto do_divu3;
13816     case M_DDIVU_3:
13817       s = "ddivu";
13818       s2 = "mflo";
13819       goto do_divu3;
13820     case M_DREMU_3:
13821       s = "ddivu";
13822       s2 = "mfhi";
13823     do_divu3:
13824       start_noreorder ();
13825       macro_build (NULL, s, ".,x,y", op[1], op[2]);
13826       expr1.X_add_number = 2;
13827       macro_build (&expr1, "bnez", "x,p", op[2]);
13828       macro_build (NULL, "break", "6", 7);
13829       end_noreorder ();
13830       macro_build (NULL, s2, "x", op[0]);
13831       break;
13832
13833     case M_DMUL:
13834       dbl = 1;
13835       /* Fall through.  */
13836     case M_MUL:
13837       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13838       macro_build (NULL, "mflo", "x", op[0]);
13839       break;
13840
13841     case M_DSUBU_I:
13842       dbl = 1;
13843       goto do_subu;
13844     case M_SUBU_I:
13845     do_subu:
13846       imm_expr.X_add_number = -imm_expr.X_add_number;
13847       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
13848       break;
13849
13850     case M_SUBU_I_2:
13851       imm_expr.X_add_number = -imm_expr.X_add_number;
13852       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13853       break;
13854
13855     case M_DSUBU_I_2:
13856       imm_expr.X_add_number = -imm_expr.X_add_number;
13857       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13858       break;
13859
13860     case M_BEQ:
13861       s = "cmp";
13862       s2 = "bteqz";
13863       goto do_branch;
13864     case M_BNE:
13865       s = "cmp";
13866       s2 = "btnez";
13867       goto do_branch;
13868     case M_BLT:
13869       s = "slt";
13870       s2 = "btnez";
13871       goto do_branch;
13872     case M_BLTU:
13873       s = "sltu";
13874       s2 = "btnez";
13875       goto do_branch;
13876     case M_BLE:
13877       s = "slt";
13878       s2 = "bteqz";
13879       goto do_reverse_branch;
13880     case M_BLEU:
13881       s = "sltu";
13882       s2 = "bteqz";
13883       goto do_reverse_branch;
13884     case M_BGE:
13885       s = "slt";
13886       s2 = "bteqz";
13887       goto do_branch;
13888     case M_BGEU:
13889       s = "sltu";
13890       s2 = "bteqz";
13891       goto do_branch;
13892     case M_BGT:
13893       s = "slt";
13894       s2 = "btnez";
13895       goto do_reverse_branch;
13896     case M_BGTU:
13897       s = "sltu";
13898       s2 = "btnez";
13899
13900     do_reverse_branch:
13901       tmp = op[1];
13902       op[1] = op[0];
13903       op[0] = tmp;
13904
13905     do_branch:
13906       macro_build (NULL, s, "x,y", op[0], op[1]);
13907       macro_build (&offset_expr, s2, "p");
13908       break;
13909
13910     case M_BEQ_I:
13911       s = "cmpi";
13912       s2 = "bteqz";
13913       s3 = "x,U";
13914       goto do_branch_i;
13915     case M_BNE_I:
13916       s = "cmpi";
13917       s2 = "btnez";
13918       s3 = "x,U";
13919       goto do_branch_i;
13920     case M_BLT_I:
13921       s = "slti";
13922       s2 = "btnez";
13923       s3 = "x,8";
13924       goto do_branch_i;
13925     case M_BLTU_I:
13926       s = "sltiu";
13927       s2 = "btnez";
13928       s3 = "x,8";
13929       goto do_branch_i;
13930     case M_BLE_I:
13931       s = "slti";
13932       s2 = "btnez";
13933       s3 = "x,8";
13934       goto do_addone_branch_i;
13935     case M_BLEU_I:
13936       s = "sltiu";
13937       s2 = "btnez";
13938       s3 = "x,8";
13939       goto do_addone_branch_i;
13940     case M_BGE_I:
13941       s = "slti";
13942       s2 = "bteqz";
13943       s3 = "x,8";
13944       goto do_branch_i;
13945     case M_BGEU_I:
13946       s = "sltiu";
13947       s2 = "bteqz";
13948       s3 = "x,8";
13949       goto do_branch_i;
13950     case M_BGT_I:
13951       s = "slti";
13952       s2 = "bteqz";
13953       s3 = "x,8";
13954       goto do_addone_branch_i;
13955     case M_BGTU_I:
13956       s = "sltiu";
13957       s2 = "bteqz";
13958       s3 = "x,8";
13959
13960     do_addone_branch_i:
13961       ++imm_expr.X_add_number;
13962
13963     do_branch_i:
13964       macro_build (&imm_expr, s, s3, op[0]);
13965       macro_build (&offset_expr, s2, "p");
13966       break;
13967
13968     case M_ABS:
13969       expr1.X_add_number = 0;
13970       macro_build (&expr1, "slti", "x,8", op[1]);
13971       if (op[0] != op[1])
13972         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13973       expr1.X_add_number = 2;
13974       macro_build (&expr1, "bteqz", "p");
13975       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13976       break;
13977     }
13978 }
13979
13980 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13981    opcode bits in *OPCODE_EXTRA.  */
13982
13983 static struct mips_opcode *
13984 mips_lookup_insn (struct hash_control *hash, const char *start,
13985                   ssize_t length, unsigned int *opcode_extra)
13986 {
13987   char *name, *dot, *p;
13988   unsigned int mask, suffix;
13989   ssize_t opend;
13990   struct mips_opcode *insn;
13991
13992   /* Make a copy of the instruction so that we can fiddle with it.  */
13993   name = xstrndup (start, length);
13994
13995   /* Look up the instruction as-is.  */
13996   insn = (struct mips_opcode *) hash_find (hash, name);
13997   if (insn)
13998     goto end;
13999
14000   dot = strchr (name, '.');
14001   if (dot && dot[1])
14002     {
14003       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
14004       p = mips_parse_vu0_channels (dot + 1, &mask);
14005       if (*p == 0 && mask != 0)
14006         {
14007           *dot = 0;
14008           insn = (struct mips_opcode *) hash_find (hash, name);
14009           *dot = '.';
14010           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
14011             {
14012               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
14013               goto end;
14014             }
14015         }
14016     }
14017
14018   if (mips_opts.micromips)
14019     {
14020       /* See if there's an instruction size override suffix,
14021          either `16' or `32', at the end of the mnemonic proper,
14022          that defines the operation, i.e. before the first `.'
14023          character if any.  Strip it and retry.  */
14024       opend = dot != NULL ? dot - name : length;
14025       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
14026         suffix = 2;
14027       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
14028         suffix = 4;
14029       else
14030         suffix = 0;
14031       if (suffix)
14032         {
14033           memmove (name + opend - 2, name + opend, length - opend + 1);
14034           insn = (struct mips_opcode *) hash_find (hash, name);
14035           if (insn)
14036             {
14037               forced_insn_length = suffix;
14038               goto end;
14039             }
14040         }
14041     }
14042
14043   insn = NULL;
14044  end:
14045   free (name);
14046   return insn;
14047 }
14048
14049 /* Assemble an instruction into its binary format.  If the instruction
14050    is a macro, set imm_expr and offset_expr to the values associated
14051    with "I" and "A" operands respectively.  Otherwise store the value
14052    of the relocatable field (if any) in offset_expr.  In both cases
14053    set offset_reloc to the relocation operators applied to offset_expr.  */
14054
14055 static void
14056 mips_ip (char *str, struct mips_cl_insn *insn)
14057 {
14058   const struct mips_opcode *first, *past;
14059   struct hash_control *hash;
14060   char format;
14061   size_t end;
14062   struct mips_operand_token *tokens;
14063   unsigned int opcode_extra;
14064
14065   if (mips_opts.micromips)
14066     {
14067       hash = micromips_op_hash;
14068       past = &micromips_opcodes[bfd_micromips_num_opcodes];
14069     }
14070   else
14071     {
14072       hash = op_hash;
14073       past = &mips_opcodes[NUMOPCODES];
14074     }
14075   forced_insn_length = 0;
14076   opcode_extra = 0;
14077
14078   /* We first try to match an instruction up to a space or to the end.  */
14079   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
14080     continue;
14081
14082   first = mips_lookup_insn (hash, str, end, &opcode_extra);
14083   if (first == NULL)
14084     {
14085       set_insn_error (0, _("unrecognized opcode"));
14086       return;
14087     }
14088
14089   if (strcmp (first->name, "li.s") == 0)
14090     format = 'f';
14091   else if (strcmp (first->name, "li.d") == 0)
14092     format = 'd';
14093   else
14094     format = 0;
14095   tokens = mips_parse_arguments (str + end, format);
14096   if (!tokens)
14097     return;
14098
14099   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
14100       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
14101     set_insn_error (0, _("invalid operands"));
14102
14103   obstack_free (&mips_operand_tokens, tokens);
14104 }
14105
14106 /* As for mips_ip, but used when assembling MIPS16 code.
14107    Also set forced_insn_length to the resulting instruction size in
14108    bytes if the user explicitly requested a small or extended instruction.  */
14109
14110 static void
14111 mips16_ip (char *str, struct mips_cl_insn *insn)
14112 {
14113   char *end, *s, c;
14114   struct mips_opcode *first;
14115   struct mips_operand_token *tokens;
14116   unsigned int l;
14117
14118   for (s = str; *s != '\0' && *s != '.' && *s != ' '; ++s)
14119     ;
14120   end = s;
14121   c = *end;
14122
14123   l = 0;
14124   switch (c)
14125     {
14126     case '\0':
14127       break;
14128
14129     case ' ':
14130       s++;
14131       break;
14132
14133     case '.':
14134       s++;
14135       if (*s == 't')
14136         {
14137           l = 2;
14138           s++;
14139         }
14140       else if (*s == 'e')
14141         {
14142           l = 4;
14143           s++;
14144         }
14145       if (*s == '\0')
14146         break;
14147       else if (*s++ == ' ')
14148         break;
14149       set_insn_error (0, _("unrecognized opcode"));
14150       return;
14151     }
14152   forced_insn_length = l;
14153
14154   *end = 0;
14155   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
14156   *end = c;
14157
14158   if (!first)
14159     {
14160       set_insn_error (0, _("unrecognized opcode"));
14161       return;
14162     }
14163
14164   tokens = mips_parse_arguments (s, 0);
14165   if (!tokens)
14166     return;
14167
14168   if (!match_mips16_insns (insn, first, tokens))
14169     set_insn_error (0, _("invalid operands"));
14170
14171   obstack_free (&mips_operand_tokens, tokens);
14172 }
14173
14174 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14175    NBITS is the number of significant bits in VAL.  */
14176
14177 static unsigned long
14178 mips16_immed_extend (offsetT val, unsigned int nbits)
14179 {
14180   int extval;
14181
14182   extval = 0;
14183   val &= (1U << nbits) - 1;
14184   if (nbits == 16 || nbits == 9)
14185     {
14186       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14187       val &= 0x1f;
14188     }
14189   else if (nbits == 15)
14190     {
14191       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14192       val &= 0xf;
14193     }
14194   else if (nbits == 6)
14195     {
14196       extval = ((val & 0x1f) << 6) | (val & 0x20);
14197       val = 0;
14198     }
14199   return (extval << 16) | val;
14200 }
14201
14202 /* Like decode_mips16_operand, but require the operand to be defined and
14203    require it to be an integer.  */
14204
14205 static const struct mips_int_operand *
14206 mips16_immed_operand (int type, bfd_boolean extended_p)
14207 {
14208   const struct mips_operand *operand;
14209
14210   operand = decode_mips16_operand (type, extended_p);
14211   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
14212     abort ();
14213   return (const struct mips_int_operand *) operand;
14214 }
14215
14216 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14217
14218 static bfd_boolean
14219 mips16_immed_in_range_p (const struct mips_int_operand *operand,
14220                          bfd_reloc_code_real_type reloc, offsetT sval)
14221 {
14222   int min_val, max_val;
14223
14224   min_val = mips_int_operand_min (operand);
14225   max_val = mips_int_operand_max (operand);
14226   if (reloc != BFD_RELOC_UNUSED)
14227     {
14228       if (min_val < 0)
14229         sval = SEXT_16BIT (sval);
14230       else
14231         sval &= 0xffff;
14232     }
14233
14234   return (sval >= min_val
14235           && sval <= max_val
14236           && (sval & ((1 << operand->shift) - 1)) == 0);
14237 }
14238
14239 /* Install immediate value VAL into MIPS16 instruction *INSN,
14240    extending it if necessary.  The instruction in *INSN may
14241    already be extended.
14242
14243    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14244    if none.  In the former case, VAL is a 16-bit number with no
14245    defined signedness.
14246
14247    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14248    is the length that the user requested, or 0 if none.  */
14249
14250 static void
14251 mips16_immed (const char *file, unsigned int line, int type,
14252               bfd_reloc_code_real_type reloc, offsetT val,
14253               unsigned int user_insn_length, unsigned long *insn)
14254 {
14255   const struct mips_int_operand *operand;
14256   unsigned int uval, length;
14257
14258   operand = mips16_immed_operand (type, FALSE);
14259   if (!mips16_immed_in_range_p (operand, reloc, val))
14260     {
14261       /* We need an extended instruction.  */
14262       if (user_insn_length == 2)
14263         as_bad_where (file, line, _("invalid unextended operand value"));
14264       else
14265         *insn |= MIPS16_EXTEND;
14266     }
14267   else if (user_insn_length == 4)
14268     {
14269       /* The operand doesn't force an unextended instruction to be extended.
14270          Warn if the user wanted an extended instruction anyway.  */
14271       *insn |= MIPS16_EXTEND;
14272       as_warn_where (file, line,
14273                      _("extended operand requested but not required"));
14274     }
14275
14276   length = mips16_opcode_length (*insn);
14277   if (length == 4)
14278     {
14279       operand = mips16_immed_operand (type, TRUE);
14280       if (!mips16_immed_in_range_p (operand, reloc, val))
14281         as_bad_where (file, line,
14282                       _("operand value out of range for instruction"));
14283     }
14284   uval = ((unsigned int) val >> operand->shift) - operand->bias;
14285   if (length == 2 || operand->root.lsb != 0)
14286     *insn = mips_insert_operand (&operand->root, *insn, uval);
14287   else
14288     *insn |= mips16_immed_extend (uval, operand->root.size);
14289 }
14290 \f
14291 struct percent_op_match
14292 {
14293   const char *str;
14294   bfd_reloc_code_real_type reloc;
14295 };
14296
14297 static const struct percent_op_match mips_percent_op[] =
14298 {
14299   {"%lo", BFD_RELOC_LO16},
14300   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14301   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14302   {"%call16", BFD_RELOC_MIPS_CALL16},
14303   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14304   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14305   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14306   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14307   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14308   {"%got", BFD_RELOC_MIPS_GOT16},
14309   {"%gp_rel", BFD_RELOC_GPREL16},
14310   {"%gprel", BFD_RELOC_GPREL16},
14311   {"%half", BFD_RELOC_16},
14312   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14313   {"%higher", BFD_RELOC_MIPS_HIGHER},
14314   {"%neg", BFD_RELOC_MIPS_SUB},
14315   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14316   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14317   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14318   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14319   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14320   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14321   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14322   {"%hi", BFD_RELOC_HI16_S},
14323   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14324   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14325 };
14326
14327 static const struct percent_op_match mips16_percent_op[] =
14328 {
14329   {"%lo", BFD_RELOC_MIPS16_LO16},
14330   {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14331   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14332   {"%got", BFD_RELOC_MIPS16_GOT16},
14333   {"%call16", BFD_RELOC_MIPS16_CALL16},
14334   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14335   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14336   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14337   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14338   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14339   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14340   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14341   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14342 };
14343
14344
14345 /* Return true if *STR points to a relocation operator.  When returning true,
14346    move *STR over the operator and store its relocation code in *RELOC.
14347    Leave both *STR and *RELOC alone when returning false.  */
14348
14349 static bfd_boolean
14350 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14351 {
14352   const struct percent_op_match *percent_op;
14353   size_t limit, i;
14354
14355   if (mips_opts.mips16)
14356     {
14357       percent_op = mips16_percent_op;
14358       limit = ARRAY_SIZE (mips16_percent_op);
14359     }
14360   else
14361     {
14362       percent_op = mips_percent_op;
14363       limit = ARRAY_SIZE (mips_percent_op);
14364     }
14365
14366   for (i = 0; i < limit; i++)
14367     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14368       {
14369         int len = strlen (percent_op[i].str);
14370
14371         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14372           continue;
14373
14374         *str += strlen (percent_op[i].str);
14375         *reloc = percent_op[i].reloc;
14376
14377         /* Check whether the output BFD supports this relocation.
14378            If not, issue an error and fall back on something safe.  */
14379         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14380           {
14381             as_bad (_("relocation %s isn't supported by the current ABI"),
14382                     percent_op[i].str);
14383             *reloc = BFD_RELOC_UNUSED;
14384           }
14385         return TRUE;
14386       }
14387   return FALSE;
14388 }
14389
14390
14391 /* Parse string STR as a 16-bit relocatable operand.  Store the
14392    expression in *EP and the relocations in the array starting
14393    at RELOC.  Return the number of relocation operators used.
14394
14395    On exit, EXPR_END points to the first character after the expression.  */
14396
14397 static size_t
14398 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14399                        char *str)
14400 {
14401   bfd_reloc_code_real_type reversed_reloc[3];
14402   size_t reloc_index, i;
14403   int crux_depth, str_depth;
14404   char *crux;
14405
14406   /* Search for the start of the main expression, recoding relocations
14407      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14408      of the main expression and with CRUX_DEPTH containing the number
14409      of open brackets at that point.  */
14410   reloc_index = -1;
14411   str_depth = 0;
14412   do
14413     {
14414       reloc_index++;
14415       crux = str;
14416       crux_depth = str_depth;
14417
14418       /* Skip over whitespace and brackets, keeping count of the number
14419          of brackets.  */
14420       while (*str == ' ' || *str == '\t' || *str == '(')
14421         if (*str++ == '(')
14422           str_depth++;
14423     }
14424   while (*str == '%'
14425          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14426          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14427
14428   my_getExpression (ep, crux);
14429   str = expr_end;
14430
14431   /* Match every open bracket.  */
14432   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14433     if (*str++ == ')')
14434       crux_depth--;
14435
14436   if (crux_depth > 0)
14437     as_bad (_("unclosed '('"));
14438
14439   expr_end = str;
14440
14441   if (reloc_index != 0)
14442     {
14443       prev_reloc_op_frag = frag_now;
14444       for (i = 0; i < reloc_index; i++)
14445         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14446     }
14447
14448   return reloc_index;
14449 }
14450
14451 static void
14452 my_getExpression (expressionS *ep, char *str)
14453 {
14454   char *save_in;
14455
14456   save_in = input_line_pointer;
14457   input_line_pointer = str;
14458   expression (ep);
14459   expr_end = input_line_pointer;
14460   input_line_pointer = save_in;
14461 }
14462
14463 const char *
14464 md_atof (int type, char *litP, int *sizeP)
14465 {
14466   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14467 }
14468
14469 void
14470 md_number_to_chars (char *buf, valueT val, int n)
14471 {
14472   if (target_big_endian)
14473     number_to_chars_bigendian (buf, val, n);
14474   else
14475     number_to_chars_littleendian (buf, val, n);
14476 }
14477 \f
14478 static int support_64bit_objects(void)
14479 {
14480   const char **list, **l;
14481   int yes;
14482
14483   list = bfd_target_list ();
14484   for (l = list; *l != NULL; l++)
14485     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14486         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14487       break;
14488   yes = (*l != NULL);
14489   free (list);
14490   return yes;
14491 }
14492
14493 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14494    NEW_VALUE.  Warn if another value was already specified.  Note:
14495    we have to defer parsing the -march and -mtune arguments in order
14496    to handle 'from-abi' correctly, since the ABI might be specified
14497    in a later argument.  */
14498
14499 static void
14500 mips_set_option_string (const char **string_ptr, const char *new_value)
14501 {
14502   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14503     as_warn (_("a different %s was already specified, is now %s"),
14504              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14505              new_value);
14506
14507   *string_ptr = new_value;
14508 }
14509
14510 int
14511 md_parse_option (int c, const char *arg)
14512 {
14513   unsigned int i;
14514
14515   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14516     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14517       {
14518         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14519                                            c == mips_ases[i].option_on);
14520         return 1;
14521       }
14522
14523   switch (c)
14524     {
14525     case OPTION_CONSTRUCT_FLOATS:
14526       mips_disable_float_construction = 0;
14527       break;
14528
14529     case OPTION_NO_CONSTRUCT_FLOATS:
14530       mips_disable_float_construction = 1;
14531       break;
14532
14533     case OPTION_TRAP:
14534       mips_trap = 1;
14535       break;
14536
14537     case OPTION_BREAK:
14538       mips_trap = 0;
14539       break;
14540
14541     case OPTION_EB:
14542       target_big_endian = 1;
14543       break;
14544
14545     case OPTION_EL:
14546       target_big_endian = 0;
14547       break;
14548
14549     case 'O':
14550       if (arg == NULL)
14551         mips_optimize = 1;
14552       else if (arg[0] == '0')
14553         mips_optimize = 0;
14554       else if (arg[0] == '1')
14555         mips_optimize = 1;
14556       else
14557         mips_optimize = 2;
14558       break;
14559
14560     case 'g':
14561       if (arg == NULL)
14562         mips_debug = 2;
14563       else
14564         mips_debug = atoi (arg);
14565       break;
14566
14567     case OPTION_MIPS1:
14568       file_mips_opts.isa = ISA_MIPS1;
14569       break;
14570
14571     case OPTION_MIPS2:
14572       file_mips_opts.isa = ISA_MIPS2;
14573       break;
14574
14575     case OPTION_MIPS3:
14576       file_mips_opts.isa = ISA_MIPS3;
14577       break;
14578
14579     case OPTION_MIPS4:
14580       file_mips_opts.isa = ISA_MIPS4;
14581       break;
14582
14583     case OPTION_MIPS5:
14584       file_mips_opts.isa = ISA_MIPS5;
14585       break;
14586
14587     case OPTION_MIPS32:
14588       file_mips_opts.isa = ISA_MIPS32;
14589       break;
14590
14591     case OPTION_MIPS32R2:
14592       file_mips_opts.isa = ISA_MIPS32R2;
14593       break;
14594
14595     case OPTION_MIPS32R3:
14596       file_mips_opts.isa = ISA_MIPS32R3;
14597       break;
14598
14599     case OPTION_MIPS32R5:
14600       file_mips_opts.isa = ISA_MIPS32R5;
14601       break;
14602
14603     case OPTION_MIPS32R6:
14604       file_mips_opts.isa = ISA_MIPS32R6;
14605       break;
14606
14607     case OPTION_MIPS64R2:
14608       file_mips_opts.isa = ISA_MIPS64R2;
14609       break;
14610
14611     case OPTION_MIPS64R3:
14612       file_mips_opts.isa = ISA_MIPS64R3;
14613       break;
14614
14615     case OPTION_MIPS64R5:
14616       file_mips_opts.isa = ISA_MIPS64R5;
14617       break;
14618
14619     case OPTION_MIPS64R6:
14620       file_mips_opts.isa = ISA_MIPS64R6;
14621       break;
14622
14623     case OPTION_MIPS64:
14624       file_mips_opts.isa = ISA_MIPS64;
14625       break;
14626
14627     case OPTION_MTUNE:
14628       mips_set_option_string (&mips_tune_string, arg);
14629       break;
14630
14631     case OPTION_MARCH:
14632       mips_set_option_string (&mips_arch_string, arg);
14633       break;
14634
14635     case OPTION_M4650:
14636       mips_set_option_string (&mips_arch_string, "4650");
14637       mips_set_option_string (&mips_tune_string, "4650");
14638       break;
14639
14640     case OPTION_NO_M4650:
14641       break;
14642
14643     case OPTION_M4010:
14644       mips_set_option_string (&mips_arch_string, "4010");
14645       mips_set_option_string (&mips_tune_string, "4010");
14646       break;
14647
14648     case OPTION_NO_M4010:
14649       break;
14650
14651     case OPTION_M4100:
14652       mips_set_option_string (&mips_arch_string, "4100");
14653       mips_set_option_string (&mips_tune_string, "4100");
14654       break;
14655
14656     case OPTION_NO_M4100:
14657       break;
14658
14659     case OPTION_M3900:
14660       mips_set_option_string (&mips_arch_string, "3900");
14661       mips_set_option_string (&mips_tune_string, "3900");
14662       break;
14663
14664     case OPTION_NO_M3900:
14665       break;
14666
14667     case OPTION_MICROMIPS:
14668       if (file_mips_opts.mips16 == 1)
14669         {
14670           as_bad (_("-mmicromips cannot be used with -mips16"));
14671           return 0;
14672         }
14673       file_mips_opts.micromips = 1;
14674       mips_no_prev_insn ();
14675       break;
14676
14677     case OPTION_NO_MICROMIPS:
14678       file_mips_opts.micromips = 0;
14679       mips_no_prev_insn ();
14680       break;
14681
14682     case OPTION_MIPS16:
14683       if (file_mips_opts.micromips == 1)
14684         {
14685           as_bad (_("-mips16 cannot be used with -micromips"));
14686           return 0;
14687         }
14688       file_mips_opts.mips16 = 1;
14689       mips_no_prev_insn ();
14690       break;
14691
14692     case OPTION_NO_MIPS16:
14693       file_mips_opts.mips16 = 0;
14694       mips_no_prev_insn ();
14695       break;
14696
14697     case OPTION_FIX_24K:
14698       mips_fix_24k = 1;
14699       break;
14700
14701     case OPTION_NO_FIX_24K:
14702       mips_fix_24k = 0;
14703       break;
14704
14705     case OPTION_FIX_RM7000:
14706       mips_fix_rm7000 = 1;
14707       break;
14708
14709     case OPTION_NO_FIX_RM7000:
14710       mips_fix_rm7000 = 0;
14711       break;
14712
14713     case OPTION_FIX_LOONGSON2F_JUMP:
14714       mips_fix_loongson2f_jump = TRUE;
14715       break;
14716
14717     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14718       mips_fix_loongson2f_jump = FALSE;
14719       break;
14720
14721     case OPTION_FIX_LOONGSON2F_NOP:
14722       mips_fix_loongson2f_nop = TRUE;
14723       break;
14724
14725     case OPTION_NO_FIX_LOONGSON2F_NOP:
14726       mips_fix_loongson2f_nop = FALSE;
14727       break;
14728
14729     case OPTION_FIX_VR4120:
14730       mips_fix_vr4120 = 1;
14731       break;
14732
14733     case OPTION_NO_FIX_VR4120:
14734       mips_fix_vr4120 = 0;
14735       break;
14736
14737     case OPTION_FIX_VR4130:
14738       mips_fix_vr4130 = 1;
14739       break;
14740
14741     case OPTION_NO_FIX_VR4130:
14742       mips_fix_vr4130 = 0;
14743       break;
14744
14745     case OPTION_FIX_CN63XXP1:
14746       mips_fix_cn63xxp1 = TRUE;
14747       break;
14748
14749     case OPTION_NO_FIX_CN63XXP1:
14750       mips_fix_cn63xxp1 = FALSE;
14751       break;
14752
14753     case OPTION_RELAX_BRANCH:
14754       mips_relax_branch = 1;
14755       break;
14756
14757     case OPTION_NO_RELAX_BRANCH:
14758       mips_relax_branch = 0;
14759       break;
14760
14761     case OPTION_IGNORE_BRANCH_ISA:
14762       mips_ignore_branch_isa = TRUE;
14763       break;
14764
14765     case OPTION_NO_IGNORE_BRANCH_ISA:
14766       mips_ignore_branch_isa = FALSE;
14767       break;
14768
14769     case OPTION_INSN32:
14770       file_mips_opts.insn32 = TRUE;
14771       break;
14772
14773     case OPTION_NO_INSN32:
14774       file_mips_opts.insn32 = FALSE;
14775       break;
14776
14777     case OPTION_MSHARED:
14778       mips_in_shared = TRUE;
14779       break;
14780
14781     case OPTION_MNO_SHARED:
14782       mips_in_shared = FALSE;
14783       break;
14784
14785     case OPTION_MSYM32:
14786       file_mips_opts.sym32 = TRUE;
14787       break;
14788
14789     case OPTION_MNO_SYM32:
14790       file_mips_opts.sym32 = FALSE;
14791       break;
14792
14793       /* When generating ELF code, we permit -KPIC and -call_shared to
14794          select SVR4_PIC, and -non_shared to select no PIC.  This is
14795          intended to be compatible with Irix 5.  */
14796     case OPTION_CALL_SHARED:
14797       mips_pic = SVR4_PIC;
14798       mips_abicalls = TRUE;
14799       break;
14800
14801     case OPTION_CALL_NONPIC:
14802       mips_pic = NO_PIC;
14803       mips_abicalls = TRUE;
14804       break;
14805
14806     case OPTION_NON_SHARED:
14807       mips_pic = NO_PIC;
14808       mips_abicalls = FALSE;
14809       break;
14810
14811       /* The -xgot option tells the assembler to use 32 bit offsets
14812          when accessing the got in SVR4_PIC mode.  It is for Irix
14813          compatibility.  */
14814     case OPTION_XGOT:
14815       mips_big_got = 1;
14816       break;
14817
14818     case 'G':
14819       g_switch_value = atoi (arg);
14820       g_switch_seen = 1;
14821       break;
14822
14823       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14824          and -mabi=64.  */
14825     case OPTION_32:
14826       mips_abi = O32_ABI;
14827       break;
14828
14829     case OPTION_N32:
14830       mips_abi = N32_ABI;
14831       break;
14832
14833     case OPTION_64:
14834       mips_abi = N64_ABI;
14835       if (!support_64bit_objects())
14836         as_fatal (_("no compiled in support for 64 bit object file format"));
14837       break;
14838
14839     case OPTION_GP32:
14840       file_mips_opts.gp = 32;
14841       break;
14842
14843     case OPTION_GP64:
14844       file_mips_opts.gp = 64;
14845       break;
14846
14847     case OPTION_FP32:
14848       file_mips_opts.fp = 32;
14849       break;
14850
14851     case OPTION_FPXX:
14852       file_mips_opts.fp = 0;
14853       break;
14854
14855     case OPTION_FP64:
14856       file_mips_opts.fp = 64;
14857       break;
14858
14859     case OPTION_ODD_SPREG:
14860       file_mips_opts.oddspreg = 1;
14861       break;
14862
14863     case OPTION_NO_ODD_SPREG:
14864       file_mips_opts.oddspreg = 0;
14865       break;
14866
14867     case OPTION_SINGLE_FLOAT:
14868       file_mips_opts.single_float = 1;
14869       break;
14870
14871     case OPTION_DOUBLE_FLOAT:
14872       file_mips_opts.single_float = 0;
14873       break;
14874
14875     case OPTION_SOFT_FLOAT:
14876       file_mips_opts.soft_float = 1;
14877       break;
14878
14879     case OPTION_HARD_FLOAT:
14880       file_mips_opts.soft_float = 0;
14881       break;
14882
14883     case OPTION_MABI:
14884       if (strcmp (arg, "32") == 0)
14885         mips_abi = O32_ABI;
14886       else if (strcmp (arg, "o64") == 0)
14887         mips_abi = O64_ABI;
14888       else if (strcmp (arg, "n32") == 0)
14889         mips_abi = N32_ABI;
14890       else if (strcmp (arg, "64") == 0)
14891         {
14892           mips_abi = N64_ABI;
14893           if (! support_64bit_objects())
14894             as_fatal (_("no compiled in support for 64 bit object file "
14895                         "format"));
14896         }
14897       else if (strcmp (arg, "eabi") == 0)
14898         mips_abi = EABI_ABI;
14899       else
14900         {
14901           as_fatal (_("invalid abi -mabi=%s"), arg);
14902           return 0;
14903         }
14904       break;
14905
14906     case OPTION_M7000_HILO_FIX:
14907       mips_7000_hilo_fix = TRUE;
14908       break;
14909
14910     case OPTION_MNO_7000_HILO_FIX:
14911       mips_7000_hilo_fix = FALSE;
14912       break;
14913
14914     case OPTION_MDEBUG:
14915       mips_flag_mdebug = TRUE;
14916       break;
14917
14918     case OPTION_NO_MDEBUG:
14919       mips_flag_mdebug = FALSE;
14920       break;
14921
14922     case OPTION_PDR:
14923       mips_flag_pdr = TRUE;
14924       break;
14925
14926     case OPTION_NO_PDR:
14927       mips_flag_pdr = FALSE;
14928       break;
14929
14930     case OPTION_MVXWORKS_PIC:
14931       mips_pic = VXWORKS_PIC;
14932       break;
14933
14934     case OPTION_NAN:
14935       if (strcmp (arg, "2008") == 0)
14936         mips_nan2008 = 1;
14937       else if (strcmp (arg, "legacy") == 0)
14938         mips_nan2008 = 0;
14939       else
14940         {
14941           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14942           return 0;
14943         }
14944       break;
14945
14946     default:
14947       return 0;
14948     }
14949
14950     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14951
14952   return 1;
14953 }
14954 \f
14955 /* Set up globals to tune for the ISA or processor described by INFO.  */
14956
14957 static void
14958 mips_set_tune (const struct mips_cpu_info *info)
14959 {
14960   if (info != 0)
14961     mips_tune = info->cpu;
14962 }
14963
14964
14965 void
14966 mips_after_parse_args (void)
14967 {
14968   const struct mips_cpu_info *arch_info = 0;
14969   const struct mips_cpu_info *tune_info = 0;
14970
14971   /* GP relative stuff not working for PE */
14972   if (strncmp (TARGET_OS, "pe", 2) == 0)
14973     {
14974       if (g_switch_seen && g_switch_value != 0)
14975         as_bad (_("-G not supported in this configuration"));
14976       g_switch_value = 0;
14977     }
14978
14979   if (mips_abi == NO_ABI)
14980     mips_abi = MIPS_DEFAULT_ABI;
14981
14982   /* The following code determines the architecture.
14983      Similar code was added to GCC 3.3 (see override_options() in
14984      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14985      as much as possible.  */
14986
14987   if (mips_arch_string != 0)
14988     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14989
14990   if (file_mips_opts.isa != ISA_UNKNOWN)
14991     {
14992       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14993          ISA level specified by -mipsN, while arch_info->isa contains
14994          the -march selection (if any).  */
14995       if (arch_info != 0)
14996         {
14997           /* -march takes precedence over -mipsN, since it is more descriptive.
14998              There's no harm in specifying both as long as the ISA levels
14999              are the same.  */
15000           if (file_mips_opts.isa != arch_info->isa)
15001             as_bad (_("-%s conflicts with the other architecture options,"
15002                       " which imply -%s"),
15003                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
15004                     mips_cpu_info_from_isa (arch_info->isa)->name);
15005         }
15006       else
15007         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
15008     }
15009
15010   if (arch_info == 0)
15011     {
15012       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15013       gas_assert (arch_info);
15014     }
15015
15016   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15017     as_bad (_("-march=%s is not compatible with the selected ABI"),
15018             arch_info->name);
15019
15020   file_mips_opts.arch = arch_info->cpu;
15021   file_mips_opts.isa = arch_info->isa;
15022
15023   /* Set up initial mips_opts state.  */
15024   mips_opts = file_mips_opts;
15025
15026   /* The register size inference code is now placed in
15027      file_mips_check_options.  */
15028
15029   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
15030      processor.  */
15031   if (mips_tune_string != 0)
15032     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15033
15034   if (tune_info == 0)
15035     mips_set_tune (arch_info);
15036   else
15037     mips_set_tune (tune_info);
15038
15039   if (mips_flag_mdebug < 0)
15040     mips_flag_mdebug = 0;
15041 }
15042 \f
15043 void
15044 mips_init_after_args (void)
15045 {
15046   /* initialize opcodes */
15047   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15048   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15049 }
15050
15051 long
15052 md_pcrel_from (fixS *fixP)
15053 {
15054   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15055   switch (fixP->fx_r_type)
15056     {
15057     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15058     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15059       /* Return the address of the delay slot.  */
15060       return addr + 2;
15061
15062     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15063     case BFD_RELOC_MICROMIPS_JMP:
15064     case BFD_RELOC_MIPS16_16_PCREL_S1:
15065     case BFD_RELOC_16_PCREL_S2:
15066     case BFD_RELOC_MIPS_21_PCREL_S2:
15067     case BFD_RELOC_MIPS_26_PCREL_S2:
15068     case BFD_RELOC_MIPS_JMP:
15069       /* Return the address of the delay slot.  */
15070       return addr + 4;
15071
15072     case BFD_RELOC_MIPS_18_PCREL_S3:
15073       /* Return the aligned address of the doubleword containing
15074          the instruction.  */
15075       return addr & ~7;
15076
15077     default:
15078       return addr;
15079     }
15080 }
15081
15082 /* This is called before the symbol table is processed.  In order to
15083    work with gcc when using mips-tfile, we must keep all local labels.
15084    However, in other cases, we want to discard them.  If we were
15085    called with -g, but we didn't see any debugging information, it may
15086    mean that gcc is smuggling debugging information through to
15087    mips-tfile, in which case we must generate all local labels.  */
15088
15089 void
15090 mips_frob_file_before_adjust (void)
15091 {
15092 #ifndef NO_ECOFF_DEBUGGING
15093   if (ECOFF_DEBUGGING
15094       && mips_debug != 0
15095       && ! ecoff_debugging_seen)
15096     flag_keep_locals = 1;
15097 #endif
15098 }
15099
15100 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15101    the corresponding LO16 reloc.  This is called before md_apply_fix and
15102    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15103    relocation operators.
15104
15105    For our purposes, a %lo() expression matches a %got() or %hi()
15106    expression if:
15107
15108       (a) it refers to the same symbol; and
15109       (b) the offset applied in the %lo() expression is no lower than
15110           the offset applied in the %got() or %hi().
15111
15112    (b) allows us to cope with code like:
15113
15114         lui     $4,%hi(foo)
15115         lh      $4,%lo(foo+2)($4)
15116
15117    ...which is legal on RELA targets, and has a well-defined behaviour
15118    if the user knows that adding 2 to "foo" will not induce a carry to
15119    the high 16 bits.
15120
15121    When several %lo()s match a particular %got() or %hi(), we use the
15122    following rules to distinguish them:
15123
15124      (1) %lo()s with smaller offsets are a better match than %lo()s with
15125          higher offsets.
15126
15127      (2) %lo()s with no matching %got() or %hi() are better than those
15128          that already have a matching %got() or %hi().
15129
15130      (3) later %lo()s are better than earlier %lo()s.
15131
15132    These rules are applied in order.
15133
15134    (1) means, among other things, that %lo()s with identical offsets are
15135    chosen if they exist.
15136
15137    (2) means that we won't associate several high-part relocations with
15138    the same low-part relocation unless there's no alternative.  Having
15139    several high parts for the same low part is a GNU extension; this rule
15140    allows careful users to avoid it.
15141
15142    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15143    with the last high-part relocation being at the front of the list.
15144    It therefore makes sense to choose the last matching low-part
15145    relocation, all other things being equal.  It's also easier
15146    to code that way.  */
15147
15148 void
15149 mips_frob_file (void)
15150 {
15151   struct mips_hi_fixup *l;
15152   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15153
15154   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15155     {
15156       segment_info_type *seginfo;
15157       bfd_boolean matched_lo_p;
15158       fixS **hi_pos, **lo_pos, **pos;
15159
15160       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15161
15162       /* If a GOT16 relocation turns out to be against a global symbol,
15163          there isn't supposed to be a matching LO.  Ignore %gots against
15164          constants; we'll report an error for those later.  */
15165       if (got16_reloc_p (l->fixp->fx_r_type)
15166           && !(l->fixp->fx_addsy
15167                && pic_need_relax (l->fixp->fx_addsy)))
15168         continue;
15169
15170       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15171       if (fixup_has_matching_lo_p (l->fixp))
15172         continue;
15173
15174       seginfo = seg_info (l->seg);
15175
15176       /* Set HI_POS to the position of this relocation in the chain.
15177          Set LO_POS to the position of the chosen low-part relocation.
15178          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15179          relocation that matches an immediately-preceding high-part
15180          relocation.  */
15181       hi_pos = NULL;
15182       lo_pos = NULL;
15183       matched_lo_p = FALSE;
15184       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15185
15186       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15187         {
15188           if (*pos == l->fixp)
15189             hi_pos = pos;
15190
15191           if ((*pos)->fx_r_type == looking_for_rtype
15192               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15193               && (*pos)->fx_offset >= l->fixp->fx_offset
15194               && (lo_pos == NULL
15195                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15196                   || (!matched_lo_p
15197                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15198             lo_pos = pos;
15199
15200           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15201                           && fixup_has_matching_lo_p (*pos));
15202         }
15203
15204       /* If we found a match, remove the high-part relocation from its
15205          current position and insert it before the low-part relocation.
15206          Make the offsets match so that fixup_has_matching_lo_p()
15207          will return true.
15208
15209          We don't warn about unmatched high-part relocations since some
15210          versions of gcc have been known to emit dead "lui ...%hi(...)"
15211          instructions.  */
15212       if (lo_pos != NULL)
15213         {
15214           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15215           if (l->fixp->fx_next != *lo_pos)
15216             {
15217               *hi_pos = l->fixp->fx_next;
15218               l->fixp->fx_next = *lo_pos;
15219               *lo_pos = l->fixp;
15220             }
15221         }
15222     }
15223 }
15224
15225 int
15226 mips_force_relocation (fixS *fixp)
15227 {
15228   if (generic_force_reloc (fixp))
15229     return 1;
15230
15231   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15232      so that the linker relaxation can update targets.  */
15233   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15234       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15235       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15236     return 1;
15237
15238   /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15239      and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15240      microMIPS symbols so that we can do cross-mode branch diagnostics
15241      and BAL to JALX conversion by the linker.  */
15242   if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15243        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15244        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15245       && fixp->fx_addsy
15246       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15247     return 1;
15248
15249   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15250   if (ISA_IS_R6 (file_mips_opts.isa)
15251       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15252           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15253           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15254           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15255           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15256           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15257           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15258     return 1;
15259
15260   return 0;
15261 }
15262
15263 /* Implement TC_FORCE_RELOCATION_ABS.  */
15264
15265 bfd_boolean
15266 mips_force_relocation_abs (fixS *fixp)
15267 {
15268   if (generic_force_reloc (fixp))
15269     return TRUE;
15270
15271   /* These relocations do not have enough bits in the in-place addend
15272      to hold an arbitrary absolute section's offset.  */
15273   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15274     return TRUE;
15275
15276   return FALSE;
15277 }
15278
15279 /* Read the instruction associated with RELOC from BUF.  */
15280
15281 static unsigned int
15282 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15283 {
15284   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15285     return read_compressed_insn (buf, 4);
15286   else
15287     return read_insn (buf);
15288 }
15289
15290 /* Write instruction INSN to BUF, given that it has been relocated
15291    by RELOC.  */
15292
15293 static void
15294 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15295                   unsigned long insn)
15296 {
15297   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15298     write_compressed_insn (buf, insn, 4);
15299   else
15300     write_insn (buf, insn);
15301 }
15302
15303 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15304    to a symbol in another ISA mode, which cannot be converted to JALX.  */
15305
15306 static bfd_boolean
15307 fix_bad_cross_mode_jump_p (fixS *fixP)
15308 {
15309   unsigned long opcode;
15310   int other;
15311   char *buf;
15312
15313   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15314     return FALSE;
15315
15316   other = S_GET_OTHER (fixP->fx_addsy);
15317   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15318   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15319   switch (fixP->fx_r_type)
15320     {
15321     case BFD_RELOC_MIPS_JMP:
15322       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15323     case BFD_RELOC_MICROMIPS_JMP:
15324       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15325     default:
15326       return FALSE;
15327     }
15328 }
15329
15330 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15331    jump to a symbol in the same ISA mode.  */
15332
15333 static bfd_boolean
15334 fix_bad_same_mode_jalx_p (fixS *fixP)
15335 {
15336   unsigned long opcode;
15337   int other;
15338   char *buf;
15339
15340   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15341     return FALSE;
15342
15343   other = S_GET_OTHER (fixP->fx_addsy);
15344   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15345   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15346   switch (fixP->fx_r_type)
15347     {
15348     case BFD_RELOC_MIPS_JMP:
15349       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15350     case BFD_RELOC_MIPS16_JMP:
15351       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15352     case BFD_RELOC_MICROMIPS_JMP:
15353       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15354     default:
15355       return FALSE;
15356     }
15357 }
15358
15359 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15360    to a symbol whose value plus addend is not aligned according to the
15361    ultimate (after linker relaxation) jump instruction's immediate field
15362    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15363    regular MIPS code, to (1 << 2).  */
15364
15365 static bfd_boolean
15366 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15367 {
15368   bfd_boolean micro_to_mips_p;
15369   valueT val;
15370   int other;
15371
15372   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15373     return FALSE;
15374
15375   other = S_GET_OTHER (fixP->fx_addsy);
15376   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15377   val += fixP->fx_offset;
15378   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15379                      && !ELF_ST_IS_MICROMIPS (other));
15380   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15381           != ELF_ST_IS_COMPRESSED (other));
15382 }
15383
15384 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15385    to a symbol whose annotation indicates another ISA mode.  For absolute
15386    symbols check the ISA bit instead.
15387
15388    We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15389    symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15390    MIPS symbols and associated with BAL instructions as these instructions
15391    may be converted to JALX by the linker.  */
15392
15393 static bfd_boolean
15394 fix_bad_cross_mode_branch_p (fixS *fixP)
15395 {
15396   bfd_boolean absolute_p;
15397   unsigned long opcode;
15398   asection *symsec;
15399   valueT val;
15400   int other;
15401   char *buf;
15402
15403   if (mips_ignore_branch_isa)
15404     return FALSE;
15405
15406   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15407     return FALSE;
15408
15409   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15410   absolute_p = bfd_is_abs_section (symsec);
15411
15412   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15413   other = S_GET_OTHER (fixP->fx_addsy);
15414
15415   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15416   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15417   switch (fixP->fx_r_type)
15418     {
15419     case BFD_RELOC_16_PCREL_S2:
15420       return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15421               && opcode != 0x0411);
15422     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15423       return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15424               && opcode != 0x4060);
15425     case BFD_RELOC_MIPS_21_PCREL_S2:
15426     case BFD_RELOC_MIPS_26_PCREL_S2:
15427       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15428     case BFD_RELOC_MIPS16_16_PCREL_S1:
15429       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15430     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15431     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15432       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15433     default:
15434       abort ();
15435     }
15436 }
15437
15438 /* Return TRUE if the symbol plus addend associated with a regular MIPS
15439    branch instruction pointed to by FIXP is not aligned according to the
15440    branch instruction's immediate field requirement.  We need the addend
15441    to preserve the ISA bit and also the sum must not have bit 2 set.  We
15442    must explicitly OR in the ISA bit from symbol annotation as the bit
15443    won't be set in the symbol's value then.  */
15444
15445 static bfd_boolean
15446 fix_bad_misaligned_branch_p (fixS *fixP)
15447 {
15448   bfd_boolean absolute_p;
15449   asection *symsec;
15450   valueT isa_bit;
15451   valueT val;
15452   valueT off;
15453   int other;
15454
15455   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15456     return FALSE;
15457
15458   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15459   absolute_p = bfd_is_abs_section (symsec);
15460
15461   val = S_GET_VALUE (fixP->fx_addsy);
15462   other = S_GET_OTHER (fixP->fx_addsy);
15463   off = fixP->fx_offset;
15464
15465   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15466   val |= ELF_ST_IS_COMPRESSED (other);
15467   val += off;
15468   return (val & 0x3) != isa_bit;
15469 }
15470
15471 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15472    and its calculated value VAL.  */
15473
15474 static void
15475 fix_validate_branch (fixS *fixP, valueT val)
15476 {
15477   if (fixP->fx_done && (val & 0x3) != 0)
15478     as_bad_where (fixP->fx_file, fixP->fx_line,
15479                   _("branch to misaligned address (0x%lx)"),
15480                   (long) (val + md_pcrel_from (fixP)));
15481   else if (fix_bad_cross_mode_branch_p (fixP))
15482     as_bad_where (fixP->fx_file, fixP->fx_line,
15483                   _("branch to a symbol in another ISA mode"));
15484   else if (fix_bad_misaligned_branch_p (fixP))
15485     as_bad_where (fixP->fx_file, fixP->fx_line,
15486                   _("branch to misaligned address (0x%lx)"),
15487                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15488   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15489     as_bad_where (fixP->fx_file, fixP->fx_line,
15490                   _("cannot encode misaligned addend "
15491                     "in the relocatable field (0x%lx)"),
15492                   (long) fixP->fx_offset);
15493 }
15494
15495 /* Apply a fixup to the object file.  */
15496
15497 void
15498 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15499 {
15500   char *buf;
15501   unsigned long insn;
15502   reloc_howto_type *howto;
15503
15504   if (fixP->fx_pcrel)
15505     switch (fixP->fx_r_type)
15506       {
15507       case BFD_RELOC_16_PCREL_S2:
15508       case BFD_RELOC_MIPS16_16_PCREL_S1:
15509       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15510       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15511       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15512       case BFD_RELOC_32_PCREL:
15513       case BFD_RELOC_MIPS_21_PCREL_S2:
15514       case BFD_RELOC_MIPS_26_PCREL_S2:
15515       case BFD_RELOC_MIPS_18_PCREL_S3:
15516       case BFD_RELOC_MIPS_19_PCREL_S2:
15517       case BFD_RELOC_HI16_S_PCREL:
15518       case BFD_RELOC_LO16_PCREL:
15519         break;
15520
15521       case BFD_RELOC_32:
15522         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15523         break;
15524
15525       default:
15526         as_bad_where (fixP->fx_file, fixP->fx_line,
15527                       _("PC-relative reference to a different section"));
15528         break;
15529       }
15530
15531   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15532      that have no MIPS ELF equivalent.  */
15533   if (fixP->fx_r_type != BFD_RELOC_8)
15534     {
15535       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15536       if (!howto)
15537         return;
15538     }
15539
15540   gas_assert (fixP->fx_size == 2
15541               || fixP->fx_size == 4
15542               || fixP->fx_r_type == BFD_RELOC_8
15543               || fixP->fx_r_type == BFD_RELOC_16
15544               || fixP->fx_r_type == BFD_RELOC_64
15545               || fixP->fx_r_type == BFD_RELOC_CTOR
15546               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15547               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15548               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15549               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15550               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15551               || fixP->fx_r_type == BFD_RELOC_NONE);
15552
15553   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15554
15555   /* Don't treat parts of a composite relocation as done.  There are two
15556      reasons for this:
15557
15558      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15559          should nevertheless be emitted if the first part is.
15560
15561      (2) In normal usage, composite relocations are never assembly-time
15562          constants.  The easiest way of dealing with the pathological
15563          exceptions is to generate a relocation against STN_UNDEF and
15564          leave everything up to the linker.  */
15565   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15566     fixP->fx_done = 1;
15567
15568   switch (fixP->fx_r_type)
15569     {
15570     case BFD_RELOC_MIPS_TLS_GD:
15571     case BFD_RELOC_MIPS_TLS_LDM:
15572     case BFD_RELOC_MIPS_TLS_DTPREL32:
15573     case BFD_RELOC_MIPS_TLS_DTPREL64:
15574     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15575     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15576     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15577     case BFD_RELOC_MIPS_TLS_TPREL32:
15578     case BFD_RELOC_MIPS_TLS_TPREL64:
15579     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15580     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15581     case BFD_RELOC_MICROMIPS_TLS_GD:
15582     case BFD_RELOC_MICROMIPS_TLS_LDM:
15583     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15584     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15585     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15586     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15587     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15588     case BFD_RELOC_MIPS16_TLS_GD:
15589     case BFD_RELOC_MIPS16_TLS_LDM:
15590     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15591     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15592     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15593     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15594     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15595       if (fixP->fx_addsy)
15596         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15597       else
15598         as_bad_where (fixP->fx_file, fixP->fx_line,
15599                       _("TLS relocation against a constant"));
15600       break;
15601
15602     case BFD_RELOC_MIPS_JMP:
15603     case BFD_RELOC_MIPS16_JMP:
15604     case BFD_RELOC_MICROMIPS_JMP:
15605       {
15606         int shift;
15607
15608         gas_assert (!fixP->fx_done);
15609
15610         /* Shift is 2, unusually, for microMIPS JALX.  */
15611         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15612             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15613           shift = 1;
15614         else
15615           shift = 2;
15616
15617         if (fix_bad_cross_mode_jump_p (fixP))
15618           as_bad_where (fixP->fx_file, fixP->fx_line,
15619                         _("jump to a symbol in another ISA mode"));
15620         else if (fix_bad_same_mode_jalx_p (fixP))
15621           as_bad_where (fixP->fx_file, fixP->fx_line,
15622                         _("JALX to a symbol in the same ISA mode"));
15623         else if (fix_bad_misaligned_jump_p (fixP, shift))
15624           as_bad_where (fixP->fx_file, fixP->fx_line,
15625                         _("jump to misaligned address (0x%lx)"),
15626                         (long) (S_GET_VALUE (fixP->fx_addsy)
15627                                 + fixP->fx_offset));
15628         else if (HAVE_IN_PLACE_ADDENDS
15629                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15630           as_bad_where (fixP->fx_file, fixP->fx_line,
15631                         _("cannot encode misaligned addend "
15632                           "in the relocatable field (0x%lx)"),
15633                         (long) fixP->fx_offset);
15634       }
15635       /* Fall through.  */
15636
15637     case BFD_RELOC_MIPS_SHIFT5:
15638     case BFD_RELOC_MIPS_SHIFT6:
15639     case BFD_RELOC_MIPS_GOT_DISP:
15640     case BFD_RELOC_MIPS_GOT_PAGE:
15641     case BFD_RELOC_MIPS_GOT_OFST:
15642     case BFD_RELOC_MIPS_SUB:
15643     case BFD_RELOC_MIPS_INSERT_A:
15644     case BFD_RELOC_MIPS_INSERT_B:
15645     case BFD_RELOC_MIPS_DELETE:
15646     case BFD_RELOC_MIPS_HIGHEST:
15647     case BFD_RELOC_MIPS_HIGHER:
15648     case BFD_RELOC_MIPS_SCN_DISP:
15649     case BFD_RELOC_MIPS_REL16:
15650     case BFD_RELOC_MIPS_RELGOT:
15651     case BFD_RELOC_MIPS_JALR:
15652     case BFD_RELOC_HI16:
15653     case BFD_RELOC_HI16_S:
15654     case BFD_RELOC_LO16:
15655     case BFD_RELOC_GPREL16:
15656     case BFD_RELOC_MIPS_LITERAL:
15657     case BFD_RELOC_MIPS_CALL16:
15658     case BFD_RELOC_MIPS_GOT16:
15659     case BFD_RELOC_GPREL32:
15660     case BFD_RELOC_MIPS_GOT_HI16:
15661     case BFD_RELOC_MIPS_GOT_LO16:
15662     case BFD_RELOC_MIPS_CALL_HI16:
15663     case BFD_RELOC_MIPS_CALL_LO16:
15664     case BFD_RELOC_HI16_S_PCREL:
15665     case BFD_RELOC_LO16_PCREL:
15666     case BFD_RELOC_MIPS16_GPREL:
15667     case BFD_RELOC_MIPS16_GOT16:
15668     case BFD_RELOC_MIPS16_CALL16:
15669     case BFD_RELOC_MIPS16_HI16:
15670     case BFD_RELOC_MIPS16_HI16_S:
15671     case BFD_RELOC_MIPS16_LO16:
15672     case BFD_RELOC_MICROMIPS_GOT_DISP:
15673     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15674     case BFD_RELOC_MICROMIPS_GOT_OFST:
15675     case BFD_RELOC_MICROMIPS_SUB:
15676     case BFD_RELOC_MICROMIPS_HIGHEST:
15677     case BFD_RELOC_MICROMIPS_HIGHER:
15678     case BFD_RELOC_MICROMIPS_SCN_DISP:
15679     case BFD_RELOC_MICROMIPS_JALR:
15680     case BFD_RELOC_MICROMIPS_HI16:
15681     case BFD_RELOC_MICROMIPS_HI16_S:
15682     case BFD_RELOC_MICROMIPS_LO16:
15683     case BFD_RELOC_MICROMIPS_GPREL16:
15684     case BFD_RELOC_MICROMIPS_LITERAL:
15685     case BFD_RELOC_MICROMIPS_CALL16:
15686     case BFD_RELOC_MICROMIPS_GOT16:
15687     case BFD_RELOC_MICROMIPS_GOT_HI16:
15688     case BFD_RELOC_MICROMIPS_GOT_LO16:
15689     case BFD_RELOC_MICROMIPS_CALL_HI16:
15690     case BFD_RELOC_MICROMIPS_CALL_LO16:
15691     case BFD_RELOC_MIPS_EH:
15692       if (fixP->fx_done)
15693         {
15694           offsetT value;
15695
15696           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15697             {
15698               insn = read_reloc_insn (buf, fixP->fx_r_type);
15699               if (mips16_reloc_p (fixP->fx_r_type))
15700                 insn |= mips16_immed_extend (value, 16);
15701               else
15702                 insn |= (value & 0xffff);
15703               write_reloc_insn (buf, fixP->fx_r_type, insn);
15704             }
15705           else
15706             as_bad_where (fixP->fx_file, fixP->fx_line,
15707                           _("unsupported constant in relocation"));
15708         }
15709       break;
15710
15711     case BFD_RELOC_64:
15712       /* This is handled like BFD_RELOC_32, but we output a sign
15713          extended value if we are only 32 bits.  */
15714       if (fixP->fx_done)
15715         {
15716           if (8 <= sizeof (valueT))
15717             md_number_to_chars (buf, *valP, 8);
15718           else
15719             {
15720               valueT hiv;
15721
15722               if ((*valP & 0x80000000) != 0)
15723                 hiv = 0xffffffff;
15724               else
15725                 hiv = 0;
15726               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15727               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15728             }
15729         }
15730       break;
15731
15732     case BFD_RELOC_RVA:
15733     case BFD_RELOC_32:
15734     case BFD_RELOC_32_PCREL:
15735     case BFD_RELOC_16:
15736     case BFD_RELOC_8:
15737       /* If we are deleting this reloc entry, we must fill in the
15738          value now.  This can happen if we have a .word which is not
15739          resolved when it appears but is later defined.  */
15740       if (fixP->fx_done)
15741         md_number_to_chars (buf, *valP, fixP->fx_size);
15742       break;
15743
15744     case BFD_RELOC_MIPS_21_PCREL_S2:
15745       fix_validate_branch (fixP, *valP);
15746       if (!fixP->fx_done)
15747         break;
15748
15749       if (*valP + 0x400000 <= 0x7fffff)
15750         {
15751           insn = read_insn (buf);
15752           insn |= (*valP >> 2) & 0x1fffff;
15753           write_insn (buf, insn);
15754         }
15755       else
15756         as_bad_where (fixP->fx_file, fixP->fx_line,
15757                       _("branch out of range"));
15758       break;
15759
15760     case BFD_RELOC_MIPS_26_PCREL_S2:
15761       fix_validate_branch (fixP, *valP);
15762       if (!fixP->fx_done)
15763         break;
15764
15765       if (*valP + 0x8000000 <= 0xfffffff)
15766         {
15767           insn = read_insn (buf);
15768           insn |= (*valP >> 2) & 0x3ffffff;
15769           write_insn (buf, insn);
15770         }
15771       else
15772         as_bad_where (fixP->fx_file, fixP->fx_line,
15773                       _("branch out of range"));
15774       break;
15775
15776     case BFD_RELOC_MIPS_18_PCREL_S3:
15777       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15778         as_bad_where (fixP->fx_file, fixP->fx_line,
15779                       _("PC-relative access using misaligned symbol (%lx)"),
15780                       (long) S_GET_VALUE (fixP->fx_addsy));
15781       if ((fixP->fx_offset & 0x7) != 0)
15782         as_bad_where (fixP->fx_file, fixP->fx_line,
15783                       _("PC-relative access using misaligned offset (%lx)"),
15784                       (long) fixP->fx_offset);
15785       if (!fixP->fx_done)
15786         break;
15787
15788       if (*valP + 0x100000 <= 0x1fffff)
15789         {
15790           insn = read_insn (buf);
15791           insn |= (*valP >> 3) & 0x3ffff;
15792           write_insn (buf, insn);
15793         }
15794       else
15795         as_bad_where (fixP->fx_file, fixP->fx_line,
15796                       _("PC-relative access out of range"));
15797       break;
15798
15799     case BFD_RELOC_MIPS_19_PCREL_S2:
15800       if ((*valP & 0x3) != 0)
15801         as_bad_where (fixP->fx_file, fixP->fx_line,
15802                       _("PC-relative access to misaligned address (%lx)"),
15803                       (long) *valP);
15804       if (!fixP->fx_done)
15805         break;
15806
15807       if (*valP + 0x100000 <= 0x1fffff)
15808         {
15809           insn = read_insn (buf);
15810           insn |= (*valP >> 2) & 0x7ffff;
15811           write_insn (buf, insn);
15812         }
15813       else
15814         as_bad_where (fixP->fx_file, fixP->fx_line,
15815                       _("PC-relative access out of range"));
15816       break;
15817
15818     case BFD_RELOC_16_PCREL_S2:
15819       fix_validate_branch (fixP, *valP);
15820
15821       /* We need to save the bits in the instruction since fixup_segment()
15822          might be deleting the relocation entry (i.e., a branch within
15823          the current segment).  */
15824       if (! fixP->fx_done)
15825         break;
15826
15827       /* Update old instruction data.  */
15828       insn = read_insn (buf);
15829
15830       if (*valP + 0x20000 <= 0x3ffff)
15831         {
15832           insn |= (*valP >> 2) & 0xffff;
15833           write_insn (buf, insn);
15834         }
15835       else if (fixP->fx_tcbit2
15836                && fixP->fx_done
15837                && fixP->fx_frag->fr_address >= text_section->vma
15838                && (fixP->fx_frag->fr_address
15839                    < text_section->vma + bfd_get_section_size (text_section))
15840                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15841                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15842                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15843         {
15844           /* The branch offset is too large.  If this is an
15845              unconditional branch, and we are not generating PIC code,
15846              we can convert it to an absolute jump instruction.  */
15847           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15848             insn = 0x0c000000;  /* jal */
15849           else
15850             insn = 0x08000000;  /* j */
15851           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15852           fixP->fx_done = 0;
15853           fixP->fx_addsy = section_symbol (text_section);
15854           *valP += md_pcrel_from (fixP);
15855           write_insn (buf, insn);
15856         }
15857       else
15858         {
15859           /* If we got here, we have branch-relaxation disabled,
15860              and there's nothing we can do to fix this instruction
15861              without turning it into a longer sequence.  */
15862           as_bad_where (fixP->fx_file, fixP->fx_line,
15863                         _("branch out of range"));
15864         }
15865       break;
15866
15867     case BFD_RELOC_MIPS16_16_PCREL_S1:
15868     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15869     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15870     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15871       gas_assert (!fixP->fx_done);
15872       if (fix_bad_cross_mode_branch_p (fixP))
15873         as_bad_where (fixP->fx_file, fixP->fx_line,
15874                       _("branch to a symbol in another ISA mode"));
15875       else if (fixP->fx_addsy
15876                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15877                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15878                && (fixP->fx_offset & 0x1) != 0)
15879         as_bad_where (fixP->fx_file, fixP->fx_line,
15880                       _("branch to misaligned address (0x%lx)"),
15881                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15882       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15883         as_bad_where (fixP->fx_file, fixP->fx_line,
15884                       _("cannot encode misaligned addend "
15885                         "in the relocatable field (0x%lx)"),
15886                       (long) fixP->fx_offset);
15887       break;
15888
15889     case BFD_RELOC_VTABLE_INHERIT:
15890       fixP->fx_done = 0;
15891       if (fixP->fx_addsy
15892           && !S_IS_DEFINED (fixP->fx_addsy)
15893           && !S_IS_WEAK (fixP->fx_addsy))
15894         S_SET_WEAK (fixP->fx_addsy);
15895       break;
15896
15897     case BFD_RELOC_NONE:
15898     case BFD_RELOC_VTABLE_ENTRY:
15899       fixP->fx_done = 0;
15900       break;
15901
15902     default:
15903       abort ();
15904     }
15905
15906   /* Remember value for tc_gen_reloc.  */
15907   fixP->fx_addnumber = *valP;
15908 }
15909
15910 static symbolS *
15911 get_symbol (void)
15912 {
15913   int c;
15914   char *name;
15915   symbolS *p;
15916
15917   c = get_symbol_name (&name);
15918   p = (symbolS *) symbol_find_or_make (name);
15919   (void) restore_line_pointer (c);
15920   return p;
15921 }
15922
15923 /* Align the current frag to a given power of two.  If a particular
15924    fill byte should be used, FILL points to an integer that contains
15925    that byte, otherwise FILL is null.
15926
15927    This function used to have the comment:
15928
15929       The MIPS assembler also automatically adjusts any preceding label.
15930
15931    The implementation therefore applied the adjustment to a maximum of
15932    one label.  However, other label adjustments are applied to batches
15933    of labels, and adjusting just one caused problems when new labels
15934    were added for the sake of debugging or unwind information.
15935    We therefore adjust all preceding labels (given as LABELS) instead.  */
15936
15937 static void
15938 mips_align (int to, int *fill, struct insn_label_list *labels)
15939 {
15940   mips_emit_delays ();
15941   mips_record_compressed_mode ();
15942   if (fill == NULL && subseg_text_p (now_seg))
15943     frag_align_code (to, 0);
15944   else
15945     frag_align (to, fill ? *fill : 0, 0);
15946   record_alignment (now_seg, to);
15947   mips_move_labels (labels, FALSE);
15948 }
15949
15950 /* Align to a given power of two.  .align 0 turns off the automatic
15951    alignment used by the data creating pseudo-ops.  */
15952
15953 static void
15954 s_align (int x ATTRIBUTE_UNUSED)
15955 {
15956   int temp, fill_value, *fill_ptr;
15957   long max_alignment = 28;
15958
15959   /* o Note that the assembler pulls down any immediately preceding label
15960        to the aligned address.
15961      o It's not documented but auto alignment is reinstated by
15962        a .align pseudo instruction.
15963      o Note also that after auto alignment is turned off the mips assembler
15964        issues an error on attempt to assemble an improperly aligned data item.
15965        We don't.  */
15966
15967   temp = get_absolute_expression ();
15968   if (temp > max_alignment)
15969     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15970   else if (temp < 0)
15971     {
15972       as_warn (_("alignment negative, 0 assumed"));
15973       temp = 0;
15974     }
15975   if (*input_line_pointer == ',')
15976     {
15977       ++input_line_pointer;
15978       fill_value = get_absolute_expression ();
15979       fill_ptr = &fill_value;
15980     }
15981   else
15982     fill_ptr = 0;
15983   if (temp)
15984     {
15985       segment_info_type *si = seg_info (now_seg);
15986       struct insn_label_list *l = si->label_list;
15987       /* Auto alignment should be switched on by next section change.  */
15988       auto_align = 1;
15989       mips_align (temp, fill_ptr, l);
15990     }
15991   else
15992     {
15993       auto_align = 0;
15994     }
15995
15996   demand_empty_rest_of_line ();
15997 }
15998
15999 static void
16000 s_change_sec (int sec)
16001 {
16002   segT seg;
16003
16004   /* The ELF backend needs to know that we are changing sections, so
16005      that .previous works correctly.  We could do something like check
16006      for an obj_section_change_hook macro, but that might be confusing
16007      as it would not be appropriate to use it in the section changing
16008      functions in read.c, since obj-elf.c intercepts those.  FIXME:
16009      This should be cleaner, somehow.  */
16010   obj_elf_section_change_hook ();
16011
16012   mips_emit_delays ();
16013
16014   switch (sec)
16015     {
16016     case 't':
16017       s_text (0);
16018       break;
16019     case 'd':
16020       s_data (0);
16021       break;
16022     case 'b':
16023       subseg_set (bss_section, (subsegT) get_absolute_expression ());
16024       demand_empty_rest_of_line ();
16025       break;
16026
16027     case 'r':
16028       seg = subseg_new (RDATA_SECTION_NAME,
16029                         (subsegT) get_absolute_expression ());
16030       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
16031                                               | SEC_READONLY | SEC_RELOC
16032                                               | SEC_DATA));
16033       if (strncmp (TARGET_OS, "elf", 3) != 0)
16034         record_alignment (seg, 4);
16035       demand_empty_rest_of_line ();
16036       break;
16037
16038     case 's':
16039       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
16040       bfd_set_section_flags (stdoutput, seg,
16041                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
16042       if (strncmp (TARGET_OS, "elf", 3) != 0)
16043         record_alignment (seg, 4);
16044       demand_empty_rest_of_line ();
16045       break;
16046
16047     case 'B':
16048       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
16049       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
16050       if (strncmp (TARGET_OS, "elf", 3) != 0)
16051         record_alignment (seg, 4);
16052       demand_empty_rest_of_line ();
16053       break;
16054     }
16055
16056   auto_align = 1;
16057 }
16058
16059 void
16060 s_change_section (int ignore ATTRIBUTE_UNUSED)
16061 {
16062   char *saved_ilp;
16063   char *section_name;
16064   char c, endc;
16065   char next_c = 0;
16066   int section_type;
16067   int section_flag;
16068   int section_entry_size;
16069   int section_alignment;
16070
16071   saved_ilp = input_line_pointer;
16072   endc = get_symbol_name (&section_name);
16073   c = (endc == '"' ? input_line_pointer[1] : endc);
16074   if (c)
16075     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
16076
16077   /* Do we have .section Name<,"flags">?  */
16078   if (c != ',' || (c == ',' && next_c == '"'))
16079     {
16080       /* Just after name is now '\0'.  */
16081       (void) restore_line_pointer (endc);
16082       input_line_pointer = saved_ilp;
16083       obj_elf_section (ignore);
16084       return;
16085     }
16086
16087   section_name = xstrdup (section_name);
16088   c = restore_line_pointer (endc);
16089
16090   input_line_pointer++;
16091
16092   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16093   if (c == ',')
16094     section_type = get_absolute_expression ();
16095   else
16096     section_type = 0;
16097
16098   if (*input_line_pointer++ == ',')
16099     section_flag = get_absolute_expression ();
16100   else
16101     section_flag = 0;
16102
16103   if (*input_line_pointer++ == ',')
16104     section_entry_size = get_absolute_expression ();
16105   else
16106     section_entry_size = 0;
16107
16108   if (*input_line_pointer++ == ',')
16109     section_alignment = get_absolute_expression ();
16110   else
16111     section_alignment = 0;
16112
16113   /* FIXME: really ignore?  */
16114   (void) section_alignment;
16115
16116   /* When using the generic form of .section (as implemented by obj-elf.c),
16117      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16118      traditionally had to fall back on the more common @progbits instead.
16119
16120      There's nothing really harmful in this, since bfd will correct
16121      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16122      means that, for backwards compatibility, the special_section entries
16123      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16124
16125      Even so, we shouldn't force users of the MIPS .section syntax to
16126      incorrectly label the sections as SHT_PROGBITS.  The best compromise
16127      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16128      generic type-checking code.  */
16129   if (section_type == SHT_MIPS_DWARF)
16130     section_type = SHT_PROGBITS;
16131
16132   obj_elf_change_section (section_name, section_type, 0, section_flag,
16133                           section_entry_size, 0, 0, 0);
16134
16135   if (now_seg->name != section_name)
16136     free (section_name);
16137 }
16138
16139 void
16140 mips_enable_auto_align (void)
16141 {
16142   auto_align = 1;
16143 }
16144
16145 static void
16146 s_cons (int log_size)
16147 {
16148   segment_info_type *si = seg_info (now_seg);
16149   struct insn_label_list *l = si->label_list;
16150
16151   mips_emit_delays ();
16152   if (log_size > 0 && auto_align)
16153     mips_align (log_size, 0, l);
16154   cons (1 << log_size);
16155   mips_clear_insn_labels ();
16156 }
16157
16158 static void
16159 s_float_cons (int type)
16160 {
16161   segment_info_type *si = seg_info (now_seg);
16162   struct insn_label_list *l = si->label_list;
16163
16164   mips_emit_delays ();
16165
16166   if (auto_align)
16167     {
16168       if (type == 'd')
16169         mips_align (3, 0, l);
16170       else
16171         mips_align (2, 0, l);
16172     }
16173
16174   float_cons (type);
16175   mips_clear_insn_labels ();
16176 }
16177
16178 /* Handle .globl.  We need to override it because on Irix 5 you are
16179    permitted to say
16180        .globl foo .text
16181    where foo is an undefined symbol, to mean that foo should be
16182    considered to be the address of a function.  */
16183
16184 static void
16185 s_mips_globl (int x ATTRIBUTE_UNUSED)
16186 {
16187   char *name;
16188   int c;
16189   symbolS *symbolP;
16190   flagword flag;
16191
16192   do
16193     {
16194       c = get_symbol_name (&name);
16195       symbolP = symbol_find_or_make (name);
16196       S_SET_EXTERNAL (symbolP);
16197
16198       *input_line_pointer = c;
16199       SKIP_WHITESPACE_AFTER_NAME ();
16200
16201       /* On Irix 5, every global symbol that is not explicitly labelled as
16202          being a function is apparently labelled as being an object.  */
16203       flag = BSF_OBJECT;
16204
16205       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16206           && (*input_line_pointer != ','))
16207         {
16208           char *secname;
16209           asection *sec;
16210
16211           c = get_symbol_name (&secname);
16212           sec = bfd_get_section_by_name (stdoutput, secname);
16213           if (sec == NULL)
16214             as_bad (_("%s: no such section"), secname);
16215           (void) restore_line_pointer (c);
16216
16217           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16218             flag = BSF_FUNCTION;
16219         }
16220
16221       symbol_get_bfdsym (symbolP)->flags |= flag;
16222
16223       c = *input_line_pointer;
16224       if (c == ',')
16225         {
16226           input_line_pointer++;
16227           SKIP_WHITESPACE ();
16228           if (is_end_of_line[(unsigned char) *input_line_pointer])
16229             c = '\n';
16230         }
16231     }
16232   while (c == ',');
16233
16234   demand_empty_rest_of_line ();
16235 }
16236
16237 static void
16238 s_option (int x ATTRIBUTE_UNUSED)
16239 {
16240   char *opt;
16241   char c;
16242
16243   c = get_symbol_name (&opt);
16244
16245   if (*opt == 'O')
16246     {
16247       /* FIXME: What does this mean?  */
16248     }
16249   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
16250     {
16251       int i;
16252
16253       i = atoi (opt + 3);
16254       if (i != 0 && i != 2)
16255         as_bad (_(".option pic%d not supported"), i);
16256       else if (mips_pic == VXWORKS_PIC)
16257         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16258       else if (i == 0)
16259         mips_pic = NO_PIC;
16260       else if (i == 2)
16261         {
16262           mips_pic = SVR4_PIC;
16263           mips_abicalls = TRUE;
16264         }
16265
16266       if (mips_pic == SVR4_PIC)
16267         {
16268           if (g_switch_seen && g_switch_value != 0)
16269             as_warn (_("-G may not be used with SVR4 PIC code"));
16270           g_switch_value = 0;
16271           bfd_set_gp_size (stdoutput, 0);
16272         }
16273     }
16274   else
16275     as_warn (_("unrecognized option \"%s\""), opt);
16276
16277   (void) restore_line_pointer (c);
16278   demand_empty_rest_of_line ();
16279 }
16280
16281 /* This structure is used to hold a stack of .set values.  */
16282
16283 struct mips_option_stack
16284 {
16285   struct mips_option_stack *next;
16286   struct mips_set_options options;
16287 };
16288
16289 static struct mips_option_stack *mips_opts_stack;
16290
16291 /* Return status for .set/.module option handling.  */
16292
16293 enum code_option_type
16294 {
16295   /* Unrecognized option.  */
16296   OPTION_TYPE_BAD = -1,
16297
16298   /* Ordinary option.  */
16299   OPTION_TYPE_NORMAL,
16300
16301   /* ISA changing option.  */
16302   OPTION_TYPE_ISA
16303 };
16304
16305 /* Handle common .set/.module options.  Return status indicating option
16306    type.  */
16307
16308 static enum code_option_type
16309 parse_code_option (char * name)
16310 {
16311   bfd_boolean isa_set = FALSE;
16312   const struct mips_ase *ase;
16313
16314   if (strncmp (name, "at=", 3) == 0)
16315     {
16316       char *s = name + 3;
16317
16318       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16319         as_bad (_("unrecognized register name `%s'"), s);
16320     }
16321   else if (strcmp (name, "at") == 0)
16322     mips_opts.at = ATREG;
16323   else if (strcmp (name, "noat") == 0)
16324     mips_opts.at = ZERO;
16325   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16326     mips_opts.nomove = 0;
16327   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16328     mips_opts.nomove = 1;
16329   else if (strcmp (name, "bopt") == 0)
16330     mips_opts.nobopt = 0;
16331   else if (strcmp (name, "nobopt") == 0)
16332     mips_opts.nobopt = 1;
16333   else if (strcmp (name, "gp=32") == 0)
16334     mips_opts.gp = 32;
16335   else if (strcmp (name, "gp=64") == 0)
16336     mips_opts.gp = 64;
16337   else if (strcmp (name, "fp=32") == 0)
16338     mips_opts.fp = 32;
16339   else if (strcmp (name, "fp=xx") == 0)
16340     mips_opts.fp = 0;
16341   else if (strcmp (name, "fp=64") == 0)
16342     mips_opts.fp = 64;
16343   else if (strcmp (name, "softfloat") == 0)
16344     mips_opts.soft_float = 1;
16345   else if (strcmp (name, "hardfloat") == 0)
16346     mips_opts.soft_float = 0;
16347   else if (strcmp (name, "singlefloat") == 0)
16348     mips_opts.single_float = 1;
16349   else if (strcmp (name, "doublefloat") == 0)
16350     mips_opts.single_float = 0;
16351   else if (strcmp (name, "nooddspreg") == 0)
16352     mips_opts.oddspreg = 0;
16353   else if (strcmp (name, "oddspreg") == 0)
16354     mips_opts.oddspreg = 1;
16355   else if (strcmp (name, "mips16") == 0
16356            || strcmp (name, "MIPS-16") == 0)
16357     mips_opts.mips16 = 1;
16358   else if (strcmp (name, "nomips16") == 0
16359            || strcmp (name, "noMIPS-16") == 0)
16360     mips_opts.mips16 = 0;
16361   else if (strcmp (name, "micromips") == 0)
16362     mips_opts.micromips = 1;
16363   else if (strcmp (name, "nomicromips") == 0)
16364     mips_opts.micromips = 0;
16365   else if (name[0] == 'n'
16366            && name[1] == 'o'
16367            && (ase = mips_lookup_ase (name + 2)))
16368     mips_set_ase (ase, &mips_opts, FALSE);
16369   else if ((ase = mips_lookup_ase (name)))
16370     mips_set_ase (ase, &mips_opts, TRUE);
16371   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16372     {
16373       /* Permit the user to change the ISA and architecture on the fly.
16374          Needless to say, misuse can cause serious problems.  */
16375       if (strncmp (name, "arch=", 5) == 0)
16376         {
16377           const struct mips_cpu_info *p;
16378
16379           p = mips_parse_cpu ("internal use", name + 5);
16380           if (!p)
16381             as_bad (_("unknown architecture %s"), name + 5);
16382           else
16383             {
16384               mips_opts.arch = p->cpu;
16385               mips_opts.isa = p->isa;
16386               isa_set = TRUE;
16387             }
16388         }
16389       else if (strncmp (name, "mips", 4) == 0)
16390         {
16391           const struct mips_cpu_info *p;
16392
16393           p = mips_parse_cpu ("internal use", name);
16394           if (!p)
16395             as_bad (_("unknown ISA level %s"), name + 4);
16396           else
16397             {
16398               mips_opts.arch = p->cpu;
16399               mips_opts.isa = p->isa;
16400               isa_set = TRUE;
16401             }
16402         }
16403       else
16404         as_bad (_("unknown ISA or architecture %s"), name);
16405     }
16406   else if (strcmp (name, "autoextend") == 0)
16407     mips_opts.noautoextend = 0;
16408   else if (strcmp (name, "noautoextend") == 0)
16409     mips_opts.noautoextend = 1;
16410   else if (strcmp (name, "insn32") == 0)
16411     mips_opts.insn32 = TRUE;
16412   else if (strcmp (name, "noinsn32") == 0)
16413     mips_opts.insn32 = FALSE;
16414   else if (strcmp (name, "sym32") == 0)
16415     mips_opts.sym32 = TRUE;
16416   else if (strcmp (name, "nosym32") == 0)
16417     mips_opts.sym32 = FALSE;
16418   else
16419     return OPTION_TYPE_BAD;
16420
16421   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16422 }
16423
16424 /* Handle the .set pseudo-op.  */
16425
16426 static void
16427 s_mipsset (int x ATTRIBUTE_UNUSED)
16428 {
16429   enum code_option_type type = OPTION_TYPE_NORMAL;
16430   char *name = input_line_pointer, ch;
16431
16432   file_mips_check_options ();
16433
16434   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16435     ++input_line_pointer;
16436   ch = *input_line_pointer;
16437   *input_line_pointer = '\0';
16438
16439   if (strchr (name, ','))
16440     {
16441       /* Generic ".set" directive; use the generic handler.  */
16442       *input_line_pointer = ch;
16443       input_line_pointer = name;
16444       s_set (0);
16445       return;
16446     }
16447
16448   if (strcmp (name, "reorder") == 0)
16449     {
16450       if (mips_opts.noreorder)
16451         end_noreorder ();
16452     }
16453   else if (strcmp (name, "noreorder") == 0)
16454     {
16455       if (!mips_opts.noreorder)
16456         start_noreorder ();
16457     }
16458   else if (strcmp (name, "macro") == 0)
16459     mips_opts.warn_about_macros = 0;
16460   else if (strcmp (name, "nomacro") == 0)
16461     {
16462       if (mips_opts.noreorder == 0)
16463         as_bad (_("`noreorder' must be set before `nomacro'"));
16464       mips_opts.warn_about_macros = 1;
16465     }
16466   else if (strcmp (name, "gp=default") == 0)
16467     mips_opts.gp = file_mips_opts.gp;
16468   else if (strcmp (name, "fp=default") == 0)
16469     mips_opts.fp = file_mips_opts.fp;
16470   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16471     {
16472       mips_opts.isa = file_mips_opts.isa;
16473       mips_opts.arch = file_mips_opts.arch;
16474       mips_opts.gp = file_mips_opts.gp;
16475       mips_opts.fp = file_mips_opts.fp;
16476     }
16477   else if (strcmp (name, "push") == 0)
16478     {
16479       struct mips_option_stack *s;
16480
16481       s = XNEW (struct mips_option_stack);
16482       s->next = mips_opts_stack;
16483       s->options = mips_opts;
16484       mips_opts_stack = s;
16485     }
16486   else if (strcmp (name, "pop") == 0)
16487     {
16488       struct mips_option_stack *s;
16489
16490       s = mips_opts_stack;
16491       if (s == NULL)
16492         as_bad (_(".set pop with no .set push"));
16493       else
16494         {
16495           /* If we're changing the reorder mode we need to handle
16496              delay slots correctly.  */
16497           if (s->options.noreorder && ! mips_opts.noreorder)
16498             start_noreorder ();
16499           else if (! s->options.noreorder && mips_opts.noreorder)
16500             end_noreorder ();
16501
16502           mips_opts = s->options;
16503           mips_opts_stack = s->next;
16504           free (s);
16505         }
16506     }
16507   else
16508     {
16509       type = parse_code_option (name);
16510       if (type == OPTION_TYPE_BAD)
16511         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16512     }
16513
16514   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16515      registers based on what is supported by the arch/cpu.  */
16516   if (type == OPTION_TYPE_ISA)
16517     {
16518       switch (mips_opts.isa)
16519         {
16520         case 0:
16521           break;
16522         case ISA_MIPS1:
16523           /* MIPS I cannot support FPXX.  */
16524           mips_opts.fp = 32;
16525           /* fall-through.  */
16526         case ISA_MIPS2:
16527         case ISA_MIPS32:
16528         case ISA_MIPS32R2:
16529         case ISA_MIPS32R3:
16530         case ISA_MIPS32R5:
16531           mips_opts.gp = 32;
16532           if (mips_opts.fp != 0)
16533             mips_opts.fp = 32;
16534           break;
16535         case ISA_MIPS32R6:
16536           mips_opts.gp = 32;
16537           mips_opts.fp = 64;
16538           break;
16539         case ISA_MIPS3:
16540         case ISA_MIPS4:
16541         case ISA_MIPS5:
16542         case ISA_MIPS64:
16543         case ISA_MIPS64R2:
16544         case ISA_MIPS64R3:
16545         case ISA_MIPS64R5:
16546         case ISA_MIPS64R6:
16547           mips_opts.gp = 64;
16548           if (mips_opts.fp != 0)
16549             {
16550               if (mips_opts.arch == CPU_R5900)
16551                 mips_opts.fp = 32;
16552               else
16553                 mips_opts.fp = 64;
16554             }
16555           break;
16556         default:
16557           as_bad (_("unknown ISA level %s"), name + 4);
16558           break;
16559         }
16560     }
16561
16562   mips_check_options (&mips_opts, FALSE);
16563
16564   mips_check_isa_supports_ases ();
16565   *input_line_pointer = ch;
16566   demand_empty_rest_of_line ();
16567 }
16568
16569 /* Handle the .module pseudo-op.  */
16570
16571 static void
16572 s_module (int ignore ATTRIBUTE_UNUSED)
16573 {
16574   char *name = input_line_pointer, ch;
16575
16576   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16577     ++input_line_pointer;
16578   ch = *input_line_pointer;
16579   *input_line_pointer = '\0';
16580
16581   if (!file_mips_opts_checked)
16582     {
16583       if (parse_code_option (name) == OPTION_TYPE_BAD)
16584         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16585
16586       /* Update module level settings from mips_opts.  */
16587       file_mips_opts = mips_opts;
16588     }
16589   else
16590     as_bad (_(".module is not permitted after generating code"));
16591
16592   *input_line_pointer = ch;
16593   demand_empty_rest_of_line ();
16594 }
16595
16596 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16597    .option pic2.  It means to generate SVR4 PIC calls.  */
16598
16599 static void
16600 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16601 {
16602   mips_pic = SVR4_PIC;
16603   mips_abicalls = TRUE;
16604
16605   if (g_switch_seen && g_switch_value != 0)
16606     as_warn (_("-G may not be used with SVR4 PIC code"));
16607   g_switch_value = 0;
16608
16609   bfd_set_gp_size (stdoutput, 0);
16610   demand_empty_rest_of_line ();
16611 }
16612
16613 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16614    PIC code.  It sets the $gp register for the function based on the
16615    function address, which is in the register named in the argument.
16616    This uses a relocation against _gp_disp, which is handled specially
16617    by the linker.  The result is:
16618         lui     $gp,%hi(_gp_disp)
16619         addiu   $gp,$gp,%lo(_gp_disp)
16620         addu    $gp,$gp,.cpload argument
16621    The .cpload argument is normally $25 == $t9.
16622
16623    The -mno-shared option changes this to:
16624         lui     $gp,%hi(__gnu_local_gp)
16625         addiu   $gp,$gp,%lo(__gnu_local_gp)
16626    and the argument is ignored.  This saves an instruction, but the
16627    resulting code is not position independent; it uses an absolute
16628    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16629    can go into an ordinary executable, but not into a shared library.  */
16630
16631 static void
16632 s_cpload (int ignore ATTRIBUTE_UNUSED)
16633 {
16634   expressionS ex;
16635   int reg;
16636   int in_shared;
16637
16638   file_mips_check_options ();
16639
16640   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16641      .cpload is ignored.  */
16642   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16643     {
16644       s_ignore (0);
16645       return;
16646     }
16647
16648   if (mips_opts.mips16)
16649     {
16650       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16651       ignore_rest_of_line ();
16652       return;
16653     }
16654
16655   /* .cpload should be in a .set noreorder section.  */
16656   if (mips_opts.noreorder == 0)
16657     as_warn (_(".cpload not in noreorder section"));
16658
16659   reg = tc_get_register (0);
16660
16661   /* If we need to produce a 64-bit address, we are better off using
16662      the default instruction sequence.  */
16663   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16664
16665   ex.X_op = O_symbol;
16666   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16667                                          "__gnu_local_gp");
16668   ex.X_op_symbol = NULL;
16669   ex.X_add_number = 0;
16670
16671   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16672   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16673
16674   mips_mark_labels ();
16675   mips_assembling_insn = TRUE;
16676
16677   macro_start ();
16678   macro_build_lui (&ex, mips_gp_register);
16679   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16680                mips_gp_register, BFD_RELOC_LO16);
16681   if (in_shared)
16682     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16683                  mips_gp_register, reg);
16684   macro_end ();
16685
16686   mips_assembling_insn = FALSE;
16687   demand_empty_rest_of_line ();
16688 }
16689
16690 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16691      .cpsetup $reg1, offset|$reg2, label
16692
16693    If offset is given, this results in:
16694      sd         $gp, offset($sp)
16695      lui        $gp, %hi(%neg(%gp_rel(label)))
16696      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16697      daddu      $gp, $gp, $reg1
16698
16699    If $reg2 is given, this results in:
16700      or         $reg2, $gp, $0
16701      lui        $gp, %hi(%neg(%gp_rel(label)))
16702      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16703      daddu      $gp, $gp, $reg1
16704    $reg1 is normally $25 == $t9.
16705
16706    The -mno-shared option replaces the last three instructions with
16707         lui     $gp,%hi(_gp)
16708         addiu   $gp,$gp,%lo(_gp)  */
16709
16710 static void
16711 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16712 {
16713   expressionS ex_off;
16714   expressionS ex_sym;
16715   int reg1;
16716
16717   file_mips_check_options ();
16718
16719   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16720      We also need NewABI support.  */
16721   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16722     {
16723       s_ignore (0);
16724       return;
16725     }
16726
16727   if (mips_opts.mips16)
16728     {
16729       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16730       ignore_rest_of_line ();
16731       return;
16732     }
16733
16734   reg1 = tc_get_register (0);
16735   SKIP_WHITESPACE ();
16736   if (*input_line_pointer != ',')
16737     {
16738       as_bad (_("missing argument separator ',' for .cpsetup"));
16739       return;
16740     }
16741   else
16742     ++input_line_pointer;
16743   SKIP_WHITESPACE ();
16744   if (*input_line_pointer == '$')
16745     {
16746       mips_cpreturn_register = tc_get_register (0);
16747       mips_cpreturn_offset = -1;
16748     }
16749   else
16750     {
16751       mips_cpreturn_offset = get_absolute_expression ();
16752       mips_cpreturn_register = -1;
16753     }
16754   SKIP_WHITESPACE ();
16755   if (*input_line_pointer != ',')
16756     {
16757       as_bad (_("missing argument separator ',' for .cpsetup"));
16758       return;
16759     }
16760   else
16761     ++input_line_pointer;
16762   SKIP_WHITESPACE ();
16763   expression (&ex_sym);
16764
16765   mips_mark_labels ();
16766   mips_assembling_insn = TRUE;
16767
16768   macro_start ();
16769   if (mips_cpreturn_register == -1)
16770     {
16771       ex_off.X_op = O_constant;
16772       ex_off.X_add_symbol = NULL;
16773       ex_off.X_op_symbol = NULL;
16774       ex_off.X_add_number = mips_cpreturn_offset;
16775
16776       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16777                    BFD_RELOC_LO16, SP);
16778     }
16779   else
16780     move_register (mips_cpreturn_register, mips_gp_register);
16781
16782   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16783     {
16784       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16785                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16786                    BFD_RELOC_HI16_S);
16787
16788       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16789                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16790                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16791
16792       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16793                    mips_gp_register, reg1);
16794     }
16795   else
16796     {
16797       expressionS ex;
16798
16799       ex.X_op = O_symbol;
16800       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16801       ex.X_op_symbol = NULL;
16802       ex.X_add_number = 0;
16803
16804       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16805       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16806
16807       macro_build_lui (&ex, mips_gp_register);
16808       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16809                    mips_gp_register, BFD_RELOC_LO16);
16810     }
16811
16812   macro_end ();
16813
16814   mips_assembling_insn = FALSE;
16815   demand_empty_rest_of_line ();
16816 }
16817
16818 static void
16819 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16820 {
16821   file_mips_check_options ();
16822
16823   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16824      .cplocal is ignored.  */
16825   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16826     {
16827       s_ignore (0);
16828       return;
16829     }
16830
16831   if (mips_opts.mips16)
16832     {
16833       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16834       ignore_rest_of_line ();
16835       return;
16836     }
16837
16838   mips_gp_register = tc_get_register (0);
16839   demand_empty_rest_of_line ();
16840 }
16841
16842 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16843    offset from $sp.  The offset is remembered, and after making a PIC
16844    call $gp is restored from that location.  */
16845
16846 static void
16847 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16848 {
16849   expressionS ex;
16850
16851   file_mips_check_options ();
16852
16853   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16854      .cprestore is ignored.  */
16855   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16856     {
16857       s_ignore (0);
16858       return;
16859     }
16860
16861   if (mips_opts.mips16)
16862     {
16863       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16864       ignore_rest_of_line ();
16865       return;
16866     }
16867
16868   mips_cprestore_offset = get_absolute_expression ();
16869   mips_cprestore_valid = 1;
16870
16871   ex.X_op = O_constant;
16872   ex.X_add_symbol = NULL;
16873   ex.X_op_symbol = NULL;
16874   ex.X_add_number = mips_cprestore_offset;
16875
16876   mips_mark_labels ();
16877   mips_assembling_insn = TRUE;
16878
16879   macro_start ();
16880   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16881                                 SP, HAVE_64BIT_ADDRESSES);
16882   macro_end ();
16883
16884   mips_assembling_insn = FALSE;
16885   demand_empty_rest_of_line ();
16886 }
16887
16888 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16889    was given in the preceding .cpsetup, it results in:
16890      ld         $gp, offset($sp)
16891
16892    If a register $reg2 was given there, it results in:
16893      or         $gp, $reg2, $0  */
16894
16895 static void
16896 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16897 {
16898   expressionS ex;
16899
16900   file_mips_check_options ();
16901
16902   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16903      We also need NewABI support.  */
16904   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16905     {
16906       s_ignore (0);
16907       return;
16908     }
16909
16910   if (mips_opts.mips16)
16911     {
16912       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16913       ignore_rest_of_line ();
16914       return;
16915     }
16916
16917   mips_mark_labels ();
16918   mips_assembling_insn = TRUE;
16919
16920   macro_start ();
16921   if (mips_cpreturn_register == -1)
16922     {
16923       ex.X_op = O_constant;
16924       ex.X_add_symbol = NULL;
16925       ex.X_op_symbol = NULL;
16926       ex.X_add_number = mips_cpreturn_offset;
16927
16928       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16929     }
16930   else
16931     move_register (mips_gp_register, mips_cpreturn_register);
16932
16933   macro_end ();
16934
16935   mips_assembling_insn = FALSE;
16936   demand_empty_rest_of_line ();
16937 }
16938
16939 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16940    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16941    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16942    debug information or MIPS16 TLS.  */
16943
16944 static void
16945 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16946                      bfd_reloc_code_real_type rtype)
16947 {
16948   expressionS ex;
16949   char *p;
16950
16951   expression (&ex);
16952
16953   if (ex.X_op != O_symbol)
16954     {
16955       as_bad (_("unsupported use of %s"), dirstr);
16956       ignore_rest_of_line ();
16957     }
16958
16959   p = frag_more (bytes);
16960   md_number_to_chars (p, 0, bytes);
16961   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16962   demand_empty_rest_of_line ();
16963   mips_clear_insn_labels ();
16964 }
16965
16966 /* Handle .dtprelword.  */
16967
16968 static void
16969 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16970 {
16971   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16972 }
16973
16974 /* Handle .dtpreldword.  */
16975
16976 static void
16977 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16978 {
16979   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16980 }
16981
16982 /* Handle .tprelword.  */
16983
16984 static void
16985 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16986 {
16987   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16988 }
16989
16990 /* Handle .tpreldword.  */
16991
16992 static void
16993 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16994 {
16995   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16996 }
16997
16998 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16999    code.  It sets the offset to use in gp_rel relocations.  */
17000
17001 static void
17002 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
17003 {
17004   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
17005      We also need NewABI support.  */
17006   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17007     {
17008       s_ignore (0);
17009       return;
17010     }
17011
17012   mips_gprel_offset = get_absolute_expression ();
17013
17014   demand_empty_rest_of_line ();
17015 }
17016
17017 /* Handle the .gpword pseudo-op.  This is used when generating PIC
17018    code.  It generates a 32 bit GP relative reloc.  */
17019
17020 static void
17021 s_gpword (int ignore ATTRIBUTE_UNUSED)
17022 {
17023   segment_info_type *si;
17024   struct insn_label_list *l;
17025   expressionS ex;
17026   char *p;
17027
17028   /* When not generating PIC code, this is treated as .word.  */
17029   if (mips_pic != SVR4_PIC)
17030     {
17031       s_cons (2);
17032       return;
17033     }
17034
17035   si = seg_info (now_seg);
17036   l = si->label_list;
17037   mips_emit_delays ();
17038   if (auto_align)
17039     mips_align (2, 0, l);
17040
17041   expression (&ex);
17042   mips_clear_insn_labels ();
17043
17044   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17045     {
17046       as_bad (_("unsupported use of .gpword"));
17047       ignore_rest_of_line ();
17048     }
17049
17050   p = frag_more (4);
17051   md_number_to_chars (p, 0, 4);
17052   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17053                BFD_RELOC_GPREL32);
17054
17055   demand_empty_rest_of_line ();
17056 }
17057
17058 static void
17059 s_gpdword (int ignore ATTRIBUTE_UNUSED)
17060 {
17061   segment_info_type *si;
17062   struct insn_label_list *l;
17063   expressionS ex;
17064   char *p;
17065
17066   /* When not generating PIC code, this is treated as .dword.  */
17067   if (mips_pic != SVR4_PIC)
17068     {
17069       s_cons (3);
17070       return;
17071     }
17072
17073   si = seg_info (now_seg);
17074   l = si->label_list;
17075   mips_emit_delays ();
17076   if (auto_align)
17077     mips_align (3, 0, l);
17078
17079   expression (&ex);
17080   mips_clear_insn_labels ();
17081
17082   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17083     {
17084       as_bad (_("unsupported use of .gpdword"));
17085       ignore_rest_of_line ();
17086     }
17087
17088   p = frag_more (8);
17089   md_number_to_chars (p, 0, 8);
17090   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17091                BFD_RELOC_GPREL32)->fx_tcbit = 1;
17092
17093   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17094   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17095            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
17096
17097   demand_empty_rest_of_line ();
17098 }
17099
17100 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
17101    tables.  It generates a R_MIPS_EH reloc.  */
17102
17103 static void
17104 s_ehword (int ignore ATTRIBUTE_UNUSED)
17105 {
17106   expressionS ex;
17107   char *p;
17108
17109   mips_emit_delays ();
17110
17111   expression (&ex);
17112   mips_clear_insn_labels ();
17113
17114   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17115     {
17116       as_bad (_("unsupported use of .ehword"));
17117       ignore_rest_of_line ();
17118     }
17119
17120   p = frag_more (4);
17121   md_number_to_chars (p, 0, 4);
17122   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17123                BFD_RELOC_32_PCREL);
17124
17125   demand_empty_rest_of_line ();
17126 }
17127
17128 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17129    tables in SVR4 PIC code.  */
17130
17131 static void
17132 s_cpadd (int ignore ATTRIBUTE_UNUSED)
17133 {
17134   int reg;
17135
17136   file_mips_check_options ();
17137
17138   /* This is ignored when not generating SVR4 PIC code.  */
17139   if (mips_pic != SVR4_PIC)
17140     {
17141       s_ignore (0);
17142       return;
17143     }
17144
17145   mips_mark_labels ();
17146   mips_assembling_insn = TRUE;
17147
17148   /* Add $gp to the register named as an argument.  */
17149   macro_start ();
17150   reg = tc_get_register (0);
17151   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17152   macro_end ();
17153
17154   mips_assembling_insn = FALSE;
17155   demand_empty_rest_of_line ();
17156 }
17157
17158 /* Handle the .insn pseudo-op.  This marks instruction labels in
17159    mips16/micromips mode.  This permits the linker to handle them specially,
17160    such as generating jalx instructions when needed.  We also make
17161    them odd for the duration of the assembly, in order to generate the
17162    right sort of code.  We will make them even in the adjust_symtab
17163    routine, while leaving them marked.  This is convenient for the
17164    debugger and the disassembler.  The linker knows to make them odd
17165    again.  */
17166
17167 static void
17168 s_insn (int ignore ATTRIBUTE_UNUSED)
17169 {
17170   file_mips_check_options ();
17171   file_ase_mips16 |= mips_opts.mips16;
17172   file_ase_micromips |= mips_opts.micromips;
17173
17174   mips_mark_labels ();
17175
17176   demand_empty_rest_of_line ();
17177 }
17178
17179 /* Handle the .nan pseudo-op.  */
17180
17181 static void
17182 s_nan (int ignore ATTRIBUTE_UNUSED)
17183 {
17184   static const char str_legacy[] = "legacy";
17185   static const char str_2008[] = "2008";
17186   size_t i;
17187
17188   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
17189
17190   if (i == sizeof (str_2008) - 1
17191       && memcmp (input_line_pointer, str_2008, i) == 0)
17192     mips_nan2008 = 1;
17193   else if (i == sizeof (str_legacy) - 1
17194            && memcmp (input_line_pointer, str_legacy, i) == 0)
17195     {
17196       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
17197         mips_nan2008 = 0;
17198       else
17199         as_bad (_("`%s' does not support legacy NaN"),
17200                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
17201     }
17202   else
17203     as_bad (_("bad .nan directive"));
17204
17205   input_line_pointer += i;
17206   demand_empty_rest_of_line ();
17207 }
17208
17209 /* Handle a .stab[snd] directive.  Ideally these directives would be
17210    implemented in a transparent way, so that removing them would not
17211    have any effect on the generated instructions.  However, s_stab
17212    internally changes the section, so in practice we need to decide
17213    now whether the preceding label marks compressed code.  We do not
17214    support changing the compression mode of a label after a .stab*
17215    directive, such as in:
17216
17217    foo:
17218         .stabs ...
17219         .set mips16
17220
17221    so the current mode wins.  */
17222
17223 static void
17224 s_mips_stab (int type)
17225 {
17226   file_mips_check_options ();
17227   mips_mark_labels ();
17228   s_stab (type);
17229 }
17230
17231 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17232
17233 static void
17234 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17235 {
17236   char *name;
17237   int c;
17238   symbolS *symbolP;
17239   expressionS exp;
17240
17241   c = get_symbol_name (&name);
17242   symbolP = symbol_find_or_make (name);
17243   S_SET_WEAK (symbolP);
17244   *input_line_pointer = c;
17245
17246   SKIP_WHITESPACE_AFTER_NAME ();
17247
17248   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17249     {
17250       if (S_IS_DEFINED (symbolP))
17251         {
17252           as_bad (_("ignoring attempt to redefine symbol %s"),
17253                   S_GET_NAME (symbolP));
17254           ignore_rest_of_line ();
17255           return;
17256         }
17257
17258       if (*input_line_pointer == ',')
17259         {
17260           ++input_line_pointer;
17261           SKIP_WHITESPACE ();
17262         }
17263
17264       expression (&exp);
17265       if (exp.X_op != O_symbol)
17266         {
17267           as_bad (_("bad .weakext directive"));
17268           ignore_rest_of_line ();
17269           return;
17270         }
17271       symbol_set_value_expression (symbolP, &exp);
17272     }
17273
17274   demand_empty_rest_of_line ();
17275 }
17276
17277 /* Parse a register string into a number.  Called from the ECOFF code
17278    to parse .frame.  The argument is non-zero if this is the frame
17279    register, so that we can record it in mips_frame_reg.  */
17280
17281 int
17282 tc_get_register (int frame)
17283 {
17284   unsigned int reg;
17285
17286   SKIP_WHITESPACE ();
17287   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17288     reg = 0;
17289   if (frame)
17290     {
17291       mips_frame_reg = reg != 0 ? reg : SP;
17292       mips_frame_reg_valid = 1;
17293       mips_cprestore_valid = 0;
17294     }
17295   return reg;
17296 }
17297
17298 valueT
17299 md_section_align (asection *seg, valueT addr)
17300 {
17301   int align = bfd_get_section_alignment (stdoutput, seg);
17302
17303   /* We don't need to align ELF sections to the full alignment.
17304      However, Irix 5 may prefer that we align them at least to a 16
17305      byte boundary.  We don't bother to align the sections if we
17306      are targeted for an embedded system.  */
17307   if (strncmp (TARGET_OS, "elf", 3) == 0)
17308     return addr;
17309   if (align > 4)
17310     align = 4;
17311
17312   return ((addr + (1 << align) - 1) & -(1 << align));
17313 }
17314
17315 /* Utility routine, called from above as well.  If called while the
17316    input file is still being read, it's only an approximation.  (For
17317    example, a symbol may later become defined which appeared to be
17318    undefined earlier.)  */
17319
17320 static int
17321 nopic_need_relax (symbolS *sym, int before_relaxing)
17322 {
17323   if (sym == 0)
17324     return 0;
17325
17326   if (g_switch_value > 0)
17327     {
17328       const char *symname;
17329       int change;
17330
17331       /* Find out whether this symbol can be referenced off the $gp
17332          register.  It can be if it is smaller than the -G size or if
17333          it is in the .sdata or .sbss section.  Certain symbols can
17334          not be referenced off the $gp, although it appears as though
17335          they can.  */
17336       symname = S_GET_NAME (sym);
17337       if (symname != (const char *) NULL
17338           && (strcmp (symname, "eprol") == 0
17339               || strcmp (symname, "etext") == 0
17340               || strcmp (symname, "_gp") == 0
17341               || strcmp (symname, "edata") == 0
17342               || strcmp (symname, "_fbss") == 0
17343               || strcmp (symname, "_fdata") == 0
17344               || strcmp (symname, "_ftext") == 0
17345               || strcmp (symname, "end") == 0
17346               || strcmp (symname, "_gp_disp") == 0))
17347         change = 1;
17348       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17349                && (0
17350 #ifndef NO_ECOFF_DEBUGGING
17351                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17352                        && (symbol_get_obj (sym)->ecoff_extern_size
17353                            <= g_switch_value))
17354 #endif
17355                    /* We must defer this decision until after the whole
17356                       file has been read, since there might be a .extern
17357                       after the first use of this symbol.  */
17358                    || (before_relaxing
17359 #ifndef NO_ECOFF_DEBUGGING
17360                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17361 #endif
17362                        && S_GET_VALUE (sym) == 0)
17363                    || (S_GET_VALUE (sym) != 0
17364                        && S_GET_VALUE (sym) <= g_switch_value)))
17365         change = 0;
17366       else
17367         {
17368           const char *segname;
17369
17370           segname = segment_name (S_GET_SEGMENT (sym));
17371           gas_assert (strcmp (segname, ".lit8") != 0
17372                   && strcmp (segname, ".lit4") != 0);
17373           change = (strcmp (segname, ".sdata") != 0
17374                     && strcmp (segname, ".sbss") != 0
17375                     && strncmp (segname, ".sdata.", 7) != 0
17376                     && strncmp (segname, ".sbss.", 6) != 0
17377                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17378                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17379         }
17380       return change;
17381     }
17382   else
17383     /* We are not optimizing for the $gp register.  */
17384     return 1;
17385 }
17386
17387
17388 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17389
17390 static bfd_boolean
17391 pic_need_relax (symbolS *sym)
17392 {
17393   asection *symsec;
17394
17395   /* Handle the case of a symbol equated to another symbol.  */
17396   while (symbol_equated_reloc_p (sym))
17397     {
17398       symbolS *n;
17399
17400       /* It's possible to get a loop here in a badly written program.  */
17401       n = symbol_get_value_expression (sym)->X_add_symbol;
17402       if (n == sym)
17403         break;
17404       sym = n;
17405     }
17406
17407   if (symbol_section_p (sym))
17408     return TRUE;
17409
17410   symsec = S_GET_SEGMENT (sym);
17411
17412   /* This must duplicate the test in adjust_reloc_syms.  */
17413   return (!bfd_is_und_section (symsec)
17414           && !bfd_is_abs_section (symsec)
17415           && !bfd_is_com_section (symsec)
17416           /* A global or weak symbol is treated as external.  */
17417           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17418 }
17419 \f
17420 /* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17421    convert a section-relative value VAL to the equivalent PC-relative
17422    value.  */
17423
17424 static offsetT
17425 mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17426                   offsetT val, long stretch)
17427 {
17428   fragS *sym_frag;
17429   addressT addr;
17430
17431   gas_assert (pcrel_op->root.root.type == OP_PCREL);
17432
17433   sym_frag = symbol_get_frag (fragp->fr_symbol);
17434
17435   /* If the relax_marker of the symbol fragment differs from the
17436      relax_marker of this fragment, we have not yet adjusted the
17437      symbol fragment fr_address.  We want to add in STRETCH in
17438      order to get a better estimate of the address.  This
17439      particularly matters because of the shift bits.  */
17440   if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17441     {
17442       fragS *f;
17443
17444       /* Adjust stretch for any alignment frag.  Note that if have
17445          been expanding the earlier code, the symbol may be
17446          defined in what appears to be an earlier frag.  FIXME:
17447          This doesn't handle the fr_subtype field, which specifies
17448          a maximum number of bytes to skip when doing an
17449          alignment.  */
17450       for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17451         {
17452           if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17453             {
17454               if (stretch < 0)
17455                 stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17456               else
17457                 stretch &= ~((1 << (int) f->fr_offset) - 1);
17458               if (stretch == 0)
17459                 break;
17460             }
17461         }
17462       if (f != NULL)
17463         val += stretch;
17464     }
17465
17466   addr = fragp->fr_address + fragp->fr_fix;
17467
17468   /* The base address rules are complicated.  The base address of
17469      a branch is the following instruction.  The base address of a
17470      PC relative load or add is the instruction itself, but if it
17471      is in a delay slot (in which case it can not be extended) use
17472      the address of the instruction whose delay slot it is in.  */
17473   if (pcrel_op->include_isa_bit)
17474     {
17475       addr += 2;
17476
17477       /* If we are currently assuming that this frag should be
17478          extended, then the current address is two bytes higher.  */
17479       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17480         addr += 2;
17481
17482       /* Ignore the low bit in the target, since it will be set
17483          for a text label.  */
17484       val &= -2;
17485     }
17486   else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17487     addr -= 4;
17488   else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17489     addr -= 2;
17490
17491   val -= addr & -(1 << pcrel_op->align_log2);
17492
17493   return val;
17494 }
17495
17496 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17497    extended opcode.  SEC is the section the frag is in.  */
17498
17499 static int
17500 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17501 {
17502   const struct mips_int_operand *operand;
17503   offsetT val;
17504   segT symsec;
17505   int type;
17506
17507   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17508     return 0;
17509   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17510     return 1;
17511
17512   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17513   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17514   operand = mips16_immed_operand (type, FALSE);
17515   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
17516       || (operand->root.type == OP_PCREL
17517           ? sec != symsec
17518           : !bfd_is_abs_section (symsec)))
17519     return 1;
17520
17521   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17522
17523   if (operand->root.type == OP_PCREL)
17524     {
17525       const struct mips_pcrel_operand *pcrel_op;
17526       offsetT maxtiny;
17527
17528       if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17529         return 1;
17530
17531       pcrel_op = (const struct mips_pcrel_operand *) operand;
17532       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17533
17534       /* If any of the shifted bits are set, we must use an extended
17535          opcode.  If the address depends on the size of this
17536          instruction, this can lead to a loop, so we arrange to always
17537          use an extended opcode.  */
17538       if ((val & ((1 << operand->shift) - 1)) != 0)
17539         {
17540           fragp->fr_subtype =
17541             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17542           return 1;
17543         }
17544
17545       /* If we are about to mark a frag as extended because the value
17546          is precisely the next value above maxtiny, then there is a
17547          chance of an infinite loop as in the following code:
17548              la $4,foo
17549              .skip      1020
17550              .align     2
17551            foo:
17552          In this case when the la is extended, foo is 0x3fc bytes
17553          away, so the la can be shrunk, but then foo is 0x400 away, so
17554          the la must be extended.  To avoid this loop, we mark the
17555          frag as extended if it was small, and is about to become
17556          extended with the next value above maxtiny.  */
17557       maxtiny = mips_int_operand_max (operand);
17558       if (val == maxtiny + (1 << operand->shift)
17559           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17560         {
17561           fragp->fr_subtype =
17562             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17563           return 1;
17564         }
17565     }
17566
17567   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17568 }
17569
17570 /* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
17571    macro expansion.  SEC is the section the frag is in.  We only
17572    support PC-relative instructions (LA, DLA, LW, LD) here, in
17573    non-PIC code using 32-bit addressing.  */
17574
17575 static int
17576 mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
17577 {
17578   const struct mips_pcrel_operand *pcrel_op;
17579   const struct mips_int_operand *operand;
17580   offsetT val;
17581   segT symsec;
17582   int type;
17583
17584   gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
17585
17586   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17587     return 0;
17588   if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
17589     return 0;
17590
17591   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17592   switch (type)
17593     {
17594     case 'A':
17595     case 'B':
17596     case 'E':
17597       symsec = S_GET_SEGMENT (fragp->fr_symbol);
17598       if (bfd_is_abs_section (symsec))
17599         return 1;
17600       if (RELAX_MIPS16_PIC (fragp->fr_subtype))
17601         return 0;
17602       if (S_FORCE_RELOC (fragp->fr_symbol, TRUE) || sec != symsec)
17603         return 1;
17604
17605       operand = mips16_immed_operand (type, TRUE);
17606       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17607       pcrel_op = (const struct mips_pcrel_operand *) operand;
17608       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17609
17610       return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17611
17612     default:
17613       return 0;
17614     }
17615 }
17616
17617 /* Compute the length of a branch sequence, and adjust the
17618    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17619    worst-case length is computed, with UPDATE being used to indicate
17620    whether an unconditional (-1), branch-likely (+1) or regular (0)
17621    branch is to be computed.  */
17622 static int
17623 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17624 {
17625   bfd_boolean toofar;
17626   int length;
17627
17628   if (fragp
17629       && S_IS_DEFINED (fragp->fr_symbol)
17630       && !S_IS_WEAK (fragp->fr_symbol)
17631       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17632     {
17633       addressT addr;
17634       offsetT val;
17635
17636       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17637
17638       addr = fragp->fr_address + fragp->fr_fix + 4;
17639
17640       val -= addr;
17641
17642       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17643     }
17644   else
17645     /* If the symbol is not defined or it's in a different segment,
17646        we emit the long sequence.  */
17647     toofar = TRUE;
17648
17649   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17650     fragp->fr_subtype
17651       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17652                              RELAX_BRANCH_PIC (fragp->fr_subtype),
17653                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17654                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17655                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17656                              toofar);
17657
17658   length = 4;
17659   if (toofar)
17660     {
17661       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17662         length += 8;
17663
17664       if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
17665         {
17666           /* Additional space for PIC loading of target address.  */
17667           length += 8;
17668           if (mips_opts.isa == ISA_MIPS1)
17669             /* Additional space for $at-stabilizing nop.  */
17670             length += 4;
17671         }
17672
17673       /* If branch is conditional.  */
17674       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17675         length += 8;
17676     }
17677
17678   return length;
17679 }
17680
17681 /* Get a FRAG's branch instruction delay slot size, either from the
17682    short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
17683    or SHORT_INSN_SIZE otherwise.  */
17684
17685 static int
17686 frag_branch_delay_slot_size (fragS *fragp, bfd_boolean al, int short_insn_size)
17687 {
17688   char *buf = fragp->fr_literal + fragp->fr_fix;
17689
17690   if (al)
17691     return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
17692   else
17693     return short_insn_size;
17694 }
17695
17696 /* Compute the length of a branch sequence, and adjust the
17697    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17698    worst-case length is computed, with UPDATE being used to indicate
17699    whether an unconditional (-1), or regular (0) branch is to be
17700    computed.  */
17701
17702 static int
17703 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17704 {
17705   bfd_boolean insn32 = TRUE;
17706   bfd_boolean nods = TRUE;
17707   bfd_boolean pic = TRUE;
17708   bfd_boolean al = TRUE;
17709   int short_insn_size;
17710   bfd_boolean toofar;
17711   int length;
17712
17713   if (fragp)
17714     {
17715       insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
17716       nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
17717       pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
17718       al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17719     }
17720   short_insn_size = insn32 ? 4 : 2;
17721
17722   if (fragp
17723       && S_IS_DEFINED (fragp->fr_symbol)
17724       && !S_IS_WEAK (fragp->fr_symbol)
17725       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17726     {
17727       addressT addr;
17728       offsetT val;
17729
17730       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17731       /* Ignore the low bit in the target, since it will be set
17732          for a text label.  */
17733       if ((val & 1) != 0)
17734         --val;
17735
17736       addr = fragp->fr_address + fragp->fr_fix + 4;
17737
17738       val -= addr;
17739
17740       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17741     }
17742   else
17743     /* If the symbol is not defined or it's in a different segment,
17744        we emit the long sequence.  */
17745     toofar = TRUE;
17746
17747   if (fragp && update
17748       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17749     fragp->fr_subtype = (toofar
17750                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17751                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17752
17753   length = 4;
17754   if (toofar)
17755     {
17756       bfd_boolean compact_known = fragp != NULL;
17757       bfd_boolean compact = FALSE;
17758       bfd_boolean uncond;
17759
17760       if (fragp)
17761         {
17762           compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17763           uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17764         }
17765       else
17766         uncond = update < 0;
17767
17768       /* If label is out of range, we turn branch <br>:
17769
17770                 <br>    label                   # 4 bytes
17771             0:
17772
17773          into:
17774
17775                 j       label                   # 4 bytes
17776                 nop                             # 2/4 bytes if
17777                                                 #  compact && (!PIC || insn32)
17778             0:
17779        */
17780       if ((!pic || insn32) && (!compact_known || compact))
17781         length += short_insn_size;
17782
17783       /* If assembling PIC code, we further turn:
17784
17785                         j       label                   # 4 bytes
17786
17787          into:
17788
17789                         lw/ld   at, %got(label)(gp)     # 4 bytes
17790                         d/addiu at, %lo(label)          # 4 bytes
17791                         jr/c    at                      # 2/4 bytes
17792        */
17793       if (pic)
17794         length += 4 + short_insn_size;
17795
17796       /* Add an extra nop if the jump has no compact form and we need
17797          to fill the delay slot.  */
17798       if ((!pic || al) && nods)
17799         length += (fragp
17800                    ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
17801                    : short_insn_size);
17802
17803       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17804
17805                         <brneg> 0f                      # 4 bytes
17806                         nop                             # 2/4 bytes if !compact
17807        */
17808       if (!uncond)
17809         length += (compact_known && compact) ? 4 : 4 + short_insn_size;
17810     }
17811   else if (nods)
17812     {
17813       /* Add an extra nop to fill the delay slot.  */
17814       gas_assert (fragp);
17815       length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
17816     }
17817
17818   return length;
17819 }
17820
17821 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17822    bit accordingly.  */
17823
17824 static int
17825 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17826 {
17827   bfd_boolean toofar;
17828
17829   if (fragp
17830       && S_IS_DEFINED (fragp->fr_symbol)
17831       && !S_IS_WEAK (fragp->fr_symbol)
17832       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17833     {
17834       addressT addr;
17835       offsetT val;
17836       int type;
17837
17838       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17839       /* Ignore the low bit in the target, since it will be set
17840          for a text label.  */
17841       if ((val & 1) != 0)
17842         --val;
17843
17844       /* Assume this is a 2-byte branch.  */
17845       addr = fragp->fr_address + fragp->fr_fix + 2;
17846
17847       /* We try to avoid the infinite loop by not adding 2 more bytes for
17848          long branches.  */
17849
17850       val -= addr;
17851
17852       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17853       if (type == 'D')
17854         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17855       else if (type == 'E')
17856         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17857       else
17858         abort ();
17859     }
17860   else
17861     /* If the symbol is not defined or it's in a different segment,
17862        we emit a normal 32-bit branch.  */
17863     toofar = TRUE;
17864
17865   if (fragp && update
17866       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17867     fragp->fr_subtype
17868       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17869                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17870
17871   if (toofar)
17872     return 4;
17873
17874   return 2;
17875 }
17876
17877 /* Estimate the size of a frag before relaxing.  Unless this is the
17878    mips16, we are not really relaxing here, and the final size is
17879    encoded in the subtype information.  For the mips16, we have to
17880    decide whether we are using an extended opcode or not.  */
17881
17882 int
17883 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17884 {
17885   int change;
17886
17887   if (RELAX_BRANCH_P (fragp->fr_subtype))
17888     {
17889
17890       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17891
17892       return fragp->fr_var;
17893     }
17894
17895   if (RELAX_MIPS16_P (fragp->fr_subtype))
17896     {
17897       /* We don't want to modify the EXTENDED bit here; it might get us
17898          into infinite loops.  We change it only in mips_relax_frag().  */
17899       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17900         return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 8 : 12;
17901       else
17902         return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
17903     }
17904
17905   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17906     {
17907       int length = 4;
17908
17909       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17910         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17911       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17912         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17913       fragp->fr_var = length;
17914
17915       return length;
17916     }
17917
17918   if (mips_pic == VXWORKS_PIC)
17919     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17920     change = 0;
17921   else if (RELAX_PIC (fragp->fr_subtype))
17922     change = pic_need_relax (fragp->fr_symbol);
17923   else
17924     change = nopic_need_relax (fragp->fr_symbol, 0);
17925
17926   if (change)
17927     {
17928       fragp->fr_subtype |= RELAX_USE_SECOND;
17929       return -RELAX_FIRST (fragp->fr_subtype);
17930     }
17931   else
17932     return -RELAX_SECOND (fragp->fr_subtype);
17933 }
17934
17935 /* This is called to see whether a reloc against a defined symbol
17936    should be converted into a reloc against a section.  */
17937
17938 int
17939 mips_fix_adjustable (fixS *fixp)
17940 {
17941   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17942       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17943     return 0;
17944
17945   if (fixp->fx_addsy == NULL)
17946     return 1;
17947
17948   /* Allow relocs used for EH tables.  */
17949   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17950     return 1;
17951
17952   /* If symbol SYM is in a mergeable section, relocations of the form
17953      SYM + 0 can usually be made section-relative.  The mergeable data
17954      is then identified by the section offset rather than by the symbol.
17955
17956      However, if we're generating REL LO16 relocations, the offset is split
17957      between the LO16 and partnering high part relocation.  The linker will
17958      need to recalculate the complete offset in order to correctly identify
17959      the merge data.
17960
17961      The linker has traditionally not looked for the partnering high part
17962      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17963      placed anywhere.  Rather than break backwards compatibility by changing
17964      this, it seems better not to force the issue, and instead keep the
17965      original symbol.  This will work with either linker behavior.  */
17966   if ((lo16_reloc_p (fixp->fx_r_type)
17967        || reloc_needs_lo_p (fixp->fx_r_type))
17968       && HAVE_IN_PLACE_ADDENDS
17969       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17970     return 0;
17971
17972   /* There is no place to store an in-place offset for JALR relocations.  */
17973   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17974     return 0;
17975
17976   /* Likewise an in-range offset of limited PC-relative relocations may
17977      overflow the in-place relocatable field if recalculated against the
17978      start address of the symbol's containing section.
17979
17980      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17981      section relative to allow linker relaxations to be performed later on.  */
17982   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17983       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17984     return 0;
17985
17986   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17987      to a floating-point stub.  The same is true for non-R_MIPS16_26
17988      relocations against MIPS16 functions; in this case, the stub becomes
17989      the function's canonical address.
17990
17991      Floating-point stubs are stored in unique .mips16.call.* or
17992      .mips16.fn.* sections.  If a stub T for function F is in section S,
17993      the first relocation in section S must be against F; this is how the
17994      linker determines the target function.  All relocations that might
17995      resolve to T must also be against F.  We therefore have the following
17996      restrictions, which are given in an intentionally-redundant way:
17997
17998        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17999           symbols.
18000
18001        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
18002           if that stub might be used.
18003
18004        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
18005           symbols.
18006
18007        4. We cannot reduce a stub's relocations against MIPS16 symbols if
18008           that stub might be used.
18009
18010      There is a further restriction:
18011
18012        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
18013           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
18014           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
18015           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
18016           against MIPS16 or microMIPS symbols because we need to keep the
18017           MIPS16 or microMIPS symbol for the purpose of mode mismatch
18018           detection and JAL or BAL to JALX instruction conversion in the
18019           linker.
18020
18021      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
18022      against a MIPS16 symbol.  We deal with (5) by additionally leaving
18023      alone any jump and branch relocations against a microMIPS symbol.
18024
18025      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
18026      relocation against some symbol R, no relocation against R may be
18027      reduced.  (Note that this deals with (2) as well as (1) because
18028      relocations against global symbols will never be reduced on ELF
18029      targets.)  This approach is a little simpler than trying to detect
18030      stub sections, and gives the "all or nothing" per-symbol consistency
18031      that we have for MIPS16 symbols.  */
18032   if (fixp->fx_subsy == NULL
18033       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
18034           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
18035               && (jmp_reloc_p (fixp->fx_r_type)
18036                   || b_reloc_p (fixp->fx_r_type)))
18037           || *symbol_get_tc (fixp->fx_addsy)))
18038     return 0;
18039
18040   return 1;
18041 }
18042
18043 /* Translate internal representation of relocation info to BFD target
18044    format.  */
18045
18046 arelent **
18047 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
18048 {
18049   static arelent *retval[4];
18050   arelent *reloc;
18051   bfd_reloc_code_real_type code;
18052
18053   memset (retval, 0, sizeof(retval));
18054   reloc = retval[0] = XCNEW (arelent);
18055   reloc->sym_ptr_ptr = XNEW (asymbol *);
18056   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
18057   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
18058
18059   if (fixp->fx_pcrel)
18060     {
18061       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
18062                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
18063                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
18064                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
18065                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
18066                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
18067                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
18068                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
18069                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
18070                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
18071                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
18072                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
18073
18074       /* At this point, fx_addnumber is "symbol offset - pcrel address".
18075          Relocations want only the symbol offset.  */
18076       switch (fixp->fx_r_type)
18077         {
18078         case BFD_RELOC_MIPS_18_PCREL_S3:
18079           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
18080           break;
18081         default:
18082           reloc->addend = fixp->fx_addnumber + reloc->address;
18083           break;
18084         }
18085     }
18086   else if (HAVE_IN_PLACE_ADDENDS
18087            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
18088            && (read_compressed_insn (fixp->fx_frag->fr_literal
18089                                      + fixp->fx_where, 4) >> 26) == 0x3c)
18090     {
18091       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
18092          addend accordingly.  */
18093       reloc->addend = fixp->fx_addnumber >> 1;
18094     }
18095   else
18096     reloc->addend = fixp->fx_addnumber;
18097
18098   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18099      entry to be used in the relocation's section offset.  */
18100   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18101     {
18102       reloc->address = reloc->addend;
18103       reloc->addend = 0;
18104     }
18105
18106   code = fixp->fx_r_type;
18107
18108   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18109   if (reloc->howto == NULL)
18110     {
18111       as_bad_where (fixp->fx_file, fixp->fx_line,
18112                     _("cannot represent %s relocation in this object file"
18113                       " format"),
18114                     bfd_get_reloc_code_name (code));
18115       retval[0] = NULL;
18116     }
18117
18118   return retval;
18119 }
18120
18121 /* Relax a machine dependent frag.  This returns the amount by which
18122    the current size of the frag should change.  */
18123
18124 int
18125 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18126 {
18127   if (RELAX_BRANCH_P (fragp->fr_subtype))
18128     {
18129       offsetT old_var = fragp->fr_var;
18130
18131       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
18132
18133       return fragp->fr_var - old_var;
18134     }
18135
18136   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18137     {
18138       offsetT old_var = fragp->fr_var;
18139       offsetT new_var = 4;
18140
18141       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18142         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
18143       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18144         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
18145       fragp->fr_var = new_var;
18146
18147       return new_var - old_var;
18148     }
18149
18150   if (! RELAX_MIPS16_P (fragp->fr_subtype))
18151     return 0;
18152
18153   if (!mips16_extended_frag (fragp, sec, stretch))
18154     {
18155       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18156         {
18157           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18158           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -6 : -10;
18159         }
18160       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18161         {
18162           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18163           return -2;
18164         }
18165       else
18166         return 0;
18167     }
18168   else if (!mips16_macro_frag (fragp, sec, stretch))
18169     {
18170       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18171         {
18172           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18173           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18174           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -4 : -8;
18175         }
18176       else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18177         {
18178           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18179           return 2;
18180         }
18181       else
18182         return 0;
18183     }
18184   else
18185     {
18186       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18187         return 0;
18188       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18189         {
18190           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18191           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18192           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 4 : 8;
18193         }
18194       else
18195         {
18196           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18197           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 6 : 10;
18198         }
18199     }
18200
18201   return 0;
18202 }
18203
18204 /* Convert a machine dependent frag.  */
18205
18206 void
18207 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18208 {
18209   if (RELAX_BRANCH_P (fragp->fr_subtype))
18210     {
18211       char *buf;
18212       unsigned long insn;
18213       fixS *fixp;
18214
18215       buf = fragp->fr_literal + fragp->fr_fix;
18216       insn = read_insn (buf);
18217
18218       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18219         {
18220           /* We generate a fixup instead of applying it right now
18221              because, if there are linker relaxations, we're going to
18222              need the relocations.  */
18223           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18224                           fragp->fr_symbol, fragp->fr_offset,
18225                           TRUE, BFD_RELOC_16_PCREL_S2);
18226           fixp->fx_file = fragp->fr_file;
18227           fixp->fx_line = fragp->fr_line;
18228
18229           buf = write_insn (buf, insn);
18230         }
18231       else
18232         {
18233           int i;
18234
18235           as_warn_where (fragp->fr_file, fragp->fr_line,
18236                          _("relaxed out-of-range branch into a jump"));
18237
18238           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18239             goto uncond;
18240
18241           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18242             {
18243               /* Reverse the branch.  */
18244               switch ((insn >> 28) & 0xf)
18245                 {
18246                 case 4:
18247                   if ((insn & 0xff000000) == 0x47000000
18248                       || (insn & 0xff600000) == 0x45600000)
18249                     {
18250                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18251                          reversed by tweaking bit 23.  */
18252                       insn ^= 0x00800000;
18253                     }
18254                   else
18255                     {
18256                       /* bc[0-3][tf]l? instructions can have the condition
18257                          reversed by tweaking a single TF bit, and their
18258                          opcodes all have 0x4???????.  */
18259                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
18260                       insn ^= 0x00010000;
18261                     }
18262                   break;
18263
18264                 case 0:
18265                   /* bltz       0x04000000      bgez    0x04010000
18266                      bltzal     0x04100000      bgezal  0x04110000  */
18267                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18268                   insn ^= 0x00010000;
18269                   break;
18270
18271                 case 1:
18272                   /* beq        0x10000000      bne     0x14000000
18273                      blez       0x18000000      bgtz    0x1c000000  */
18274                   insn ^= 0x04000000;
18275                   break;
18276
18277                 default:
18278                   abort ();
18279                 }
18280             }
18281
18282           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18283             {
18284               /* Clear the and-link bit.  */
18285               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18286
18287               /* bltzal         0x04100000      bgezal  0x04110000
18288                  bltzall        0x04120000      bgezall 0x04130000  */
18289               insn &= ~0x00100000;
18290             }
18291
18292           /* Branch over the branch (if the branch was likely) or the
18293              full jump (not likely case).  Compute the offset from the
18294              current instruction to branch to.  */
18295           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18296             i = 16;
18297           else
18298             {
18299               /* How many bytes in instructions we've already emitted?  */
18300               i = buf - fragp->fr_literal - fragp->fr_fix;
18301               /* How many bytes in instructions from here to the end?  */
18302               i = fragp->fr_var - i;
18303             }
18304           /* Convert to instruction count.  */
18305           i >>= 2;
18306           /* Branch counts from the next instruction.  */
18307           i--;
18308           insn |= i;
18309           /* Branch over the jump.  */
18310           buf = write_insn (buf, insn);
18311
18312           /* nop */
18313           buf = write_insn (buf, 0);
18314
18315           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18316             {
18317               /* beql $0, $0, 2f */
18318               insn = 0x50000000;
18319               /* Compute the PC offset from the current instruction to
18320                  the end of the variable frag.  */
18321               /* How many bytes in instructions we've already emitted?  */
18322               i = buf - fragp->fr_literal - fragp->fr_fix;
18323               /* How many bytes in instructions from here to the end?  */
18324               i = fragp->fr_var - i;
18325               /* Convert to instruction count.  */
18326               i >>= 2;
18327               /* Don't decrement i, because we want to branch over the
18328                  delay slot.  */
18329               insn |= i;
18330
18331               buf = write_insn (buf, insn);
18332               buf = write_insn (buf, 0);
18333             }
18334
18335         uncond:
18336           if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18337             {
18338               /* j or jal.  */
18339               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18340                       ? 0x0c000000 : 0x08000000);
18341
18342               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18343                               fragp->fr_symbol, fragp->fr_offset,
18344                               FALSE, BFD_RELOC_MIPS_JMP);
18345               fixp->fx_file = fragp->fr_file;
18346               fixp->fx_line = fragp->fr_line;
18347
18348               buf = write_insn (buf, insn);
18349             }
18350           else
18351             {
18352               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18353
18354               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18355               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18356               insn |= at << OP_SH_RT;
18357
18358               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18359                               fragp->fr_symbol, fragp->fr_offset,
18360                               FALSE, BFD_RELOC_MIPS_GOT16);
18361               fixp->fx_file = fragp->fr_file;
18362               fixp->fx_line = fragp->fr_line;
18363
18364               buf = write_insn (buf, insn);
18365
18366               if (mips_opts.isa == ISA_MIPS1)
18367                 /* nop */
18368                 buf = write_insn (buf, 0);
18369
18370               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18371               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18372               insn |= at << OP_SH_RS | at << OP_SH_RT;
18373
18374               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18375                               fragp->fr_symbol, fragp->fr_offset,
18376                               FALSE, BFD_RELOC_LO16);
18377               fixp->fx_file = fragp->fr_file;
18378               fixp->fx_line = fragp->fr_line;
18379
18380               buf = write_insn (buf, insn);
18381
18382               /* j(al)r $at.  */
18383               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18384                 insn = 0x0000f809;
18385               else
18386                 insn = 0x00000008;
18387               insn |= at << OP_SH_RS;
18388
18389               buf = write_insn (buf, insn);
18390             }
18391         }
18392
18393       fragp->fr_fix += fragp->fr_var;
18394       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18395       return;
18396     }
18397
18398   /* Relax microMIPS branches.  */
18399   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18400     {
18401       char *buf = fragp->fr_literal + fragp->fr_fix;
18402       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18403       bfd_boolean insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18404       bfd_boolean nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18405       bfd_boolean pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18406       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18407       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18408       bfd_boolean short_ds;
18409       unsigned long insn;
18410       fixS *fixp;
18411
18412       fragp->fr_fix += fragp->fr_var;
18413
18414       /* Handle 16-bit branches that fit or are forced to fit.  */
18415       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18416         {
18417           /* We generate a fixup instead of applying it right now,
18418              because if there is linker relaxation, we're going to
18419              need the relocations.  */
18420           switch (type)
18421             {
18422             case 'D':
18423               fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18424                               fragp->fr_symbol, fragp->fr_offset,
18425                               TRUE, BFD_RELOC_MICROMIPS_10_PCREL_S1);
18426               break;
18427             case 'E':
18428               fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18429                               fragp->fr_symbol, fragp->fr_offset,
18430                               TRUE, BFD_RELOC_MICROMIPS_7_PCREL_S1);
18431               break;
18432             default:
18433               abort ();
18434             }
18435
18436           fixp->fx_file = fragp->fr_file;
18437           fixp->fx_line = fragp->fr_line;
18438
18439           /* These relocations can have an addend that won't fit in
18440              2 octets.  */
18441           fixp->fx_no_overflow = 1;
18442
18443           return;
18444         }
18445
18446       /* Handle 32-bit branches that fit or are forced to fit.  */
18447       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18448           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18449         {
18450           /* We generate a fixup instead of applying it right now,
18451              because if there is linker relaxation, we're going to
18452              need the relocations.  */
18453           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18454                           fragp->fr_symbol, fragp->fr_offset,
18455                           TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
18456           fixp->fx_file = fragp->fr_file;
18457           fixp->fx_line = fragp->fr_line;
18458
18459           if (type == 0)
18460             {
18461               insn = read_compressed_insn (buf, 4);
18462               buf += 4;
18463
18464               if (nods)
18465                 {
18466                   /* Check the short-delay-slot bit.  */
18467                   if (!al || (insn & 0x02000000) != 0)
18468                     buf = write_compressed_insn (buf, 0x0c00, 2);
18469                   else
18470                     buf = write_compressed_insn (buf, 0x00000000, 4);
18471                 }
18472
18473               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18474               return;
18475             }
18476         }
18477
18478       /* Relax 16-bit branches to 32-bit branches.  */
18479       if (type != 0)
18480         {
18481           insn = read_compressed_insn (buf, 2);
18482
18483           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18484             insn = 0x94000000;                          /* beq  */
18485           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18486             {
18487               unsigned long regno;
18488
18489               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18490               regno = micromips_to_32_reg_d_map [regno];
18491               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18492               insn |= regno << MICROMIPSOP_SH_RS;
18493             }
18494           else
18495             abort ();
18496
18497           /* Nothing else to do, just write it out.  */
18498           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18499               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18500             {
18501               buf = write_compressed_insn (buf, insn, 4);
18502               if (nods)
18503                 buf = write_compressed_insn (buf, 0x0c00, 2);
18504               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18505               return;
18506             }
18507         }
18508       else
18509         insn = read_compressed_insn (buf, 4);
18510
18511       /* Relax 32-bit branches to a sequence of instructions.  */
18512       as_warn_where (fragp->fr_file, fragp->fr_line,
18513                      _("relaxed out-of-range branch into a jump"));
18514
18515       /* Set the short-delay-slot bit.  */
18516       short_ds = !al || (insn & 0x02000000) != 0;
18517
18518       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18519         {
18520           symbolS *l;
18521
18522           /* Reverse the branch.  */
18523           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18524               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18525             insn ^= 0x20000000;
18526           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18527                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18528                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18529                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18530                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18531                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18532                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18533                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18534                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18535                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18536             insn ^= 0x00400000;
18537           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18538                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18539                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18540                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18541             insn ^= 0x00200000;
18542           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
18543                                                                    BNZ.df  */
18544                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
18545                                                                    BNZ.V */
18546             insn ^= 0x00800000;
18547           else
18548             abort ();
18549
18550           if (al)
18551             {
18552               /* Clear the and-link and short-delay-slot bits.  */
18553               gas_assert ((insn & 0xfda00000) == 0x40200000);
18554
18555               /* bltzal  0x40200000     bgezal  0x40600000  */
18556               /* bltzals 0x42200000     bgezals 0x42600000  */
18557               insn &= ~0x02200000;
18558             }
18559
18560           /* Make a label at the end for use with the branch.  */
18561           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18562           micromips_label_inc ();
18563           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18564
18565           /* Refer to it.  */
18566           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18567                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18568           fixp->fx_file = fragp->fr_file;
18569           fixp->fx_line = fragp->fr_line;
18570
18571           /* Branch over the jump.  */
18572           buf = write_compressed_insn (buf, insn, 4);
18573
18574           if (!compact)
18575             {
18576               /* nop  */
18577               if (insn32)
18578                 buf = write_compressed_insn (buf, 0x00000000, 4);
18579               else
18580                 buf = write_compressed_insn (buf, 0x0c00, 2);
18581             }
18582         }
18583
18584       if (!pic)
18585         {
18586           unsigned long jal = (short_ds || nods
18587                                ? 0x74000000 : 0xf4000000);      /* jal/s  */
18588
18589           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18590           insn = al ? jal : 0xd4000000;
18591
18592           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18593                           fragp->fr_symbol, fragp->fr_offset,
18594                           FALSE, BFD_RELOC_MICROMIPS_JMP);
18595           fixp->fx_file = fragp->fr_file;
18596           fixp->fx_line = fragp->fr_line;
18597
18598           buf = write_compressed_insn (buf, insn, 4);
18599
18600           if (compact || nods)
18601             {
18602               /* nop  */
18603               if (insn32)
18604                 buf = write_compressed_insn (buf, 0x00000000, 4);
18605               else
18606                 buf = write_compressed_insn (buf, 0x0c00, 2);
18607             }
18608         }
18609       else
18610         {
18611           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18612
18613           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18614           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18615           insn |= at << MICROMIPSOP_SH_RT;
18616
18617           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18618                           fragp->fr_symbol, fragp->fr_offset,
18619                           FALSE, BFD_RELOC_MICROMIPS_GOT16);
18620           fixp->fx_file = fragp->fr_file;
18621           fixp->fx_line = fragp->fr_line;
18622
18623           buf = write_compressed_insn (buf, insn, 4);
18624
18625           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18626           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18627           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18628
18629           fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18630                           fragp->fr_symbol, fragp->fr_offset,
18631                           FALSE, BFD_RELOC_MICROMIPS_LO16);
18632           fixp->fx_file = fragp->fr_file;
18633           fixp->fx_line = fragp->fr_line;
18634
18635           buf = write_compressed_insn (buf, insn, 4);
18636
18637           if (insn32)
18638             {
18639               /* jr/jalr $at  */
18640               insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
18641               insn |= at << MICROMIPSOP_SH_RS;
18642
18643               buf = write_compressed_insn (buf, insn, 4);
18644
18645               if (compact || nods)
18646                 /* nop  */
18647                 buf = write_compressed_insn (buf, 0x00000000, 4);
18648             }
18649           else
18650             {
18651               /* jr/jrc/jalr/jalrs $at  */
18652               unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;  /* jalr/s  */
18653               unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
18654
18655               insn = al ? jalr : jr;
18656               insn |= at << MICROMIPSOP_SH_MJ;
18657
18658               buf = write_compressed_insn (buf, insn, 2);
18659               if (al && nods)
18660                 {
18661                   /* nop  */
18662                   if (short_ds)
18663                     buf = write_compressed_insn (buf, 0x0c00, 2);
18664                   else
18665                     buf = write_compressed_insn (buf, 0x00000000, 4);
18666                 }
18667             }
18668         }
18669
18670       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18671       return;
18672     }
18673
18674   if (RELAX_MIPS16_P (fragp->fr_subtype))
18675     {
18676       int type;
18677       const struct mips_int_operand *operand;
18678       offsetT val;
18679       char *buf;
18680       unsigned int user_length;
18681       bfd_boolean need_reloc;
18682       unsigned long insn;
18683       bfd_boolean mac;
18684       bfd_boolean ext;
18685       segT symsec;
18686
18687       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18688       operand = mips16_immed_operand (type, FALSE);
18689
18690       mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
18691       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18692       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18693
18694       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18695       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18696                     || (operand->root.type == OP_PCREL && !mac
18697                         ? asec != symsec
18698                         : !bfd_is_abs_section (symsec)));
18699
18700       if (operand->root.type == OP_PCREL && !mac)
18701         {
18702           const struct mips_pcrel_operand *pcrel_op;
18703
18704           pcrel_op = (const struct mips_pcrel_operand *) operand;
18705
18706           if (pcrel_op->include_isa_bit && !need_reloc)
18707             {
18708               if (!mips_ignore_branch_isa
18709                   && !ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18710                 as_bad_where (fragp->fr_file, fragp->fr_line,
18711                               _("branch to a symbol in another ISA mode"));
18712               else if ((fragp->fr_offset & 0x1) != 0)
18713                 as_bad_where (fragp->fr_file, fragp->fr_line,
18714                               _("branch to misaligned address (0x%lx)"),
18715                               (long) val);
18716             }
18717
18718           val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
18719
18720           /* Make sure the section winds up with the alignment we have
18721              assumed.  */
18722           if (operand->shift > 0)
18723             record_alignment (asec, operand->shift);
18724         }
18725
18726       if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18727           || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18728         {
18729           if (mac)
18730             as_warn_where (fragp->fr_file, fragp->fr_line,
18731                            _("macro instruction expanded into multiple "
18732                              "instructions in a branch delay slot"));
18733           else if (ext)
18734             as_warn_where (fragp->fr_file, fragp->fr_line,
18735                            _("extended instruction in a branch delay slot"));
18736         }
18737       else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
18738         as_warn_where (fragp->fr_file, fragp->fr_line,
18739                        _("macro instruction expanded into multiple "
18740                          "instructions"));
18741
18742       buf = fragp->fr_literal + fragp->fr_fix;
18743
18744       insn = read_compressed_insn (buf, 2);
18745       if (ext)
18746         insn |= MIPS16_EXTEND;
18747
18748       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18749         user_length = 4;
18750       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18751         user_length = 2;
18752       else
18753         user_length = 0;
18754
18755       if (mac)
18756         {
18757           unsigned long reg;
18758           unsigned long new;
18759           unsigned long op;
18760           bfd_boolean e2;
18761
18762           gas_assert (type == 'A' || type == 'B' || type == 'E');
18763           gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
18764
18765           e2 = RELAX_MIPS16_E2 (fragp->fr_subtype);
18766
18767           if (need_reloc)
18768             {
18769               fixS *fixp;
18770
18771               gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
18772
18773               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18774                               fragp->fr_symbol, fragp->fr_offset,
18775                               FALSE, BFD_RELOC_MIPS16_HI16_S);
18776               fixp->fx_file = fragp->fr_file;
18777               fixp->fx_line = fragp->fr_line;
18778
18779               fixp = fix_new (fragp, buf - fragp->fr_literal + (e2 ? 4 : 8), 4,
18780                               fragp->fr_symbol, fragp->fr_offset,
18781                               FALSE, BFD_RELOC_MIPS16_LO16);
18782               fixp->fx_file = fragp->fr_file;
18783               fixp->fx_line = fragp->fr_line;
18784
18785               val = 0;
18786             }
18787
18788           switch (insn & 0xf800)
18789             {
18790             case 0x0800:                                        /* ADDIU */
18791               reg = (insn >> 8) & 0x7;
18792               op = 0xf0004800 | (reg << 8);
18793               break;
18794             case 0xb000:                                        /* LW */
18795               reg = (insn >> 8) & 0x7;
18796               op = 0xf0009800 | (reg << 8) | (reg << 5);
18797               break;
18798             case 0xf800:                                        /* I64 */
18799               reg = (insn >> 5) & 0x7;
18800               switch (insn & 0x0700)
18801                 {
18802                 case 0x0400:                                    /* LD */
18803                   op = 0xf0003800 | (reg << 8) | (reg << 5);
18804                   break;
18805                 case 0x0600:                                    /* DADDIU */
18806                   op = 0xf000fd00 | (reg << 5);
18807                   break;
18808                 default:
18809                   abort ();
18810                 }
18811               break;
18812             default:
18813               abort ();
18814             }
18815
18816           new = (e2 ? 0xf0006820 : 0xf0006800) | (reg << 8);    /* LUI/LI */
18817           new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
18818           buf = write_compressed_insn (buf, new, 4);
18819           if (!e2)
18820             {
18821               new = 0xf4003000 | (reg << 8) | (reg << 5);       /* SLL */
18822               buf = write_compressed_insn (buf, new, 4);
18823             }
18824           op |= mips16_immed_extend (val, 16);
18825           buf = write_compressed_insn (buf, op, 4);
18826
18827           fragp->fr_fix += e2 ? 8 : 12;
18828         }
18829       else
18830         {
18831           unsigned int length = ext ? 4 : 2;
18832
18833           if (need_reloc)
18834             {
18835               bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18836               fixS *fixp;
18837
18838               switch (type)
18839                 {
18840                 case 'p':
18841                 case 'q':
18842                   reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18843                   break;
18844                 default:
18845                   break;
18846                 }
18847               if (mac || reloc == BFD_RELOC_NONE)
18848                 as_bad_where (fragp->fr_file, fragp->fr_line,
18849                               _("unsupported relocation"));
18850               else if (ext)
18851                 {
18852                   fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18853                                   fragp->fr_symbol, fragp->fr_offset,
18854                                   TRUE, reloc);
18855                   fixp->fx_file = fragp->fr_file;
18856                   fixp->fx_line = fragp->fr_line;
18857                 }
18858               else
18859                 as_bad_where (fragp->fr_file, fragp->fr_line,
18860                               _("invalid unextended operand value"));
18861             }
18862           else
18863             mips16_immed (fragp->fr_file, fragp->fr_line, type,
18864                           BFD_RELOC_UNUSED, val, user_length, &insn);
18865
18866           gas_assert (mips16_opcode_length (insn) == length);
18867           write_compressed_insn (buf, insn, length);
18868           fragp->fr_fix += length;
18869         }
18870     }
18871   else
18872     {
18873       relax_substateT subtype = fragp->fr_subtype;
18874       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18875       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18876       int first, second;
18877       fixS *fixp;
18878
18879       first = RELAX_FIRST (subtype);
18880       second = RELAX_SECOND (subtype);
18881       fixp = (fixS *) fragp->fr_opcode;
18882
18883       /* If the delay slot chosen does not match the size of the instruction,
18884          then emit a warning.  */
18885       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18886            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18887         {
18888           relax_substateT s;
18889           const char *msg;
18890
18891           s = subtype & (RELAX_DELAY_SLOT_16BIT
18892                          | RELAX_DELAY_SLOT_SIZE_FIRST
18893                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18894           msg = macro_warning (s);
18895           if (msg != NULL)
18896             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18897           subtype &= ~s;
18898         }
18899
18900       /* Possibly emit a warning if we've chosen the longer option.  */
18901       if (use_second == second_longer)
18902         {
18903           relax_substateT s;
18904           const char *msg;
18905
18906           s = (subtype
18907                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18908           msg = macro_warning (s);
18909           if (msg != NULL)
18910             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18911           subtype &= ~s;
18912         }
18913
18914       /* Go through all the fixups for the first sequence.  Disable them
18915          (by marking them as done) if we're going to use the second
18916          sequence instead.  */
18917       while (fixp
18918              && fixp->fx_frag == fragp
18919              && fixp->fx_where < fragp->fr_fix - second)
18920         {
18921           if (subtype & RELAX_USE_SECOND)
18922             fixp->fx_done = 1;
18923           fixp = fixp->fx_next;
18924         }
18925
18926       /* Go through the fixups for the second sequence.  Disable them if
18927          we're going to use the first sequence, otherwise adjust their
18928          addresses to account for the relaxation.  */
18929       while (fixp && fixp->fx_frag == fragp)
18930         {
18931           if (subtype & RELAX_USE_SECOND)
18932             fixp->fx_where -= first;
18933           else
18934             fixp->fx_done = 1;
18935           fixp = fixp->fx_next;
18936         }
18937
18938       /* Now modify the frag contents.  */
18939       if (subtype & RELAX_USE_SECOND)
18940         {
18941           char *start;
18942
18943           start = fragp->fr_literal + fragp->fr_fix - first - second;
18944           memmove (start, start + first, second);
18945           fragp->fr_fix -= first;
18946         }
18947       else
18948         fragp->fr_fix -= second;
18949     }
18950 }
18951
18952 /* This function is called after the relocs have been generated.
18953    We've been storing mips16 text labels as odd.  Here we convert them
18954    back to even for the convenience of the debugger.  */
18955
18956 void
18957 mips_frob_file_after_relocs (void)
18958 {
18959   asymbol **syms;
18960   unsigned int count, i;
18961
18962   syms = bfd_get_outsymbols (stdoutput);
18963   count = bfd_get_symcount (stdoutput);
18964   for (i = 0; i < count; i++, syms++)
18965     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18966         && ((*syms)->value & 1) != 0)
18967       {
18968         (*syms)->value &= ~1;
18969         /* If the symbol has an odd size, it was probably computed
18970            incorrectly, so adjust that as well.  */
18971         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18972           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18973       }
18974 }
18975
18976 /* This function is called whenever a label is defined, including fake
18977    labels instantiated off the dot special symbol.  It is used when
18978    handling branch delays; if a branch has a label, we assume we cannot
18979    move it.  This also bumps the value of the symbol by 1 in compressed
18980    code.  */
18981
18982 static void
18983 mips_record_label (symbolS *sym)
18984 {
18985   segment_info_type *si = seg_info (now_seg);
18986   struct insn_label_list *l;
18987
18988   if (free_insn_labels == NULL)
18989     l = XNEW (struct insn_label_list);
18990   else
18991     {
18992       l = free_insn_labels;
18993       free_insn_labels = l->next;
18994     }
18995
18996   l->label = sym;
18997   l->next = si->label_list;
18998   si->label_list = l;
18999 }
19000
19001 /* This function is called as tc_frob_label() whenever a label is defined
19002    and adds a DWARF-2 record we only want for true labels.  */
19003
19004 void
19005 mips_define_label (symbolS *sym)
19006 {
19007   mips_record_label (sym);
19008   dwarf2_emit_label (sym);
19009 }
19010
19011 /* This function is called by tc_new_dot_label whenever a new dot symbol
19012    is defined.  */
19013
19014 void
19015 mips_add_dot_label (symbolS *sym)
19016 {
19017   mips_record_label (sym);
19018   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
19019     mips_compressed_mark_label (sym);
19020 }
19021 \f
19022 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
19023 static unsigned int
19024 mips_convert_ase_flags (int ase)
19025 {
19026   unsigned int ext_ases = 0;
19027
19028   if (ase & ASE_DSP)
19029     ext_ases |= AFL_ASE_DSP;
19030   if (ase & ASE_DSPR2)
19031     ext_ases |= AFL_ASE_DSPR2;
19032   if (ase & ASE_DSPR3)
19033     ext_ases |= AFL_ASE_DSPR3;
19034   if (ase & ASE_EVA)
19035     ext_ases |= AFL_ASE_EVA;
19036   if (ase & ASE_MCU)
19037     ext_ases |= AFL_ASE_MCU;
19038   if (ase & ASE_MDMX)
19039     ext_ases |= AFL_ASE_MDMX;
19040   if (ase & ASE_MIPS3D)
19041     ext_ases |= AFL_ASE_MIPS3D;
19042   if (ase & ASE_MT)
19043     ext_ases |= AFL_ASE_MT;
19044   if (ase & ASE_SMARTMIPS)
19045     ext_ases |= AFL_ASE_SMARTMIPS;
19046   if (ase & ASE_VIRT)
19047     ext_ases |= AFL_ASE_VIRT;
19048   if (ase & ASE_MSA)
19049     ext_ases |= AFL_ASE_MSA;
19050   if (ase & ASE_XPA)
19051     ext_ases |= AFL_ASE_XPA;
19052   if (ase & ASE_MIPS16E2)
19053     ext_ases |= file_ase_mips16 ? AFL_ASE_MIPS16E2 : 0;
19054   if (ase & ASE_CRC)
19055     ext_ases |= AFL_ASE_CRC;
19056   if (ase & ASE_GINV)
19057     ext_ases |= AFL_ASE_GINV;
19058   if (ase & ASE_LOONGSON_MMI)
19059     ext_ases |= AFL_ASE_LOONGSON_MMI;
19060   if (ase & ASE_LOONGSON_CAM)
19061     ext_ases |= AFL_ASE_LOONGSON_CAM;
19062   if (ase & ASE_LOONGSON_EXT)
19063     ext_ases |= AFL_ASE_LOONGSON_EXT;
19064   if (ase & ASE_LOONGSON_EXT2)
19065     ext_ases |= AFL_ASE_LOONGSON_EXT2;
19066
19067   return ext_ases;
19068 }
19069 /* Some special processing for a MIPS ELF file.  */
19070
19071 void
19072 mips_elf_final_processing (void)
19073 {
19074   int fpabi;
19075   Elf_Internal_ABIFlags_v0 flags;
19076
19077   flags.version = 0;
19078   flags.isa_rev = 0;
19079   switch (file_mips_opts.isa)
19080     {
19081     case INSN_ISA1:
19082       flags.isa_level = 1;
19083       break;
19084     case INSN_ISA2:
19085       flags.isa_level = 2;
19086       break;
19087     case INSN_ISA3:
19088       flags.isa_level = 3;
19089       break;
19090     case INSN_ISA4:
19091       flags.isa_level = 4;
19092       break;
19093     case INSN_ISA5:
19094       flags.isa_level = 5;
19095       break;
19096     case INSN_ISA32:
19097       flags.isa_level = 32;
19098       flags.isa_rev = 1;
19099       break;
19100     case INSN_ISA32R2:
19101       flags.isa_level = 32;
19102       flags.isa_rev = 2;
19103       break;
19104     case INSN_ISA32R3:
19105       flags.isa_level = 32;
19106       flags.isa_rev = 3;
19107       break;
19108     case INSN_ISA32R5:
19109       flags.isa_level = 32;
19110       flags.isa_rev = 5;
19111       break;
19112     case INSN_ISA32R6:
19113       flags.isa_level = 32;
19114       flags.isa_rev = 6;
19115       break;
19116     case INSN_ISA64:
19117       flags.isa_level = 64;
19118       flags.isa_rev = 1;
19119       break;
19120     case INSN_ISA64R2:
19121       flags.isa_level = 64;
19122       flags.isa_rev = 2;
19123       break;
19124     case INSN_ISA64R3:
19125       flags.isa_level = 64;
19126       flags.isa_rev = 3;
19127       break;
19128     case INSN_ISA64R5:
19129       flags.isa_level = 64;
19130       flags.isa_rev = 5;
19131       break;
19132     case INSN_ISA64R6:
19133       flags.isa_level = 64;
19134       flags.isa_rev = 6;
19135       break;
19136     }
19137
19138   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
19139   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
19140                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
19141                     : (file_mips_opts.fp == 64) ? AFL_REG_64
19142                     : AFL_REG_32;
19143   flags.cpr2_size = AFL_REG_NONE;
19144   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19145                                            Tag_GNU_MIPS_ABI_FP);
19146   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
19147   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
19148   if (file_ase_mips16)
19149     flags.ases |= AFL_ASE_MIPS16;
19150   if (file_ase_micromips)
19151     flags.ases |= AFL_ASE_MICROMIPS;
19152   flags.flags1 = 0;
19153   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
19154        || file_mips_opts.fp == 64)
19155       && file_mips_opts.oddspreg)
19156     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
19157   flags.flags2 = 0;
19158
19159   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
19160                                      ((Elf_External_ABIFlags_v0 *)
19161                                      mips_flags_frag));
19162
19163   /* Write out the register information.  */
19164   if (mips_abi != N64_ABI)
19165     {
19166       Elf32_RegInfo s;
19167
19168       s.ri_gprmask = mips_gprmask;
19169       s.ri_cprmask[0] = mips_cprmask[0];
19170       s.ri_cprmask[1] = mips_cprmask[1];
19171       s.ri_cprmask[2] = mips_cprmask[2];
19172       s.ri_cprmask[3] = mips_cprmask[3];
19173       /* The gp_value field is set by the MIPS ELF backend.  */
19174
19175       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
19176                                        ((Elf32_External_RegInfo *)
19177                                         mips_regmask_frag));
19178     }
19179   else
19180     {
19181       Elf64_Internal_RegInfo s;
19182
19183       s.ri_gprmask = mips_gprmask;
19184       s.ri_pad = 0;
19185       s.ri_cprmask[0] = mips_cprmask[0];
19186       s.ri_cprmask[1] = mips_cprmask[1];
19187       s.ri_cprmask[2] = mips_cprmask[2];
19188       s.ri_cprmask[3] = mips_cprmask[3];
19189       /* The gp_value field is set by the MIPS ELF backend.  */
19190
19191       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
19192                                        ((Elf64_External_RegInfo *)
19193                                         mips_regmask_frag));
19194     }
19195
19196   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
19197      sort of BFD interface for this.  */
19198   if (mips_any_noreorder)
19199     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
19200   if (mips_pic != NO_PIC)
19201     {
19202       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19203       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19204     }
19205   if (mips_abicalls)
19206     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19207
19208   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19209      defined at present; this might need to change in future.  */
19210   if (file_ase_mips16)
19211     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19212   if (file_ase_micromips)
19213     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19214   if (file_mips_opts.ase & ASE_MDMX)
19215     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19216
19217   /* Set the MIPS ELF ABI flags.  */
19218   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19219     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19220   else if (mips_abi == O64_ABI)
19221     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19222   else if (mips_abi == EABI_ABI)
19223     {
19224       if (file_mips_opts.gp == 64)
19225         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19226       else
19227         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19228     }
19229
19230   /* Nothing to do for N32_ABI or N64_ABI.  */
19231
19232   if (mips_32bitmode)
19233     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19234
19235   if (mips_nan2008 == 1)
19236     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19237
19238   /* 32 bit code with 64 bit FP registers.  */
19239   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19240                                     Tag_GNU_MIPS_ABI_FP);
19241   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19242     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19243 }
19244 \f
19245 typedef struct proc {
19246   symbolS *func_sym;
19247   symbolS *func_end_sym;
19248   unsigned long reg_mask;
19249   unsigned long reg_offset;
19250   unsigned long fpreg_mask;
19251   unsigned long fpreg_offset;
19252   unsigned long frame_offset;
19253   unsigned long frame_reg;
19254   unsigned long pc_reg;
19255 } procS;
19256
19257 static procS cur_proc;
19258 static procS *cur_proc_ptr;
19259 static int numprocs;
19260
19261 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19262    as "2", and a normal nop as "0".  */
19263
19264 #define NOP_OPCODE_MIPS         0
19265 #define NOP_OPCODE_MIPS16       1
19266 #define NOP_OPCODE_MICROMIPS    2
19267
19268 char
19269 mips_nop_opcode (void)
19270 {
19271   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19272     return NOP_OPCODE_MICROMIPS;
19273   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19274     return NOP_OPCODE_MIPS16;
19275   else
19276     return NOP_OPCODE_MIPS;
19277 }
19278
19279 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19280    32-bit microMIPS NOPs here (if applicable).  */
19281
19282 void
19283 mips_handle_align (fragS *fragp)
19284 {
19285   char nop_opcode;
19286   char *p;
19287   int bytes, size, excess;
19288   valueT opcode;
19289
19290   if (fragp->fr_type != rs_align_code)
19291     return;
19292
19293   p = fragp->fr_literal + fragp->fr_fix;
19294   nop_opcode = *p;
19295   switch (nop_opcode)
19296     {
19297     case NOP_OPCODE_MICROMIPS:
19298       opcode = micromips_nop32_insn.insn_opcode;
19299       size = 4;
19300       break;
19301     case NOP_OPCODE_MIPS16:
19302       opcode = mips16_nop_insn.insn_opcode;
19303       size = 2;
19304       break;
19305     case NOP_OPCODE_MIPS:
19306     default:
19307       opcode = nop_insn.insn_opcode;
19308       size = 4;
19309       break;
19310     }
19311
19312   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19313   excess = bytes % size;
19314
19315   /* Handle the leading part if we're not inserting a whole number of
19316      instructions, and make it the end of the fixed part of the frag.
19317      Try to fit in a short microMIPS NOP if applicable and possible,
19318      and use zeroes otherwise.  */
19319   gas_assert (excess < 4);
19320   fragp->fr_fix += excess;
19321   switch (excess)
19322     {
19323     case 3:
19324       *p++ = '\0';
19325       /* Fall through.  */
19326     case 2:
19327       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19328         {
19329           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19330           break;
19331         }
19332       *p++ = '\0';
19333       /* Fall through.  */
19334     case 1:
19335       *p++ = '\0';
19336       /* Fall through.  */
19337     case 0:
19338       break;
19339     }
19340
19341   md_number_to_chars (p, opcode, size);
19342   fragp->fr_var = size;
19343 }
19344
19345 static long
19346 get_number (void)
19347 {
19348   int negative = 0;
19349   long val = 0;
19350
19351   if (*input_line_pointer == '-')
19352     {
19353       ++input_line_pointer;
19354       negative = 1;
19355     }
19356   if (!ISDIGIT (*input_line_pointer))
19357     as_bad (_("expected simple number"));
19358   if (input_line_pointer[0] == '0')
19359     {
19360       if (input_line_pointer[1] == 'x')
19361         {
19362           input_line_pointer += 2;
19363           while (ISXDIGIT (*input_line_pointer))
19364             {
19365               val <<= 4;
19366               val |= hex_value (*input_line_pointer++);
19367             }
19368           return negative ? -val : val;
19369         }
19370       else
19371         {
19372           ++input_line_pointer;
19373           while (ISDIGIT (*input_line_pointer))
19374             {
19375               val <<= 3;
19376               val |= *input_line_pointer++ - '0';
19377             }
19378           return negative ? -val : val;
19379         }
19380     }
19381   if (!ISDIGIT (*input_line_pointer))
19382     {
19383       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19384               *input_line_pointer, *input_line_pointer);
19385       as_warn (_("invalid number"));
19386       return -1;
19387     }
19388   while (ISDIGIT (*input_line_pointer))
19389     {
19390       val *= 10;
19391       val += *input_line_pointer++ - '0';
19392     }
19393   return negative ? -val : val;
19394 }
19395
19396 /* The .file directive; just like the usual .file directive, but there
19397    is an initial number which is the ECOFF file index.  In the non-ECOFF
19398    case .file implies DWARF-2.  */
19399
19400 static void
19401 s_mips_file (int x ATTRIBUTE_UNUSED)
19402 {
19403   static int first_file_directive = 0;
19404
19405   if (ECOFF_DEBUGGING)
19406     {
19407       get_number ();
19408       s_app_file (0);
19409     }
19410   else
19411     {
19412       char *filename;
19413
19414       filename = dwarf2_directive_filename ();
19415
19416       /* Versions of GCC up to 3.1 start files with a ".file"
19417          directive even for stabs output.  Make sure that this
19418          ".file" is handled.  Note that you need a version of GCC
19419          after 3.1 in order to support DWARF-2 on MIPS.  */
19420       if (filename != NULL && ! first_file_directive)
19421         {
19422           (void) new_logical_line (filename, -1);
19423           s_app_file_string (filename, 0);
19424         }
19425       first_file_directive = 1;
19426     }
19427 }
19428
19429 /* The .loc directive, implying DWARF-2.  */
19430
19431 static void
19432 s_mips_loc (int x ATTRIBUTE_UNUSED)
19433 {
19434   if (!ECOFF_DEBUGGING)
19435     dwarf2_directive_loc (0);
19436 }
19437
19438 /* The .end directive.  */
19439
19440 static void
19441 s_mips_end (int x ATTRIBUTE_UNUSED)
19442 {
19443   symbolS *p;
19444
19445   /* Following functions need their own .frame and .cprestore directives.  */
19446   mips_frame_reg_valid = 0;
19447   mips_cprestore_valid = 0;
19448
19449   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19450     {
19451       p = get_symbol ();
19452       demand_empty_rest_of_line ();
19453     }
19454   else
19455     p = NULL;
19456
19457   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19458     as_warn (_(".end not in text section"));
19459
19460   if (!cur_proc_ptr)
19461     {
19462       as_warn (_(".end directive without a preceding .ent directive"));
19463       demand_empty_rest_of_line ();
19464       return;
19465     }
19466
19467   if (p != NULL)
19468     {
19469       gas_assert (S_GET_NAME (p));
19470       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19471         as_warn (_(".end symbol does not match .ent symbol"));
19472
19473       if (debug_type == DEBUG_STABS)
19474         stabs_generate_asm_endfunc (S_GET_NAME (p),
19475                                     S_GET_NAME (p));
19476     }
19477   else
19478     as_warn (_(".end directive missing or unknown symbol"));
19479
19480   /* Create an expression to calculate the size of the function.  */
19481   if (p && cur_proc_ptr)
19482     {
19483       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19484       expressionS *exp = XNEW (expressionS);
19485
19486       obj->size = exp;
19487       exp->X_op = O_subtract;
19488       exp->X_add_symbol = symbol_temp_new_now ();
19489       exp->X_op_symbol = p;
19490       exp->X_add_number = 0;
19491
19492       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19493     }
19494
19495 #ifdef md_flush_pending_output
19496   md_flush_pending_output ();
19497 #endif
19498
19499   /* Generate a .pdr section.  */
19500   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19501     {
19502       segT saved_seg = now_seg;
19503       subsegT saved_subseg = now_subseg;
19504       expressionS exp;
19505       char *fragp;
19506
19507       gas_assert (pdr_seg);
19508       subseg_set (pdr_seg, 0);
19509
19510       /* Write the symbol.  */
19511       exp.X_op = O_symbol;
19512       exp.X_add_symbol = p;
19513       exp.X_add_number = 0;
19514       emit_expr (&exp, 4);
19515
19516       fragp = frag_more (7 * 4);
19517
19518       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19519       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19520       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19521       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19522       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19523       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19524       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19525
19526       subseg_set (saved_seg, saved_subseg);
19527     }
19528
19529   cur_proc_ptr = NULL;
19530 }
19531
19532 /* The .aent and .ent directives.  */
19533
19534 static void
19535 s_mips_ent (int aent)
19536 {
19537   symbolS *symbolP;
19538
19539   symbolP = get_symbol ();
19540   if (*input_line_pointer == ',')
19541     ++input_line_pointer;
19542   SKIP_WHITESPACE ();
19543   if (ISDIGIT (*input_line_pointer)
19544       || *input_line_pointer == '-')
19545     get_number ();
19546
19547   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19548     as_warn (_(".ent or .aent not in text section"));
19549
19550   if (!aent && cur_proc_ptr)
19551     as_warn (_("missing .end"));
19552
19553   if (!aent)
19554     {
19555       /* This function needs its own .frame and .cprestore directives.  */
19556       mips_frame_reg_valid = 0;
19557       mips_cprestore_valid = 0;
19558
19559       cur_proc_ptr = &cur_proc;
19560       memset (cur_proc_ptr, '\0', sizeof (procS));
19561
19562       cur_proc_ptr->func_sym = symbolP;
19563
19564       ++numprocs;
19565
19566       if (debug_type == DEBUG_STABS)
19567         stabs_generate_asm_func (S_GET_NAME (symbolP),
19568                                  S_GET_NAME (symbolP));
19569     }
19570
19571   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19572
19573   demand_empty_rest_of_line ();
19574 }
19575
19576 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19577    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19578    s_mips_frame is used so that we can set the PDR information correctly.
19579    We can't use the ecoff routines because they make reference to the ecoff
19580    symbol table (in the mdebug section).  */
19581
19582 static void
19583 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19584 {
19585   if (ECOFF_DEBUGGING)
19586     s_ignore (ignore);
19587   else
19588     {
19589       long val;
19590
19591       if (cur_proc_ptr == (procS *) NULL)
19592         {
19593           as_warn (_(".frame outside of .ent"));
19594           demand_empty_rest_of_line ();
19595           return;
19596         }
19597
19598       cur_proc_ptr->frame_reg = tc_get_register (1);
19599
19600       SKIP_WHITESPACE ();
19601       if (*input_line_pointer++ != ','
19602           || get_absolute_expression_and_terminator (&val) != ',')
19603         {
19604           as_warn (_("bad .frame directive"));
19605           --input_line_pointer;
19606           demand_empty_rest_of_line ();
19607           return;
19608         }
19609
19610       cur_proc_ptr->frame_offset = val;
19611       cur_proc_ptr->pc_reg = tc_get_register (0);
19612
19613       demand_empty_rest_of_line ();
19614     }
19615 }
19616
19617 /* The .fmask and .mask directives. If the mdebug section is present
19618    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19619    embedded targets, s_mips_mask is used so that we can set the PDR
19620    information correctly. We can't use the ecoff routines because they
19621    make reference to the ecoff symbol table (in the mdebug section).  */
19622
19623 static void
19624 s_mips_mask (int reg_type)
19625 {
19626   if (ECOFF_DEBUGGING)
19627     s_ignore (reg_type);
19628   else
19629     {
19630       long mask, off;
19631
19632       if (cur_proc_ptr == (procS *) NULL)
19633         {
19634           as_warn (_(".mask/.fmask outside of .ent"));
19635           demand_empty_rest_of_line ();
19636           return;
19637         }
19638
19639       if (get_absolute_expression_and_terminator (&mask) != ',')
19640         {
19641           as_warn (_("bad .mask/.fmask directive"));
19642           --input_line_pointer;
19643           demand_empty_rest_of_line ();
19644           return;
19645         }
19646
19647       off = get_absolute_expression ();
19648
19649       if (reg_type == 'F')
19650         {
19651           cur_proc_ptr->fpreg_mask = mask;
19652           cur_proc_ptr->fpreg_offset = off;
19653         }
19654       else
19655         {
19656           cur_proc_ptr->reg_mask = mask;
19657           cur_proc_ptr->reg_offset = off;
19658         }
19659
19660       demand_empty_rest_of_line ();
19661     }
19662 }
19663
19664 /* A table describing all the processors gas knows about.  Names are
19665    matched in the order listed.
19666
19667    To ease comparison, please keep this table in the same order as
19668    gcc's mips_cpu_info_table[].  */
19669 static const struct mips_cpu_info mips_cpu_info_table[] =
19670 {
19671   /* Entries for generic ISAs */
19672   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19673   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19674   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19675   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19676   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19677   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19678   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19679   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
19680   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
19681   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
19682   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19683   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19684   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
19685   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
19686   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
19687
19688   /* MIPS I */
19689   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19690   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19691   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19692
19693   /* MIPS II */
19694   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19695
19696   /* MIPS III */
19697   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19698   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19699   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19700   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19701   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19702   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19703   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19704   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19705   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19706   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19707   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19708   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19709   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19710   /* ST Microelectronics Loongson 2E and 2F cores */
19711   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19712   { "loongson2f",     0, ASE_LOONGSON_MMI,      ISA_MIPS3,    CPU_LOONGSON_2F },
19713
19714   /* MIPS IV */
19715   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19716   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19717   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19718   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19719   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19720   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19721   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19722   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19723   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19724   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19725   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19726   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19727   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19728   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19729   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19730
19731   /* MIPS 32 */
19732   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19733   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19734   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19735   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19736
19737   /* MIPS 32 Release 2 */
19738   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19739   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19740   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19741   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19742   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19743   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19744   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19745   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19746   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19747                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19748   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19749                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19750   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19751   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19752   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19753   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19754   /* Deprecated forms of the above.  */
19755   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19756   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19757   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19758   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19759   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19760   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19761   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19762   /* Deprecated forms of the above.  */
19763   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19764   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19765   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19766   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19767   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19768   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19769   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19770   /* Deprecated forms of the above.  */
19771   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19772   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19773   /* 34Kn is a 34kc without DSP.  */
19774   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19775   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19776   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19777   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19778   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19779   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19780   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19781   /* Deprecated forms of the above.  */
19782   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19783   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19784   /* 1004K cores are multiprocessor versions of the 34K.  */
19785   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19786   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19787   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19788   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19789   /* interaptiv is the new name for 1004kf */
19790   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19791   { "interaptiv-mr2", 0,
19792     ASE_DSP | ASE_EVA | ASE_MT | ASE_MIPS16E2 | ASE_MIPS16E2_MT,
19793     ISA_MIPS32R3, CPU_INTERAPTIV_MR2 },
19794   /* M5100 family */
19795   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19796   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19797   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19798   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19799
19800   /* MIPS 64 */
19801   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19802   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19803   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19804   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19805
19806   /* Broadcom SB-1 CPU core */
19807   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19808   /* Broadcom SB-1A CPU core */
19809   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19810
19811   /* MIPS 64 Release 2 */
19812   /* Loongson CPU core */
19813   /* -march=loongson3a is an alias of -march=gs464 for compatibility */
19814   { "loongson3a",     0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT,
19815      ISA_MIPS64R2,      CPU_GS464 },
19816   { "gs464",          0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT,
19817      ISA_MIPS64R2,      CPU_GS464 },
19818   { "gs464e",         0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT
19819      | ASE_LOONGSON_EXT2,       ISA_MIPS64R2,   CPU_GS464E },
19820
19821   /* Cavium Networks Octeon CPU core */
19822   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19823   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19824   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19825   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19826
19827   /* RMI Xlr */
19828   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19829
19830   /* Broadcom XLP.
19831      XLP is mostly like XLR, with the prominent exception that it is
19832      MIPS64R2 rather than MIPS64.  */
19833   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19834
19835   /* MIPS 64 Release 6 */
19836   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19837   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19838
19839   /* End marker */
19840   { NULL, 0, 0, 0, 0 }
19841 };
19842
19843
19844 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19845    with a final "000" replaced by "k".  Ignore case.
19846
19847    Note: this function is shared between GCC and GAS.  */
19848
19849 static bfd_boolean
19850 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19851 {
19852   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19853     given++, canonical++;
19854
19855   return ((*given == 0 && *canonical == 0)
19856           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19857 }
19858
19859
19860 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19861    CPU name.  We've traditionally allowed a lot of variation here.
19862
19863    Note: this function is shared between GCC and GAS.  */
19864
19865 static bfd_boolean
19866 mips_matching_cpu_name_p (const char *canonical, const char *given)
19867 {
19868   /* First see if the name matches exactly, or with a final "000"
19869      turned into "k".  */
19870   if (mips_strict_matching_cpu_name_p (canonical, given))
19871     return TRUE;
19872
19873   /* If not, try comparing based on numerical designation alone.
19874      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19875   if (TOLOWER (*given) == 'r')
19876     given++;
19877   if (!ISDIGIT (*given))
19878     return FALSE;
19879
19880   /* Skip over some well-known prefixes in the canonical name,
19881      hoping to find a number there too.  */
19882   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19883     canonical += 2;
19884   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19885     canonical += 2;
19886   else if (TOLOWER (canonical[0]) == 'r')
19887     canonical += 1;
19888
19889   return mips_strict_matching_cpu_name_p (canonical, given);
19890 }
19891
19892
19893 /* Parse an option that takes the name of a processor as its argument.
19894    OPTION is the name of the option and CPU_STRING is the argument.
19895    Return the corresponding processor enumeration if the CPU_STRING is
19896    recognized, otherwise report an error and return null.
19897
19898    A similar function exists in GCC.  */
19899
19900 static const struct mips_cpu_info *
19901 mips_parse_cpu (const char *option, const char *cpu_string)
19902 {
19903   const struct mips_cpu_info *p;
19904
19905   /* 'from-abi' selects the most compatible architecture for the given
19906      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19907      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19908      version.  Look first at the -mgp options, if given, otherwise base
19909      the choice on MIPS_DEFAULT_64BIT.
19910
19911      Treat NO_ABI like the EABIs.  One reason to do this is that the
19912      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19913      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19914      'mips64', just as we did in the days before 'from-abi'.  */
19915   if (strcasecmp (cpu_string, "from-abi") == 0)
19916     {
19917       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19918         return mips_cpu_info_from_isa (ISA_MIPS1);
19919
19920       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19921         return mips_cpu_info_from_isa (ISA_MIPS3);
19922
19923       if (file_mips_opts.gp >= 0)
19924         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19925                                        ? ISA_MIPS1 : ISA_MIPS3);
19926
19927       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19928                                      ? ISA_MIPS3
19929                                      : ISA_MIPS1);
19930     }
19931
19932   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19933   if (strcasecmp (cpu_string, "default") == 0)
19934     return 0;
19935
19936   for (p = mips_cpu_info_table; p->name != 0; p++)
19937     if (mips_matching_cpu_name_p (p->name, cpu_string))
19938       return p;
19939
19940   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19941   return 0;
19942 }
19943
19944 /* Return the canonical processor information for ISA (a member of the
19945    ISA_MIPS* enumeration).  */
19946
19947 static const struct mips_cpu_info *
19948 mips_cpu_info_from_isa (int isa)
19949 {
19950   int i;
19951
19952   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19953     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19954         && isa == mips_cpu_info_table[i].isa)
19955       return (&mips_cpu_info_table[i]);
19956
19957   return NULL;
19958 }
19959
19960 static const struct mips_cpu_info *
19961 mips_cpu_info_from_arch (int arch)
19962 {
19963   int i;
19964
19965   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19966     if (arch == mips_cpu_info_table[i].cpu)
19967       return (&mips_cpu_info_table[i]);
19968
19969   return NULL;
19970 }
19971 \f
19972 static void
19973 show (FILE *stream, const char *string, int *col_p, int *first_p)
19974 {
19975   if (*first_p)
19976     {
19977       fprintf (stream, "%24s", "");
19978       *col_p = 24;
19979     }
19980   else
19981     {
19982       fprintf (stream, ", ");
19983       *col_p += 2;
19984     }
19985
19986   if (*col_p + strlen (string) > 72)
19987     {
19988       fprintf (stream, "\n%24s", "");
19989       *col_p = 24;
19990     }
19991
19992   fprintf (stream, "%s", string);
19993   *col_p += strlen (string);
19994
19995   *first_p = 0;
19996 }
19997
19998 void
19999 md_show_usage (FILE *stream)
20000 {
20001   int column, first;
20002   size_t i;
20003
20004   fprintf (stream, _("\
20005 MIPS options:\n\
20006 -EB                     generate big endian output\n\
20007 -EL                     generate little endian output\n\
20008 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
20009 -G NUM                  allow referencing objects up to NUM bytes\n\
20010                         implicitly with the gp register [default 8]\n"));
20011   fprintf (stream, _("\
20012 -mips1                  generate MIPS ISA I instructions\n\
20013 -mips2                  generate MIPS ISA II instructions\n\
20014 -mips3                  generate MIPS ISA III instructions\n\
20015 -mips4                  generate MIPS ISA IV instructions\n\
20016 -mips5                  generate MIPS ISA V instructions\n\
20017 -mips32                 generate MIPS32 ISA instructions\n\
20018 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
20019 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
20020 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
20021 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
20022 -mips64                 generate MIPS64 ISA instructions\n\
20023 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
20024 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
20025 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
20026 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
20027 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
20028
20029   first = 1;
20030
20031   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
20032     show (stream, mips_cpu_info_table[i].name, &column, &first);
20033   show (stream, "from-abi", &column, &first);
20034   fputc ('\n', stream);
20035
20036   fprintf (stream, _("\
20037 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
20038 -no-mCPU                don't generate code specific to CPU.\n\
20039                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
20040
20041   first = 1;
20042
20043   show (stream, "3900", &column, &first);
20044   show (stream, "4010", &column, &first);
20045   show (stream, "4100", &column, &first);
20046   show (stream, "4650", &column, &first);
20047   fputc ('\n', stream);
20048
20049   fprintf (stream, _("\
20050 -mips16                 generate mips16 instructions\n\
20051 -no-mips16              do not generate mips16 instructions\n"));
20052   fprintf (stream, _("\
20053 -mmips16e2              generate MIPS16e2 instructions\n\
20054 -mno-mips16e2           do not generate MIPS16e2 instructions\n"));
20055   fprintf (stream, _("\
20056 -mmicromips             generate microMIPS instructions\n\
20057 -mno-micromips          do not generate microMIPS instructions\n"));
20058   fprintf (stream, _("\
20059 -msmartmips             generate smartmips instructions\n\
20060 -mno-smartmips          do not generate smartmips instructions\n"));
20061   fprintf (stream, _("\
20062 -mdsp                   generate DSP instructions\n\
20063 -mno-dsp                do not generate DSP instructions\n"));
20064   fprintf (stream, _("\
20065 -mdspr2                 generate DSP R2 instructions\n\
20066 -mno-dspr2              do not generate DSP R2 instructions\n"));
20067   fprintf (stream, _("\
20068 -mdspr3                 generate DSP R3 instructions\n\
20069 -mno-dspr3              do not generate DSP R3 instructions\n"));
20070   fprintf (stream, _("\
20071 -mmt                    generate MT instructions\n\
20072 -mno-mt                 do not generate MT instructions\n"));
20073   fprintf (stream, _("\
20074 -mmcu                   generate MCU instructions\n\
20075 -mno-mcu                do not generate MCU instructions\n"));
20076   fprintf (stream, _("\
20077 -mmsa                   generate MSA instructions\n\
20078 -mno-msa                do not generate MSA instructions\n"));
20079   fprintf (stream, _("\
20080 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
20081 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
20082   fprintf (stream, _("\
20083 -mvirt                  generate Virtualization instructions\n\
20084 -mno-virt               do not generate Virtualization instructions\n"));
20085   fprintf (stream, _("\
20086 -mcrc                   generate CRC instructions\n\
20087 -mno-crc                do not generate CRC instructions\n"));
20088   fprintf (stream, _("\
20089 -mginv                  generate Global INValidate (GINV) instructions\n\
20090 -mno-ginv               do not generate Global INValidate instructions\n"));
20091   fprintf (stream, _("\
20092 -mloongson-mmi          generate Loongson MultiMedia extensions Instructions (MMI) instructions\n\
20093 -mno-loongson-mmi       do not generate Loongson MultiMedia extensions Instructions\n"));
20094   fprintf (stream, _("\
20095 -mloongson-cam          generate Loongson Content Address Memory (CAM) instructions\n\
20096 -mno-loongson-cam       do not generate Loongson Content Address Memory Instructions\n"));
20097   fprintf (stream, _("\
20098 -mloongson-ext          generate Loongson EXTensions (EXT) instructions\n\
20099 -mno-loongson-ext       do not generate Loongson EXTensions Instructions\n"));
20100   fprintf (stream, _("\
20101 -mloongson-ext2         generate Loongson EXTensions R2 (EXT2) instructions\n\
20102 -mno-loongson-ext2      do not generate Loongson EXTensions R2 Instructions\n"));
20103   fprintf (stream, _("\
20104 -minsn32                only generate 32-bit microMIPS instructions\n\
20105 -mno-insn32             generate all microMIPS instructions\n"));
20106   fprintf (stream, _("\
20107 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
20108 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
20109 -mfix-vr4120            work around certain VR4120 errata\n\
20110 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
20111 -mfix-24k               insert a nop after ERET and DERET instructions\n\
20112 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
20113 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
20114 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
20115 -msym32                 assume all symbols have 32-bit values\n\
20116 -O0                     do not remove unneeded NOPs, do not swap branches\n\
20117 -O, -O1                 remove unneeded NOPs, do not swap branches\n\
20118 -O2                     remove unneeded NOPs and swap branches\n\
20119 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
20120 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
20121   fprintf (stream, _("\
20122 -mhard-float            allow floating-point instructions\n\
20123 -msoft-float            do not allow floating-point instructions\n\
20124 -msingle-float          only allow 32-bit floating-point operations\n\
20125 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
20126 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
20127 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
20128 -mignore-branch-isa     accept invalid branches requiring an ISA mode switch\n\
20129 -mno-ignore-branch-isa  reject invalid branches requiring an ISA mode switch\n\
20130 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
20131
20132   first = 1;
20133
20134   show (stream, "legacy", &column, &first);
20135   show (stream, "2008", &column, &first);
20136
20137   fputc ('\n', stream);
20138
20139   fprintf (stream, _("\
20140 -KPIC, -call_shared     generate SVR4 position independent code\n\
20141 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
20142 -mvxworks-pic           generate VxWorks position independent code\n\
20143 -non_shared             do not generate code that can operate with DSOs\n\
20144 -xgot                   assume a 32 bit GOT\n\
20145 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
20146 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
20147                         position dependent (non shared) code\n\
20148 -mabi=ABI               create ABI conformant object file for:\n"));
20149
20150   first = 1;
20151
20152   show (stream, "32", &column, &first);
20153   show (stream, "o64", &column, &first);
20154   show (stream, "n32", &column, &first);
20155   show (stream, "64", &column, &first);
20156   show (stream, "eabi", &column, &first);
20157
20158   fputc ('\n', stream);
20159
20160   fprintf (stream, _("\
20161 -32                     create o32 ABI object file%s\n"),
20162            MIPS_DEFAULT_ABI == O32_ABI ? _(" (default)") : "");
20163   fprintf (stream, _("\
20164 -n32                    create n32 ABI object file%s\n"),
20165            MIPS_DEFAULT_ABI == N32_ABI ? _(" (default)") : "");
20166   fprintf (stream, _("\
20167 -64                     create 64 ABI object file%s\n"),
20168            MIPS_DEFAULT_ABI == N64_ABI ? _(" (default)") : "");
20169 }
20170
20171 #ifdef TE_IRIX
20172 enum dwarf2_format
20173 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
20174 {
20175   if (HAVE_64BIT_SYMBOLS)
20176     return dwarf2_format_64bit_irix;
20177   else
20178     return dwarf2_format_32bit;
20179 }
20180 #endif
20181
20182 int
20183 mips_dwarf2_addr_size (void)
20184 {
20185   if (HAVE_64BIT_OBJECTS)
20186     return 8;
20187   else
20188     return 4;
20189 }
20190
20191 /* Standard calling conventions leave the CFA at SP on entry.  */
20192 void
20193 mips_cfi_frame_initial_instructions (void)
20194 {
20195   cfi_add_CFA_def_cfa_register (SP);
20196 }
20197
20198 int
20199 tc_mips_regname_to_dw2regnum (char *regname)
20200 {
20201   unsigned int regnum = -1;
20202   unsigned int reg;
20203
20204   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
20205     regnum = reg;
20206
20207   return regnum;
20208 }
20209
20210 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
20211    Given a symbolic attribute NAME, return the proper integer value.
20212    Returns -1 if the attribute is not known.  */
20213
20214 int
20215 mips_convert_symbolic_attribute (const char *name)
20216 {
20217   static const struct
20218   {
20219     const char * name;
20220     const int    tag;
20221   }
20222   attribute_table[] =
20223     {
20224 #define T(tag) {#tag, tag}
20225       T (Tag_GNU_MIPS_ABI_FP),
20226       T (Tag_GNU_MIPS_ABI_MSA),
20227 #undef T
20228     };
20229   unsigned int i;
20230
20231   if (name == NULL)
20232     return -1;
20233
20234   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
20235     if (streq (name, attribute_table[i].name))
20236       return attribute_table[i].tag;
20237
20238   return -1;
20239 }
20240
20241 void
20242 md_mips_end (void)
20243 {
20244   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
20245
20246   mips_emit_delays ();
20247   if (cur_proc_ptr)
20248     as_warn (_("missing .end at end of assembly"));
20249
20250   /* Just in case no code was emitted, do the consistency check.  */
20251   file_mips_check_options ();
20252
20253   /* Set a floating-point ABI if the user did not.  */
20254   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20255     {
20256       /* Perform consistency checks on the floating-point ABI.  */
20257       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20258                                         Tag_GNU_MIPS_ABI_FP);
20259       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20260         check_fpabi (fpabi);
20261     }
20262   else
20263     {
20264       /* Soft-float gets precedence over single-float, the two options should
20265          not be used together so this should not matter.  */
20266       if (file_mips_opts.soft_float == 1)
20267         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20268       /* Single-float gets precedence over all double_float cases.  */
20269       else if (file_mips_opts.single_float == 1)
20270         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20271       else
20272         {
20273           switch (file_mips_opts.fp)
20274             {
20275             case 32:
20276               if (file_mips_opts.gp == 32)
20277                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20278               break;
20279             case 0:
20280               fpabi = Val_GNU_MIPS_ABI_FP_XX;
20281               break;
20282             case 64:
20283               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20284                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
20285               else if (file_mips_opts.gp == 32)
20286                 fpabi = Val_GNU_MIPS_ABI_FP_64;
20287               else
20288                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20289               break;
20290             }
20291         }
20292
20293       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20294                                 Tag_GNU_MIPS_ABI_FP, fpabi);
20295     }
20296 }
20297
20298 /*  Returns the relocation type required for a particular CFI encoding.  */
20299
20300 bfd_reloc_code_real_type
20301 mips_cfi_reloc_for_encoding (int encoding)
20302 {
20303   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20304     return BFD_RELOC_32_PCREL;
20305   else return BFD_RELOC_NONE;
20306 }