MIPS/GAS: Improve bignum operand error diagnostics
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2017 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define streq(a, b)           (strcmp (a, b) == 0)
46
47 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92 static char *mips_flags_frag;
93
94 #define ZERO 0
95 #define ATREG 1
96 #define S0  16
97 #define S7  23
98 #define TREG 24
99 #define PIC_CALL_REG 25
100 #define KT0 26
101 #define KT1 27
102 #define GP  28
103 #define SP  29
104 #define FP  30
105 #define RA  31
106
107 #define ILLEGAL_REG (32)
108
109 #define AT  mips_opts.at
110
111 extern int target_big_endian;
112
113 /* The name of the readonly data section.  */
114 #define RDATA_SECTION_NAME ".rodata"
115
116 /* Ways in which an instruction can be "appended" to the output.  */
117 enum append_method {
118   /* Just add it normally.  */
119   APPEND_ADD,
120
121   /* Add it normally and then add a nop.  */
122   APPEND_ADD_WITH_NOP,
123
124   /* Turn an instruction with a delay slot into a "compact" version.  */
125   APPEND_ADD_COMPACT,
126
127   /* Insert the instruction before the last one.  */
128   APPEND_SWAP
129 };
130
131 /* Information about an instruction, including its format, operands
132    and fixups.  */
133 struct mips_cl_insn
134 {
135   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
136   const struct mips_opcode *insn_mo;
137
138   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
139      a copy of INSN_MO->match with the operands filled in.  If we have
140      decided to use an extended MIPS16 instruction, this includes the
141      extension.  */
142   unsigned long insn_opcode;
143
144   /* The frag that contains the instruction.  */
145   struct frag *frag;
146
147   /* The offset into FRAG of the first instruction byte.  */
148   long where;
149
150   /* The relocs associated with the instruction, if any.  */
151   fixS *fixp[3];
152
153   /* True if this entry cannot be moved from its current position.  */
154   unsigned int fixed_p : 1;
155
156   /* True if this instruction occurred in a .set noreorder block.  */
157   unsigned int noreorder_p : 1;
158
159   /* True for mips16 instructions that jump to an absolute address.  */
160   unsigned int mips16_absolute_jump_p : 1;
161
162   /* True if this instruction is complete.  */
163   unsigned int complete_p : 1;
164
165   /* True if this instruction is cleared from history by unconditional
166      branch.  */
167   unsigned int cleared_p : 1;
168 };
169
170 /* The ABI to use.  */
171 enum mips_abi_level
172 {
173   NO_ABI = 0,
174   O32_ABI,
175   O64_ABI,
176   N32_ABI,
177   N64_ABI,
178   EABI_ABI
179 };
180
181 /* MIPS ABI we are using for this output file.  */
182 static enum mips_abi_level mips_abi = NO_ABI;
183
184 /* Whether or not we have code that can call pic code.  */
185 int mips_abicalls = FALSE;
186
187 /* Whether or not we have code which can be put into a shared
188    library.  */
189 static bfd_boolean mips_in_shared = TRUE;
190
191 /* This is the set of options which may be modified by the .set
192    pseudo-op.  We use a struct so that .set push and .set pop are more
193    reliable.  */
194
195 struct mips_set_options
196 {
197   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
198      if it has not been initialized.  Changed by `.set mipsN', and the
199      -mipsN command line option, and the default CPU.  */
200   int isa;
201   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
202      <asename>', by command line options, and based on the default
203      architecture.  */
204   int ase;
205   /* Whether we are assembling for the mips16 processor.  0 if we are
206      not, 1 if we are, and -1 if the value has not been initialized.
207      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
208      -nomips16 command line options, and the default CPU.  */
209   int mips16;
210   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
211      1 if we are, and -1 if the value has not been initialized.  Changed
212      by `.set micromips' and `.set nomicromips', and the -mmicromips
213      and -mno-micromips command line options, and the default CPU.  */
214   int micromips;
215   /* Non-zero if we should not reorder instructions.  Changed by `.set
216      reorder' and `.set noreorder'.  */
217   int noreorder;
218   /* Non-zero if we should not permit the register designated "assembler
219      temporary" to be used in instructions.  The value is the register
220      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
221      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
222   unsigned int at;
223   /* Non-zero if we should warn when a macro instruction expands into
224      more than one machine instruction.  Changed by `.set nomacro' and
225      `.set macro'.  */
226   int warn_about_macros;
227   /* Non-zero if we should not move instructions.  Changed by `.set
228      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
229   int nomove;
230   /* Non-zero if we should not optimize branches by moving the target
231      of the branch into the delay slot.  Actually, we don't perform
232      this optimization anyhow.  Changed by `.set bopt' and `.set
233      nobopt'.  */
234   int nobopt;
235   /* Non-zero if we should not autoextend mips16 instructions.
236      Changed by `.set autoextend' and `.set noautoextend'.  */
237   int noautoextend;
238   /* True if we should only emit 32-bit microMIPS instructions.
239      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
240      and -mno-insn32 command line options.  */
241   bfd_boolean insn32;
242   /* Restrict general purpose registers and floating point registers
243      to 32 bit.  This is initially determined when -mgp32 or -mfp32
244      is passed but can changed if the assembler code uses .set mipsN.  */
245   int gp;
246   int fp;
247   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
248      command line option, and the default CPU.  */
249   int arch;
250   /* True if ".set sym32" is in effect.  */
251   bfd_boolean sym32;
252   /* True if floating-point operations are not allowed.  Changed by .set
253      softfloat or .set hardfloat, by command line options -msoft-float or
254      -mhard-float.  The default is false.  */
255   bfd_boolean soft_float;
256
257   /* True if only single-precision floating-point operations are allowed.
258      Changed by .set singlefloat or .set doublefloat, command-line options
259      -msingle-float or -mdouble-float.  The default is false.  */
260   bfd_boolean single_float;
261
262   /* 1 if single-precision operations on odd-numbered registers are
263      allowed.  */
264   int oddspreg;
265 };
266
267 /* Specifies whether module level options have been checked yet.  */
268 static bfd_boolean file_mips_opts_checked = FALSE;
269
270 /* Do we support nan2008?  0 if we don't, 1 if we do, and -1 if the
271    value has not been initialized.  Changed by `.nan legacy' and
272    `.nan 2008', and the -mnan=legacy and -mnan=2008 command line
273    options, and the default CPU.  */
274 static int mips_nan2008 = -1;
275
276 /* This is the struct we use to hold the module level set of options.
277    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
278    fp fields to -1 to indicate that they have not been initialized.  */
279
280 static struct mips_set_options file_mips_opts =
281 {
282   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
283   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
284   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
285   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
286   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
287 };
288
289 /* This is similar to file_mips_opts, but for the current set of options.  */
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
294   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
295   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
296   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
297   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
298 };
299
300 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
301 static unsigned int file_ase_explicit;
302
303 /* These variables are filled in with the masks of registers used.
304    The object format code reads them and puts them in the appropriate
305    place.  */
306 unsigned long mips_gprmask;
307 unsigned long mips_cprmask[4];
308
309 /* True if any MIPS16 code was produced.  */
310 static int file_ase_mips16;
311
312 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
313                               || mips_opts.isa == ISA_MIPS32R2          \
314                               || mips_opts.isa == ISA_MIPS32R3          \
315                               || mips_opts.isa == ISA_MIPS32R5          \
316                               || mips_opts.isa == ISA_MIPS64            \
317                               || mips_opts.isa == ISA_MIPS64R2          \
318                               || mips_opts.isa == ISA_MIPS64R3          \
319                               || mips_opts.isa == ISA_MIPS64R5)
320
321 /* True if any microMIPS code was produced.  */
322 static int file_ase_micromips;
323
324 /* True if we want to create R_MIPS_JALR for jalr $25.  */
325 #ifdef TE_IRIX
326 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
327 #else
328 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
329    because there's no place for any addend, the only acceptable
330    expression is a bare symbol.  */
331 #define MIPS_JALR_HINT_P(EXPR) \
332   (!HAVE_IN_PLACE_ADDENDS \
333    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
334 #endif
335
336 /* The argument of the -march= flag.  The architecture we are assembling.  */
337 static const char *mips_arch_string;
338
339 /* The argument of the -mtune= flag.  The architecture for which we
340    are optimizing.  */
341 static int mips_tune = CPU_UNKNOWN;
342 static const char *mips_tune_string;
343
344 /* True when generating 32-bit code for a 64-bit processor.  */
345 static int mips_32bitmode = 0;
346
347 /* True if the given ABI requires 32-bit registers.  */
348 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
349
350 /* Likewise 64-bit registers.  */
351 #define ABI_NEEDS_64BIT_REGS(ABI)       \
352   ((ABI) == N32_ABI                     \
353    || (ABI) == N64_ABI                  \
354    || (ABI) == O64_ABI)
355
356 #define ISA_IS_R6(ISA)                  \
357   ((ISA) == ISA_MIPS32R6                \
358    || (ISA) == ISA_MIPS64R6)
359
360 /*  Return true if ISA supports 64 bit wide gp registers.  */
361 #define ISA_HAS_64BIT_REGS(ISA)         \
362   ((ISA) == ISA_MIPS3                   \
363    || (ISA) == ISA_MIPS4                \
364    || (ISA) == ISA_MIPS5                \
365    || (ISA) == ISA_MIPS64               \
366    || (ISA) == ISA_MIPS64R2             \
367    || (ISA) == ISA_MIPS64R3             \
368    || (ISA) == ISA_MIPS64R5             \
369    || (ISA) == ISA_MIPS64R6)
370
371 /*  Return true if ISA supports 64 bit wide float registers.  */
372 #define ISA_HAS_64BIT_FPRS(ISA)         \
373   ((ISA) == ISA_MIPS3                   \
374    || (ISA) == ISA_MIPS4                \
375    || (ISA) == ISA_MIPS5                \
376    || (ISA) == ISA_MIPS32R2             \
377    || (ISA) == ISA_MIPS32R3             \
378    || (ISA) == ISA_MIPS32R5             \
379    || (ISA) == ISA_MIPS32R6             \
380    || (ISA) == ISA_MIPS64               \
381    || (ISA) == ISA_MIPS64R2             \
382    || (ISA) == ISA_MIPS64R3             \
383    || (ISA) == ISA_MIPS64R5             \
384    || (ISA) == ISA_MIPS64R6)
385
386 /* Return true if ISA supports 64-bit right rotate (dror et al.)
387    instructions.  */
388 #define ISA_HAS_DROR(ISA)               \
389   ((ISA) == ISA_MIPS64R2                \
390    || (ISA) == ISA_MIPS64R3             \
391    || (ISA) == ISA_MIPS64R5             \
392    || (ISA) == ISA_MIPS64R6             \
393    || (mips_opts.micromips              \
394        && ISA_HAS_64BIT_REGS (ISA))     \
395    )
396
397 /* Return true if ISA supports 32-bit right rotate (ror et al.)
398    instructions.  */
399 #define ISA_HAS_ROR(ISA)                \
400   ((ISA) == ISA_MIPS32R2                \
401    || (ISA) == ISA_MIPS32R3             \
402    || (ISA) == ISA_MIPS32R5             \
403    || (ISA) == ISA_MIPS32R6             \
404    || (ISA) == ISA_MIPS64R2             \
405    || (ISA) == ISA_MIPS64R3             \
406    || (ISA) == ISA_MIPS64R5             \
407    || (ISA) == ISA_MIPS64R6             \
408    || (mips_opts.ase & ASE_SMARTMIPS)   \
409    || mips_opts.micromips               \
410    )
411
412 /* Return true if ISA supports single-precision floats in odd registers.  */
413 #define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
414   (((ISA) == ISA_MIPS32                 \
415     || (ISA) == ISA_MIPS32R2            \
416     || (ISA) == ISA_MIPS32R3            \
417     || (ISA) == ISA_MIPS32R5            \
418     || (ISA) == ISA_MIPS32R6            \
419     || (ISA) == ISA_MIPS64              \
420     || (ISA) == ISA_MIPS64R2            \
421     || (ISA) == ISA_MIPS64R3            \
422     || (ISA) == ISA_MIPS64R5            \
423     || (ISA) == ISA_MIPS64R6            \
424     || (CPU) == CPU_R5900)              \
425    && (CPU) != CPU_LOONGSON_3A)
426
427 /* Return true if ISA supports move to/from high part of a 64-bit
428    floating-point register. */
429 #define ISA_HAS_MXHC1(ISA)              \
430   ((ISA) == ISA_MIPS32R2                \
431    || (ISA) == ISA_MIPS32R3             \
432    || (ISA) == ISA_MIPS32R5             \
433    || (ISA) == ISA_MIPS32R6             \
434    || (ISA) == ISA_MIPS64R2             \
435    || (ISA) == ISA_MIPS64R3             \
436    || (ISA) == ISA_MIPS64R5             \
437    || (ISA) == ISA_MIPS64R6)
438
439 /*  Return true if ISA supports legacy NAN.  */
440 #define ISA_HAS_LEGACY_NAN(ISA)         \
441   ((ISA) == ISA_MIPS1                   \
442    || (ISA) == ISA_MIPS2                \
443    || (ISA) == ISA_MIPS3                \
444    || (ISA) == ISA_MIPS4                \
445    || (ISA) == ISA_MIPS5                \
446    || (ISA) == ISA_MIPS32               \
447    || (ISA) == ISA_MIPS32R2             \
448    || (ISA) == ISA_MIPS32R3             \
449    || (ISA) == ISA_MIPS32R5             \
450    || (ISA) == ISA_MIPS64               \
451    || (ISA) == ISA_MIPS64R2             \
452    || (ISA) == ISA_MIPS64R3             \
453    || (ISA) == ISA_MIPS64R5)
454
455 #define GPR_SIZE \
456     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
457      ? 32 \
458      : mips_opts.gp)
459
460 #define FPR_SIZE \
461     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
462      ? 32 \
463      : mips_opts.fp)
464
465 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
466
467 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
468
469 /* True if relocations are stored in-place.  */
470 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
471
472 /* The ABI-derived address size.  */
473 #define HAVE_64BIT_ADDRESSES \
474   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
475 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
476
477 /* The size of symbolic constants (i.e., expressions of the form
478    "SYMBOL" or "SYMBOL + OFFSET").  */
479 #define HAVE_32BIT_SYMBOLS \
480   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
481 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
482
483 /* Addresses are loaded in different ways, depending on the address size
484    in use.  The n32 ABI Documentation also mandates the use of additions
485    with overflow checking, but existing implementations don't follow it.  */
486 #define ADDRESS_ADD_INSN                                                \
487    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
488
489 #define ADDRESS_ADDI_INSN                                               \
490    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
491
492 #define ADDRESS_LOAD_INSN                                               \
493    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
494
495 #define ADDRESS_STORE_INSN                                              \
496    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
497
498 /* Return true if the given CPU supports the MIPS16 ASE.  */
499 #define CPU_HAS_MIPS16(cpu)                                             \
500    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
501     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
502
503 /* Return true if the given CPU supports the microMIPS ASE.  */
504 #define CPU_HAS_MICROMIPS(cpu)  0
505
506 /* True if CPU has a dror instruction.  */
507 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
508
509 /* True if CPU has a ror instruction.  */
510 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
511
512 /* True if CPU is in the Octeon family */
513 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
514                             || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
515
516 /* True if CPU has seq/sne and seqi/snei instructions.  */
517 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
518
519 /* True, if CPU has support for ldc1 and sdc1. */
520 #define CPU_HAS_LDC1_SDC1(CPU)  \
521    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
522
523 /* True if mflo and mfhi can be immediately followed by instructions
524    which write to the HI and LO registers.
525
526    According to MIPS specifications, MIPS ISAs I, II, and III need
527    (at least) two instructions between the reads of HI/LO and
528    instructions which write them, and later ISAs do not.  Contradicting
529    the MIPS specifications, some MIPS IV processor user manuals (e.g.
530    the UM for the NEC Vr5000) document needing the instructions between
531    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
532    MIPS64 and later ISAs to have the interlocks, plus any specific
533    earlier-ISA CPUs for which CPU documentation declares that the
534    instructions are really interlocked.  */
535 #define hilo_interlocks \
536   (mips_opts.isa == ISA_MIPS32                        \
537    || mips_opts.isa == ISA_MIPS32R2                   \
538    || mips_opts.isa == ISA_MIPS32R3                   \
539    || mips_opts.isa == ISA_MIPS32R5                   \
540    || mips_opts.isa == ISA_MIPS32R6                   \
541    || mips_opts.isa == ISA_MIPS64                     \
542    || mips_opts.isa == ISA_MIPS64R2                   \
543    || mips_opts.isa == ISA_MIPS64R3                   \
544    || mips_opts.isa == ISA_MIPS64R5                   \
545    || mips_opts.isa == ISA_MIPS64R6                   \
546    || mips_opts.arch == CPU_R4010                     \
547    || mips_opts.arch == CPU_R5900                     \
548    || mips_opts.arch == CPU_R10000                    \
549    || mips_opts.arch == CPU_R12000                    \
550    || mips_opts.arch == CPU_R14000                    \
551    || mips_opts.arch == CPU_R16000                    \
552    || mips_opts.arch == CPU_RM7000                    \
553    || mips_opts.arch == CPU_VR5500                    \
554    || mips_opts.micromips                             \
555    )
556
557 /* Whether the processor uses hardware interlocks to protect reads
558    from the GPRs after they are loaded from memory, and thus does not
559    require nops to be inserted.  This applies to instructions marked
560    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
561    level I and microMIPS mode instructions are always interlocked.  */
562 #define gpr_interlocks                                \
563   (mips_opts.isa != ISA_MIPS1                         \
564    || mips_opts.arch == CPU_R3900                     \
565    || mips_opts.arch == CPU_R5900                     \
566    || mips_opts.micromips                             \
567    )
568
569 /* Whether the processor uses hardware interlocks to avoid delays
570    required by coprocessor instructions, and thus does not require
571    nops to be inserted.  This applies to instructions marked
572    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
573    instructions marked INSN_WRITE_COND_CODE and ones marked
574    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
575    levels I, II, and III and microMIPS mode instructions are always
576    interlocked.  */
577 /* Itbl support may require additional care here.  */
578 #define cop_interlocks                                \
579   ((mips_opts.isa != ISA_MIPS1                        \
580     && mips_opts.isa != ISA_MIPS2                     \
581     && mips_opts.isa != ISA_MIPS3)                    \
582    || mips_opts.arch == CPU_R4300                     \
583    || mips_opts.micromips                             \
584    )
585
586 /* Whether the processor uses hardware interlocks to protect reads
587    from coprocessor registers after they are loaded from memory, and
588    thus does not require nops to be inserted.  This applies to
589    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
590    requires at MIPS ISA level I and microMIPS mode instructions are
591    always interlocked.  */
592 #define cop_mem_interlocks                            \
593   (mips_opts.isa != ISA_MIPS1                         \
594    || mips_opts.micromips                             \
595    )
596
597 /* Is this a mfhi or mflo instruction?  */
598 #define MF_HILO_INSN(PINFO) \
599   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
600
601 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
602    has been selected.  This implies, in particular, that addresses of text
603    labels have their LSB set.  */
604 #define HAVE_CODE_COMPRESSION                                           \
605   ((mips_opts.mips16 | mips_opts.micromips) != 0)
606
607 /* The minimum and maximum signed values that can be stored in a GPR.  */
608 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
609 #define GPR_SMIN (-GPR_SMAX - 1)
610
611 /* MIPS PIC level.  */
612
613 enum mips_pic_level mips_pic;
614
615 /* 1 if we should generate 32 bit offsets from the $gp register in
616    SVR4_PIC mode.  Currently has no meaning in other modes.  */
617 static int mips_big_got = 0;
618
619 /* 1 if trap instructions should used for overflow rather than break
620    instructions.  */
621 static int mips_trap = 0;
622
623 /* 1 if double width floating point constants should not be constructed
624    by assembling two single width halves into two single width floating
625    point registers which just happen to alias the double width destination
626    register.  On some architectures this aliasing can be disabled by a bit
627    in the status register, and the setting of this bit cannot be determined
628    automatically at assemble time.  */
629 static int mips_disable_float_construction;
630
631 /* Non-zero if any .set noreorder directives were used.  */
632
633 static int mips_any_noreorder;
634
635 /* Non-zero if nops should be inserted when the register referenced in
636    an mfhi/mflo instruction is read in the next two instructions.  */
637 static int mips_7000_hilo_fix;
638
639 /* The size of objects in the small data section.  */
640 static unsigned int g_switch_value = 8;
641 /* Whether the -G option was used.  */
642 static int g_switch_seen = 0;
643
644 #define N_RMASK 0xc4
645 #define N_VFP   0xd4
646
647 /* If we can determine in advance that GP optimization won't be
648    possible, we can skip the relaxation stuff that tries to produce
649    GP-relative references.  This makes delay slot optimization work
650    better.
651
652    This function can only provide a guess, but it seems to work for
653    gcc output.  It needs to guess right for gcc, otherwise gcc
654    will put what it thinks is a GP-relative instruction in a branch
655    delay slot.
656
657    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
658    fixed it for the non-PIC mode.  KR 95/04/07  */
659 static int nopic_need_relax (symbolS *, int);
660
661 /* handle of the OPCODE hash table */
662 static struct hash_control *op_hash = NULL;
663
664 /* The opcode hash table we use for the mips16.  */
665 static struct hash_control *mips16_op_hash = NULL;
666
667 /* The opcode hash table we use for the microMIPS ASE.  */
668 static struct hash_control *micromips_op_hash = NULL;
669
670 /* This array holds the chars that always start a comment.  If the
671     pre-processor is disabled, these aren't very useful */
672 const char comment_chars[] = "#";
673
674 /* This array holds the chars that only start a comment at the beginning of
675    a line.  If the line seems to have the form '# 123 filename'
676    .line and .file directives will appear in the pre-processed output */
677 /* Note that input_file.c hand checks for '#' at the beginning of the
678    first line of the input file.  This is because the compiler outputs
679    #NO_APP at the beginning of its output.  */
680 /* Also note that C style comments are always supported.  */
681 const char line_comment_chars[] = "#";
682
683 /* This array holds machine specific line separator characters.  */
684 const char line_separator_chars[] = ";";
685
686 /* Chars that can be used to separate mant from exp in floating point nums */
687 const char EXP_CHARS[] = "eE";
688
689 /* Chars that mean this number is a floating point constant */
690 /* As in 0f12.456 */
691 /* or    0d1.2345e12 */
692 const char FLT_CHARS[] = "rRsSfFdDxXpP";
693
694 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
695    changed in read.c .  Ideally it shouldn't have to know about it at all,
696    but nothing is ideal around here.
697  */
698
699 /* Types of printf format used for instruction-related error messages.
700    "I" means int ("%d") and "S" means string ("%s"). */
701 enum mips_insn_error_format {
702   ERR_FMT_PLAIN,
703   ERR_FMT_I,
704   ERR_FMT_SS,
705 };
706
707 /* Information about an error that was found while assembling the current
708    instruction.  */
709 struct mips_insn_error {
710   /* We sometimes need to match an instruction against more than one
711      opcode table entry.  Errors found during this matching are reported
712      against a particular syntactic argument rather than against the
713      instruction as a whole.  We grade these messages so that errors
714      against argument N have a greater priority than an error against
715      any argument < N, since the former implies that arguments up to N
716      were acceptable and that the opcode entry was therefore a closer match.
717      If several matches report an error against the same argument,
718      we only use that error if it is the same in all cases.
719
720      min_argnum is the minimum argument number for which an error message
721      should be accepted.  It is 0 if MSG is against the instruction as
722      a whole.  */
723   int min_argnum;
724
725   /* The printf()-style message, including its format and arguments.  */
726   enum mips_insn_error_format format;
727   const char *msg;
728   union {
729     int i;
730     const char *ss[2];
731   } u;
732 };
733
734 /* The error that should be reported for the current instruction.  */
735 static struct mips_insn_error insn_error;
736
737 static int auto_align = 1;
738
739 /* When outputting SVR4 PIC code, the assembler needs to know the
740    offset in the stack frame from which to restore the $gp register.
741    This is set by the .cprestore pseudo-op, and saved in this
742    variable.  */
743 static offsetT mips_cprestore_offset = -1;
744
745 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
746    more optimizations, it can use a register value instead of a memory-saved
747    offset and even an other register than $gp as global pointer.  */
748 static offsetT mips_cpreturn_offset = -1;
749 static int mips_cpreturn_register = -1;
750 static int mips_gp_register = GP;
751 static int mips_gprel_offset = 0;
752
753 /* Whether mips_cprestore_offset has been set in the current function
754    (or whether it has already been warned about, if not).  */
755 static int mips_cprestore_valid = 0;
756
757 /* This is the register which holds the stack frame, as set by the
758    .frame pseudo-op.  This is needed to implement .cprestore.  */
759 static int mips_frame_reg = SP;
760
761 /* Whether mips_frame_reg has been set in the current function
762    (or whether it has already been warned about, if not).  */
763 static int mips_frame_reg_valid = 0;
764
765 /* To output NOP instructions correctly, we need to keep information
766    about the previous two instructions.  */
767
768 /* Whether we are optimizing.  The default value of 2 means to remove
769    unneeded NOPs and swap branch instructions when possible.  A value
770    of 1 means to not swap branches.  A value of 0 means to always
771    insert NOPs.  */
772 static int mips_optimize = 2;
773
774 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
775    equivalent to seeing no -g option at all.  */
776 static int mips_debug = 0;
777
778 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
779 #define MAX_VR4130_NOPS 4
780
781 /* The maximum number of NOPs needed to fill delay slots.  */
782 #define MAX_DELAY_NOPS 2
783
784 /* The maximum number of NOPs needed for any purpose.  */
785 #define MAX_NOPS 4
786
787 /* A list of previous instructions, with index 0 being the most recent.
788    We need to look back MAX_NOPS instructions when filling delay slots
789    or working around processor errata.  We need to look back one
790    instruction further if we're thinking about using history[0] to
791    fill a branch delay slot.  */
792 static struct mips_cl_insn history[1 + MAX_NOPS];
793
794 /* Arrays of operands for each instruction.  */
795 #define MAX_OPERANDS 6
796 struct mips_operand_array {
797   const struct mips_operand *operand[MAX_OPERANDS];
798 };
799 static struct mips_operand_array *mips_operands;
800 static struct mips_operand_array *mips16_operands;
801 static struct mips_operand_array *micromips_operands;
802
803 /* Nop instructions used by emit_nop.  */
804 static struct mips_cl_insn nop_insn;
805 static struct mips_cl_insn mips16_nop_insn;
806 static struct mips_cl_insn micromips_nop16_insn;
807 static struct mips_cl_insn micromips_nop32_insn;
808
809 /* The appropriate nop for the current mode.  */
810 #define NOP_INSN (mips_opts.mips16                                      \
811                   ? &mips16_nop_insn                                    \
812                   : (mips_opts.micromips                                \
813                      ? (mips_opts.insn32                                \
814                         ? &micromips_nop32_insn                         \
815                         : &micromips_nop16_insn)                        \
816                      : &nop_insn))
817
818 /* The size of NOP_INSN in bytes.  */
819 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
820                         || (mips_opts.micromips && !mips_opts.insn32))  \
821                        ? 2 : 4)
822
823 /* If this is set, it points to a frag holding nop instructions which
824    were inserted before the start of a noreorder section.  If those
825    nops turn out to be unnecessary, the size of the frag can be
826    decreased.  */
827 static fragS *prev_nop_frag;
828
829 /* The number of nop instructions we created in prev_nop_frag.  */
830 static int prev_nop_frag_holds;
831
832 /* The number of nop instructions that we know we need in
833    prev_nop_frag.  */
834 static int prev_nop_frag_required;
835
836 /* The number of instructions we've seen since prev_nop_frag.  */
837 static int prev_nop_frag_since;
838
839 /* Relocations against symbols are sometimes done in two parts, with a HI
840    relocation and a LO relocation.  Each relocation has only 16 bits of
841    space to store an addend.  This means that in order for the linker to
842    handle carries correctly, it must be able to locate both the HI and
843    the LO relocation.  This means that the relocations must appear in
844    order in the relocation table.
845
846    In order to implement this, we keep track of each unmatched HI
847    relocation.  We then sort them so that they immediately precede the
848    corresponding LO relocation.  */
849
850 struct mips_hi_fixup
851 {
852   /* Next HI fixup.  */
853   struct mips_hi_fixup *next;
854   /* This fixup.  */
855   fixS *fixp;
856   /* The section this fixup is in.  */
857   segT seg;
858 };
859
860 /* The list of unmatched HI relocs.  */
861
862 static struct mips_hi_fixup *mips_hi_fixup_list;
863
864 /* The frag containing the last explicit relocation operator.
865    Null if explicit relocations have not been used.  */
866
867 static fragS *prev_reloc_op_frag;
868
869 /* Map mips16 register numbers to normal MIPS register numbers.  */
870
871 static const unsigned int mips16_to_32_reg_map[] =
872 {
873   16, 17, 2, 3, 4, 5, 6, 7
874 };
875
876 /* Map microMIPS register numbers to normal MIPS register numbers.  */
877
878 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
879
880 /* The microMIPS registers with type h.  */
881 static const unsigned int micromips_to_32_reg_h_map1[] =
882 {
883   5, 5, 6, 4, 4, 4, 4, 4
884 };
885 static const unsigned int micromips_to_32_reg_h_map2[] =
886 {
887   6, 7, 7, 21, 22, 5, 6, 7
888 };
889
890 /* The microMIPS registers with type m.  */
891 static const unsigned int micromips_to_32_reg_m_map[] =
892 {
893   0, 17, 2, 3, 16, 18, 19, 20
894 };
895
896 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
897
898 /* Classifies the kind of instructions we're interested in when
899    implementing -mfix-vr4120.  */
900 enum fix_vr4120_class
901 {
902   FIX_VR4120_MACC,
903   FIX_VR4120_DMACC,
904   FIX_VR4120_MULT,
905   FIX_VR4120_DMULT,
906   FIX_VR4120_DIV,
907   FIX_VR4120_MTHILO,
908   NUM_FIX_VR4120_CLASSES
909 };
910
911 /* ...likewise -mfix-loongson2f-jump.  */
912 static bfd_boolean mips_fix_loongson2f_jump;
913
914 /* ...likewise -mfix-loongson2f-nop.  */
915 static bfd_boolean mips_fix_loongson2f_nop;
916
917 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
918 static bfd_boolean mips_fix_loongson2f;
919
920 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
921    there must be at least one other instruction between an instruction
922    of type X and an instruction of type Y.  */
923 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
924
925 /* True if -mfix-vr4120 is in force.  */
926 static int mips_fix_vr4120;
927
928 /* ...likewise -mfix-vr4130.  */
929 static int mips_fix_vr4130;
930
931 /* ...likewise -mfix-24k.  */
932 static int mips_fix_24k;
933
934 /* ...likewise -mfix-rm7000  */
935 static int mips_fix_rm7000;
936
937 /* ...likewise -mfix-cn63xxp1 */
938 static bfd_boolean mips_fix_cn63xxp1;
939
940 /* We don't relax branches by default, since this causes us to expand
941    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
942    fail to compute the offset before expanding the macro to the most
943    efficient expansion.  */
944
945 static int mips_relax_branch;
946
947 /* TRUE if checks are suppressed for invalid branches between ISA modes.
948    Needed for broken assembly produced by some GCC versions and some
949    sloppy code out there, where branches to data labels are present.  */
950 static bfd_boolean mips_ignore_branch_isa;
951 \f
952 /* The expansion of many macros depends on the type of symbol that
953    they refer to.  For example, when generating position-dependent code,
954    a macro that refers to a symbol may have two different expansions,
955    one which uses GP-relative addresses and one which uses absolute
956    addresses.  When generating SVR4-style PIC, a macro may have
957    different expansions for local and global symbols.
958
959    We handle these situations by generating both sequences and putting
960    them in variant frags.  In position-dependent code, the first sequence
961    will be the GP-relative one and the second sequence will be the
962    absolute one.  In SVR4 PIC, the first sequence will be for global
963    symbols and the second will be for local symbols.
964
965    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
966    SECOND are the lengths of the two sequences in bytes.  These fields
967    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
968    the subtype has the following flags:
969
970    RELAX_PIC
971         Set if generating PIC code.
972
973    RELAX_USE_SECOND
974         Set if it has been decided that we should use the second
975         sequence instead of the first.
976
977    RELAX_SECOND_LONGER
978         Set in the first variant frag if the macro's second implementation
979         is longer than its first.  This refers to the macro as a whole,
980         not an individual relaxation.
981
982    RELAX_NOMACRO
983         Set in the first variant frag if the macro appeared in a .set nomacro
984         block and if one alternative requires a warning but the other does not.
985
986    RELAX_DELAY_SLOT
987         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
988         delay slot.
989
990    RELAX_DELAY_SLOT_16BIT
991         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
992         16-bit instruction.
993
994    RELAX_DELAY_SLOT_SIZE_FIRST
995         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
996         the macro is of the wrong size for the branch delay slot.
997
998    RELAX_DELAY_SLOT_SIZE_SECOND
999         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1000         the macro is of the wrong size for the branch delay slot.
1001
1002    The frag's "opcode" points to the first fixup for relaxable code.
1003
1004    Relaxable macros are generated using a sequence such as:
1005
1006       relax_start (SYMBOL);
1007       ... generate first expansion ...
1008       relax_switch ();
1009       ... generate second expansion ...
1010       relax_end ();
1011
1012    The code and fixups for the unwanted alternative are discarded
1013    by md_convert_frag.  */
1014 #define RELAX_ENCODE(FIRST, SECOND, PIC)                        \
1015   (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1016
1017 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1018 #define RELAX_SECOND(X) ((X) & 0xff)
1019 #define RELAX_PIC(X) (((X) & 0x10000) != 0)
1020 #define RELAX_USE_SECOND 0x20000
1021 #define RELAX_SECOND_LONGER 0x40000
1022 #define RELAX_NOMACRO 0x80000
1023 #define RELAX_DELAY_SLOT 0x100000
1024 #define RELAX_DELAY_SLOT_16BIT 0x200000
1025 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1026 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1027
1028 /* Branch without likely bit.  If label is out of range, we turn:
1029
1030         beq reg1, reg2, label
1031         delay slot
1032
1033    into
1034
1035         bne reg1, reg2, 0f
1036         nop
1037         j label
1038      0: delay slot
1039
1040    with the following opcode replacements:
1041
1042         beq <-> bne
1043         blez <-> bgtz
1044         bltz <-> bgez
1045         bc1f <-> bc1t
1046
1047         bltzal <-> bgezal  (with jal label instead of j label)
1048
1049    Even though keeping the delay slot instruction in the delay slot of
1050    the branch would be more efficient, it would be very tricky to do
1051    correctly, because we'd have to introduce a variable frag *after*
1052    the delay slot instruction, and expand that instead.  Let's do it
1053    the easy way for now, even if the branch-not-taken case now costs
1054    one additional instruction.  Out-of-range branches are not supposed
1055    to be common, anyway.
1056
1057    Branch likely.  If label is out of range, we turn:
1058
1059         beql reg1, reg2, label
1060         delay slot (annulled if branch not taken)
1061
1062    into
1063
1064         beql reg1, reg2, 1f
1065         nop
1066         beql $0, $0, 2f
1067         nop
1068      1: j[al] label
1069         delay slot (executed only if branch taken)
1070      2:
1071
1072    It would be possible to generate a shorter sequence by losing the
1073    likely bit, generating something like:
1074
1075         bne reg1, reg2, 0f
1076         nop
1077         j[al] label
1078         delay slot (executed only if branch taken)
1079      0:
1080
1081         beql -> bne
1082         bnel -> beq
1083         blezl -> bgtz
1084         bgtzl -> blez
1085         bltzl -> bgez
1086         bgezl -> bltz
1087         bc1fl -> bc1t
1088         bc1tl -> bc1f
1089
1090         bltzall -> bgezal  (with jal label instead of j label)
1091         bgezall -> bltzal  (ditto)
1092
1093
1094    but it's not clear that it would actually improve performance.  */
1095 #define RELAX_BRANCH_ENCODE(at, pic,                            \
1096                             uncond, likely, link, toofar)       \
1097   ((relax_substateT)                                            \
1098    (0xc0000000                                                  \
1099     | ((at) & 0x1f)                                             \
1100     | ((pic) ? 0x20 : 0)                                        \
1101     | ((toofar) ? 0x40 : 0)                                     \
1102     | ((link) ? 0x80 : 0)                                       \
1103     | ((likely) ? 0x100 : 0)                                    \
1104     | ((uncond) ? 0x200 : 0)))
1105 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1106 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1107 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1108 #define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1109 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1110 #define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1111 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1112
1113 /* For mips16 code, we use an entirely different form of relaxation.
1114    mips16 supports two versions of most instructions which take
1115    immediate values: a small one which takes some small value, and a
1116    larger one which takes a 16 bit value.  Since branches also follow
1117    this pattern, relaxing these values is required.
1118
1119    We can assemble both mips16 and normal MIPS code in a single
1120    object.  Therefore, we need to support this type of relaxation at
1121    the same time that we support the relaxation described above.  We
1122    use the high bit of the subtype field to distinguish these cases.
1123
1124    The information we store for this type of relaxation is the
1125    argument code found in the opcode file for this relocation, whether
1126    the user explicitly requested a small or extended form, and whether
1127    the relocation is in a jump or jal delay slot.  That tells us the
1128    size of the value, and how it should be stored.  We also store
1129    whether the fragment is considered to be extended or not.  We also
1130    store whether this is known to be a branch to a different section,
1131    whether we have tried to relax this frag yet, and whether we have
1132    ever extended a PC relative fragment because of a shift count.  */
1133 #define RELAX_MIPS16_ENCODE(type, pic, sym32, nomacro,          \
1134                             small, ext,                         \
1135                             dslot, jal_dslot)                   \
1136   (0x80000000                                                   \
1137    | ((type) & 0xff)                                            \
1138    | ((pic) ? 0x100 : 0)                                        \
1139    | ((sym32) ? 0x200 : 0)                                      \
1140    | ((nomacro) ? 0x400 : 0)                                    \
1141    | ((small) ? 0x800 : 0)                                      \
1142    | ((ext) ? 0x1000 : 0)                                       \
1143    | ((dslot) ? 0x2000 : 0)                                     \
1144    | ((jal_dslot) ? 0x4000 : 0))
1145
1146 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1147 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1148 #define RELAX_MIPS16_PIC(i) (((i) & 0x100) != 0)
1149 #define RELAX_MIPS16_SYM32(i) (((i) & 0x200) != 0)
1150 #define RELAX_MIPS16_NOMACRO(i) (((i) & 0x400) != 0)
1151 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x800) != 0)
1152 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x1000) != 0)
1153 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x2000) != 0)
1154 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x4000) != 0)
1155
1156 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x8000) != 0)
1157 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x8000)
1158 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x8000)
1159 #define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x10000) != 0)
1160 #define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x10000)
1161 #define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x10000)
1162 #define RELAX_MIPS16_MACRO(i) (((i) & 0x20000) != 0)
1163 #define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x20000)
1164 #define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x20000)
1165
1166 /* For microMIPS code, we use relaxation similar to one we use for
1167    MIPS16 code.  Some instructions that take immediate values support
1168    two encodings: a small one which takes some small value, and a
1169    larger one which takes a 16 bit value.  As some branches also follow
1170    this pattern, relaxing these values is required.
1171
1172    We can assemble both microMIPS and normal MIPS code in a single
1173    object.  Therefore, we need to support this type of relaxation at
1174    the same time that we support the relaxation described above.  We
1175    use one of the high bits of the subtype field to distinguish these
1176    cases.
1177
1178    The information we store for this type of relaxation is the argument
1179    code found in the opcode file for this relocation, the register
1180    selected as the assembler temporary, whether in the 32-bit
1181    instruction mode, whether the branch is unconditional, whether it is
1182    compact, whether there is no delay-slot instruction available to fill
1183    in, whether it stores the link address implicitly in $ra, whether
1184    relaxation of out-of-range 32-bit branches to a sequence of
1185    instructions is enabled, and whether the displacement of a branch is
1186    too large to fit as an immediate argument of a 16-bit and a 32-bit
1187    branch, respectively.  */
1188 #define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,           \
1189                                uncond, compact, link, nods,     \
1190                                relax32, toofar16, toofar32)     \
1191   (0x40000000                                                   \
1192    | ((type) & 0xff)                                            \
1193    | (((at) & 0x1f) << 8)                                       \
1194    | ((insn32) ? 0x2000 : 0)                                    \
1195    | ((pic) ? 0x4000 : 0)                                       \
1196    | ((uncond) ? 0x8000 : 0)                                    \
1197    | ((compact) ? 0x10000 : 0)                                  \
1198    | ((link) ? 0x20000 : 0)                                     \
1199    | ((nods) ? 0x40000 : 0)                                     \
1200    | ((relax32) ? 0x80000 : 0)                                  \
1201    | ((toofar16) ? 0x100000 : 0)                                \
1202    | ((toofar32) ? 0x200000 : 0))
1203 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1204 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1205 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1206 #define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1207 #define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1208 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1209 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1210 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1211 #define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1212 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1213
1214 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1215 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1216 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1217 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1218 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1219 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1220
1221 /* Sign-extend 16-bit value X.  */
1222 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1223
1224 /* Is the given value a sign-extended 32-bit value?  */
1225 #define IS_SEXT_32BIT_NUM(x)                                            \
1226   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1227    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1228
1229 /* Is the given value a sign-extended 16-bit value?  */
1230 #define IS_SEXT_16BIT_NUM(x)                                            \
1231   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1232    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1233
1234 /* Is the given value a sign-extended 12-bit value?  */
1235 #define IS_SEXT_12BIT_NUM(x)                                            \
1236   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1237
1238 /* Is the given value a sign-extended 9-bit value?  */
1239 #define IS_SEXT_9BIT_NUM(x)                                             \
1240   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1241
1242 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1243 #define IS_ZEXT_32BIT_NUM(x)                                            \
1244   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1245    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1246
1247 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1248    SHIFT places.  */
1249 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1250   (((STRUCT) >> (SHIFT)) & (MASK))
1251
1252 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1253 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1254   (!(MICROMIPS) \
1255    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1256    : EXTRACT_BITS ((INSN).insn_opcode, \
1257                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1258 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1259   EXTRACT_BITS ((INSN).insn_opcode, \
1260                 MIPS16OP_MASK_##FIELD, \
1261                 MIPS16OP_SH_##FIELD)
1262
1263 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1264 #define MIPS16_EXTEND (0xf000U << 16)
1265 \f
1266 /* Whether or not we are emitting a branch-likely macro.  */
1267 static bfd_boolean emit_branch_likely_macro = FALSE;
1268
1269 /* Global variables used when generating relaxable macros.  See the
1270    comment above RELAX_ENCODE for more details about how relaxation
1271    is used.  */
1272 static struct {
1273   /* 0 if we're not emitting a relaxable macro.
1274      1 if we're emitting the first of the two relaxation alternatives.
1275      2 if we're emitting the second alternative.  */
1276   int sequence;
1277
1278   /* The first relaxable fixup in the current frag.  (In other words,
1279      the first fixup that refers to relaxable code.)  */
1280   fixS *first_fixup;
1281
1282   /* sizes[0] says how many bytes of the first alternative are stored in
1283      the current frag.  Likewise sizes[1] for the second alternative.  */
1284   unsigned int sizes[2];
1285
1286   /* The symbol on which the choice of sequence depends.  */
1287   symbolS *symbol;
1288 } mips_relax;
1289 \f
1290 /* Global variables used to decide whether a macro needs a warning.  */
1291 static struct {
1292   /* True if the macro is in a branch delay slot.  */
1293   bfd_boolean delay_slot_p;
1294
1295   /* Set to the length in bytes required if the macro is in a delay slot
1296      that requires a specific length of instruction, otherwise zero.  */
1297   unsigned int delay_slot_length;
1298
1299   /* For relaxable macros, sizes[0] is the length of the first alternative
1300      in bytes and sizes[1] is the length of the second alternative.
1301      For non-relaxable macros, both elements give the length of the
1302      macro in bytes.  */
1303   unsigned int sizes[2];
1304
1305   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1306      instruction of the first alternative in bytes and first_insn_sizes[1]
1307      is the length of the first instruction of the second alternative.
1308      For non-relaxable macros, both elements give the length of the first
1309      instruction in bytes.
1310
1311      Set to zero if we haven't yet seen the first instruction.  */
1312   unsigned int first_insn_sizes[2];
1313
1314   /* For relaxable macros, insns[0] is the number of instructions for the
1315      first alternative and insns[1] is the number of instructions for the
1316      second alternative.
1317
1318      For non-relaxable macros, both elements give the number of
1319      instructions for the macro.  */
1320   unsigned int insns[2];
1321
1322   /* The first variant frag for this macro.  */
1323   fragS *first_frag;
1324 } mips_macro_warning;
1325 \f
1326 /* Prototypes for static functions.  */
1327
1328 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1329
1330 static void append_insn
1331   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1332    bfd_boolean expansionp);
1333 static void mips_no_prev_insn (void);
1334 static void macro_build (expressionS *, const char *, const char *, ...);
1335 static void mips16_macro_build
1336   (expressionS *, const char *, const char *, va_list *);
1337 static void load_register (int, expressionS *, int);
1338 static void macro_start (void);
1339 static void macro_end (void);
1340 static void macro (struct mips_cl_insn *ip, char *str);
1341 static void mips16_macro (struct mips_cl_insn * ip);
1342 static void mips_ip (char *str, struct mips_cl_insn * ip);
1343 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1344 static void mips16_immed
1345   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1346    unsigned int, unsigned long *);
1347 static size_t my_getSmallExpression
1348   (expressionS *, bfd_reloc_code_real_type *, char *);
1349 static void my_getExpression (expressionS *, char *);
1350 static void s_align (int);
1351 static void s_change_sec (int);
1352 static void s_change_section (int);
1353 static void s_cons (int);
1354 static void s_float_cons (int);
1355 static void s_mips_globl (int);
1356 static void s_option (int);
1357 static void s_mipsset (int);
1358 static void s_abicalls (int);
1359 static void s_cpload (int);
1360 static void s_cpsetup (int);
1361 static void s_cplocal (int);
1362 static void s_cprestore (int);
1363 static void s_cpreturn (int);
1364 static void s_dtprelword (int);
1365 static void s_dtpreldword (int);
1366 static void s_tprelword (int);
1367 static void s_tpreldword (int);
1368 static void s_gpvalue (int);
1369 static void s_gpword (int);
1370 static void s_gpdword (int);
1371 static void s_ehword (int);
1372 static void s_cpadd (int);
1373 static void s_insn (int);
1374 static void s_nan (int);
1375 static void s_module (int);
1376 static void s_mips_ent (int);
1377 static void s_mips_end (int);
1378 static void s_mips_frame (int);
1379 static void s_mips_mask (int reg_type);
1380 static void s_mips_stab (int);
1381 static void s_mips_weakext (int);
1382 static void s_mips_file (int);
1383 static void s_mips_loc (int);
1384 static bfd_boolean pic_need_relax (symbolS *);
1385 static int relaxed_branch_length (fragS *, asection *, int);
1386 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1387 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1388 static void file_mips_check_options (void);
1389
1390 /* Table and functions used to map between CPU/ISA names, and
1391    ISA levels, and CPU numbers.  */
1392
1393 struct mips_cpu_info
1394 {
1395   const char *name;           /* CPU or ISA name.  */
1396   int flags;                  /* MIPS_CPU_* flags.  */
1397   int ase;                    /* Set of ASEs implemented by the CPU.  */
1398   int isa;                    /* ISA level.  */
1399   int cpu;                    /* CPU number (default CPU if ISA).  */
1400 };
1401
1402 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1403
1404 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1405 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1406 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1407 \f
1408 /* Command-line options.  */
1409 const char *md_shortopts = "O::g::G:";
1410
1411 enum options
1412   {
1413     OPTION_MARCH = OPTION_MD_BASE,
1414     OPTION_MTUNE,
1415     OPTION_MIPS1,
1416     OPTION_MIPS2,
1417     OPTION_MIPS3,
1418     OPTION_MIPS4,
1419     OPTION_MIPS5,
1420     OPTION_MIPS32,
1421     OPTION_MIPS64,
1422     OPTION_MIPS32R2,
1423     OPTION_MIPS32R3,
1424     OPTION_MIPS32R5,
1425     OPTION_MIPS32R6,
1426     OPTION_MIPS64R2,
1427     OPTION_MIPS64R3,
1428     OPTION_MIPS64R5,
1429     OPTION_MIPS64R6,
1430     OPTION_MIPS16,
1431     OPTION_NO_MIPS16,
1432     OPTION_MIPS3D,
1433     OPTION_NO_MIPS3D,
1434     OPTION_MDMX,
1435     OPTION_NO_MDMX,
1436     OPTION_DSP,
1437     OPTION_NO_DSP,
1438     OPTION_MT,
1439     OPTION_NO_MT,
1440     OPTION_VIRT,
1441     OPTION_NO_VIRT,
1442     OPTION_MSA,
1443     OPTION_NO_MSA,
1444     OPTION_SMARTMIPS,
1445     OPTION_NO_SMARTMIPS,
1446     OPTION_DSPR2,
1447     OPTION_NO_DSPR2,
1448     OPTION_DSPR3,
1449     OPTION_NO_DSPR3,
1450     OPTION_EVA,
1451     OPTION_NO_EVA,
1452     OPTION_XPA,
1453     OPTION_NO_XPA,
1454     OPTION_MICROMIPS,
1455     OPTION_NO_MICROMIPS,
1456     OPTION_MCU,
1457     OPTION_NO_MCU,
1458     OPTION_COMPAT_ARCH_BASE,
1459     OPTION_M4650,
1460     OPTION_NO_M4650,
1461     OPTION_M4010,
1462     OPTION_NO_M4010,
1463     OPTION_M4100,
1464     OPTION_NO_M4100,
1465     OPTION_M3900,
1466     OPTION_NO_M3900,
1467     OPTION_M7000_HILO_FIX,
1468     OPTION_MNO_7000_HILO_FIX,
1469     OPTION_FIX_24K,
1470     OPTION_NO_FIX_24K,
1471     OPTION_FIX_RM7000,
1472     OPTION_NO_FIX_RM7000,
1473     OPTION_FIX_LOONGSON2F_JUMP,
1474     OPTION_NO_FIX_LOONGSON2F_JUMP,
1475     OPTION_FIX_LOONGSON2F_NOP,
1476     OPTION_NO_FIX_LOONGSON2F_NOP,
1477     OPTION_FIX_VR4120,
1478     OPTION_NO_FIX_VR4120,
1479     OPTION_FIX_VR4130,
1480     OPTION_NO_FIX_VR4130,
1481     OPTION_FIX_CN63XXP1,
1482     OPTION_NO_FIX_CN63XXP1,
1483     OPTION_TRAP,
1484     OPTION_BREAK,
1485     OPTION_EB,
1486     OPTION_EL,
1487     OPTION_FP32,
1488     OPTION_GP32,
1489     OPTION_CONSTRUCT_FLOATS,
1490     OPTION_NO_CONSTRUCT_FLOATS,
1491     OPTION_FP64,
1492     OPTION_FPXX,
1493     OPTION_GP64,
1494     OPTION_RELAX_BRANCH,
1495     OPTION_NO_RELAX_BRANCH,
1496     OPTION_IGNORE_BRANCH_ISA,
1497     OPTION_NO_IGNORE_BRANCH_ISA,
1498     OPTION_INSN32,
1499     OPTION_NO_INSN32,
1500     OPTION_MSHARED,
1501     OPTION_MNO_SHARED,
1502     OPTION_MSYM32,
1503     OPTION_MNO_SYM32,
1504     OPTION_SOFT_FLOAT,
1505     OPTION_HARD_FLOAT,
1506     OPTION_SINGLE_FLOAT,
1507     OPTION_DOUBLE_FLOAT,
1508     OPTION_32,
1509     OPTION_CALL_SHARED,
1510     OPTION_CALL_NONPIC,
1511     OPTION_NON_SHARED,
1512     OPTION_XGOT,
1513     OPTION_MABI,
1514     OPTION_N32,
1515     OPTION_64,
1516     OPTION_MDEBUG,
1517     OPTION_NO_MDEBUG,
1518     OPTION_PDR,
1519     OPTION_NO_PDR,
1520     OPTION_MVXWORKS_PIC,
1521     OPTION_NAN,
1522     OPTION_ODD_SPREG,
1523     OPTION_NO_ODD_SPREG,
1524     OPTION_END_OF_ENUM
1525   };
1526
1527 struct option md_longopts[] =
1528 {
1529   /* Options which specify architecture.  */
1530   {"march", required_argument, NULL, OPTION_MARCH},
1531   {"mtune", required_argument, NULL, OPTION_MTUNE},
1532   {"mips0", no_argument, NULL, OPTION_MIPS1},
1533   {"mips1", no_argument, NULL, OPTION_MIPS1},
1534   {"mips2", no_argument, NULL, OPTION_MIPS2},
1535   {"mips3", no_argument, NULL, OPTION_MIPS3},
1536   {"mips4", no_argument, NULL, OPTION_MIPS4},
1537   {"mips5", no_argument, NULL, OPTION_MIPS5},
1538   {"mips32", no_argument, NULL, OPTION_MIPS32},
1539   {"mips64", no_argument, NULL, OPTION_MIPS64},
1540   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1541   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1542   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1543   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1544   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1545   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1546   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1547   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1548
1549   /* Options which specify Application Specific Extensions (ASEs).  */
1550   {"mips16", no_argument, NULL, OPTION_MIPS16},
1551   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1552   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1553   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1554   {"mdmx", no_argument, NULL, OPTION_MDMX},
1555   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1556   {"mdsp", no_argument, NULL, OPTION_DSP},
1557   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1558   {"mmt", no_argument, NULL, OPTION_MT},
1559   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1560   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1561   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1562   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1563   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1564   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1565   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1566   {"meva", no_argument, NULL, OPTION_EVA},
1567   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1568   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1569   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1570   {"mmcu", no_argument, NULL, OPTION_MCU},
1571   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1572   {"mvirt", no_argument, NULL, OPTION_VIRT},
1573   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1574   {"mmsa", no_argument, NULL, OPTION_MSA},
1575   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1576   {"mxpa", no_argument, NULL, OPTION_XPA},
1577   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1578
1579   /* Old-style architecture options.  Don't add more of these.  */
1580   {"m4650", no_argument, NULL, OPTION_M4650},
1581   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1582   {"m4010", no_argument, NULL, OPTION_M4010},
1583   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1584   {"m4100", no_argument, NULL, OPTION_M4100},
1585   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1586   {"m3900", no_argument, NULL, OPTION_M3900},
1587   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1588
1589   /* Options which enable bug fixes.  */
1590   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1591   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1592   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1593   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1594   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1595   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1596   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1597   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1598   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1599   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1600   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1601   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1602   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1603   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1604   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1605   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1606   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1607
1608   /* Miscellaneous options.  */
1609   {"trap", no_argument, NULL, OPTION_TRAP},
1610   {"no-break", no_argument, NULL, OPTION_TRAP},
1611   {"break", no_argument, NULL, OPTION_BREAK},
1612   {"no-trap", no_argument, NULL, OPTION_BREAK},
1613   {"EB", no_argument, NULL, OPTION_EB},
1614   {"EL", no_argument, NULL, OPTION_EL},
1615   {"mfp32", no_argument, NULL, OPTION_FP32},
1616   {"mgp32", no_argument, NULL, OPTION_GP32},
1617   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1618   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1619   {"mfp64", no_argument, NULL, OPTION_FP64},
1620   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1621   {"mgp64", no_argument, NULL, OPTION_GP64},
1622   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1623   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1624   {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1625   {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1626   {"minsn32", no_argument, NULL, OPTION_INSN32},
1627   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1628   {"mshared", no_argument, NULL, OPTION_MSHARED},
1629   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1630   {"msym32", no_argument, NULL, OPTION_MSYM32},
1631   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1632   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1633   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1634   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1635   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1636   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1637   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1638
1639   /* Strictly speaking this next option is ELF specific,
1640      but we allow it for other ports as well in order to
1641      make testing easier.  */
1642   {"32", no_argument, NULL, OPTION_32},
1643
1644   /* ELF-specific options.  */
1645   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1646   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1647   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1648   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1649   {"xgot", no_argument, NULL, OPTION_XGOT},
1650   {"mabi", required_argument, NULL, OPTION_MABI},
1651   {"n32", no_argument, NULL, OPTION_N32},
1652   {"64", no_argument, NULL, OPTION_64},
1653   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1654   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1655   {"mpdr", no_argument, NULL, OPTION_PDR},
1656   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1657   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1658   {"mnan", required_argument, NULL, OPTION_NAN},
1659
1660   {NULL, no_argument, NULL, 0}
1661 };
1662 size_t md_longopts_size = sizeof (md_longopts);
1663 \f
1664 /* Information about either an Application Specific Extension or an
1665    optional architecture feature that, for simplicity, we treat in the
1666    same way as an ASE.  */
1667 struct mips_ase
1668 {
1669   /* The name of the ASE, used in both the command-line and .set options.  */
1670   const char *name;
1671
1672   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1673      and 64-bit architectures, the flags here refer to the subset that
1674      is available on both.  */
1675   unsigned int flags;
1676
1677   /* The ASE_* flag used for instructions that are available on 64-bit
1678      architectures but that are not included in FLAGS.  */
1679   unsigned int flags64;
1680
1681   /* The command-line options that turn the ASE on and off.  */
1682   int option_on;
1683   int option_off;
1684
1685   /* The minimum required architecture revisions for MIPS32, MIPS64,
1686      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1687   int mips32_rev;
1688   int mips64_rev;
1689   int micromips32_rev;
1690   int micromips64_rev;
1691
1692   /* The architecture where the ASE was removed or -1 if the extension has not
1693      been removed.  */
1694   int rem_rev;
1695 };
1696
1697 /* A table of all supported ASEs.  */
1698 static const struct mips_ase mips_ases[] = {
1699   { "dsp", ASE_DSP, ASE_DSP64,
1700     OPTION_DSP, OPTION_NO_DSP,
1701     2, 2, 2, 2,
1702     -1 },
1703
1704   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1705     OPTION_DSPR2, OPTION_NO_DSPR2,
1706     2, 2, 2, 2,
1707     -1 },
1708
1709   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1710     OPTION_DSPR3, OPTION_NO_DSPR3,
1711     6, 6, -1, -1,
1712     -1 },
1713
1714   { "eva", ASE_EVA, 0,
1715     OPTION_EVA, OPTION_NO_EVA,
1716      2,  2,  2,  2,
1717     -1 },
1718
1719   { "mcu", ASE_MCU, 0,
1720     OPTION_MCU, OPTION_NO_MCU,
1721      2,  2,  2,  2,
1722     -1 },
1723
1724   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1725   { "mdmx", ASE_MDMX, 0,
1726     OPTION_MDMX, OPTION_NO_MDMX,
1727     -1, 1, -1, -1,
1728      6 },
1729
1730   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1731   { "mips3d", ASE_MIPS3D, 0,
1732     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1733     2, 1, -1, -1,
1734     6 },
1735
1736   { "mt", ASE_MT, 0,
1737     OPTION_MT, OPTION_NO_MT,
1738      2,  2, -1, -1,
1739     -1 },
1740
1741   { "smartmips", ASE_SMARTMIPS, 0,
1742     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1743     1, -1, -1, -1,
1744     6 },
1745
1746   { "virt", ASE_VIRT, ASE_VIRT64,
1747     OPTION_VIRT, OPTION_NO_VIRT,
1748      2,  2,  2,  2,
1749     -1 },
1750
1751   { "msa", ASE_MSA, ASE_MSA64,
1752     OPTION_MSA, OPTION_NO_MSA,
1753      2,  2,  2,  2,
1754     -1 },
1755
1756   { "xpa", ASE_XPA, 0,
1757     OPTION_XPA, OPTION_NO_XPA,
1758      2,  2, -1, -1,
1759     -1 },
1760 };
1761
1762 /* The set of ASEs that require -mfp64.  */
1763 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1764
1765 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1766 static const unsigned int mips_ase_groups[] = {
1767   ASE_DSP | ASE_DSPR2 | ASE_DSPR3
1768 };
1769 \f
1770 /* Pseudo-op table.
1771
1772    The following pseudo-ops from the Kane and Heinrich MIPS book
1773    should be defined here, but are currently unsupported: .alias,
1774    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1775
1776    The following pseudo-ops from the Kane and Heinrich MIPS book are
1777    specific to the type of debugging information being generated, and
1778    should be defined by the object format: .aent, .begin, .bend,
1779    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1780    .vreg.
1781
1782    The following pseudo-ops from the Kane and Heinrich MIPS book are
1783    not MIPS CPU specific, but are also not specific to the object file
1784    format.  This file is probably the best place to define them, but
1785    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1786
1787 static const pseudo_typeS mips_pseudo_table[] =
1788 {
1789   /* MIPS specific pseudo-ops.  */
1790   {"option", s_option, 0},
1791   {"set", s_mipsset, 0},
1792   {"rdata", s_change_sec, 'r'},
1793   {"sdata", s_change_sec, 's'},
1794   {"livereg", s_ignore, 0},
1795   {"abicalls", s_abicalls, 0},
1796   {"cpload", s_cpload, 0},
1797   {"cpsetup", s_cpsetup, 0},
1798   {"cplocal", s_cplocal, 0},
1799   {"cprestore", s_cprestore, 0},
1800   {"cpreturn", s_cpreturn, 0},
1801   {"dtprelword", s_dtprelword, 0},
1802   {"dtpreldword", s_dtpreldword, 0},
1803   {"tprelword", s_tprelword, 0},
1804   {"tpreldword", s_tpreldword, 0},
1805   {"gpvalue", s_gpvalue, 0},
1806   {"gpword", s_gpword, 0},
1807   {"gpdword", s_gpdword, 0},
1808   {"ehword", s_ehword, 0},
1809   {"cpadd", s_cpadd, 0},
1810   {"insn", s_insn, 0},
1811   {"nan", s_nan, 0},
1812   {"module", s_module, 0},
1813
1814   /* Relatively generic pseudo-ops that happen to be used on MIPS
1815      chips.  */
1816   {"asciiz", stringer, 8 + 1},
1817   {"bss", s_change_sec, 'b'},
1818   {"err", s_err, 0},
1819   {"half", s_cons, 1},
1820   {"dword", s_cons, 3},
1821   {"weakext", s_mips_weakext, 0},
1822   {"origin", s_org, 0},
1823   {"repeat", s_rept, 0},
1824
1825   /* For MIPS this is non-standard, but we define it for consistency.  */
1826   {"sbss", s_change_sec, 'B'},
1827
1828   /* These pseudo-ops are defined in read.c, but must be overridden
1829      here for one reason or another.  */
1830   {"align", s_align, 0},
1831   {"byte", s_cons, 0},
1832   {"data", s_change_sec, 'd'},
1833   {"double", s_float_cons, 'd'},
1834   {"float", s_float_cons, 'f'},
1835   {"globl", s_mips_globl, 0},
1836   {"global", s_mips_globl, 0},
1837   {"hword", s_cons, 1},
1838   {"int", s_cons, 2},
1839   {"long", s_cons, 2},
1840   {"octa", s_cons, 4},
1841   {"quad", s_cons, 3},
1842   {"section", s_change_section, 0},
1843   {"short", s_cons, 1},
1844   {"single", s_float_cons, 'f'},
1845   {"stabd", s_mips_stab, 'd'},
1846   {"stabn", s_mips_stab, 'n'},
1847   {"stabs", s_mips_stab, 's'},
1848   {"text", s_change_sec, 't'},
1849   {"word", s_cons, 2},
1850
1851   { "extern", ecoff_directive_extern, 0},
1852
1853   { NULL, NULL, 0 },
1854 };
1855
1856 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1857 {
1858   /* These pseudo-ops should be defined by the object file format.
1859      However, a.out doesn't support them, so we have versions here.  */
1860   {"aent", s_mips_ent, 1},
1861   {"bgnb", s_ignore, 0},
1862   {"end", s_mips_end, 0},
1863   {"endb", s_ignore, 0},
1864   {"ent", s_mips_ent, 0},
1865   {"file", s_mips_file, 0},
1866   {"fmask", s_mips_mask, 'F'},
1867   {"frame", s_mips_frame, 0},
1868   {"loc", s_mips_loc, 0},
1869   {"mask", s_mips_mask, 'R'},
1870   {"verstamp", s_ignore, 0},
1871   { NULL, NULL, 0 },
1872 };
1873
1874 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1875    purpose of the `.dc.a' internal pseudo-op.  */
1876
1877 int
1878 mips_address_bytes (void)
1879 {
1880   file_mips_check_options ();
1881   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1882 }
1883
1884 extern void pop_insert (const pseudo_typeS *);
1885
1886 void
1887 mips_pop_insert (void)
1888 {
1889   pop_insert (mips_pseudo_table);
1890   if (! ECOFF_DEBUGGING)
1891     pop_insert (mips_nonecoff_pseudo_table);
1892 }
1893 \f
1894 /* Symbols labelling the current insn.  */
1895
1896 struct insn_label_list
1897 {
1898   struct insn_label_list *next;
1899   symbolS *label;
1900 };
1901
1902 static struct insn_label_list *free_insn_labels;
1903 #define label_list tc_segment_info_data.labels
1904
1905 static void mips_clear_insn_labels (void);
1906 static void mips_mark_labels (void);
1907 static void mips_compressed_mark_labels (void);
1908
1909 static inline void
1910 mips_clear_insn_labels (void)
1911 {
1912   struct insn_label_list **pl;
1913   segment_info_type *si;
1914
1915   if (now_seg)
1916     {
1917       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1918         ;
1919
1920       si = seg_info (now_seg);
1921       *pl = si->label_list;
1922       si->label_list = NULL;
1923     }
1924 }
1925
1926 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1927
1928 static inline void
1929 mips_mark_labels (void)
1930 {
1931   if (HAVE_CODE_COMPRESSION)
1932     mips_compressed_mark_labels ();
1933 }
1934 \f
1935 static char *expr_end;
1936
1937 /* An expression in a macro instruction.  This is set by mips_ip and
1938    mips16_ip and when populated is always an O_constant.  */
1939
1940 static expressionS imm_expr;
1941
1942 /* The relocatable field in an instruction and the relocs associated
1943    with it.  These variables are used for instructions like LUI and
1944    JAL as well as true offsets.  They are also used for address
1945    operands in macros.  */
1946
1947 static expressionS offset_expr;
1948 static bfd_reloc_code_real_type offset_reloc[3]
1949   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1950
1951 /* This is set to the resulting size of the instruction to be produced
1952    by mips16_ip if an explicit extension is used or by mips_ip if an
1953    explicit size is supplied.  */
1954
1955 static unsigned int forced_insn_length;
1956
1957 /* True if we are assembling an instruction.  All dot symbols defined during
1958    this time should be treated as code labels.  */
1959
1960 static bfd_boolean mips_assembling_insn;
1961
1962 /* The pdr segment for per procedure frame/regmask info.  Not used for
1963    ECOFF debugging.  */
1964
1965 static segT pdr_seg;
1966
1967 /* The default target format to use.  */
1968
1969 #if defined (TE_FreeBSD)
1970 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1971 #elif defined (TE_TMIPS)
1972 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1973 #else
1974 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1975 #endif
1976
1977 const char *
1978 mips_target_format (void)
1979 {
1980   switch (OUTPUT_FLAVOR)
1981     {
1982     case bfd_target_elf_flavour:
1983 #ifdef TE_VXWORKS
1984       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1985         return (target_big_endian
1986                 ? "elf32-bigmips-vxworks"
1987                 : "elf32-littlemips-vxworks");
1988 #endif
1989       return (target_big_endian
1990               ? (HAVE_64BIT_OBJECTS
1991                  ? ELF_TARGET ("elf64-", "big")
1992                  : (HAVE_NEWABI
1993                     ? ELF_TARGET ("elf32-n", "big")
1994                     : ELF_TARGET ("elf32-", "big")))
1995               : (HAVE_64BIT_OBJECTS
1996                  ? ELF_TARGET ("elf64-", "little")
1997                  : (HAVE_NEWABI
1998                     ? ELF_TARGET ("elf32-n", "little")
1999                     : ELF_TARGET ("elf32-", "little"))));
2000     default:
2001       abort ();
2002       return NULL;
2003     }
2004 }
2005
2006 /* Return the ISA revision that is currently in use, or 0 if we are
2007    generating code for MIPS V or below.  */
2008
2009 static int
2010 mips_isa_rev (void)
2011 {
2012   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2013     return 2;
2014
2015   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2016     return 3;
2017
2018   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2019     return 5;
2020
2021   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2022     return 6;
2023
2024   /* microMIPS implies revision 2 or above.  */
2025   if (mips_opts.micromips)
2026     return 2;
2027
2028   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2029     return 1;
2030
2031   return 0;
2032 }
2033
2034 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2035
2036 static unsigned int
2037 mips_ase_mask (unsigned int flags)
2038 {
2039   unsigned int i;
2040
2041   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2042     if (flags & mips_ase_groups[i])
2043       flags |= mips_ase_groups[i];
2044   return flags;
2045 }
2046
2047 /* Check whether the current ISA supports ASE.  Issue a warning if
2048    appropriate.  */
2049
2050 static void
2051 mips_check_isa_supports_ase (const struct mips_ase *ase)
2052 {
2053   const char *base;
2054   int min_rev, size;
2055   static unsigned int warned_isa;
2056   static unsigned int warned_fp32;
2057
2058   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2059     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2060   else
2061     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2062   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2063       && (warned_isa & ase->flags) != ase->flags)
2064     {
2065       warned_isa |= ase->flags;
2066       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2067       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2068       if (min_rev < 0)
2069         as_warn (_("the %d-bit %s architecture does not support the"
2070                    " `%s' extension"), size, base, ase->name);
2071       else
2072         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2073                  ase->name, base, size, min_rev);
2074     }
2075   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2076            && (warned_isa & ase->flags) != ase->flags)
2077     {
2078       warned_isa |= ase->flags;
2079       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2080       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2081       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2082                ase->name, base, size, ase->rem_rev);
2083     }
2084
2085   if ((ase->flags & FP64_ASES)
2086       && mips_opts.fp != 64
2087       && (warned_fp32 & ase->flags) != ase->flags)
2088     {
2089       warned_fp32 |= ase->flags;
2090       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2091     }
2092 }
2093
2094 /* Check all enabled ASEs to see whether they are supported by the
2095    chosen architecture.  */
2096
2097 static void
2098 mips_check_isa_supports_ases (void)
2099 {
2100   unsigned int i, mask;
2101
2102   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2103     {
2104       mask = mips_ase_mask (mips_ases[i].flags);
2105       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2106         mips_check_isa_supports_ase (&mips_ases[i]);
2107     }
2108 }
2109
2110 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2111    that were affected.  */
2112
2113 static unsigned int
2114 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2115               bfd_boolean enabled_p)
2116 {
2117   unsigned int mask;
2118
2119   mask = mips_ase_mask (ase->flags);
2120   opts->ase &= ~mask;
2121   if (enabled_p)
2122     opts->ase |= ase->flags;
2123   return mask;
2124 }
2125
2126 /* Return the ASE called NAME, or null if none.  */
2127
2128 static const struct mips_ase *
2129 mips_lookup_ase (const char *name)
2130 {
2131   unsigned int i;
2132
2133   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2134     if (strcmp (name, mips_ases[i].name) == 0)
2135       return &mips_ases[i];
2136   return NULL;
2137 }
2138
2139 /* Return the length of a microMIPS instruction in bytes.  If bits of
2140    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2141    otherwise it is a 32-bit instruction.  */
2142
2143 static inline unsigned int
2144 micromips_insn_length (const struct mips_opcode *mo)
2145 {
2146   return mips_opcode_32bit_p (mo) ? 4 : 2;
2147 }
2148
2149 /* Return the length of MIPS16 instruction OPCODE.  */
2150
2151 static inline unsigned int
2152 mips16_opcode_length (unsigned long opcode)
2153 {
2154   return (opcode >> 16) == 0 ? 2 : 4;
2155 }
2156
2157 /* Return the length of instruction INSN.  */
2158
2159 static inline unsigned int
2160 insn_length (const struct mips_cl_insn *insn)
2161 {
2162   if (mips_opts.micromips)
2163     return micromips_insn_length (insn->insn_mo);
2164   else if (mips_opts.mips16)
2165     return mips16_opcode_length (insn->insn_opcode);
2166   else
2167     return 4;
2168 }
2169
2170 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2171
2172 static void
2173 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2174 {
2175   size_t i;
2176
2177   insn->insn_mo = mo;
2178   insn->insn_opcode = mo->match;
2179   insn->frag = NULL;
2180   insn->where = 0;
2181   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2182     insn->fixp[i] = NULL;
2183   insn->fixed_p = (mips_opts.noreorder > 0);
2184   insn->noreorder_p = (mips_opts.noreorder > 0);
2185   insn->mips16_absolute_jump_p = 0;
2186   insn->complete_p = 0;
2187   insn->cleared_p = 0;
2188 }
2189
2190 /* Get a list of all the operands in INSN.  */
2191
2192 static const struct mips_operand_array *
2193 insn_operands (const struct mips_cl_insn *insn)
2194 {
2195   if (insn->insn_mo >= &mips_opcodes[0]
2196       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2197     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2198
2199   if (insn->insn_mo >= &mips16_opcodes[0]
2200       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2201     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2202
2203   if (insn->insn_mo >= &micromips_opcodes[0]
2204       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2205     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2206
2207   abort ();
2208 }
2209
2210 /* Get a description of operand OPNO of INSN.  */
2211
2212 static const struct mips_operand *
2213 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2214 {
2215   const struct mips_operand_array *operands;
2216
2217   operands = insn_operands (insn);
2218   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2219     abort ();
2220   return operands->operand[opno];
2221 }
2222
2223 /* Install UVAL as the value of OPERAND in INSN.  */
2224
2225 static inline void
2226 insn_insert_operand (struct mips_cl_insn *insn,
2227                      const struct mips_operand *operand, unsigned int uval)
2228 {
2229   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2230 }
2231
2232 /* Extract the value of OPERAND from INSN.  */
2233
2234 static inline unsigned
2235 insn_extract_operand (const struct mips_cl_insn *insn,
2236                       const struct mips_operand *operand)
2237 {
2238   return mips_extract_operand (operand, insn->insn_opcode);
2239 }
2240
2241 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2242
2243 static void
2244 mips_record_compressed_mode (void)
2245 {
2246   segment_info_type *si;
2247
2248   si = seg_info (now_seg);
2249   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2250     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2251   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2252     si->tc_segment_info_data.micromips = mips_opts.micromips;
2253 }
2254
2255 /* Read a standard MIPS instruction from BUF.  */
2256
2257 static unsigned long
2258 read_insn (char *buf)
2259 {
2260   if (target_big_endian)
2261     return bfd_getb32 ((bfd_byte *) buf);
2262   else
2263     return bfd_getl32 ((bfd_byte *) buf);
2264 }
2265
2266 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2267    the next byte.  */
2268
2269 static char *
2270 write_insn (char *buf, unsigned int insn)
2271 {
2272   md_number_to_chars (buf, insn, 4);
2273   return buf + 4;
2274 }
2275
2276 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2277    has length LENGTH.  */
2278
2279 static unsigned long
2280 read_compressed_insn (char *buf, unsigned int length)
2281 {
2282   unsigned long insn;
2283   unsigned int i;
2284
2285   insn = 0;
2286   for (i = 0; i < length; i += 2)
2287     {
2288       insn <<= 16;
2289       if (target_big_endian)
2290         insn |= bfd_getb16 ((char *) buf);
2291       else
2292         insn |= bfd_getl16 ((char *) buf);
2293       buf += 2;
2294     }
2295   return insn;
2296 }
2297
2298 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2299    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2300
2301 static char *
2302 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2303 {
2304   unsigned int i;
2305
2306   for (i = 0; i < length; i += 2)
2307     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2308   return buf + length;
2309 }
2310
2311 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2312
2313 static void
2314 install_insn (const struct mips_cl_insn *insn)
2315 {
2316   char *f = insn->frag->fr_literal + insn->where;
2317   if (HAVE_CODE_COMPRESSION)
2318     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2319   else
2320     write_insn (f, insn->insn_opcode);
2321   mips_record_compressed_mode ();
2322 }
2323
2324 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2325    and install the opcode in the new location.  */
2326
2327 static void
2328 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2329 {
2330   size_t i;
2331
2332   insn->frag = frag;
2333   insn->where = where;
2334   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2335     if (insn->fixp[i] != NULL)
2336       {
2337         insn->fixp[i]->fx_frag = frag;
2338         insn->fixp[i]->fx_where = where;
2339       }
2340   install_insn (insn);
2341 }
2342
2343 /* Add INSN to the end of the output.  */
2344
2345 static void
2346 add_fixed_insn (struct mips_cl_insn *insn)
2347 {
2348   char *f = frag_more (insn_length (insn));
2349   move_insn (insn, frag_now, f - frag_now->fr_literal);
2350 }
2351
2352 /* Start a variant frag and move INSN to the start of the variant part,
2353    marking it as fixed.  The other arguments are as for frag_var.  */
2354
2355 static void
2356 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2357                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2358 {
2359   frag_grow (max_chars);
2360   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2361   insn->fixed_p = 1;
2362   frag_var (rs_machine_dependent, max_chars, var,
2363             subtype, symbol, offset, NULL);
2364 }
2365
2366 /* Insert N copies of INSN into the history buffer, starting at
2367    position FIRST.  Neither FIRST nor N need to be clipped.  */
2368
2369 static void
2370 insert_into_history (unsigned int first, unsigned int n,
2371                      const struct mips_cl_insn *insn)
2372 {
2373   if (mips_relax.sequence != 2)
2374     {
2375       unsigned int i;
2376
2377       for (i = ARRAY_SIZE (history); i-- > first;)
2378         if (i >= first + n)
2379           history[i] = history[i - n];
2380         else
2381           history[i] = *insn;
2382     }
2383 }
2384
2385 /* Clear the error in insn_error.  */
2386
2387 static void
2388 clear_insn_error (void)
2389 {
2390   memset (&insn_error, 0, sizeof (insn_error));
2391 }
2392
2393 /* Possibly record error message MSG for the current instruction.
2394    If the error is about a particular argument, ARGNUM is the 1-based
2395    number of that argument, otherwise it is 0.  FORMAT is the format
2396    of MSG.  Return true if MSG was used, false if the current message
2397    was kept.  */
2398
2399 static bfd_boolean
2400 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2401                        const char *msg)
2402 {
2403   if (argnum == 0)
2404     {
2405       /* Give priority to errors against specific arguments, and to
2406          the first whole-instruction message.  */
2407       if (insn_error.msg)
2408         return FALSE;
2409     }
2410   else
2411     {
2412       /* Keep insn_error if it is against a later argument.  */
2413       if (argnum < insn_error.min_argnum)
2414         return FALSE;
2415
2416       /* If both errors are against the same argument but are different,
2417          give up on reporting a specific error for this argument.
2418          See the comment about mips_insn_error for details.  */
2419       if (argnum == insn_error.min_argnum
2420           && insn_error.msg
2421           && strcmp (insn_error.msg, msg) != 0)
2422         {
2423           insn_error.msg = 0;
2424           insn_error.min_argnum += 1;
2425           return FALSE;
2426         }
2427     }
2428   insn_error.min_argnum = argnum;
2429   insn_error.format = format;
2430   insn_error.msg = msg;
2431   return TRUE;
2432 }
2433
2434 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2435    as for set_insn_error_format.  */
2436
2437 static void
2438 set_insn_error (int argnum, const char *msg)
2439 {
2440   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2441 }
2442
2443 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2444    as for set_insn_error_format.  */
2445
2446 static void
2447 set_insn_error_i (int argnum, const char *msg, int i)
2448 {
2449   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2450     insn_error.u.i = i;
2451 }
2452
2453 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2454    are as for set_insn_error_format.  */
2455
2456 static void
2457 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2458 {
2459   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2460     {
2461       insn_error.u.ss[0] = s1;
2462       insn_error.u.ss[1] = s2;
2463     }
2464 }
2465
2466 /* Report the error in insn_error, which is against assembly code STR.  */
2467
2468 static void
2469 report_insn_error (const char *str)
2470 {
2471   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2472
2473   switch (insn_error.format)
2474     {
2475     case ERR_FMT_PLAIN:
2476       as_bad (msg, str);
2477       break;
2478
2479     case ERR_FMT_I:
2480       as_bad (msg, insn_error.u.i, str);
2481       break;
2482
2483     case ERR_FMT_SS:
2484       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2485       break;
2486     }
2487
2488   free ((char *) msg);
2489 }
2490
2491 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2492    the idea is to make it obvious at a glance that each errata is
2493    included.  */
2494
2495 static void
2496 init_vr4120_conflicts (void)
2497 {
2498 #define CONFLICT(FIRST, SECOND) \
2499     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2500
2501   /* Errata 21 - [D]DIV[U] after [D]MACC */
2502   CONFLICT (MACC, DIV);
2503   CONFLICT (DMACC, DIV);
2504
2505   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2506   CONFLICT (DMULT, DMULT);
2507   CONFLICT (DMULT, DMACC);
2508   CONFLICT (DMACC, DMULT);
2509   CONFLICT (DMACC, DMACC);
2510
2511   /* Errata 24 - MT{LO,HI} after [D]MACC */
2512   CONFLICT (MACC, MTHILO);
2513   CONFLICT (DMACC, MTHILO);
2514
2515   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2516      instruction is executed immediately after a MACC or DMACC
2517      instruction, the result of [either instruction] is incorrect."  */
2518   CONFLICT (MACC, MULT);
2519   CONFLICT (MACC, DMULT);
2520   CONFLICT (DMACC, MULT);
2521   CONFLICT (DMACC, DMULT);
2522
2523   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2524      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2525      DDIV or DDIVU instruction, the result of the MACC or
2526      DMACC instruction is incorrect.".  */
2527   CONFLICT (DMULT, MACC);
2528   CONFLICT (DMULT, DMACC);
2529   CONFLICT (DIV, MACC);
2530   CONFLICT (DIV, DMACC);
2531
2532 #undef CONFLICT
2533 }
2534
2535 struct regname {
2536   const char *name;
2537   unsigned int num;
2538 };
2539
2540 #define RNUM_MASK       0x00000ff
2541 #define RTYPE_MASK      0x0ffff00
2542 #define RTYPE_NUM       0x0000100
2543 #define RTYPE_FPU       0x0000200
2544 #define RTYPE_FCC       0x0000400
2545 #define RTYPE_VEC       0x0000800
2546 #define RTYPE_GP        0x0001000
2547 #define RTYPE_CP0       0x0002000
2548 #define RTYPE_PC        0x0004000
2549 #define RTYPE_ACC       0x0008000
2550 #define RTYPE_CCC       0x0010000
2551 #define RTYPE_VI        0x0020000
2552 #define RTYPE_VF        0x0040000
2553 #define RTYPE_R5900_I   0x0080000
2554 #define RTYPE_R5900_Q   0x0100000
2555 #define RTYPE_R5900_R   0x0200000
2556 #define RTYPE_R5900_ACC 0x0400000
2557 #define RTYPE_MSA       0x0800000
2558 #define RWARN           0x8000000
2559
2560 #define GENERIC_REGISTER_NUMBERS \
2561     {"$0",      RTYPE_NUM | 0},  \
2562     {"$1",      RTYPE_NUM | 1},  \
2563     {"$2",      RTYPE_NUM | 2},  \
2564     {"$3",      RTYPE_NUM | 3},  \
2565     {"$4",      RTYPE_NUM | 4},  \
2566     {"$5",      RTYPE_NUM | 5},  \
2567     {"$6",      RTYPE_NUM | 6},  \
2568     {"$7",      RTYPE_NUM | 7},  \
2569     {"$8",      RTYPE_NUM | 8},  \
2570     {"$9",      RTYPE_NUM | 9},  \
2571     {"$10",     RTYPE_NUM | 10}, \
2572     {"$11",     RTYPE_NUM | 11}, \
2573     {"$12",     RTYPE_NUM | 12}, \
2574     {"$13",     RTYPE_NUM | 13}, \
2575     {"$14",     RTYPE_NUM | 14}, \
2576     {"$15",     RTYPE_NUM | 15}, \
2577     {"$16",     RTYPE_NUM | 16}, \
2578     {"$17",     RTYPE_NUM | 17}, \
2579     {"$18",     RTYPE_NUM | 18}, \
2580     {"$19",     RTYPE_NUM | 19}, \
2581     {"$20",     RTYPE_NUM | 20}, \
2582     {"$21",     RTYPE_NUM | 21}, \
2583     {"$22",     RTYPE_NUM | 22}, \
2584     {"$23",     RTYPE_NUM | 23}, \
2585     {"$24",     RTYPE_NUM | 24}, \
2586     {"$25",     RTYPE_NUM | 25}, \
2587     {"$26",     RTYPE_NUM | 26}, \
2588     {"$27",     RTYPE_NUM | 27}, \
2589     {"$28",     RTYPE_NUM | 28}, \
2590     {"$29",     RTYPE_NUM | 29}, \
2591     {"$30",     RTYPE_NUM | 30}, \
2592     {"$31",     RTYPE_NUM | 31}
2593
2594 #define FPU_REGISTER_NAMES       \
2595     {"$f0",     RTYPE_FPU | 0},  \
2596     {"$f1",     RTYPE_FPU | 1},  \
2597     {"$f2",     RTYPE_FPU | 2},  \
2598     {"$f3",     RTYPE_FPU | 3},  \
2599     {"$f4",     RTYPE_FPU | 4},  \
2600     {"$f5",     RTYPE_FPU | 5},  \
2601     {"$f6",     RTYPE_FPU | 6},  \
2602     {"$f7",     RTYPE_FPU | 7},  \
2603     {"$f8",     RTYPE_FPU | 8},  \
2604     {"$f9",     RTYPE_FPU | 9},  \
2605     {"$f10",    RTYPE_FPU | 10}, \
2606     {"$f11",    RTYPE_FPU | 11}, \
2607     {"$f12",    RTYPE_FPU | 12}, \
2608     {"$f13",    RTYPE_FPU | 13}, \
2609     {"$f14",    RTYPE_FPU | 14}, \
2610     {"$f15",    RTYPE_FPU | 15}, \
2611     {"$f16",    RTYPE_FPU | 16}, \
2612     {"$f17",    RTYPE_FPU | 17}, \
2613     {"$f18",    RTYPE_FPU | 18}, \
2614     {"$f19",    RTYPE_FPU | 19}, \
2615     {"$f20",    RTYPE_FPU | 20}, \
2616     {"$f21",    RTYPE_FPU | 21}, \
2617     {"$f22",    RTYPE_FPU | 22}, \
2618     {"$f23",    RTYPE_FPU | 23}, \
2619     {"$f24",    RTYPE_FPU | 24}, \
2620     {"$f25",    RTYPE_FPU | 25}, \
2621     {"$f26",    RTYPE_FPU | 26}, \
2622     {"$f27",    RTYPE_FPU | 27}, \
2623     {"$f28",    RTYPE_FPU | 28}, \
2624     {"$f29",    RTYPE_FPU | 29}, \
2625     {"$f30",    RTYPE_FPU | 30}, \
2626     {"$f31",    RTYPE_FPU | 31}
2627
2628 #define FPU_CONDITION_CODE_NAMES \
2629     {"$fcc0",   RTYPE_FCC | 0},  \
2630     {"$fcc1",   RTYPE_FCC | 1},  \
2631     {"$fcc2",   RTYPE_FCC | 2},  \
2632     {"$fcc3",   RTYPE_FCC | 3},  \
2633     {"$fcc4",   RTYPE_FCC | 4},  \
2634     {"$fcc5",   RTYPE_FCC | 5},  \
2635     {"$fcc6",   RTYPE_FCC | 6},  \
2636     {"$fcc7",   RTYPE_FCC | 7}
2637
2638 #define COPROC_CONDITION_CODE_NAMES         \
2639     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2640     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2641     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2642     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2643     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2644     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2645     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2646     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2647
2648 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2649     {"$a4",     RTYPE_GP | 8},  \
2650     {"$a5",     RTYPE_GP | 9},  \
2651     {"$a6",     RTYPE_GP | 10}, \
2652     {"$a7",     RTYPE_GP | 11}, \
2653     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2654     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2655     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2656     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2657     {"$t0",     RTYPE_GP | 12}, \
2658     {"$t1",     RTYPE_GP | 13}, \
2659     {"$t2",     RTYPE_GP | 14}, \
2660     {"$t3",     RTYPE_GP | 15}
2661
2662 #define O32_SYMBOLIC_REGISTER_NAMES \
2663     {"$t0",     RTYPE_GP | 8},  \
2664     {"$t1",     RTYPE_GP | 9},  \
2665     {"$t2",     RTYPE_GP | 10}, \
2666     {"$t3",     RTYPE_GP | 11}, \
2667     {"$t4",     RTYPE_GP | 12}, \
2668     {"$t5",     RTYPE_GP | 13}, \
2669     {"$t6",     RTYPE_GP | 14}, \
2670     {"$t7",     RTYPE_GP | 15}, \
2671     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2672     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2673     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2674     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2675
2676 /* Remaining symbolic register names */
2677 #define SYMBOLIC_REGISTER_NAMES \
2678     {"$zero",   RTYPE_GP | 0},  \
2679     {"$at",     RTYPE_GP | 1},  \
2680     {"$AT",     RTYPE_GP | 1},  \
2681     {"$v0",     RTYPE_GP | 2},  \
2682     {"$v1",     RTYPE_GP | 3},  \
2683     {"$a0",     RTYPE_GP | 4},  \
2684     {"$a1",     RTYPE_GP | 5},  \
2685     {"$a2",     RTYPE_GP | 6},  \
2686     {"$a3",     RTYPE_GP | 7},  \
2687     {"$s0",     RTYPE_GP | 16}, \
2688     {"$s1",     RTYPE_GP | 17}, \
2689     {"$s2",     RTYPE_GP | 18}, \
2690     {"$s3",     RTYPE_GP | 19}, \
2691     {"$s4",     RTYPE_GP | 20}, \
2692     {"$s5",     RTYPE_GP | 21}, \
2693     {"$s6",     RTYPE_GP | 22}, \
2694     {"$s7",     RTYPE_GP | 23}, \
2695     {"$t8",     RTYPE_GP | 24}, \
2696     {"$t9",     RTYPE_GP | 25}, \
2697     {"$k0",     RTYPE_GP | 26}, \
2698     {"$kt0",    RTYPE_GP | 26}, \
2699     {"$k1",     RTYPE_GP | 27}, \
2700     {"$kt1",    RTYPE_GP | 27}, \
2701     {"$gp",     RTYPE_GP | 28}, \
2702     {"$sp",     RTYPE_GP | 29}, \
2703     {"$s8",     RTYPE_GP | 30}, \
2704     {"$fp",     RTYPE_GP | 30}, \
2705     {"$ra",     RTYPE_GP | 31}
2706
2707 #define MIPS16_SPECIAL_REGISTER_NAMES \
2708     {"$pc",     RTYPE_PC | 0}
2709
2710 #define MDMX_VECTOR_REGISTER_NAMES \
2711     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2712     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2713     {"$v2",     RTYPE_VEC | 2},  \
2714     {"$v3",     RTYPE_VEC | 3},  \
2715     {"$v4",     RTYPE_VEC | 4},  \
2716     {"$v5",     RTYPE_VEC | 5},  \
2717     {"$v6",     RTYPE_VEC | 6},  \
2718     {"$v7",     RTYPE_VEC | 7},  \
2719     {"$v8",     RTYPE_VEC | 8},  \
2720     {"$v9",     RTYPE_VEC | 9},  \
2721     {"$v10",    RTYPE_VEC | 10}, \
2722     {"$v11",    RTYPE_VEC | 11}, \
2723     {"$v12",    RTYPE_VEC | 12}, \
2724     {"$v13",    RTYPE_VEC | 13}, \
2725     {"$v14",    RTYPE_VEC | 14}, \
2726     {"$v15",    RTYPE_VEC | 15}, \
2727     {"$v16",    RTYPE_VEC | 16}, \
2728     {"$v17",    RTYPE_VEC | 17}, \
2729     {"$v18",    RTYPE_VEC | 18}, \
2730     {"$v19",    RTYPE_VEC | 19}, \
2731     {"$v20",    RTYPE_VEC | 20}, \
2732     {"$v21",    RTYPE_VEC | 21}, \
2733     {"$v22",    RTYPE_VEC | 22}, \
2734     {"$v23",    RTYPE_VEC | 23}, \
2735     {"$v24",    RTYPE_VEC | 24}, \
2736     {"$v25",    RTYPE_VEC | 25}, \
2737     {"$v26",    RTYPE_VEC | 26}, \
2738     {"$v27",    RTYPE_VEC | 27}, \
2739     {"$v28",    RTYPE_VEC | 28}, \
2740     {"$v29",    RTYPE_VEC | 29}, \
2741     {"$v30",    RTYPE_VEC | 30}, \
2742     {"$v31",    RTYPE_VEC | 31}
2743
2744 #define R5900_I_NAMES \
2745     {"$I",      RTYPE_R5900_I | 0}
2746
2747 #define R5900_Q_NAMES \
2748     {"$Q",      RTYPE_R5900_Q | 0}
2749
2750 #define R5900_R_NAMES \
2751     {"$R",      RTYPE_R5900_R | 0}
2752
2753 #define R5900_ACC_NAMES \
2754     {"$ACC",    RTYPE_R5900_ACC | 0 }
2755
2756 #define MIPS_DSP_ACCUMULATOR_NAMES \
2757     {"$ac0",    RTYPE_ACC | 0}, \
2758     {"$ac1",    RTYPE_ACC | 1}, \
2759     {"$ac2",    RTYPE_ACC | 2}, \
2760     {"$ac3",    RTYPE_ACC | 3}
2761
2762 static const struct regname reg_names[] = {
2763   GENERIC_REGISTER_NUMBERS,
2764   FPU_REGISTER_NAMES,
2765   FPU_CONDITION_CODE_NAMES,
2766   COPROC_CONDITION_CODE_NAMES,
2767
2768   /* The $txx registers depends on the abi,
2769      these will be added later into the symbol table from
2770      one of the tables below once mips_abi is set after
2771      parsing of arguments from the command line. */
2772   SYMBOLIC_REGISTER_NAMES,
2773
2774   MIPS16_SPECIAL_REGISTER_NAMES,
2775   MDMX_VECTOR_REGISTER_NAMES,
2776   R5900_I_NAMES,
2777   R5900_Q_NAMES,
2778   R5900_R_NAMES,
2779   R5900_ACC_NAMES,
2780   MIPS_DSP_ACCUMULATOR_NAMES,
2781   {0, 0}
2782 };
2783
2784 static const struct regname reg_names_o32[] = {
2785   O32_SYMBOLIC_REGISTER_NAMES,
2786   {0, 0}
2787 };
2788
2789 static const struct regname reg_names_n32n64[] = {
2790   N32N64_SYMBOLIC_REGISTER_NAMES,
2791   {0, 0}
2792 };
2793
2794 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2795    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2796    of these register symbols, return the associated vector register,
2797    otherwise return SYMVAL itself.  */
2798
2799 static unsigned int
2800 mips_prefer_vec_regno (unsigned int symval)
2801 {
2802   if ((symval & -2) == (RTYPE_GP | 2))
2803     return RTYPE_VEC | (symval & 1);
2804   return symval;
2805 }
2806
2807 /* Return true if string [S, E) is a valid register name, storing its
2808    symbol value in *SYMVAL_PTR if so.  */
2809
2810 static bfd_boolean
2811 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2812 {
2813   char save_c;
2814   symbolS *symbol;
2815
2816   /* Terminate name.  */
2817   save_c = *e;
2818   *e = '\0';
2819
2820   /* Look up the name.  */
2821   symbol = symbol_find (s);
2822   *e = save_c;
2823
2824   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2825     return FALSE;
2826
2827   *symval_ptr = S_GET_VALUE (symbol);
2828   return TRUE;
2829 }
2830
2831 /* Return true if the string at *SPTR is a valid register name.  Allow it
2832    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2833    is nonnull.
2834
2835    When returning true, move *SPTR past the register, store the
2836    register's symbol value in *SYMVAL_PTR and the channel mask in
2837    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2838    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2839    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2840
2841 static bfd_boolean
2842 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2843                      unsigned int *channels_ptr)
2844 {
2845   char *s, *e, *m;
2846   const char *q;
2847   unsigned int channels, symval, bit;
2848
2849   /* Find end of name.  */
2850   s = e = *sptr;
2851   if (is_name_beginner (*e))
2852     ++e;
2853   while (is_part_of_name (*e))
2854     ++e;
2855
2856   channels = 0;
2857   if (!mips_parse_register_1 (s, e, &symval))
2858     {
2859       if (!channels_ptr)
2860         return FALSE;
2861
2862       /* Eat characters from the end of the string that are valid
2863          channel suffixes.  The preceding register must be $ACC or
2864          end with a digit, so there is no ambiguity.  */
2865       bit = 1;
2866       m = e;
2867       for (q = "wzyx"; *q; q++, bit <<= 1)
2868         if (m > s && m[-1] == *q)
2869           {
2870             --m;
2871             channels |= bit;
2872           }
2873
2874       if (channels == 0
2875           || !mips_parse_register_1 (s, m, &symval)
2876           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2877         return FALSE;
2878     }
2879
2880   *sptr = e;
2881   *symval_ptr = symval;
2882   if (channels_ptr)
2883     *channels_ptr = channels;
2884   return TRUE;
2885 }
2886
2887 /* Check if SPTR points at a valid register specifier according to TYPES.
2888    If so, then return 1, advance S to consume the specifier and store
2889    the register's number in REGNOP, otherwise return 0.  */
2890
2891 static int
2892 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2893 {
2894   unsigned int regno;
2895
2896   if (mips_parse_register (s, &regno, NULL))
2897     {
2898       if (types & RTYPE_VEC)
2899         regno = mips_prefer_vec_regno (regno);
2900       if (regno & types)
2901         regno &= RNUM_MASK;
2902       else
2903         regno = ~0;
2904     }
2905   else
2906     {
2907       if (types & RWARN)
2908         as_warn (_("unrecognized register name `%s'"), *s);
2909       regno = ~0;
2910     }
2911   if (regnop)
2912     *regnop = regno;
2913   return regno <= RNUM_MASK;
2914 }
2915
2916 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2917    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2918
2919 static char *
2920 mips_parse_vu0_channels (char *s, unsigned int *channels)
2921 {
2922   unsigned int i;
2923
2924   *channels = 0;
2925   for (i = 0; i < 4; i++)
2926     if (*s == "xyzw"[i])
2927       {
2928         *channels |= 1 << (3 - i);
2929         ++s;
2930       }
2931   return s;
2932 }
2933
2934 /* Token types for parsed operand lists.  */
2935 enum mips_operand_token_type {
2936   /* A plain register, e.g. $f2.  */
2937   OT_REG,
2938
2939   /* A 4-bit XYZW channel mask.  */
2940   OT_CHANNELS,
2941
2942   /* A constant vector index, e.g. [1].  */
2943   OT_INTEGER_INDEX,
2944
2945   /* A register vector index, e.g. [$2].  */
2946   OT_REG_INDEX,
2947
2948   /* A continuous range of registers, e.g. $s0-$s4.  */
2949   OT_REG_RANGE,
2950
2951   /* A (possibly relocated) expression.  */
2952   OT_INTEGER,
2953
2954   /* A floating-point value.  */
2955   OT_FLOAT,
2956
2957   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2958      before OT_REGs.  */
2959   OT_CHAR,
2960
2961   /* A doubled character, either "--" or "++".  */
2962   OT_DOUBLE_CHAR,
2963
2964   /* The end of the operand list.  */
2965   OT_END
2966 };
2967
2968 /* A parsed operand token.  */
2969 struct mips_operand_token
2970 {
2971   /* The type of token.  */
2972   enum mips_operand_token_type type;
2973   union
2974   {
2975     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2976     unsigned int regno;
2977
2978     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2979     unsigned int channels;
2980
2981     /* The integer value of an OT_INTEGER_INDEX.  */
2982     addressT index;
2983
2984     /* The two register symbol values involved in an OT_REG_RANGE.  */
2985     struct {
2986       unsigned int regno1;
2987       unsigned int regno2;
2988     } reg_range;
2989
2990     /* The value of an OT_INTEGER.  The value is represented as an
2991        expression and the relocation operators that were applied to
2992        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2993        relocation operators were used.  */
2994     struct {
2995       expressionS value;
2996       bfd_reloc_code_real_type relocs[3];
2997     } integer;
2998
2999     /* The binary data for an OT_FLOAT constant, and the number of bytes
3000        in the constant.  */
3001     struct {
3002       unsigned char data[8];
3003       int length;
3004     } flt;
3005
3006     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3007     char ch;
3008   } u;
3009 };
3010
3011 /* An obstack used to construct lists of mips_operand_tokens.  */
3012 static struct obstack mips_operand_tokens;
3013
3014 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3015
3016 static void
3017 mips_add_token (struct mips_operand_token *token,
3018                 enum mips_operand_token_type type)
3019 {
3020   token->type = type;
3021   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3022 }
3023
3024 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
3025    and OT_REG tokens for them if so, and return a pointer to the first
3026    unconsumed character.  Return null otherwise.  */
3027
3028 static char *
3029 mips_parse_base_start (char *s)
3030 {
3031   struct mips_operand_token token;
3032   unsigned int regno, channels;
3033   bfd_boolean decrement_p;
3034
3035   if (*s != '(')
3036     return 0;
3037
3038   ++s;
3039   SKIP_SPACE_TABS (s);
3040
3041   /* Only match "--" as part of a base expression.  In other contexts "--X"
3042      is a double negative.  */
3043   decrement_p = (s[0] == '-' && s[1] == '-');
3044   if (decrement_p)
3045     {
3046       s += 2;
3047       SKIP_SPACE_TABS (s);
3048     }
3049
3050   /* Allow a channel specifier because that leads to better error messages
3051      than treating something like "$vf0x++" as an expression.  */
3052   if (!mips_parse_register (&s, &regno, &channels))
3053     return 0;
3054
3055   token.u.ch = '(';
3056   mips_add_token (&token, OT_CHAR);
3057
3058   if (decrement_p)
3059     {
3060       token.u.ch = '-';
3061       mips_add_token (&token, OT_DOUBLE_CHAR);
3062     }
3063
3064   token.u.regno = regno;
3065   mips_add_token (&token, OT_REG);
3066
3067   if (channels)
3068     {
3069       token.u.channels = channels;
3070       mips_add_token (&token, OT_CHANNELS);
3071     }
3072
3073   /* For consistency, only match "++" as part of base expressions too.  */
3074   SKIP_SPACE_TABS (s);
3075   if (s[0] == '+' && s[1] == '+')
3076     {
3077       s += 2;
3078       token.u.ch = '+';
3079       mips_add_token (&token, OT_DOUBLE_CHAR);
3080     }
3081
3082   return s;
3083 }
3084
3085 /* Parse one or more tokens from S.  Return a pointer to the first
3086    unconsumed character on success.  Return null if an error was found
3087    and store the error text in insn_error.  FLOAT_FORMAT is as for
3088    mips_parse_arguments.  */
3089
3090 static char *
3091 mips_parse_argument_token (char *s, char float_format)
3092 {
3093   char *end, *save_in;
3094   const char *err;
3095   unsigned int regno1, regno2, channels;
3096   struct mips_operand_token token;
3097
3098   /* First look for "($reg", since we want to treat that as an
3099      OT_CHAR and OT_REG rather than an expression.  */
3100   end = mips_parse_base_start (s);
3101   if (end)
3102     return end;
3103
3104   /* Handle other characters that end up as OT_CHARs.  */
3105   if (*s == ')' || *s == ',')
3106     {
3107       token.u.ch = *s;
3108       mips_add_token (&token, OT_CHAR);
3109       ++s;
3110       return s;
3111     }
3112
3113   /* Handle tokens that start with a register.  */
3114   if (mips_parse_register (&s, &regno1, &channels))
3115     {
3116       if (channels)
3117         {
3118           /* A register and a VU0 channel suffix.  */
3119           token.u.regno = regno1;
3120           mips_add_token (&token, OT_REG);
3121
3122           token.u.channels = channels;
3123           mips_add_token (&token, OT_CHANNELS);
3124           return s;
3125         }
3126
3127       SKIP_SPACE_TABS (s);
3128       if (*s == '-')
3129         {
3130           /* A register range.  */
3131           ++s;
3132           SKIP_SPACE_TABS (s);
3133           if (!mips_parse_register (&s, &regno2, NULL))
3134             {
3135               set_insn_error (0, _("invalid register range"));
3136               return 0;
3137             }
3138
3139           token.u.reg_range.regno1 = regno1;
3140           token.u.reg_range.regno2 = regno2;
3141           mips_add_token (&token, OT_REG_RANGE);
3142           return s;
3143         }
3144
3145       /* Add the register itself.  */
3146       token.u.regno = regno1;
3147       mips_add_token (&token, OT_REG);
3148
3149       /* Check for a vector index.  */
3150       if (*s == '[')
3151         {
3152           ++s;
3153           SKIP_SPACE_TABS (s);
3154           if (mips_parse_register (&s, &token.u.regno, NULL))
3155             mips_add_token (&token, OT_REG_INDEX);
3156           else
3157             {
3158               expressionS element;
3159
3160               my_getExpression (&element, s);
3161               if (element.X_op != O_constant)
3162                 {
3163                   set_insn_error (0, _("vector element must be constant"));
3164                   return 0;
3165                 }
3166               s = expr_end;
3167               token.u.index = element.X_add_number;
3168               mips_add_token (&token, OT_INTEGER_INDEX);
3169             }
3170           SKIP_SPACE_TABS (s);
3171           if (*s != ']')
3172             {
3173               set_insn_error (0, _("missing `]'"));
3174               return 0;
3175             }
3176           ++s;
3177         }
3178       return s;
3179     }
3180
3181   if (float_format)
3182     {
3183       /* First try to treat expressions as floats.  */
3184       save_in = input_line_pointer;
3185       input_line_pointer = s;
3186       err = md_atof (float_format, (char *) token.u.flt.data,
3187                      &token.u.flt.length);
3188       end = input_line_pointer;
3189       input_line_pointer = save_in;
3190       if (err && *err)
3191         {
3192           set_insn_error (0, err);
3193           return 0;
3194         }
3195       if (s != end)
3196         {
3197           mips_add_token (&token, OT_FLOAT);
3198           return end;
3199         }
3200     }
3201
3202   /* Treat everything else as an integer expression.  */
3203   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3204   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3205   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3206   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3207   s = expr_end;
3208   mips_add_token (&token, OT_INTEGER);
3209   return s;
3210 }
3211
3212 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3213    if expressions should be treated as 32-bit floating-point constants,
3214    'd' if they should be treated as 64-bit floating-point constants,
3215    or 0 if they should be treated as integer expressions (the usual case).
3216
3217    Return a list of tokens on success, otherwise return 0.  The caller
3218    must obstack_free the list after use.  */
3219
3220 static struct mips_operand_token *
3221 mips_parse_arguments (char *s, char float_format)
3222 {
3223   struct mips_operand_token token;
3224
3225   SKIP_SPACE_TABS (s);
3226   while (*s)
3227     {
3228       s = mips_parse_argument_token (s, float_format);
3229       if (!s)
3230         {
3231           obstack_free (&mips_operand_tokens,
3232                         obstack_finish (&mips_operand_tokens));
3233           return 0;
3234         }
3235       SKIP_SPACE_TABS (s);
3236     }
3237   mips_add_token (&token, OT_END);
3238   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3239 }
3240
3241 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3242    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3243
3244 static bfd_boolean
3245 is_opcode_valid (const struct mips_opcode *mo)
3246 {
3247   int isa = mips_opts.isa;
3248   int ase = mips_opts.ase;
3249   int fp_s, fp_d;
3250   unsigned int i;
3251
3252   if (ISA_HAS_64BIT_REGS (isa))
3253     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3254       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3255         ase |= mips_ases[i].flags64;
3256
3257   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3258     return FALSE;
3259
3260   /* Check whether the instruction or macro requires single-precision or
3261      double-precision floating-point support.  Note that this information is
3262      stored differently in the opcode table for insns and macros.  */
3263   if (mo->pinfo == INSN_MACRO)
3264     {
3265       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3266       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3267     }
3268   else
3269     {
3270       fp_s = mo->pinfo & FP_S;
3271       fp_d = mo->pinfo & FP_D;
3272     }
3273
3274   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3275     return FALSE;
3276
3277   if (fp_s && mips_opts.soft_float)
3278     return FALSE;
3279
3280   return TRUE;
3281 }
3282
3283 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3284    selected ISA and architecture.  */
3285
3286 static bfd_boolean
3287 is_opcode_valid_16 (const struct mips_opcode *mo)
3288 {
3289   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3290 }
3291
3292 /* Return TRUE if the size of the microMIPS opcode MO matches one
3293    explicitly requested.  Always TRUE in the standard MIPS mode.
3294    Use is_size_valid_16 for MIPS16 opcodes.  */
3295
3296 static bfd_boolean
3297 is_size_valid (const struct mips_opcode *mo)
3298 {
3299   if (!mips_opts.micromips)
3300     return TRUE;
3301
3302   if (mips_opts.insn32)
3303     {
3304       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3305         return FALSE;
3306       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3307         return FALSE;
3308     }
3309   if (!forced_insn_length)
3310     return TRUE;
3311   if (mo->pinfo == INSN_MACRO)
3312     return FALSE;
3313   return forced_insn_length == micromips_insn_length (mo);
3314 }
3315
3316 /* Return TRUE if the size of the MIPS16 opcode MO matches one
3317    explicitly requested.  */
3318
3319 static bfd_boolean
3320 is_size_valid_16 (const struct mips_opcode *mo)
3321 {
3322   if (!forced_insn_length)
3323     return TRUE;
3324   if (mo->pinfo == INSN_MACRO)
3325     return FALSE;
3326   if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3327     return FALSE;
3328   if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3329     return FALSE;
3330   return TRUE;
3331 }
3332
3333 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3334    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3335
3336    We don't accept macros in 16-bit delay slots to avoid a case where
3337    a macro expansion fails because it relies on a preceding 32-bit real
3338    instruction to have matched and does not handle the operands correctly.
3339    The only macros that may expand to 16-bit instructions are JAL that
3340    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3341    and BGT (that likewise cannot be placed in a delay slot) that decay to
3342    a NOP.  In all these cases the macros precede any corresponding real
3343    instruction definitions in the opcode table, so they will match in the
3344    second pass where the size of the delay slot is ignored and therefore
3345    produce correct code.  */
3346
3347 static bfd_boolean
3348 is_delay_slot_valid (const struct mips_opcode *mo)
3349 {
3350   if (!mips_opts.micromips)
3351     return TRUE;
3352
3353   if (mo->pinfo == INSN_MACRO)
3354     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3355   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3356       && micromips_insn_length (mo) != 4)
3357     return FALSE;
3358   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3359       && micromips_insn_length (mo) != 2)
3360     return FALSE;
3361
3362   return TRUE;
3363 }
3364
3365 /* For consistency checking, verify that all bits of OPCODE are specified
3366    either by the match/mask part of the instruction definition, or by the
3367    operand list.  Also build up a list of operands in OPERANDS.
3368
3369    INSN_BITS says which bits of the instruction are significant.
3370    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3371    provides the mips_operand description of each operand.  DECODE_OPERAND
3372    is null for MIPS16 instructions.  */
3373
3374 static int
3375 validate_mips_insn (const struct mips_opcode *opcode,
3376                     unsigned long insn_bits,
3377                     const struct mips_operand *(*decode_operand) (const char *),
3378                     struct mips_operand_array *operands)
3379 {
3380   const char *s;
3381   unsigned long used_bits, doubled, undefined, opno, mask;
3382   const struct mips_operand *operand;
3383
3384   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3385   if ((mask & opcode->match) != opcode->match)
3386     {
3387       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3388               opcode->name, opcode->args);
3389       return 0;
3390     }
3391   used_bits = 0;
3392   opno = 0;
3393   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3394     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3395   for (s = opcode->args; *s; ++s)
3396     switch (*s)
3397       {
3398       case ',':
3399       case '(':
3400       case ')':
3401         break;
3402
3403       case '#':
3404         s++;
3405         break;
3406
3407       default:
3408         if (!decode_operand)
3409           operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3410         else
3411           operand = decode_operand (s);
3412         if (!operand && opcode->pinfo != INSN_MACRO)
3413           {
3414             as_bad (_("internal: unknown operand type: %s %s"),
3415                     opcode->name, opcode->args);
3416             return 0;
3417           }
3418         gas_assert (opno < MAX_OPERANDS);
3419         operands->operand[opno] = operand;
3420         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3421           {
3422             used_bits = mips_insert_operand (operand, used_bits, -1);
3423             if (operand->type == OP_MDMX_IMM_REG)
3424               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3425                  has separate entries for each format.  */
3426               used_bits &= ~(1 << (operand->lsb + 5));
3427             if (operand->type == OP_ENTRY_EXIT_LIST)
3428               used_bits &= ~(mask & 0x700);
3429           }
3430         /* Skip prefix characters.  */
3431         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3432           ++s;
3433         opno += 1;
3434         break;
3435       }
3436   doubled = used_bits & mask & insn_bits;
3437   if (doubled)
3438     {
3439       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3440                 " %s %s"), doubled, opcode->name, opcode->args);
3441       return 0;
3442     }
3443   used_bits |= mask;
3444   undefined = ~used_bits & insn_bits;
3445   if (opcode->pinfo != INSN_MACRO && undefined)
3446     {
3447       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3448               undefined, opcode->name, opcode->args);
3449       return 0;
3450     }
3451   used_bits &= ~insn_bits;
3452   if (used_bits)
3453     {
3454       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3455               used_bits, opcode->name, opcode->args);
3456       return 0;
3457     }
3458   return 1;
3459 }
3460
3461 /* The MIPS16 version of validate_mips_insn.  */
3462
3463 static int
3464 validate_mips16_insn (const struct mips_opcode *opcode,
3465                       struct mips_operand_array *operands)
3466 {
3467   unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3468
3469   return validate_mips_insn (opcode, insn_bits, 0, operands);
3470 }
3471
3472 /* The microMIPS version of validate_mips_insn.  */
3473
3474 static int
3475 validate_micromips_insn (const struct mips_opcode *opc,
3476                          struct mips_operand_array *operands)
3477 {
3478   unsigned long insn_bits;
3479   unsigned long major;
3480   unsigned int length;
3481
3482   if (opc->pinfo == INSN_MACRO)
3483     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3484                                operands);
3485
3486   length = micromips_insn_length (opc);
3487   if (length != 2 && length != 4)
3488     {
3489       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3490                 "%s %s"), length, opc->name, opc->args);
3491       return 0;
3492     }
3493   major = opc->match >> (10 + 8 * (length - 2));
3494   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3495       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3496     {
3497       as_bad (_("internal error: bad microMIPS opcode "
3498                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3499       return 0;
3500     }
3501
3502   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3503   insn_bits = 1 << 4 * length;
3504   insn_bits <<= 4 * length;
3505   insn_bits -= 1;
3506   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3507                              operands);
3508 }
3509
3510 /* This function is called once, at assembler startup time.  It should set up
3511    all the tables, etc. that the MD part of the assembler will need.  */
3512
3513 void
3514 md_begin (void)
3515 {
3516   const char *retval = NULL;
3517   int i = 0;
3518   int broken = 0;
3519
3520   if (mips_pic != NO_PIC)
3521     {
3522       if (g_switch_seen && g_switch_value != 0)
3523         as_bad (_("-G may not be used in position-independent code"));
3524       g_switch_value = 0;
3525     }
3526   else if (mips_abicalls)
3527     {
3528       if (g_switch_seen && g_switch_value != 0)
3529         as_bad (_("-G may not be used with abicalls"));
3530       g_switch_value = 0;
3531     }
3532
3533   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3534     as_warn (_("could not set architecture and machine"));
3535
3536   op_hash = hash_new ();
3537
3538   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3539   for (i = 0; i < NUMOPCODES;)
3540     {
3541       const char *name = mips_opcodes[i].name;
3542
3543       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3544       if (retval != NULL)
3545         {
3546           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3547                    mips_opcodes[i].name, retval);
3548           /* Probably a memory allocation problem?  Give up now.  */
3549           as_fatal (_("broken assembler, no assembly attempted"));
3550         }
3551       do
3552         {
3553           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3554                                    decode_mips_operand, &mips_operands[i]))
3555             broken = 1;
3556           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3557             {
3558               create_insn (&nop_insn, mips_opcodes + i);
3559               if (mips_fix_loongson2f_nop)
3560                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3561               nop_insn.fixed_p = 1;
3562             }
3563           ++i;
3564         }
3565       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3566     }
3567
3568   mips16_op_hash = hash_new ();
3569   mips16_operands = XCNEWVEC (struct mips_operand_array,
3570                               bfd_mips16_num_opcodes);
3571
3572   i = 0;
3573   while (i < bfd_mips16_num_opcodes)
3574     {
3575       const char *name = mips16_opcodes[i].name;
3576
3577       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3578       if (retval != NULL)
3579         as_fatal (_("internal: can't hash `%s': %s"),
3580                   mips16_opcodes[i].name, retval);
3581       do
3582         {
3583           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3584             broken = 1;
3585           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3586             {
3587               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3588               mips16_nop_insn.fixed_p = 1;
3589             }
3590           ++i;
3591         }
3592       while (i < bfd_mips16_num_opcodes
3593              && strcmp (mips16_opcodes[i].name, name) == 0);
3594     }
3595
3596   micromips_op_hash = hash_new ();
3597   micromips_operands = XCNEWVEC (struct mips_operand_array,
3598                                  bfd_micromips_num_opcodes);
3599
3600   i = 0;
3601   while (i < bfd_micromips_num_opcodes)
3602     {
3603       const char *name = micromips_opcodes[i].name;
3604
3605       retval = hash_insert (micromips_op_hash, name,
3606                             (void *) &micromips_opcodes[i]);
3607       if (retval != NULL)
3608         as_fatal (_("internal: can't hash `%s': %s"),
3609                   micromips_opcodes[i].name, retval);
3610       do
3611         {
3612           struct mips_cl_insn *micromips_nop_insn;
3613
3614           if (!validate_micromips_insn (&micromips_opcodes[i],
3615                                         &micromips_operands[i]))
3616             broken = 1;
3617
3618           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3619             {
3620               if (micromips_insn_length (micromips_opcodes + i) == 2)
3621                 micromips_nop_insn = &micromips_nop16_insn;
3622               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3623                 micromips_nop_insn = &micromips_nop32_insn;
3624               else
3625                 continue;
3626
3627               if (micromips_nop_insn->insn_mo == NULL
3628                   && strcmp (name, "nop") == 0)
3629                 {
3630                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3631                   micromips_nop_insn->fixed_p = 1;
3632                 }
3633             }
3634         }
3635       while (++i < bfd_micromips_num_opcodes
3636              && strcmp (micromips_opcodes[i].name, name) == 0);
3637     }
3638
3639   if (broken)
3640     as_fatal (_("broken assembler, no assembly attempted"));
3641
3642   /* We add all the general register names to the symbol table.  This
3643      helps us detect invalid uses of them.  */
3644   for (i = 0; reg_names[i].name; i++)
3645     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3646                                      reg_names[i].num, /* & RNUM_MASK, */
3647                                      &zero_address_frag));
3648   if (HAVE_NEWABI)
3649     for (i = 0; reg_names_n32n64[i].name; i++)
3650       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3651                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3652                                        &zero_address_frag));
3653   else
3654     for (i = 0; reg_names_o32[i].name; i++)
3655       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3656                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3657                                        &zero_address_frag));
3658
3659   for (i = 0; i < 32; i++)
3660     {
3661       char regname[6];
3662
3663       /* R5900 VU0 floating-point register.  */
3664       sprintf (regname, "$vf%d", i);
3665       symbol_table_insert (symbol_new (regname, reg_section,
3666                                        RTYPE_VF | i, &zero_address_frag));
3667
3668       /* R5900 VU0 integer register.  */
3669       sprintf (regname, "$vi%d", i);
3670       symbol_table_insert (symbol_new (regname, reg_section,
3671                                        RTYPE_VI | i, &zero_address_frag));
3672
3673       /* MSA register.  */
3674       sprintf (regname, "$w%d", i);
3675       symbol_table_insert (symbol_new (regname, reg_section,
3676                                        RTYPE_MSA | i, &zero_address_frag));
3677     }
3678
3679   obstack_init (&mips_operand_tokens);
3680
3681   mips_no_prev_insn ();
3682
3683   mips_gprmask = 0;
3684   mips_cprmask[0] = 0;
3685   mips_cprmask[1] = 0;
3686   mips_cprmask[2] = 0;
3687   mips_cprmask[3] = 0;
3688
3689   /* set the default alignment for the text section (2**2) */
3690   record_alignment (text_section, 2);
3691
3692   bfd_set_gp_size (stdoutput, g_switch_value);
3693
3694   /* On a native system other than VxWorks, sections must be aligned
3695      to 16 byte boundaries.  When configured for an embedded ELF
3696      target, we don't bother.  */
3697   if (strncmp (TARGET_OS, "elf", 3) != 0
3698       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3699     {
3700       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3701       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3702       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3703     }
3704
3705   /* Create a .reginfo section for register masks and a .mdebug
3706      section for debugging information.  */
3707   {
3708     segT seg;
3709     subsegT subseg;
3710     flagword flags;
3711     segT sec;
3712
3713     seg = now_seg;
3714     subseg = now_subseg;
3715
3716     /* The ABI says this section should be loaded so that the
3717        running program can access it.  However, we don't load it
3718        if we are configured for an embedded target */
3719     flags = SEC_READONLY | SEC_DATA;
3720     if (strncmp (TARGET_OS, "elf", 3) != 0)
3721       flags |= SEC_ALLOC | SEC_LOAD;
3722
3723     if (mips_abi != N64_ABI)
3724       {
3725         sec = subseg_new (".reginfo", (subsegT) 0);
3726
3727         bfd_set_section_flags (stdoutput, sec, flags);
3728         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3729
3730         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3731       }
3732     else
3733       {
3734         /* The 64-bit ABI uses a .MIPS.options section rather than
3735            .reginfo section.  */
3736         sec = subseg_new (".MIPS.options", (subsegT) 0);
3737         bfd_set_section_flags (stdoutput, sec, flags);
3738         bfd_set_section_alignment (stdoutput, sec, 3);
3739
3740         /* Set up the option header.  */
3741         {
3742           Elf_Internal_Options opthdr;
3743           char *f;
3744
3745           opthdr.kind = ODK_REGINFO;
3746           opthdr.size = (sizeof (Elf_External_Options)
3747                          + sizeof (Elf64_External_RegInfo));
3748           opthdr.section = 0;
3749           opthdr.info = 0;
3750           f = frag_more (sizeof (Elf_External_Options));
3751           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3752                                          (Elf_External_Options *) f);
3753
3754           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3755         }
3756       }
3757
3758     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3759     bfd_set_section_flags (stdoutput, sec,
3760                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3761     bfd_set_section_alignment (stdoutput, sec, 3);
3762     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3763
3764     if (ECOFF_DEBUGGING)
3765       {
3766         sec = subseg_new (".mdebug", (subsegT) 0);
3767         (void) bfd_set_section_flags (stdoutput, sec,
3768                                       SEC_HAS_CONTENTS | SEC_READONLY);
3769         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3770       }
3771     else if (mips_flag_pdr)
3772       {
3773         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3774         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3775                                       SEC_READONLY | SEC_RELOC
3776                                       | SEC_DEBUGGING);
3777         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3778       }
3779
3780     subseg_set (seg, subseg);
3781   }
3782
3783   if (mips_fix_vr4120)
3784     init_vr4120_conflicts ();
3785 }
3786
3787 static inline void
3788 fpabi_incompatible_with (int fpabi, const char *what)
3789 {
3790   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3791            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3792 }
3793
3794 static inline void
3795 fpabi_requires (int fpabi, const char *what)
3796 {
3797   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3798            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3799 }
3800
3801 /* Check -mabi and register sizes against the specified FP ABI.  */
3802 static void
3803 check_fpabi (int fpabi)
3804 {
3805   switch (fpabi)
3806     {
3807     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3808       if (file_mips_opts.soft_float)
3809         fpabi_incompatible_with (fpabi, "softfloat");
3810       else if (file_mips_opts.single_float)
3811         fpabi_incompatible_with (fpabi, "singlefloat");
3812       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3813         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3814       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3815         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3816       break;
3817
3818     case Val_GNU_MIPS_ABI_FP_XX:
3819       if (mips_abi != O32_ABI)
3820         fpabi_requires (fpabi, "-mabi=32");
3821       else if (file_mips_opts.soft_float)
3822         fpabi_incompatible_with (fpabi, "softfloat");
3823       else if (file_mips_opts.single_float)
3824         fpabi_incompatible_with (fpabi, "singlefloat");
3825       else if (file_mips_opts.fp != 0)
3826         fpabi_requires (fpabi, "fp=xx");
3827       break;
3828
3829     case Val_GNU_MIPS_ABI_FP_64A:
3830     case Val_GNU_MIPS_ABI_FP_64:
3831       if (mips_abi != O32_ABI)
3832         fpabi_requires (fpabi, "-mabi=32");
3833       else if (file_mips_opts.soft_float)
3834         fpabi_incompatible_with (fpabi, "softfloat");
3835       else if (file_mips_opts.single_float)
3836         fpabi_incompatible_with (fpabi, "singlefloat");
3837       else if (file_mips_opts.fp != 64)
3838         fpabi_requires (fpabi, "fp=64");
3839       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3840         fpabi_incompatible_with (fpabi, "nooddspreg");
3841       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3842         fpabi_requires (fpabi, "nooddspreg");
3843       break;
3844
3845     case Val_GNU_MIPS_ABI_FP_SINGLE:
3846       if (file_mips_opts.soft_float)
3847         fpabi_incompatible_with (fpabi, "softfloat");
3848       else if (!file_mips_opts.single_float)
3849         fpabi_requires (fpabi, "singlefloat");
3850       break;
3851
3852     case Val_GNU_MIPS_ABI_FP_SOFT:
3853       if (!file_mips_opts.soft_float)
3854         fpabi_requires (fpabi, "softfloat");
3855       break;
3856
3857     case Val_GNU_MIPS_ABI_FP_OLD_64:
3858       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3859                Tag_GNU_MIPS_ABI_FP, fpabi);
3860       break;
3861
3862     case Val_GNU_MIPS_ABI_FP_NAN2008:
3863       /* Silently ignore compatibility value.  */
3864       break;
3865
3866     default:
3867       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3868                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3869       break;
3870     }
3871 }
3872
3873 /* Perform consistency checks on the current options.  */
3874
3875 static void
3876 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3877 {
3878   /* Check the size of integer registers agrees with the ABI and ISA.  */
3879   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3880     as_bad (_("`gp=64' used with a 32-bit processor"));
3881   else if (abi_checks
3882            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3883     as_bad (_("`gp=32' used with a 64-bit ABI"));
3884   else if (abi_checks
3885            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3886     as_bad (_("`gp=64' used with a 32-bit ABI"));
3887
3888   /* Check the size of the float registers agrees with the ABI and ISA.  */
3889   switch (opts->fp)
3890     {
3891     case 0:
3892       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3893         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3894       else if (opts->single_float == 1)
3895         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3896       break;
3897     case 64:
3898       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3899         as_bad (_("`fp=64' used with a 32-bit fpu"));
3900       else if (abi_checks
3901                && ABI_NEEDS_32BIT_REGS (mips_abi)
3902                && !ISA_HAS_MXHC1 (opts->isa))
3903         as_warn (_("`fp=64' used with a 32-bit ABI"));
3904       break;
3905     case 32:
3906       if (abi_checks
3907           && ABI_NEEDS_64BIT_REGS (mips_abi))
3908         as_warn (_("`fp=32' used with a 64-bit ABI"));
3909       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
3910         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
3911       break;
3912     default:
3913       as_bad (_("Unknown size of floating point registers"));
3914       break;
3915     }
3916
3917   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
3918     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
3919
3920   if (opts->micromips == 1 && opts->mips16 == 1)
3921     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
3922   else if (ISA_IS_R6 (opts->isa)
3923            && (opts->micromips == 1
3924                || opts->mips16 == 1))
3925     as_fatal (_("`%s' cannot be used with `%s'"),
3926               opts->micromips ? "micromips" : "mips16",
3927               mips_cpu_info_from_isa (opts->isa)->name);
3928
3929   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
3930     as_fatal (_("branch relaxation is not supported in `%s'"),
3931               mips_cpu_info_from_isa (opts->isa)->name);
3932 }
3933
3934 /* Perform consistency checks on the module level options exactly once.
3935    This is a deferred check that happens:
3936      at the first .set directive
3937      or, at the first pseudo op that generates code (inc .dc.a)
3938      or, at the first instruction
3939      or, at the end.  */
3940
3941 static void
3942 file_mips_check_options (void)
3943 {
3944   const struct mips_cpu_info *arch_info = 0;
3945
3946   if (file_mips_opts_checked)
3947     return;
3948
3949   /* The following code determines the register size.
3950      Similar code was added to GCC 3.3 (see override_options() in
3951      config/mips/mips.c).  The GAS and GCC code should be kept in sync
3952      as much as possible.  */
3953
3954   if (file_mips_opts.gp < 0)
3955     {
3956       /* Infer the integer register size from the ABI and processor.
3957          Restrict ourselves to 32-bit registers if that's all the
3958          processor has, or if the ABI cannot handle 64-bit registers.  */
3959       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
3960                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
3961                           ? 32 : 64;
3962     }
3963
3964   if (file_mips_opts.fp < 0)
3965     {
3966       /* No user specified float register size.
3967          ??? GAS treats single-float processors as though they had 64-bit
3968          float registers (although it complains when double-precision
3969          instructions are used).  As things stand, saying they have 32-bit
3970          registers would lead to spurious "register must be even" messages.
3971          So here we assume float registers are never smaller than the
3972          integer ones.  */
3973       if (file_mips_opts.gp == 64)
3974         /* 64-bit integer registers implies 64-bit float registers.  */
3975         file_mips_opts.fp = 64;
3976       else if ((file_mips_opts.ase & FP64_ASES)
3977                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
3978         /* Handle ASEs that require 64-bit float registers, if possible.  */
3979         file_mips_opts.fp = 64;
3980       else if (ISA_IS_R6 (mips_opts.isa))
3981         /* R6 implies 64-bit float registers.  */
3982         file_mips_opts.fp = 64;
3983       else
3984         /* 32-bit float registers.  */
3985         file_mips_opts.fp = 32;
3986     }
3987
3988   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
3989
3990   /* Disable operations on odd-numbered floating-point registers by default
3991      when using the FPXX ABI.  */
3992   if (file_mips_opts.oddspreg < 0)
3993     {
3994       if (file_mips_opts.fp == 0)
3995         file_mips_opts.oddspreg = 0;
3996       else
3997         file_mips_opts.oddspreg = 1;
3998     }
3999
4000   /* End of GCC-shared inference code.  */
4001
4002   /* This flag is set when we have a 64-bit capable CPU but use only
4003      32-bit wide registers.  Note that EABI does not use it.  */
4004   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4005       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4006           || mips_abi == O32_ABI))
4007     mips_32bitmode = 1;
4008
4009   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4010     as_bad (_("trap exception not supported at ISA 1"));
4011
4012   /* If the selected architecture includes support for ASEs, enable
4013      generation of code for them.  */
4014   if (file_mips_opts.mips16 == -1)
4015     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4016   if (file_mips_opts.micromips == -1)
4017     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4018                                 ? 1 : 0;
4019
4020   if (mips_nan2008 == -1)
4021     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4022   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4023     as_fatal (_("`%s' does not support legacy NaN"),
4024               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4025
4026   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4027      being selected implicitly.  */
4028   if (file_mips_opts.fp != 64)
4029     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4030
4031   /* If the user didn't explicitly select or deselect a particular ASE,
4032      use the default setting for the CPU.  */
4033   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
4034
4035   /* Set up the current options.  These may change throughout assembly.  */
4036   mips_opts = file_mips_opts;
4037
4038   mips_check_isa_supports_ases ();
4039   mips_check_options (&file_mips_opts, TRUE);
4040   file_mips_opts_checked = TRUE;
4041
4042   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4043     as_warn (_("could not set architecture and machine"));
4044 }
4045
4046 void
4047 md_assemble (char *str)
4048 {
4049   struct mips_cl_insn insn;
4050   bfd_reloc_code_real_type unused_reloc[3]
4051     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4052
4053   file_mips_check_options ();
4054
4055   imm_expr.X_op = O_absent;
4056   offset_expr.X_op = O_absent;
4057   offset_reloc[0] = BFD_RELOC_UNUSED;
4058   offset_reloc[1] = BFD_RELOC_UNUSED;
4059   offset_reloc[2] = BFD_RELOC_UNUSED;
4060
4061   mips_mark_labels ();
4062   mips_assembling_insn = TRUE;
4063   clear_insn_error ();
4064
4065   if (mips_opts.mips16)
4066     mips16_ip (str, &insn);
4067   else
4068     {
4069       mips_ip (str, &insn);
4070       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4071             str, insn.insn_opcode));
4072     }
4073
4074   if (insn_error.msg)
4075     report_insn_error (str);
4076   else if (insn.insn_mo->pinfo == INSN_MACRO)
4077     {
4078       macro_start ();
4079       if (mips_opts.mips16)
4080         mips16_macro (&insn);
4081       else
4082         macro (&insn, str);
4083       macro_end ();
4084     }
4085   else
4086     {
4087       if (offset_expr.X_op != O_absent)
4088         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4089       else
4090         append_insn (&insn, NULL, unused_reloc, FALSE);
4091     }
4092
4093   mips_assembling_insn = FALSE;
4094 }
4095
4096 /* Convenience functions for abstracting away the differences between
4097    MIPS16 and non-MIPS16 relocations.  */
4098
4099 static inline bfd_boolean
4100 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4101 {
4102   switch (reloc)
4103     {
4104     case BFD_RELOC_MIPS16_JMP:
4105     case BFD_RELOC_MIPS16_GPREL:
4106     case BFD_RELOC_MIPS16_GOT16:
4107     case BFD_RELOC_MIPS16_CALL16:
4108     case BFD_RELOC_MIPS16_HI16_S:
4109     case BFD_RELOC_MIPS16_HI16:
4110     case BFD_RELOC_MIPS16_LO16:
4111     case BFD_RELOC_MIPS16_16_PCREL_S1:
4112       return TRUE;
4113
4114     default:
4115       return FALSE;
4116     }
4117 }
4118
4119 static inline bfd_boolean
4120 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4121 {
4122   switch (reloc)
4123     {
4124     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4125     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4126     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4127     case BFD_RELOC_MICROMIPS_GPREL16:
4128     case BFD_RELOC_MICROMIPS_JMP:
4129     case BFD_RELOC_MICROMIPS_HI16:
4130     case BFD_RELOC_MICROMIPS_HI16_S:
4131     case BFD_RELOC_MICROMIPS_LO16:
4132     case BFD_RELOC_MICROMIPS_LITERAL:
4133     case BFD_RELOC_MICROMIPS_GOT16:
4134     case BFD_RELOC_MICROMIPS_CALL16:
4135     case BFD_RELOC_MICROMIPS_GOT_HI16:
4136     case BFD_RELOC_MICROMIPS_GOT_LO16:
4137     case BFD_RELOC_MICROMIPS_CALL_HI16:
4138     case BFD_RELOC_MICROMIPS_CALL_LO16:
4139     case BFD_RELOC_MICROMIPS_SUB:
4140     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4141     case BFD_RELOC_MICROMIPS_GOT_OFST:
4142     case BFD_RELOC_MICROMIPS_GOT_DISP:
4143     case BFD_RELOC_MICROMIPS_HIGHEST:
4144     case BFD_RELOC_MICROMIPS_HIGHER:
4145     case BFD_RELOC_MICROMIPS_SCN_DISP:
4146     case BFD_RELOC_MICROMIPS_JALR:
4147       return TRUE;
4148
4149     default:
4150       return FALSE;
4151     }
4152 }
4153
4154 static inline bfd_boolean
4155 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4156 {
4157   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4158 }
4159
4160 static inline bfd_boolean
4161 b_reloc_p (bfd_reloc_code_real_type reloc)
4162 {
4163   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4164           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4165           || reloc == BFD_RELOC_16_PCREL_S2
4166           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4167           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4168           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4169           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4170 }
4171
4172 static inline bfd_boolean
4173 got16_reloc_p (bfd_reloc_code_real_type reloc)
4174 {
4175   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4176           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4177 }
4178
4179 static inline bfd_boolean
4180 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4181 {
4182   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4183           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4184 }
4185
4186 static inline bfd_boolean
4187 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4188 {
4189   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4190           || reloc == BFD_RELOC_MICROMIPS_LO16);
4191 }
4192
4193 static inline bfd_boolean
4194 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4195 {
4196   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4197 }
4198
4199 static inline bfd_boolean
4200 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4201 {
4202   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4203           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4204 }
4205
4206 /* Return true if RELOC is a PC-relative relocation that does not have
4207    full address range.  */
4208
4209 static inline bfd_boolean
4210 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4211 {
4212   switch (reloc)
4213     {
4214     case BFD_RELOC_16_PCREL_S2:
4215     case BFD_RELOC_MIPS16_16_PCREL_S1:
4216     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4217     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4218     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4219     case BFD_RELOC_MIPS_21_PCREL_S2:
4220     case BFD_RELOC_MIPS_26_PCREL_S2:
4221     case BFD_RELOC_MIPS_18_PCREL_S3:
4222     case BFD_RELOC_MIPS_19_PCREL_S2:
4223       return TRUE;
4224
4225     case BFD_RELOC_32_PCREL:
4226     case BFD_RELOC_HI16_S_PCREL:
4227     case BFD_RELOC_LO16_PCREL:
4228       return HAVE_64BIT_ADDRESSES;
4229
4230     default:
4231       return FALSE;
4232     }
4233 }
4234
4235 /* Return true if the given relocation might need a matching %lo().
4236    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4237    need a matching %lo() when applied to local symbols.  */
4238
4239 static inline bfd_boolean
4240 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4241 {
4242   return (HAVE_IN_PLACE_ADDENDS
4243           && (hi16_reloc_p (reloc)
4244               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4245                  all GOT16 relocations evaluate to "G".  */
4246               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4247 }
4248
4249 /* Return the type of %lo() reloc needed by RELOC, given that
4250    reloc_needs_lo_p.  */
4251
4252 static inline bfd_reloc_code_real_type
4253 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4254 {
4255   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4256           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4257              : BFD_RELOC_LO16));
4258 }
4259
4260 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4261    relocation.  */
4262
4263 static inline bfd_boolean
4264 fixup_has_matching_lo_p (fixS *fixp)
4265 {
4266   return (fixp->fx_next != NULL
4267           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4268           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4269           && fixp->fx_offset == fixp->fx_next->fx_offset);
4270 }
4271
4272 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4273    says whether the labels refer to text or data.  */
4274
4275 static void
4276 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4277 {
4278   struct insn_label_list *l;
4279   valueT val;
4280
4281   for (l = labels; l != NULL; l = l->next)
4282     {
4283       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4284       symbol_set_frag (l->label, frag_now);
4285       val = (valueT) frag_now_fix ();
4286       /* MIPS16/microMIPS text labels are stored as odd.  */
4287       if (text_p && HAVE_CODE_COMPRESSION)
4288         ++val;
4289       S_SET_VALUE (l->label, val);
4290     }
4291 }
4292
4293 /* Move all labels in insn_labels to the current insertion point
4294    and treat them as text labels.  */
4295
4296 static void
4297 mips_move_text_labels (void)
4298 {
4299   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4300 }
4301
4302 /* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4303
4304 static bfd_boolean
4305 s_is_linkonce (symbolS *sym, segT from_seg)
4306 {
4307   bfd_boolean linkonce = FALSE;
4308   segT symseg = S_GET_SEGMENT (sym);
4309
4310   if (symseg != from_seg && !S_IS_LOCAL (sym))
4311     {
4312       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4313         linkonce = TRUE;
4314       /* The GNU toolchain uses an extension for ELF: a section
4315          beginning with the magic string .gnu.linkonce is a
4316          linkonce section.  */
4317       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4318                    sizeof ".gnu.linkonce" - 1) == 0)
4319         linkonce = TRUE;
4320     }
4321   return linkonce;
4322 }
4323
4324 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4325    linker to handle them specially, such as generating jalx instructions
4326    when needed.  We also make them odd for the duration of the assembly,
4327    in order to generate the right sort of code.  We will make them even
4328    in the adjust_symtab routine, while leaving them marked.  This is
4329    convenient for the debugger and the disassembler.  The linker knows
4330    to make them odd again.  */
4331
4332 static void
4333 mips_compressed_mark_label (symbolS *label)
4334 {
4335   gas_assert (HAVE_CODE_COMPRESSION);
4336
4337   if (mips_opts.mips16)
4338     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4339   else
4340     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4341   if ((S_GET_VALUE (label) & 1) == 0
4342       /* Don't adjust the address if the label is global or weak, or
4343          in a link-once section, since we'll be emitting symbol reloc
4344          references to it which will be patched up by the linker, and
4345          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4346       && !S_IS_WEAK (label)
4347       && !S_IS_EXTERNAL (label)
4348       && !s_is_linkonce (label, now_seg))
4349     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4350 }
4351
4352 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4353
4354 static void
4355 mips_compressed_mark_labels (void)
4356 {
4357   struct insn_label_list *l;
4358
4359   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4360     mips_compressed_mark_label (l->label);
4361 }
4362
4363 /* End the current frag.  Make it a variant frag and record the
4364    relaxation info.  */
4365
4366 static void
4367 relax_close_frag (void)
4368 {
4369   mips_macro_warning.first_frag = frag_now;
4370   frag_var (rs_machine_dependent, 0, 0,
4371             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4372                           mips_pic != NO_PIC),
4373             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4374
4375   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4376   mips_relax.first_fixup = 0;
4377 }
4378
4379 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4380    See the comment above RELAX_ENCODE for more details.  */
4381
4382 static void
4383 relax_start (symbolS *symbol)
4384 {
4385   gas_assert (mips_relax.sequence == 0);
4386   mips_relax.sequence = 1;
4387   mips_relax.symbol = symbol;
4388 }
4389
4390 /* Start generating the second version of a relaxable sequence.
4391    See the comment above RELAX_ENCODE for more details.  */
4392
4393 static void
4394 relax_switch (void)
4395 {
4396   gas_assert (mips_relax.sequence == 1);
4397   mips_relax.sequence = 2;
4398 }
4399
4400 /* End the current relaxable sequence.  */
4401
4402 static void
4403 relax_end (void)
4404 {
4405   gas_assert (mips_relax.sequence == 2);
4406   relax_close_frag ();
4407   mips_relax.sequence = 0;
4408 }
4409
4410 /* Return true if IP is a delayed branch or jump.  */
4411
4412 static inline bfd_boolean
4413 delayed_branch_p (const struct mips_cl_insn *ip)
4414 {
4415   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4416                                 | INSN_COND_BRANCH_DELAY
4417                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4418 }
4419
4420 /* Return true if IP is a compact branch or jump.  */
4421
4422 static inline bfd_boolean
4423 compact_branch_p (const struct mips_cl_insn *ip)
4424 {
4425   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4426                                  | INSN2_COND_BRANCH)) != 0;
4427 }
4428
4429 /* Return true if IP is an unconditional branch or jump.  */
4430
4431 static inline bfd_boolean
4432 uncond_branch_p (const struct mips_cl_insn *ip)
4433 {
4434   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4435           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4436 }
4437
4438 /* Return true if IP is a branch-likely instruction.  */
4439
4440 static inline bfd_boolean
4441 branch_likely_p (const struct mips_cl_insn *ip)
4442 {
4443   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4444 }
4445
4446 /* Return the type of nop that should be used to fill the delay slot
4447    of delayed branch IP.  */
4448
4449 static struct mips_cl_insn *
4450 get_delay_slot_nop (const struct mips_cl_insn *ip)
4451 {
4452   if (mips_opts.micromips
4453       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4454     return &micromips_nop32_insn;
4455   return NOP_INSN;
4456 }
4457
4458 /* Return a mask that has bit N set if OPCODE reads the register(s)
4459    in operand N.  */
4460
4461 static unsigned int
4462 insn_read_mask (const struct mips_opcode *opcode)
4463 {
4464   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4465 }
4466
4467 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4468    in operand N.  */
4469
4470 static unsigned int
4471 insn_write_mask (const struct mips_opcode *opcode)
4472 {
4473   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4474 }
4475
4476 /* Return a mask of the registers specified by operand OPERAND of INSN.
4477    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4478    is set.  */
4479
4480 static unsigned int
4481 operand_reg_mask (const struct mips_cl_insn *insn,
4482                   const struct mips_operand *operand,
4483                   unsigned int type_mask)
4484 {
4485   unsigned int uval, vsel;
4486
4487   switch (operand->type)
4488     {
4489     case OP_INT:
4490     case OP_MAPPED_INT:
4491     case OP_MSB:
4492     case OP_PCREL:
4493     case OP_PERF_REG:
4494     case OP_ADDIUSP_INT:
4495     case OP_ENTRY_EXIT_LIST:
4496     case OP_REPEAT_DEST_REG:
4497     case OP_REPEAT_PREV_REG:
4498     case OP_PC:
4499     case OP_VU0_SUFFIX:
4500     case OP_VU0_MATCH_SUFFIX:
4501     case OP_IMM_INDEX:
4502       abort ();
4503
4504     case OP_REG:
4505     case OP_OPTIONAL_REG:
4506       {
4507         const struct mips_reg_operand *reg_op;
4508
4509         reg_op = (const struct mips_reg_operand *) operand;
4510         if (!(type_mask & (1 << reg_op->reg_type)))
4511           return 0;
4512         uval = insn_extract_operand (insn, operand);
4513         return 1 << mips_decode_reg_operand (reg_op, uval);
4514       }
4515
4516     case OP_REG_PAIR:
4517       {
4518         const struct mips_reg_pair_operand *pair_op;
4519
4520         pair_op = (const struct mips_reg_pair_operand *) operand;
4521         if (!(type_mask & (1 << pair_op->reg_type)))
4522           return 0;
4523         uval = insn_extract_operand (insn, operand);
4524         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4525       }
4526
4527     case OP_CLO_CLZ_DEST:
4528       if (!(type_mask & (1 << OP_REG_GP)))
4529         return 0;
4530       uval = insn_extract_operand (insn, operand);
4531       return (1 << (uval & 31)) | (1 << (uval >> 5));
4532
4533     case OP_SAME_RS_RT:
4534       if (!(type_mask & (1 << OP_REG_GP)))
4535         return 0;
4536       uval = insn_extract_operand (insn, operand);
4537       gas_assert ((uval & 31) == (uval >> 5));
4538       return 1 << (uval & 31);
4539
4540     case OP_CHECK_PREV:
4541     case OP_NON_ZERO_REG:
4542       if (!(type_mask & (1 << OP_REG_GP)))
4543         return 0;
4544       uval = insn_extract_operand (insn, operand);
4545       return 1 << (uval & 31);
4546
4547     case OP_LWM_SWM_LIST:
4548       abort ();
4549
4550     case OP_SAVE_RESTORE_LIST:
4551       abort ();
4552
4553     case OP_MDMX_IMM_REG:
4554       if (!(type_mask & (1 << OP_REG_VEC)))
4555         return 0;
4556       uval = insn_extract_operand (insn, operand);
4557       vsel = uval >> 5;
4558       if ((vsel & 0x18) == 0x18)
4559         return 0;
4560       return 1 << (uval & 31);
4561
4562     case OP_REG_INDEX:
4563       if (!(type_mask & (1 << OP_REG_GP)))
4564         return 0;
4565       return 1 << insn_extract_operand (insn, operand);
4566     }
4567   abort ();
4568 }
4569
4570 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4571    where bit N of OPNO_MASK is set if operand N should be included.
4572    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4573    is set.  */
4574
4575 static unsigned int
4576 insn_reg_mask (const struct mips_cl_insn *insn,
4577                unsigned int type_mask, unsigned int opno_mask)
4578 {
4579   unsigned int opno, reg_mask;
4580
4581   opno = 0;
4582   reg_mask = 0;
4583   while (opno_mask != 0)
4584     {
4585       if (opno_mask & 1)
4586         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4587       opno_mask >>= 1;
4588       opno += 1;
4589     }
4590   return reg_mask;
4591 }
4592
4593 /* Return the mask of core registers that IP reads.  */
4594
4595 static unsigned int
4596 gpr_read_mask (const struct mips_cl_insn *ip)
4597 {
4598   unsigned long pinfo, pinfo2;
4599   unsigned int mask;
4600
4601   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4602   pinfo = ip->insn_mo->pinfo;
4603   pinfo2 = ip->insn_mo->pinfo2;
4604   if (pinfo & INSN_UDI)
4605     {
4606       /* UDI instructions have traditionally been assumed to read RS
4607          and RT.  */
4608       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4609       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4610     }
4611   if (pinfo & INSN_READ_GPR_24)
4612     mask |= 1 << 24;
4613   if (pinfo2 & INSN2_READ_GPR_16)
4614     mask |= 1 << 16;
4615   if (pinfo2 & INSN2_READ_SP)
4616     mask |= 1 << SP;
4617   if (pinfo2 & INSN2_READ_GPR_31)
4618     mask |= 1 << 31;
4619   /* Don't include register 0.  */
4620   return mask & ~1;
4621 }
4622
4623 /* Return the mask of core registers that IP writes.  */
4624
4625 static unsigned int
4626 gpr_write_mask (const struct mips_cl_insn *ip)
4627 {
4628   unsigned long pinfo, pinfo2;
4629   unsigned int mask;
4630
4631   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4632   pinfo = ip->insn_mo->pinfo;
4633   pinfo2 = ip->insn_mo->pinfo2;
4634   if (pinfo & INSN_WRITE_GPR_24)
4635     mask |= 1 << 24;
4636   if (pinfo & INSN_WRITE_GPR_31)
4637     mask |= 1 << 31;
4638   if (pinfo & INSN_UDI)
4639     /* UDI instructions have traditionally been assumed to write to RD.  */
4640     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4641   if (pinfo2 & INSN2_WRITE_SP)
4642     mask |= 1 << SP;
4643   /* Don't include register 0.  */
4644   return mask & ~1;
4645 }
4646
4647 /* Return the mask of floating-point registers that IP reads.  */
4648
4649 static unsigned int
4650 fpr_read_mask (const struct mips_cl_insn *ip)
4651 {
4652   unsigned long pinfo;
4653   unsigned int mask;
4654
4655   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4656                              | (1 << OP_REG_MSA)),
4657                         insn_read_mask (ip->insn_mo));
4658   pinfo = ip->insn_mo->pinfo;
4659   /* Conservatively treat all operands to an FP_D instruction are doubles.
4660      (This is overly pessimistic for things like cvt.d.s.)  */
4661   if (FPR_SIZE != 64 && (pinfo & FP_D))
4662     mask |= mask << 1;
4663   return mask;
4664 }
4665
4666 /* Return the mask of floating-point registers that IP writes.  */
4667
4668 static unsigned int
4669 fpr_write_mask (const struct mips_cl_insn *ip)
4670 {
4671   unsigned long pinfo;
4672   unsigned int mask;
4673
4674   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4675                              | (1 << OP_REG_MSA)),
4676                         insn_write_mask (ip->insn_mo));
4677   pinfo = ip->insn_mo->pinfo;
4678   /* Conservatively treat all operands to an FP_D instruction are doubles.
4679      (This is overly pessimistic for things like cvt.s.d.)  */
4680   if (FPR_SIZE != 64 && (pinfo & FP_D))
4681     mask |= mask << 1;
4682   return mask;
4683 }
4684
4685 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4686    Check whether that is allowed.  */
4687
4688 static bfd_boolean
4689 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4690 {
4691   const char *s = insn->name;
4692   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4693                           || FPR_SIZE == 64)
4694                          && mips_opts.oddspreg;
4695
4696   if (insn->pinfo == INSN_MACRO)
4697     /* Let a macro pass, we'll catch it later when it is expanded.  */
4698     return TRUE;
4699
4700   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4701      otherwise it depends on oddspreg.  */
4702   if ((insn->pinfo & FP_S)
4703       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4704                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4705     return FPR_SIZE == 32 || oddspreg;
4706
4707   /* Allow odd registers for single-precision ops and double-precision if the
4708      floating-point registers are 64-bit wide.  */
4709   switch (insn->pinfo & (FP_S | FP_D))
4710     {
4711     case FP_S:
4712     case 0:
4713       return oddspreg;
4714     case FP_D:
4715       return FPR_SIZE == 64;
4716     default:
4717       break;
4718     }
4719
4720   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4721   s = strchr (insn->name, '.');
4722   if (s != NULL && opnum == 2)
4723     s = strchr (s + 1, '.');
4724   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4725     return oddspreg;
4726
4727   return FPR_SIZE == 64;
4728 }
4729
4730 /* Information about an instruction argument that we're trying to match.  */
4731 struct mips_arg_info
4732 {
4733   /* The instruction so far.  */
4734   struct mips_cl_insn *insn;
4735
4736   /* The first unconsumed operand token.  */
4737   struct mips_operand_token *token;
4738
4739   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4740   int opnum;
4741
4742   /* The 1-based argument number, for error reporting.  This does not
4743      count elided optional registers, etc..  */
4744   int argnum;
4745
4746   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4747   unsigned int last_regno;
4748
4749   /* If the first operand was an OP_REG, this is the register that it
4750      specified, otherwise it is ILLEGAL_REG.  */
4751   unsigned int dest_regno;
4752
4753   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4754      where it gives the lsb position.  */
4755   unsigned int last_op_int;
4756
4757   /* If true, match routines should assume that no later instruction
4758      alternative matches and should therefore be as accommodating as
4759      possible.  Match routines should not report errors if something
4760      is only invalid for !LAX_MATCH.  */
4761   bfd_boolean lax_match;
4762
4763   /* True if a reference to the current AT register was seen.  */
4764   bfd_boolean seen_at;
4765 };
4766
4767 /* Record that the argument is out of range.  */
4768
4769 static void
4770 match_out_of_range (struct mips_arg_info *arg)
4771 {
4772   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4773 }
4774
4775 /* Record that the argument isn't constant but needs to be.  */
4776
4777 static void
4778 match_not_constant (struct mips_arg_info *arg)
4779 {
4780   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4781                     arg->argnum);
4782 }
4783
4784 /* Try to match an OT_CHAR token for character CH.  Consume the token
4785    and return true on success, otherwise return false.  */
4786
4787 static bfd_boolean
4788 match_char (struct mips_arg_info *arg, char ch)
4789 {
4790   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4791     {
4792       ++arg->token;
4793       if (ch == ',')
4794         arg->argnum += 1;
4795       return TRUE;
4796     }
4797   return FALSE;
4798 }
4799
4800 /* Try to get an expression from the next tokens in ARG.  Consume the
4801    tokens and return true on success, storing the expression value in
4802    VALUE and relocation types in R.  */
4803
4804 static bfd_boolean
4805 match_expression (struct mips_arg_info *arg, expressionS *value,
4806                   bfd_reloc_code_real_type *r)
4807 {
4808   /* If the next token is a '(' that was parsed as being part of a base
4809      expression, assume we have an elided offset.  The later match will fail
4810      if this turns out to be wrong.  */
4811   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4812     {
4813       value->X_op = O_constant;
4814       value->X_add_number = 0;
4815       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4816       return TRUE;
4817     }
4818
4819   /* Reject register-based expressions such as "0+$2" and "(($2))".
4820      For plain registers the default error seems more appropriate.  */
4821   if (arg->token->type == OT_INTEGER
4822       && arg->token->u.integer.value.X_op == O_register)
4823     {
4824       set_insn_error (arg->argnum, _("register value used as expression"));
4825       return FALSE;
4826     }
4827
4828   if (arg->token->type == OT_INTEGER)
4829     {
4830       *value = arg->token->u.integer.value;
4831       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4832       ++arg->token;
4833       return TRUE;
4834     }
4835
4836   set_insn_error_i
4837     (arg->argnum, _("operand %d must be an immediate expression"),
4838      arg->argnum);
4839   return FALSE;
4840 }
4841
4842 /* Try to get a constant expression from the next tokens in ARG.  Consume
4843    the tokens and return return true on success, storing the constant value
4844    in *VALUE.  */
4845
4846 static bfd_boolean
4847 match_const_int (struct mips_arg_info *arg, offsetT *value)
4848 {
4849   expressionS ex;
4850   bfd_reloc_code_real_type r[3];
4851
4852   if (!match_expression (arg, &ex, r))
4853     return FALSE;
4854
4855   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4856     *value = ex.X_add_number;
4857   else
4858     {
4859       if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_big)
4860         match_out_of_range (arg);
4861       else
4862         match_not_constant (arg);
4863       return FALSE;
4864     }
4865   return TRUE;
4866 }
4867
4868 /* Return the RTYPE_* flags for a register operand of type TYPE that
4869    appears in instruction OPCODE.  */
4870
4871 static unsigned int
4872 convert_reg_type (const struct mips_opcode *opcode,
4873                   enum mips_reg_operand_type type)
4874 {
4875   switch (type)
4876     {
4877     case OP_REG_GP:
4878       return RTYPE_NUM | RTYPE_GP;
4879
4880     case OP_REG_FP:
4881       /* Allow vector register names for MDMX if the instruction is a 64-bit
4882          FPR load, store or move (including moves to and from GPRs).  */
4883       if ((mips_opts.ase & ASE_MDMX)
4884           && (opcode->pinfo & FP_D)
4885           && (opcode->pinfo & (INSN_COPROC_MOVE
4886                                | INSN_COPROC_MEMORY_DELAY
4887                                | INSN_LOAD_COPROC
4888                                | INSN_LOAD_MEMORY
4889                                | INSN_STORE_MEMORY)))
4890         return RTYPE_FPU | RTYPE_VEC;
4891       return RTYPE_FPU;
4892
4893     case OP_REG_CCC:
4894       if (opcode->pinfo & (FP_D | FP_S))
4895         return RTYPE_CCC | RTYPE_FCC;
4896       return RTYPE_CCC;
4897
4898     case OP_REG_VEC:
4899       if (opcode->membership & INSN_5400)
4900         return RTYPE_FPU;
4901       return RTYPE_FPU | RTYPE_VEC;
4902
4903     case OP_REG_ACC:
4904       return RTYPE_ACC;
4905
4906     case OP_REG_COPRO:
4907       if (opcode->name[strlen (opcode->name) - 1] == '0')
4908         return RTYPE_NUM | RTYPE_CP0;
4909       return RTYPE_NUM;
4910
4911     case OP_REG_HW:
4912       return RTYPE_NUM;
4913
4914     case OP_REG_VI:
4915       return RTYPE_NUM | RTYPE_VI;
4916
4917     case OP_REG_VF:
4918       return RTYPE_NUM | RTYPE_VF;
4919
4920     case OP_REG_R5900_I:
4921       return RTYPE_R5900_I;
4922
4923     case OP_REG_R5900_Q:
4924       return RTYPE_R5900_Q;
4925
4926     case OP_REG_R5900_R:
4927       return RTYPE_R5900_R;
4928
4929     case OP_REG_R5900_ACC:
4930       return RTYPE_R5900_ACC;
4931
4932     case OP_REG_MSA:
4933       return RTYPE_MSA;
4934
4935     case OP_REG_MSA_CTRL:
4936       return RTYPE_NUM;
4937     }
4938   abort ();
4939 }
4940
4941 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4942
4943 static void
4944 check_regno (struct mips_arg_info *arg,
4945              enum mips_reg_operand_type type, unsigned int regno)
4946 {
4947   if (AT && type == OP_REG_GP && regno == AT)
4948     arg->seen_at = TRUE;
4949
4950   if (type == OP_REG_FP
4951       && (regno & 1) != 0
4952       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4953     {
4954       /* This was a warning prior to introducing O32 FPXX and FP64 support
4955          so maintain a warning for FP32 but raise an error for the new
4956          cases.  */
4957       if (FPR_SIZE == 32)
4958         as_warn (_("float register should be even, was %d"), regno);
4959       else
4960         as_bad (_("float register should be even, was %d"), regno);
4961     }
4962
4963   if (type == OP_REG_CCC)
4964     {
4965       const char *name;
4966       size_t length;
4967
4968       name = arg->insn->insn_mo->name;
4969       length = strlen (name);
4970       if ((regno & 1) != 0
4971           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4972               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4973         as_warn (_("condition code register should be even for %s, was %d"),
4974                  name, regno);
4975
4976       if ((regno & 3) != 0
4977           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4978         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4979                  name, regno);
4980     }
4981 }
4982
4983 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4984    a register of type TYPE.  Return true on success, storing the register
4985    number in *REGNO and warning about any dubious uses.  */
4986
4987 static bfd_boolean
4988 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4989              unsigned int symval, unsigned int *regno)
4990 {
4991   if (type == OP_REG_VEC)
4992     symval = mips_prefer_vec_regno (symval);
4993   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4994     return FALSE;
4995
4996   *regno = symval & RNUM_MASK;
4997   check_regno (arg, type, *regno);
4998   return TRUE;
4999 }
5000
5001 /* Try to interpret the next token in ARG as a register of type TYPE.
5002    Consume the token and return true on success, storing the register
5003    number in *REGNO.  Return false on failure.  */
5004
5005 static bfd_boolean
5006 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5007            unsigned int *regno)
5008 {
5009   if (arg->token->type == OT_REG
5010       && match_regno (arg, type, arg->token->u.regno, regno))
5011     {
5012       ++arg->token;
5013       return TRUE;
5014     }
5015   return FALSE;
5016 }
5017
5018 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
5019    Consume the token and return true on success, storing the register numbers
5020    in *REGNO1 and *REGNO2.  Return false on failure.  */
5021
5022 static bfd_boolean
5023 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5024                  unsigned int *regno1, unsigned int *regno2)
5025 {
5026   if (match_reg (arg, type, regno1))
5027     {
5028       *regno2 = *regno1;
5029       return TRUE;
5030     }
5031   if (arg->token->type == OT_REG_RANGE
5032       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5033       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5034       && *regno1 <= *regno2)
5035     {
5036       ++arg->token;
5037       return TRUE;
5038     }
5039   return FALSE;
5040 }
5041
5042 /* OP_INT matcher.  */
5043
5044 static bfd_boolean
5045 match_int_operand (struct mips_arg_info *arg,
5046                    const struct mips_operand *operand_base)
5047 {
5048   const struct mips_int_operand *operand;
5049   unsigned int uval;
5050   int min_val, max_val, factor;
5051   offsetT sval;
5052
5053   operand = (const struct mips_int_operand *) operand_base;
5054   factor = 1 << operand->shift;
5055   min_val = mips_int_operand_min (operand);
5056   max_val = mips_int_operand_max (operand);
5057
5058   if (operand_base->lsb == 0
5059       && operand_base->size == 16
5060       && operand->shift == 0
5061       && operand->bias == 0
5062       && (operand->max_val == 32767 || operand->max_val == 65535))
5063     {
5064       /* The operand can be relocated.  */
5065       if (!match_expression (arg, &offset_expr, offset_reloc))
5066         return FALSE;
5067
5068       if (offset_expr.X_op == O_big)
5069         {
5070           match_out_of_range (arg);
5071           return FALSE;
5072         }
5073
5074       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5075         /* Relocation operators were used.  Accept the argument and
5076            leave the relocation value in offset_expr and offset_relocs
5077            for the caller to process.  */
5078         return TRUE;
5079
5080       if (offset_expr.X_op != O_constant)
5081         {
5082           /* Accept non-constant operands if no later alternative matches,
5083              leaving it for the caller to process.  */
5084           if (!arg->lax_match)
5085             return FALSE;
5086           offset_reloc[0] = BFD_RELOC_LO16;
5087           return TRUE;
5088         }
5089
5090       /* Clear the global state; we're going to install the operand
5091          ourselves.  */
5092       sval = offset_expr.X_add_number;
5093       offset_expr.X_op = O_absent;
5094
5095       /* For compatibility with older assemblers, we accept
5096          0x8000-0xffff as signed 16-bit numbers when only
5097          signed numbers are allowed.  */
5098       if (sval > max_val)
5099         {
5100           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5101           if (!arg->lax_match && sval <= max_val)
5102             return FALSE;
5103         }
5104     }
5105   else
5106     {
5107       if (!match_const_int (arg, &sval))
5108         return FALSE;
5109     }
5110
5111   arg->last_op_int = sval;
5112
5113   if (sval < min_val || sval > max_val || sval % factor)
5114     {
5115       match_out_of_range (arg);
5116       return FALSE;
5117     }
5118
5119   uval = (unsigned int) sval >> operand->shift;
5120   uval -= operand->bias;
5121
5122   /* Handle -mfix-cn63xxp1.  */
5123   if (arg->opnum == 1
5124       && mips_fix_cn63xxp1
5125       && !mips_opts.micromips
5126       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5127     switch (uval)
5128       {
5129       case 5:
5130       case 25:
5131       case 26:
5132       case 27:
5133       case 28:
5134       case 29:
5135       case 30:
5136       case 31:
5137         /* These are ok.  */
5138         break;
5139
5140       default:
5141         /* The rest must be changed to 28.  */
5142         uval = 28;
5143         break;
5144       }
5145
5146   insn_insert_operand (arg->insn, operand_base, uval);
5147   return TRUE;
5148 }
5149
5150 /* OP_MAPPED_INT matcher.  */
5151
5152 static bfd_boolean
5153 match_mapped_int_operand (struct mips_arg_info *arg,
5154                           const struct mips_operand *operand_base)
5155 {
5156   const struct mips_mapped_int_operand *operand;
5157   unsigned int uval, num_vals;
5158   offsetT sval;
5159
5160   operand = (const struct mips_mapped_int_operand *) operand_base;
5161   if (!match_const_int (arg, &sval))
5162     return FALSE;
5163
5164   num_vals = 1 << operand_base->size;
5165   for (uval = 0; uval < num_vals; uval++)
5166     if (operand->int_map[uval] == sval)
5167       break;
5168   if (uval == num_vals)
5169     {
5170       match_out_of_range (arg);
5171       return FALSE;
5172     }
5173
5174   insn_insert_operand (arg->insn, operand_base, uval);
5175   return TRUE;
5176 }
5177
5178 /* OP_MSB matcher.  */
5179
5180 static bfd_boolean
5181 match_msb_operand (struct mips_arg_info *arg,
5182                    const struct mips_operand *operand_base)
5183 {
5184   const struct mips_msb_operand *operand;
5185   int min_val, max_val, max_high;
5186   offsetT size, sval, high;
5187
5188   operand = (const struct mips_msb_operand *) operand_base;
5189   min_val = operand->bias;
5190   max_val = min_val + (1 << operand_base->size) - 1;
5191   max_high = operand->opsize;
5192
5193   if (!match_const_int (arg, &size))
5194     return FALSE;
5195
5196   high = size + arg->last_op_int;
5197   sval = operand->add_lsb ? high : size;
5198
5199   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5200     {
5201       match_out_of_range (arg);
5202       return FALSE;
5203     }
5204   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5205   return TRUE;
5206 }
5207
5208 /* OP_REG matcher.  */
5209
5210 static bfd_boolean
5211 match_reg_operand (struct mips_arg_info *arg,
5212                    const struct mips_operand *operand_base)
5213 {
5214   const struct mips_reg_operand *operand;
5215   unsigned int regno, uval, num_vals;
5216
5217   operand = (const struct mips_reg_operand *) operand_base;
5218   if (!match_reg (arg, operand->reg_type, &regno))
5219     return FALSE;
5220
5221   if (operand->reg_map)
5222     {
5223       num_vals = 1 << operand->root.size;
5224       for (uval = 0; uval < num_vals; uval++)
5225         if (operand->reg_map[uval] == regno)
5226           break;
5227       if (num_vals == uval)
5228         return FALSE;
5229     }
5230   else
5231     uval = regno;
5232
5233   arg->last_regno = regno;
5234   if (arg->opnum == 1)
5235     arg->dest_regno = regno;
5236   insn_insert_operand (arg->insn, operand_base, uval);
5237   return TRUE;
5238 }
5239
5240 /* OP_REG_PAIR matcher.  */
5241
5242 static bfd_boolean
5243 match_reg_pair_operand (struct mips_arg_info *arg,
5244                         const struct mips_operand *operand_base)
5245 {
5246   const struct mips_reg_pair_operand *operand;
5247   unsigned int regno1, regno2, uval, num_vals;
5248
5249   operand = (const struct mips_reg_pair_operand *) operand_base;
5250   if (!match_reg (arg, operand->reg_type, &regno1)
5251       || !match_char (arg, ',')
5252       || !match_reg (arg, operand->reg_type, &regno2))
5253     return FALSE;
5254
5255   num_vals = 1 << operand_base->size;
5256   for (uval = 0; uval < num_vals; uval++)
5257     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5258       break;
5259   if (uval == num_vals)
5260     return FALSE;
5261
5262   insn_insert_operand (arg->insn, operand_base, uval);
5263   return TRUE;
5264 }
5265
5266 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5267
5268 static bfd_boolean
5269 match_pcrel_operand (struct mips_arg_info *arg)
5270 {
5271   bfd_reloc_code_real_type r[3];
5272
5273   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5274 }
5275
5276 /* OP_PERF_REG matcher.  */
5277
5278 static bfd_boolean
5279 match_perf_reg_operand (struct mips_arg_info *arg,
5280                         const struct mips_operand *operand)
5281 {
5282   offsetT sval;
5283
5284   if (!match_const_int (arg, &sval))
5285     return FALSE;
5286
5287   if (sval != 0
5288       && (sval != 1
5289           || (mips_opts.arch == CPU_R5900
5290               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5291                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5292     {
5293       set_insn_error (arg->argnum, _("invalid performance register"));
5294       return FALSE;
5295     }
5296
5297   insn_insert_operand (arg->insn, operand, sval);
5298   return TRUE;
5299 }
5300
5301 /* OP_ADDIUSP matcher.  */
5302
5303 static bfd_boolean
5304 match_addiusp_operand (struct mips_arg_info *arg,
5305                        const struct mips_operand *operand)
5306 {
5307   offsetT sval;
5308   unsigned int uval;
5309
5310   if (!match_const_int (arg, &sval))
5311     return FALSE;
5312
5313   if (sval % 4)
5314     {
5315       match_out_of_range (arg);
5316       return FALSE;
5317     }
5318
5319   sval /= 4;
5320   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5321     {
5322       match_out_of_range (arg);
5323       return FALSE;
5324     }
5325
5326   uval = (unsigned int) sval;
5327   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5328   insn_insert_operand (arg->insn, operand, uval);
5329   return TRUE;
5330 }
5331
5332 /* OP_CLO_CLZ_DEST matcher.  */
5333
5334 static bfd_boolean
5335 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5336                             const struct mips_operand *operand)
5337 {
5338   unsigned int regno;
5339
5340   if (!match_reg (arg, OP_REG_GP, &regno))
5341     return FALSE;
5342
5343   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5344   return TRUE;
5345 }
5346
5347 /* OP_CHECK_PREV matcher.  */
5348
5349 static bfd_boolean
5350 match_check_prev_operand (struct mips_arg_info *arg,
5351                           const struct mips_operand *operand_base)
5352 {
5353   const struct mips_check_prev_operand *operand;
5354   unsigned int regno;
5355
5356   operand = (const struct mips_check_prev_operand *) operand_base;
5357
5358   if (!match_reg (arg, OP_REG_GP, &regno))
5359     return FALSE;
5360
5361   if (!operand->zero_ok && regno == 0)
5362     return FALSE;
5363
5364   if ((operand->less_than_ok && regno < arg->last_regno)
5365       || (operand->greater_than_ok && regno > arg->last_regno)
5366       || (operand->equal_ok && regno == arg->last_regno))
5367     {
5368       arg->last_regno = regno;
5369       insn_insert_operand (arg->insn, operand_base, regno);
5370       return TRUE;
5371     }
5372
5373   return FALSE;
5374 }
5375
5376 /* OP_SAME_RS_RT matcher.  */
5377
5378 static bfd_boolean
5379 match_same_rs_rt_operand (struct mips_arg_info *arg,
5380                           const struct mips_operand *operand)
5381 {
5382   unsigned int regno;
5383
5384   if (!match_reg (arg, OP_REG_GP, &regno))
5385     return FALSE;
5386
5387   if (regno == 0)
5388     {
5389       set_insn_error (arg->argnum, _("the source register must not be $0"));
5390       return FALSE;
5391     }
5392
5393   arg->last_regno = regno;
5394
5395   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5396   return TRUE;
5397 }
5398
5399 /* OP_LWM_SWM_LIST matcher.  */
5400
5401 static bfd_boolean
5402 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5403                             const struct mips_operand *operand)
5404 {
5405   unsigned int reglist, sregs, ra, regno1, regno2;
5406   struct mips_arg_info reset;
5407
5408   reglist = 0;
5409   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5410     return FALSE;
5411   do
5412     {
5413       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5414         {
5415           reglist |= 1 << FP;
5416           regno2 = S7;
5417         }
5418       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5419       reset = *arg;
5420     }
5421   while (match_char (arg, ',')
5422          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5423   *arg = reset;
5424
5425   if (operand->size == 2)
5426     {
5427       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5428
5429          s0, ra
5430          s0, s1, ra, s2, s3
5431          s0-s2, ra
5432
5433          and any permutations of these.  */
5434       if ((reglist & 0xfff1ffff) != 0x80010000)
5435         return FALSE;
5436
5437       sregs = (reglist >> 17) & 7;
5438       ra = 0;
5439     }
5440   else
5441     {
5442       /* The list must include at least one of ra and s0-sN,
5443          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5444          which are $23 and $30 respectively.)  E.g.:
5445
5446          ra
5447          s0
5448          ra, s0, s1, s2
5449          s0-s8
5450          s0-s5, ra
5451
5452          and any permutations of these.  */
5453       if ((reglist & 0x3f00ffff) != 0)
5454         return FALSE;
5455
5456       ra = (reglist >> 27) & 0x10;
5457       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5458     }
5459   sregs += 1;
5460   if ((sregs & -sregs) != sregs)
5461     return FALSE;
5462
5463   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5464   return TRUE;
5465 }
5466
5467 /* OP_ENTRY_EXIT_LIST matcher.  */
5468
5469 static unsigned int
5470 match_entry_exit_operand (struct mips_arg_info *arg,
5471                           const struct mips_operand *operand)
5472 {
5473   unsigned int mask;
5474   bfd_boolean is_exit;
5475
5476   /* The format is the same for both ENTRY and EXIT, but the constraints
5477      are different.  */
5478   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5479   mask = (is_exit ? 7 << 3 : 0);
5480   do
5481     {
5482       unsigned int regno1, regno2;
5483       bfd_boolean is_freg;
5484
5485       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5486         is_freg = FALSE;
5487       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5488         is_freg = TRUE;
5489       else
5490         return FALSE;
5491
5492       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5493         {
5494           mask &= ~(7 << 3);
5495           mask |= (5 + regno2) << 3;
5496         }
5497       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5498         mask |= (regno2 - 3) << 3;
5499       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5500         mask |= (regno2 - 15) << 1;
5501       else if (regno1 == RA && regno2 == RA)
5502         mask |= 1;
5503       else
5504         return FALSE;
5505     }
5506   while (match_char (arg, ','));
5507
5508   insn_insert_operand (arg->insn, operand, mask);
5509   return TRUE;
5510 }
5511
5512 /* OP_SAVE_RESTORE_LIST matcher.  */
5513
5514 static bfd_boolean
5515 match_save_restore_list_operand (struct mips_arg_info *arg)
5516 {
5517   unsigned int opcode, args, statics, sregs;
5518   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5519   offsetT frame_size;
5520
5521   opcode = arg->insn->insn_opcode;
5522   frame_size = 0;
5523   num_frame_sizes = 0;
5524   args = 0;
5525   statics = 0;
5526   sregs = 0;
5527   do
5528     {
5529       unsigned int regno1, regno2;
5530
5531       if (arg->token->type == OT_INTEGER)
5532         {
5533           /* Handle the frame size.  */
5534           if (!match_const_int (arg, &frame_size))
5535             return FALSE;
5536           num_frame_sizes += 1;
5537         }
5538       else
5539         {
5540           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5541             return FALSE;
5542
5543           while (regno1 <= regno2)
5544             {
5545               if (regno1 >= 4 && regno1 <= 7)
5546                 {
5547                   if (num_frame_sizes == 0)
5548                     /* args $a0-$a3 */
5549                     args |= 1 << (regno1 - 4);
5550                   else
5551                     /* statics $a0-$a3 */
5552                     statics |= 1 << (regno1 - 4);
5553                 }
5554               else if (regno1 >= 16 && regno1 <= 23)
5555                 /* $s0-$s7 */
5556                 sregs |= 1 << (regno1 - 16);
5557               else if (regno1 == 30)
5558                 /* $s8 */
5559                 sregs |= 1 << 8;
5560               else if (regno1 == 31)
5561                 /* Add $ra to insn.  */
5562                 opcode |= 0x40;
5563               else
5564                 return FALSE;
5565               regno1 += 1;
5566               if (regno1 == 24)
5567                 regno1 = 30;
5568             }
5569         }
5570     }
5571   while (match_char (arg, ','));
5572
5573   /* Encode args/statics combination.  */
5574   if (args & statics)
5575     return FALSE;
5576   else if (args == 0xf)
5577     /* All $a0-$a3 are args.  */
5578     opcode |= MIPS16_ALL_ARGS << 16;
5579   else if (statics == 0xf)
5580     /* All $a0-$a3 are statics.  */
5581     opcode |= MIPS16_ALL_STATICS << 16;
5582   else
5583     {
5584       /* Count arg registers.  */
5585       num_args = 0;
5586       while (args & 0x1)
5587         {
5588           args >>= 1;
5589           num_args += 1;
5590         }
5591       if (args != 0)
5592         return FALSE;
5593
5594       /* Count static registers.  */
5595       num_statics = 0;
5596       while (statics & 0x8)
5597         {
5598           statics = (statics << 1) & 0xf;
5599           num_statics += 1;
5600         }
5601       if (statics != 0)
5602         return FALSE;
5603
5604       /* Encode args/statics.  */
5605       opcode |= ((num_args << 2) | num_statics) << 16;
5606     }
5607
5608   /* Encode $s0/$s1.  */
5609   if (sregs & (1 << 0))         /* $s0 */
5610     opcode |= 0x20;
5611   if (sregs & (1 << 1))         /* $s1 */
5612     opcode |= 0x10;
5613   sregs >>= 2;
5614
5615   /* Encode $s2-$s8. */
5616   num_sregs = 0;
5617   while (sregs & 1)
5618     {
5619       sregs >>= 1;
5620       num_sregs += 1;
5621     }
5622   if (sregs != 0)
5623     return FALSE;
5624   opcode |= num_sregs << 24;
5625
5626   /* Encode frame size.  */
5627   if (num_frame_sizes == 0)
5628     {
5629       set_insn_error (arg->argnum, _("missing frame size"));
5630       return FALSE;
5631     }
5632   if (num_frame_sizes > 1)
5633     {
5634       set_insn_error (arg->argnum, _("frame size specified twice"));
5635       return FALSE;
5636     }
5637   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5638     {
5639       set_insn_error (arg->argnum, _("invalid frame size"));
5640       return FALSE;
5641     }
5642   if (frame_size != 128 || (opcode >> 16) != 0)
5643     {
5644       frame_size /= 8;
5645       opcode |= (((frame_size & 0xf0) << 16)
5646                  | (frame_size & 0x0f));
5647     }
5648
5649   /* Finally build the instruction.  */
5650   if ((opcode >> 16) != 0 || frame_size == 0)
5651     opcode |= MIPS16_EXTEND;
5652   arg->insn->insn_opcode = opcode;
5653   return TRUE;
5654 }
5655
5656 /* OP_MDMX_IMM_REG matcher.  */
5657
5658 static bfd_boolean
5659 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5660                             const struct mips_operand *operand)
5661 {
5662   unsigned int regno, uval;
5663   bfd_boolean is_qh;
5664   const struct mips_opcode *opcode;
5665
5666   /* The mips_opcode records whether this is an octobyte or quadhalf
5667      instruction.  Start out with that bit in place.  */
5668   opcode = arg->insn->insn_mo;
5669   uval = mips_extract_operand (operand, opcode->match);
5670   is_qh = (uval != 0);
5671
5672   if (arg->token->type == OT_REG)
5673     {
5674       if ((opcode->membership & INSN_5400)
5675           && strcmp (opcode->name, "rzu.ob") == 0)
5676         {
5677           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5678                             arg->argnum);
5679           return FALSE;
5680         }
5681
5682       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5683         return FALSE;
5684       ++arg->token;
5685
5686       /* Check whether this is a vector register or a broadcast of
5687          a single element.  */
5688       if (arg->token->type == OT_INTEGER_INDEX)
5689         {
5690           if (arg->token->u.index > (is_qh ? 3 : 7))
5691             {
5692               set_insn_error (arg->argnum, _("invalid element selector"));
5693               return FALSE;
5694             }
5695           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5696           ++arg->token;
5697         }
5698       else
5699         {
5700           /* A full vector.  */
5701           if ((opcode->membership & INSN_5400)
5702               && (strcmp (opcode->name, "sll.ob") == 0
5703                   || strcmp (opcode->name, "srl.ob") == 0))
5704             {
5705               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5706                                 arg->argnum);
5707               return FALSE;
5708             }
5709
5710           if (is_qh)
5711             uval |= MDMX_FMTSEL_VEC_QH << 5;
5712           else
5713             uval |= MDMX_FMTSEL_VEC_OB << 5;
5714         }
5715       uval |= regno;
5716     }
5717   else
5718     {
5719       offsetT sval;
5720
5721       if (!match_const_int (arg, &sval))
5722         return FALSE;
5723       if (sval < 0 || sval > 31)
5724         {
5725           match_out_of_range (arg);
5726           return FALSE;
5727         }
5728       uval |= (sval & 31);
5729       if (is_qh)
5730         uval |= MDMX_FMTSEL_IMM_QH << 5;
5731       else
5732         uval |= MDMX_FMTSEL_IMM_OB << 5;
5733     }
5734   insn_insert_operand (arg->insn, operand, uval);
5735   return TRUE;
5736 }
5737
5738 /* OP_IMM_INDEX matcher.  */
5739
5740 static bfd_boolean
5741 match_imm_index_operand (struct mips_arg_info *arg,
5742                          const struct mips_operand *operand)
5743 {
5744   unsigned int max_val;
5745
5746   if (arg->token->type != OT_INTEGER_INDEX)
5747     return FALSE;
5748
5749   max_val = (1 << operand->size) - 1;
5750   if (arg->token->u.index > max_val)
5751     {
5752       match_out_of_range (arg);
5753       return FALSE;
5754     }
5755   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5756   ++arg->token;
5757   return TRUE;
5758 }
5759
5760 /* OP_REG_INDEX matcher.  */
5761
5762 static bfd_boolean
5763 match_reg_index_operand (struct mips_arg_info *arg,
5764                          const struct mips_operand *operand)
5765 {
5766   unsigned int regno;
5767
5768   if (arg->token->type != OT_REG_INDEX)
5769     return FALSE;
5770
5771   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5772     return FALSE;
5773
5774   insn_insert_operand (arg->insn, operand, regno);
5775   ++arg->token;
5776   return TRUE;
5777 }
5778
5779 /* OP_PC matcher.  */
5780
5781 static bfd_boolean
5782 match_pc_operand (struct mips_arg_info *arg)
5783 {
5784   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5785     {
5786       ++arg->token;
5787       return TRUE;
5788     }
5789   return FALSE;
5790 }
5791
5792 /* OP_NON_ZERO_REG matcher.  */
5793
5794 static bfd_boolean
5795 match_non_zero_reg_operand (struct mips_arg_info *arg,
5796                             const struct mips_operand *operand)
5797 {
5798   unsigned int regno;
5799
5800   if (!match_reg (arg, OP_REG_GP, &regno))
5801     return FALSE;
5802
5803   if (regno == 0)
5804     return FALSE;
5805
5806   arg->last_regno = regno;
5807   insn_insert_operand (arg->insn, operand, regno);
5808   return TRUE;
5809 }
5810
5811 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5812    register that we need to match.  */
5813
5814 static bfd_boolean
5815 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5816 {
5817   unsigned int regno;
5818
5819   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5820 }
5821
5822 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5823    the length of the value in bytes (4 for float, 8 for double) and
5824    USING_GPRS says whether the destination is a GPR rather than an FPR.
5825
5826    Return the constant in IMM and OFFSET as follows:
5827
5828    - If the constant should be loaded via memory, set IMM to O_absent and
5829      OFFSET to the memory address.
5830
5831    - Otherwise, if the constant should be loaded into two 32-bit registers,
5832      set IMM to the O_constant to load into the high register and OFFSET
5833      to the corresponding value for the low register.
5834
5835    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5836
5837    These constants only appear as the last operand in an instruction,
5838    and every instruction that accepts them in any variant accepts them
5839    in all variants.  This means we don't have to worry about backing out
5840    any changes if the instruction does not match.  We just match
5841    unconditionally and report an error if the constant is invalid.  */
5842
5843 static bfd_boolean
5844 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5845                       expressionS *offset, int length, bfd_boolean using_gprs)
5846 {
5847   char *p;
5848   segT seg, new_seg;
5849   subsegT subseg;
5850   const char *newname;
5851   unsigned char *data;
5852
5853   /* Where the constant is placed is based on how the MIPS assembler
5854      does things:
5855
5856      length == 4 && using_gprs  -- immediate value only
5857      length == 8 && using_gprs  -- .rdata or immediate value
5858      length == 4 && !using_gprs -- .lit4 or immediate value
5859      length == 8 && !using_gprs -- .lit8 or immediate value
5860
5861      The .lit4 and .lit8 sections are only used if permitted by the
5862      -G argument.  */
5863   if (arg->token->type != OT_FLOAT)
5864     {
5865       set_insn_error (arg->argnum, _("floating-point expression required"));
5866       return FALSE;
5867     }
5868
5869   gas_assert (arg->token->u.flt.length == length);
5870   data = arg->token->u.flt.data;
5871   ++arg->token;
5872
5873   /* Handle 32-bit constants for which an immediate value is best.  */
5874   if (length == 4
5875       && (using_gprs
5876           || g_switch_value < 4
5877           || (data[0] == 0 && data[1] == 0)
5878           || (data[2] == 0 && data[3] == 0)))
5879     {
5880       imm->X_op = O_constant;
5881       if (!target_big_endian)
5882         imm->X_add_number = bfd_getl32 (data);
5883       else
5884         imm->X_add_number = bfd_getb32 (data);
5885       offset->X_op = O_absent;
5886       return TRUE;
5887     }
5888
5889   /* Handle 64-bit constants for which an immediate value is best.  */
5890   if (length == 8
5891       && !mips_disable_float_construction
5892       /* Constants can only be constructed in GPRs and copied to FPRs if the
5893          GPRs are at least as wide as the FPRs or MTHC1 is available.
5894          Unlike most tests for 32-bit floating-point registers this check
5895          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
5896          permit 64-bit moves without MXHC1.
5897          Force the constant into memory otherwise.  */
5898       && (using_gprs
5899           || GPR_SIZE == 64
5900           || ISA_HAS_MXHC1 (mips_opts.isa)
5901           || FPR_SIZE == 32)
5902       && ((data[0] == 0 && data[1] == 0)
5903           || (data[2] == 0 && data[3] == 0))
5904       && ((data[4] == 0 && data[5] == 0)
5905           || (data[6] == 0 && data[7] == 0)))
5906     {
5907       /* The value is simple enough to load with a couple of instructions.
5908          If using 32-bit registers, set IMM to the high order 32 bits and
5909          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5910          64 bit constant.  */
5911       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
5912         {
5913           imm->X_op = O_constant;
5914           offset->X_op = O_constant;
5915           if (!target_big_endian)
5916             {
5917               imm->X_add_number = bfd_getl32 (data + 4);
5918               offset->X_add_number = bfd_getl32 (data);
5919             }
5920           else
5921             {
5922               imm->X_add_number = bfd_getb32 (data);
5923               offset->X_add_number = bfd_getb32 (data + 4);
5924             }
5925           if (offset->X_add_number == 0)
5926             offset->X_op = O_absent;
5927         }
5928       else
5929         {
5930           imm->X_op = O_constant;
5931           if (!target_big_endian)
5932             imm->X_add_number = bfd_getl64 (data);
5933           else
5934             imm->X_add_number = bfd_getb64 (data);
5935           offset->X_op = O_absent;
5936         }
5937       return TRUE;
5938     }
5939
5940   /* Switch to the right section.  */
5941   seg = now_seg;
5942   subseg = now_subseg;
5943   if (length == 4)
5944     {
5945       gas_assert (!using_gprs && g_switch_value >= 4);
5946       newname = ".lit4";
5947     }
5948   else
5949     {
5950       if (using_gprs || g_switch_value < 8)
5951         newname = RDATA_SECTION_NAME;
5952       else
5953         newname = ".lit8";
5954     }
5955
5956   new_seg = subseg_new (newname, (subsegT) 0);
5957   bfd_set_section_flags (stdoutput, new_seg,
5958                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5959   frag_align (length == 4 ? 2 : 3, 0, 0);
5960   if (strncmp (TARGET_OS, "elf", 3) != 0)
5961     record_alignment (new_seg, 4);
5962   else
5963     record_alignment (new_seg, length == 4 ? 2 : 3);
5964   if (seg == now_seg)
5965     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5966
5967   /* Set the argument to the current address in the section.  */
5968   imm->X_op = O_absent;
5969   offset->X_op = O_symbol;
5970   offset->X_add_symbol = symbol_temp_new_now ();
5971   offset->X_add_number = 0;
5972
5973   /* Put the floating point number into the section.  */
5974   p = frag_more (length);
5975   memcpy (p, data, length);
5976
5977   /* Switch back to the original section.  */
5978   subseg_set (seg, subseg);
5979   return TRUE;
5980 }
5981
5982 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5983    them.  */
5984
5985 static bfd_boolean
5986 match_vu0_suffix_operand (struct mips_arg_info *arg,
5987                           const struct mips_operand *operand,
5988                           bfd_boolean match_p)
5989 {
5990   unsigned int uval;
5991
5992   /* The operand can be an XYZW mask or a single 2-bit channel index
5993      (with X being 0).  */
5994   gas_assert (operand->size == 2 || operand->size == 4);
5995
5996   /* The suffix can be omitted when it is already part of the opcode.  */
5997   if (arg->token->type != OT_CHANNELS)
5998     return match_p;
5999
6000   uval = arg->token->u.channels;
6001   if (operand->size == 2)
6002     {
6003       /* Check that a single bit is set and convert it into a 2-bit index.  */
6004       if ((uval & -uval) != uval)
6005         return FALSE;
6006       uval = 4 - ffs (uval);
6007     }
6008
6009   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6010     return FALSE;
6011
6012   ++arg->token;
6013   if (!match_p)
6014     insn_insert_operand (arg->insn, operand, uval);
6015   return TRUE;
6016 }
6017
6018 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
6019    of the argument text if the match is successful, otherwise return null.  */
6020
6021 static bfd_boolean
6022 match_operand (struct mips_arg_info *arg,
6023                const struct mips_operand *operand)
6024 {
6025   switch (operand->type)
6026     {
6027     case OP_INT:
6028       return match_int_operand (arg, operand);
6029
6030     case OP_MAPPED_INT:
6031       return match_mapped_int_operand (arg, operand);
6032
6033     case OP_MSB:
6034       return match_msb_operand (arg, operand);
6035
6036     case OP_REG:
6037     case OP_OPTIONAL_REG:
6038       return match_reg_operand (arg, operand);
6039
6040     case OP_REG_PAIR:
6041       return match_reg_pair_operand (arg, operand);
6042
6043     case OP_PCREL:
6044       return match_pcrel_operand (arg);
6045
6046     case OP_PERF_REG:
6047       return match_perf_reg_operand (arg, operand);
6048
6049     case OP_ADDIUSP_INT:
6050       return match_addiusp_operand (arg, operand);
6051
6052     case OP_CLO_CLZ_DEST:
6053       return match_clo_clz_dest_operand (arg, operand);
6054
6055     case OP_LWM_SWM_LIST:
6056       return match_lwm_swm_list_operand (arg, operand);
6057
6058     case OP_ENTRY_EXIT_LIST:
6059       return match_entry_exit_operand (arg, operand);
6060
6061     case OP_SAVE_RESTORE_LIST:
6062       return match_save_restore_list_operand (arg);
6063
6064     case OP_MDMX_IMM_REG:
6065       return match_mdmx_imm_reg_operand (arg, operand);
6066
6067     case OP_REPEAT_DEST_REG:
6068       return match_tied_reg_operand (arg, arg->dest_regno);
6069
6070     case OP_REPEAT_PREV_REG:
6071       return match_tied_reg_operand (arg, arg->last_regno);
6072
6073     case OP_PC:
6074       return match_pc_operand (arg);
6075
6076     case OP_VU0_SUFFIX:
6077       return match_vu0_suffix_operand (arg, operand, FALSE);
6078
6079     case OP_VU0_MATCH_SUFFIX:
6080       return match_vu0_suffix_operand (arg, operand, TRUE);
6081
6082     case OP_IMM_INDEX:
6083       return match_imm_index_operand (arg, operand);
6084
6085     case OP_REG_INDEX:
6086       return match_reg_index_operand (arg, operand);
6087
6088     case OP_SAME_RS_RT:
6089       return match_same_rs_rt_operand (arg, operand);
6090
6091     case OP_CHECK_PREV:
6092       return match_check_prev_operand (arg, operand);
6093
6094     case OP_NON_ZERO_REG:
6095       return match_non_zero_reg_operand (arg, operand);
6096     }
6097   abort ();
6098 }
6099
6100 /* ARG is the state after successfully matching an instruction.
6101    Issue any queued-up warnings.  */
6102
6103 static void
6104 check_completed_insn (struct mips_arg_info *arg)
6105 {
6106   if (arg->seen_at)
6107     {
6108       if (AT == ATREG)
6109         as_warn (_("used $at without \".set noat\""));
6110       else
6111         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6112     }
6113 }
6114
6115 /* Return true if modifying general-purpose register REG needs a delay.  */
6116
6117 static bfd_boolean
6118 reg_needs_delay (unsigned int reg)
6119 {
6120   unsigned long prev_pinfo;
6121
6122   prev_pinfo = history[0].insn_mo->pinfo;
6123   if (!mips_opts.noreorder
6124       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6125           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6126       && (gpr_write_mask (&history[0]) & (1 << reg)))
6127     return TRUE;
6128
6129   return FALSE;
6130 }
6131
6132 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6133    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6134    by VR4120 errata.  */
6135
6136 static unsigned int
6137 classify_vr4120_insn (const char *name)
6138 {
6139   if (strncmp (name, "macc", 4) == 0)
6140     return FIX_VR4120_MACC;
6141   if (strncmp (name, "dmacc", 5) == 0)
6142     return FIX_VR4120_DMACC;
6143   if (strncmp (name, "mult", 4) == 0)
6144     return FIX_VR4120_MULT;
6145   if (strncmp (name, "dmult", 5) == 0)
6146     return FIX_VR4120_DMULT;
6147   if (strstr (name, "div"))
6148     return FIX_VR4120_DIV;
6149   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6150     return FIX_VR4120_MTHILO;
6151   return NUM_FIX_VR4120_CLASSES;
6152 }
6153
6154 #define INSN_ERET       0x42000018
6155 #define INSN_DERET      0x4200001f
6156 #define INSN_DMULT      0x1c
6157 #define INSN_DMULTU     0x1d
6158
6159 /* Return the number of instructions that must separate INSN1 and INSN2,
6160    where INSN1 is the earlier instruction.  Return the worst-case value
6161    for any INSN2 if INSN2 is null.  */
6162
6163 static unsigned int
6164 insns_between (const struct mips_cl_insn *insn1,
6165                const struct mips_cl_insn *insn2)
6166 {
6167   unsigned long pinfo1, pinfo2;
6168   unsigned int mask;
6169
6170   /* If INFO2 is null, pessimistically assume that all flags are set for
6171      the second instruction.  */
6172   pinfo1 = insn1->insn_mo->pinfo;
6173   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6174
6175   /* For most targets, write-after-read dependencies on the HI and LO
6176      registers must be separated by at least two instructions.  */
6177   if (!hilo_interlocks)
6178     {
6179       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6180         return 2;
6181       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6182         return 2;
6183     }
6184
6185   /* If we're working around r7000 errata, there must be two instructions
6186      between an mfhi or mflo and any instruction that uses the result.  */
6187   if (mips_7000_hilo_fix
6188       && !mips_opts.micromips
6189       && MF_HILO_INSN (pinfo1)
6190       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6191     return 2;
6192
6193   /* If we're working around 24K errata, one instruction is required
6194      if an ERET or DERET is followed by a branch instruction.  */
6195   if (mips_fix_24k && !mips_opts.micromips)
6196     {
6197       if (insn1->insn_opcode == INSN_ERET
6198           || insn1->insn_opcode == INSN_DERET)
6199         {
6200           if (insn2 == NULL
6201               || insn2->insn_opcode == INSN_ERET
6202               || insn2->insn_opcode == INSN_DERET
6203               || delayed_branch_p (insn2))
6204             return 1;
6205         }
6206     }
6207
6208   /* If we're working around PMC RM7000 errata, there must be three
6209      nops between a dmult and a load instruction.  */
6210   if (mips_fix_rm7000 && !mips_opts.micromips)
6211     {
6212       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6213           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6214         {
6215           if (pinfo2 & INSN_LOAD_MEMORY)
6216            return 3;
6217         }
6218     }
6219
6220   /* If working around VR4120 errata, check for combinations that need
6221      a single intervening instruction.  */
6222   if (mips_fix_vr4120 && !mips_opts.micromips)
6223     {
6224       unsigned int class1, class2;
6225
6226       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6227       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6228         {
6229           if (insn2 == NULL)
6230             return 1;
6231           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6232           if (vr4120_conflicts[class1] & (1 << class2))
6233             return 1;
6234         }
6235     }
6236
6237   if (!HAVE_CODE_COMPRESSION)
6238     {
6239       /* Check for GPR or coprocessor load delays.  All such delays
6240          are on the RT register.  */
6241       /* Itbl support may require additional care here.  */
6242       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6243           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6244         {
6245           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6246             return 1;
6247         }
6248
6249       /* Check for generic coprocessor hazards.
6250
6251          This case is not handled very well.  There is no special
6252          knowledge of CP0 handling, and the coprocessors other than
6253          the floating point unit are not distinguished at all.  */
6254       /* Itbl support may require additional care here. FIXME!
6255          Need to modify this to include knowledge about
6256          user specified delays!  */
6257       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6258                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6259         {
6260           /* Handle cases where INSN1 writes to a known general coprocessor
6261              register.  There must be a one instruction delay before INSN2
6262              if INSN2 reads that register, otherwise no delay is needed.  */
6263           mask = fpr_write_mask (insn1);
6264           if (mask != 0)
6265             {
6266               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6267                 return 1;
6268             }
6269           else
6270             {
6271               /* Read-after-write dependencies on the control registers
6272                  require a two-instruction gap.  */
6273               if ((pinfo1 & INSN_WRITE_COND_CODE)
6274                   && (pinfo2 & INSN_READ_COND_CODE))
6275                 return 2;
6276
6277               /* We don't know exactly what INSN1 does.  If INSN2 is
6278                  also a coprocessor instruction, assume there must be
6279                  a one instruction gap.  */
6280               if (pinfo2 & INSN_COP)
6281                 return 1;
6282             }
6283         }
6284
6285       /* Check for read-after-write dependencies on the coprocessor
6286          control registers in cases where INSN1 does not need a general
6287          coprocessor delay.  This means that INSN1 is a floating point
6288          comparison instruction.  */
6289       /* Itbl support may require additional care here.  */
6290       else if (!cop_interlocks
6291                && (pinfo1 & INSN_WRITE_COND_CODE)
6292                && (pinfo2 & INSN_READ_COND_CODE))
6293         return 1;
6294     }
6295
6296   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6297      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6298      and pause.  */
6299   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6300       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6301           || (insn2 && delayed_branch_p (insn2))))
6302     return 1;
6303
6304   return 0;
6305 }
6306
6307 /* Return the number of nops that would be needed to work around the
6308    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6309    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6310    that are contained within the first IGNORE instructions of HIST.  */
6311
6312 static int
6313 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6314                  const struct mips_cl_insn *insn)
6315 {
6316   int i, j;
6317   unsigned int mask;
6318
6319   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6320      are not affected by the errata.  */
6321   if (insn != 0
6322       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6323           || strcmp (insn->insn_mo->name, "mtlo") == 0
6324           || strcmp (insn->insn_mo->name, "mthi") == 0))
6325     return 0;
6326
6327   /* Search for the first MFLO or MFHI.  */
6328   for (i = 0; i < MAX_VR4130_NOPS; i++)
6329     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6330       {
6331         /* Extract the destination register.  */
6332         mask = gpr_write_mask (&hist[i]);
6333
6334         /* No nops are needed if INSN reads that register.  */
6335         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6336           return 0;
6337
6338         /* ...or if any of the intervening instructions do.  */
6339         for (j = 0; j < i; j++)
6340           if (gpr_read_mask (&hist[j]) & mask)
6341             return 0;
6342
6343         if (i >= ignore)
6344           return MAX_VR4130_NOPS - i;
6345       }
6346   return 0;
6347 }
6348
6349 #define BASE_REG_EQ(INSN1, INSN2)       \
6350   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6351       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6352
6353 /* Return the minimum alignment for this store instruction.  */
6354
6355 static int
6356 fix_24k_align_to (const struct mips_opcode *mo)
6357 {
6358   if (strcmp (mo->name, "sh") == 0)
6359     return 2;
6360
6361   if (strcmp (mo->name, "swc1") == 0
6362       || strcmp (mo->name, "swc2") == 0
6363       || strcmp (mo->name, "sw") == 0
6364       || strcmp (mo->name, "sc") == 0
6365       || strcmp (mo->name, "s.s") == 0)
6366     return 4;
6367
6368   if (strcmp (mo->name, "sdc1") == 0
6369       || strcmp (mo->name, "sdc2") == 0
6370       || strcmp (mo->name, "s.d") == 0)
6371     return 8;
6372
6373   /* sb, swl, swr */
6374   return 1;
6375 }
6376
6377 struct fix_24k_store_info
6378   {
6379     /* Immediate offset, if any, for this store instruction.  */
6380     short off;
6381     /* Alignment required by this store instruction.  */
6382     int align_to;
6383     /* True for register offsets.  */
6384     int register_offset;
6385   };
6386
6387 /* Comparison function used by qsort.  */
6388
6389 static int
6390 fix_24k_sort (const void *a, const void *b)
6391 {
6392   const struct fix_24k_store_info *pos1 = a;
6393   const struct fix_24k_store_info *pos2 = b;
6394
6395   return (pos1->off - pos2->off);
6396 }
6397
6398 /* INSN is a store instruction.  Try to record the store information
6399    in STINFO.  Return false if the information isn't known.  */
6400
6401 static bfd_boolean
6402 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6403                            const struct mips_cl_insn *insn)
6404 {
6405   /* The instruction must have a known offset.  */
6406   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6407     return FALSE;
6408
6409   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6410   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6411   return TRUE;
6412 }
6413
6414 /* Return the number of nops that would be needed to work around the 24k
6415    "lost data on stores during refill" errata if instruction INSN
6416    immediately followed the 2 instructions described by HIST.
6417    Ignore hazards that are contained within the first IGNORE
6418    instructions of HIST.
6419
6420    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6421    for the data cache refills and store data. The following describes
6422    the scenario where the store data could be lost.
6423
6424    * A data cache miss, due to either a load or a store, causing fill
6425      data to be supplied by the memory subsystem
6426    * The first three doublewords of fill data are returned and written
6427      into the cache
6428    * A sequence of four stores occurs in consecutive cycles around the
6429      final doubleword of the fill:
6430    * Store A
6431    * Store B
6432    * Store C
6433    * Zero, One or more instructions
6434    * Store D
6435
6436    The four stores A-D must be to different doublewords of the line that
6437    is being filled. The fourth instruction in the sequence above permits
6438    the fill of the final doubleword to be transferred from the FSB into
6439    the cache. In the sequence above, the stores may be either integer
6440    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6441    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6442    different doublewords on the line. If the floating point unit is
6443    running in 1:2 mode, it is not possible to create the sequence above
6444    using only floating point store instructions.
6445
6446    In this case, the cache line being filled is incorrectly marked
6447    invalid, thereby losing the data from any store to the line that
6448    occurs between the original miss and the completion of the five
6449    cycle sequence shown above.
6450
6451    The workarounds are:
6452
6453    * Run the data cache in write-through mode.
6454    * Insert a non-store instruction between
6455      Store A and Store B or Store B and Store C.  */
6456
6457 static int
6458 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6459               const struct mips_cl_insn *insn)
6460 {
6461   struct fix_24k_store_info pos[3];
6462   int align, i, base_offset;
6463
6464   if (ignore >= 2)
6465     return 0;
6466
6467   /* If the previous instruction wasn't a store, there's nothing to
6468      worry about.  */
6469   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6470     return 0;
6471
6472   /* If the instructions after the previous one are unknown, we have
6473      to assume the worst.  */
6474   if (!insn)
6475     return 1;
6476
6477   /* Check whether we are dealing with three consecutive stores.  */
6478   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6479       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6480     return 0;
6481
6482   /* If we don't know the relationship between the store addresses,
6483      assume the worst.  */
6484   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6485       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6486     return 1;
6487
6488   if (!fix_24k_record_store_info (&pos[0], insn)
6489       || !fix_24k_record_store_info (&pos[1], &hist[0])
6490       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6491     return 1;
6492
6493   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6494
6495   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6496      X bytes and such that the base register + X is known to be aligned
6497      to align bytes.  */
6498
6499   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6500     align = 8;
6501   else
6502     {
6503       align = pos[0].align_to;
6504       base_offset = pos[0].off;
6505       for (i = 1; i < 3; i++)
6506         if (align < pos[i].align_to)
6507           {
6508             align = pos[i].align_to;
6509             base_offset = pos[i].off;
6510           }
6511       for (i = 0; i < 3; i++)
6512         pos[i].off -= base_offset;
6513     }
6514
6515   pos[0].off &= ~align + 1;
6516   pos[1].off &= ~align + 1;
6517   pos[2].off &= ~align + 1;
6518
6519   /* If any two stores write to the same chunk, they also write to the
6520      same doubleword.  The offsets are still sorted at this point.  */
6521   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6522     return 0;
6523
6524   /* A range of at least 9 bytes is needed for the stores to be in
6525      non-overlapping doublewords.  */
6526   if (pos[2].off - pos[0].off <= 8)
6527     return 0;
6528
6529   if (pos[2].off - pos[1].off >= 24
6530       || pos[1].off - pos[0].off >= 24
6531       || pos[2].off - pos[0].off >= 32)
6532     return 0;
6533
6534   return 1;
6535 }
6536
6537 /* Return the number of nops that would be needed if instruction INSN
6538    immediately followed the MAX_NOPS instructions given by HIST,
6539    where HIST[0] is the most recent instruction.  Ignore hazards
6540    between INSN and the first IGNORE instructions in HIST.
6541
6542    If INSN is null, return the worse-case number of nops for any
6543    instruction.  */
6544
6545 static int
6546 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6547                const struct mips_cl_insn *insn)
6548 {
6549   int i, nops, tmp_nops;
6550
6551   nops = 0;
6552   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6553     {
6554       tmp_nops = insns_between (hist + i, insn) - i;
6555       if (tmp_nops > nops)
6556         nops = tmp_nops;
6557     }
6558
6559   if (mips_fix_vr4130 && !mips_opts.micromips)
6560     {
6561       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6562       if (tmp_nops > nops)
6563         nops = tmp_nops;
6564     }
6565
6566   if (mips_fix_24k && !mips_opts.micromips)
6567     {
6568       tmp_nops = nops_for_24k (ignore, hist, insn);
6569       if (tmp_nops > nops)
6570         nops = tmp_nops;
6571     }
6572
6573   return nops;
6574 }
6575
6576 /* The variable arguments provide NUM_INSNS extra instructions that
6577    might be added to HIST.  Return the largest number of nops that
6578    would be needed after the extended sequence, ignoring hazards
6579    in the first IGNORE instructions.  */
6580
6581 static int
6582 nops_for_sequence (int num_insns, int ignore,
6583                    const struct mips_cl_insn *hist, ...)
6584 {
6585   va_list args;
6586   struct mips_cl_insn buffer[MAX_NOPS];
6587   struct mips_cl_insn *cursor;
6588   int nops;
6589
6590   va_start (args, hist);
6591   cursor = buffer + num_insns;
6592   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6593   while (cursor > buffer)
6594     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6595
6596   nops = nops_for_insn (ignore, buffer, NULL);
6597   va_end (args);
6598   return nops;
6599 }
6600
6601 /* Like nops_for_insn, but if INSN is a branch, take into account the
6602    worst-case delay for the branch target.  */
6603
6604 static int
6605 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6606                          const struct mips_cl_insn *insn)
6607 {
6608   int nops, tmp_nops;
6609
6610   nops = nops_for_insn (ignore, hist, insn);
6611   if (delayed_branch_p (insn))
6612     {
6613       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6614                                     hist, insn, get_delay_slot_nop (insn));
6615       if (tmp_nops > nops)
6616         nops = tmp_nops;
6617     }
6618   else if (compact_branch_p (insn))
6619     {
6620       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6621       if (tmp_nops > nops)
6622         nops = tmp_nops;
6623     }
6624   return nops;
6625 }
6626
6627 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6628
6629 static void
6630 fix_loongson2f_nop (struct mips_cl_insn * ip)
6631 {
6632   gas_assert (!HAVE_CODE_COMPRESSION);
6633   if (strcmp (ip->insn_mo->name, "nop") == 0)
6634     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6635 }
6636
6637 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6638                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6639
6640 static void
6641 fix_loongson2f_jump (struct mips_cl_insn * ip)
6642 {
6643   gas_assert (!HAVE_CODE_COMPRESSION);
6644   if (strcmp (ip->insn_mo->name, "j") == 0
6645       || strcmp (ip->insn_mo->name, "jr") == 0
6646       || strcmp (ip->insn_mo->name, "jalr") == 0)
6647     {
6648       int sreg;
6649       expressionS ep;
6650
6651       if (! mips_opts.at)
6652         return;
6653
6654       sreg = EXTRACT_OPERAND (0, RS, *ip);
6655       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6656         return;
6657
6658       ep.X_op = O_constant;
6659       ep.X_add_number = 0xcfff0000;
6660       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6661       ep.X_add_number = 0xffff;
6662       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6663       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6664     }
6665 }
6666
6667 static void
6668 fix_loongson2f (struct mips_cl_insn * ip)
6669 {
6670   if (mips_fix_loongson2f_nop)
6671     fix_loongson2f_nop (ip);
6672
6673   if (mips_fix_loongson2f_jump)
6674     fix_loongson2f_jump (ip);
6675 }
6676
6677 /* IP is a branch that has a delay slot, and we need to fill it
6678    automatically.   Return true if we can do that by swapping IP
6679    with the previous instruction.
6680    ADDRESS_EXPR is an operand of the instruction to be used with
6681    RELOC_TYPE.  */
6682
6683 static bfd_boolean
6684 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6685                    bfd_reloc_code_real_type *reloc_type)
6686 {
6687   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6688   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6689   unsigned int fpr_read, prev_fpr_write;
6690
6691   /* -O2 and above is required for this optimization.  */
6692   if (mips_optimize < 2)
6693     return FALSE;
6694
6695   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6696   if (mips_opts.nomove)
6697     return FALSE;
6698
6699   /* We can't swap if the previous instruction's position is fixed.  */
6700   if (history[0].fixed_p)
6701     return FALSE;
6702
6703   /* If the previous previous insn was in a .set noreorder, we can't
6704      swap.  Actually, the MIPS assembler will swap in this situation.
6705      However, gcc configured -with-gnu-as will generate code like
6706
6707         .set    noreorder
6708         lw      $4,XXX
6709         .set    reorder
6710         INSN
6711         bne     $4,$0,foo
6712
6713      in which we can not swap the bne and INSN.  If gcc is not configured
6714      -with-gnu-as, it does not output the .set pseudo-ops.  */
6715   if (history[1].noreorder_p)
6716     return FALSE;
6717
6718   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6719      This means that the previous instruction was a 4-byte one anyhow.  */
6720   if (mips_opts.mips16 && history[0].fixp[0])
6721     return FALSE;
6722
6723   /* If the branch is itself the target of a branch, we can not swap.
6724      We cheat on this; all we check for is whether there is a label on
6725      this instruction.  If there are any branches to anything other than
6726      a label, users must use .set noreorder.  */
6727   if (seg_info (now_seg)->label_list)
6728     return FALSE;
6729
6730   /* If the previous instruction is in a variant frag other than this
6731      branch's one, we cannot do the swap.  This does not apply to
6732      MIPS16 code, which uses variant frags for different purposes.  */
6733   if (!mips_opts.mips16
6734       && history[0].frag
6735       && history[0].frag->fr_type == rs_machine_dependent)
6736     return FALSE;
6737
6738   /* We do not swap with instructions that cannot architecturally
6739      be placed in a branch delay slot, such as SYNC or ERET.  We
6740      also refrain from swapping with a trap instruction, since it
6741      complicates trap handlers to have the trap instruction be in
6742      a delay slot.  */
6743   prev_pinfo = history[0].insn_mo->pinfo;
6744   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6745     return FALSE;
6746
6747   /* Check for conflicts between the branch and the instructions
6748      before the candidate delay slot.  */
6749   if (nops_for_insn (0, history + 1, ip) > 0)
6750     return FALSE;
6751
6752   /* Check for conflicts between the swapped sequence and the
6753      target of the branch.  */
6754   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6755     return FALSE;
6756
6757   /* If the branch reads a register that the previous
6758      instruction sets, we can not swap.  */
6759   gpr_read = gpr_read_mask (ip);
6760   prev_gpr_write = gpr_write_mask (&history[0]);
6761   if (gpr_read & prev_gpr_write)
6762     return FALSE;
6763
6764   fpr_read = fpr_read_mask (ip);
6765   prev_fpr_write = fpr_write_mask (&history[0]);
6766   if (fpr_read & prev_fpr_write)
6767     return FALSE;
6768
6769   /* If the branch writes a register that the previous
6770      instruction sets, we can not swap.  */
6771   gpr_write = gpr_write_mask (ip);
6772   if (gpr_write & prev_gpr_write)
6773     return FALSE;
6774
6775   /* If the branch writes a register that the previous
6776      instruction reads, we can not swap.  */
6777   prev_gpr_read = gpr_read_mask (&history[0]);
6778   if (gpr_write & prev_gpr_read)
6779     return FALSE;
6780
6781   /* If one instruction sets a condition code and the
6782      other one uses a condition code, we can not swap.  */
6783   pinfo = ip->insn_mo->pinfo;
6784   if ((pinfo & INSN_READ_COND_CODE)
6785       && (prev_pinfo & INSN_WRITE_COND_CODE))
6786     return FALSE;
6787   if ((pinfo & INSN_WRITE_COND_CODE)
6788       && (prev_pinfo & INSN_READ_COND_CODE))
6789     return FALSE;
6790
6791   /* If the previous instruction uses the PC, we can not swap.  */
6792   prev_pinfo2 = history[0].insn_mo->pinfo2;
6793   if (prev_pinfo2 & INSN2_READ_PC)
6794     return FALSE;
6795
6796   /* If the previous instruction has an incorrect size for a fixed
6797      branch delay slot in microMIPS mode, we cannot swap.  */
6798   pinfo2 = ip->insn_mo->pinfo2;
6799   if (mips_opts.micromips
6800       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6801       && insn_length (history) != 2)
6802     return FALSE;
6803   if (mips_opts.micromips
6804       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6805       && insn_length (history) != 4)
6806     return FALSE;
6807
6808   /* On R5900 short loops need to be fixed by inserting a nop in
6809      the branch delay slots.
6810      A short loop can be terminated too early.  */
6811   if (mips_opts.arch == CPU_R5900
6812       /* Check if instruction has a parameter, ignore "j $31". */
6813       && (address_expr != NULL)
6814       /* Parameter must be 16 bit. */
6815       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6816       /* Branch to same segment. */
6817       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6818       /* Branch to same code fragment. */
6819       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6820       /* Can only calculate branch offset if value is known. */
6821       && symbol_constant_p (address_expr->X_add_symbol)
6822       /* Check if branch is really conditional. */
6823       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6824         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6825         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6826     {
6827       int distance;
6828       /* Check if loop is shorter than 6 instructions including
6829          branch and delay slot.  */
6830       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
6831       if (distance <= 20)
6832         {
6833           int i;
6834           int rv;
6835
6836           rv = FALSE;
6837           /* When the loop includes branches or jumps,
6838              it is not a short loop. */
6839           for (i = 0; i < (distance / 4); i++)
6840             {
6841               if ((history[i].cleared_p)
6842                   || delayed_branch_p (&history[i]))
6843                 {
6844                   rv = TRUE;
6845                   break;
6846                 }
6847             }
6848           if (rv == FALSE)
6849             {
6850               /* Insert nop after branch to fix short loop. */
6851               return FALSE;
6852             }
6853         }
6854     }
6855
6856   return TRUE;
6857 }
6858
6859 /* Decide how we should add IP to the instruction stream.
6860    ADDRESS_EXPR is an operand of the instruction to be used with
6861    RELOC_TYPE.  */
6862
6863 static enum append_method
6864 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6865                    bfd_reloc_code_real_type *reloc_type)
6866 {
6867   /* The relaxed version of a macro sequence must be inherently
6868      hazard-free.  */
6869   if (mips_relax.sequence == 2)
6870     return APPEND_ADD;
6871
6872   /* We must not dabble with instructions in a ".set noreorder" block.  */
6873   if (mips_opts.noreorder)
6874     return APPEND_ADD;
6875
6876   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6877   if (delayed_branch_p (ip))
6878     {
6879       if (!branch_likely_p (ip)
6880           && can_swap_branch_p (ip, address_expr, reloc_type))
6881         return APPEND_SWAP;
6882
6883       if (mips_opts.mips16
6884           && ISA_SUPPORTS_MIPS16E
6885           && gpr_read_mask (ip) != 0)
6886         return APPEND_ADD_COMPACT;
6887
6888       if (mips_opts.micromips
6889           && ((ip->insn_opcode & 0xffe0) == 0x4580
6890               || (!forced_insn_length
6891                   && ((ip->insn_opcode & 0xfc00) == 0xcc00
6892                       || (ip->insn_opcode & 0xdc00) == 0x8c00))
6893               || (ip->insn_opcode & 0xdfe00000) == 0x94000000
6894               || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
6895         return APPEND_ADD_COMPACT;
6896
6897       return APPEND_ADD_WITH_NOP;
6898     }
6899
6900   return APPEND_ADD;
6901 }
6902
6903 /* IP is an instruction whose opcode we have just changed, END points
6904    to the end of the opcode table processed.  Point IP->insn_mo to the
6905    new opcode's definition.  */
6906
6907 static void
6908 find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
6909 {
6910   const struct mips_opcode *mo;
6911
6912   for (mo = ip->insn_mo; mo < end; mo++)
6913     if (mo->pinfo != INSN_MACRO
6914         && (ip->insn_opcode & mo->mask) == mo->match)
6915       {
6916         ip->insn_mo = mo;
6917         return;
6918       }
6919   abort ();
6920 }
6921
6922 /* IP is a MIPS16 instruction whose opcode we have just changed.
6923    Point IP->insn_mo to the new opcode's definition.  */
6924
6925 static void
6926 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6927 {
6928   find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
6929 }
6930
6931 /* IP is a microMIPS instruction whose opcode we have just changed.
6932    Point IP->insn_mo to the new opcode's definition.  */
6933
6934 static void
6935 find_altered_micromips_opcode (struct mips_cl_insn *ip)
6936 {
6937   find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
6938 }
6939
6940 /* For microMIPS macros, we need to generate a local number label
6941    as the target of branches.  */
6942 #define MICROMIPS_LABEL_CHAR            '\037'
6943 static unsigned long micromips_target_label;
6944 static char micromips_target_name[32];
6945
6946 static char *
6947 micromips_label_name (void)
6948 {
6949   char *p = micromips_target_name;
6950   char symbol_name_temporary[24];
6951   unsigned long l;
6952   int i;
6953
6954   if (*p)
6955     return p;
6956
6957   i = 0;
6958   l = micromips_target_label;
6959 #ifdef LOCAL_LABEL_PREFIX
6960   *p++ = LOCAL_LABEL_PREFIX;
6961 #endif
6962   *p++ = 'L';
6963   *p++ = MICROMIPS_LABEL_CHAR;
6964   do
6965     {
6966       symbol_name_temporary[i++] = l % 10 + '0';
6967       l /= 10;
6968     }
6969   while (l != 0);
6970   while (i > 0)
6971     *p++ = symbol_name_temporary[--i];
6972   *p = '\0';
6973
6974   return micromips_target_name;
6975 }
6976
6977 static void
6978 micromips_label_expr (expressionS *label_expr)
6979 {
6980   label_expr->X_op = O_symbol;
6981   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6982   label_expr->X_add_number = 0;
6983 }
6984
6985 static void
6986 micromips_label_inc (void)
6987 {
6988   micromips_target_label++;
6989   *micromips_target_name = '\0';
6990 }
6991
6992 static void
6993 micromips_add_label (void)
6994 {
6995   symbolS *s;
6996
6997   s = colon (micromips_label_name ());
6998   micromips_label_inc ();
6999   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
7000 }
7001
7002 /* If assembling microMIPS code, then return the microMIPS reloc
7003    corresponding to the requested one if any.  Otherwise return
7004    the reloc unchanged.  */
7005
7006 static bfd_reloc_code_real_type
7007 micromips_map_reloc (bfd_reloc_code_real_type reloc)
7008 {
7009   static const bfd_reloc_code_real_type relocs[][2] =
7010     {
7011       /* Keep sorted incrementally by the left-hand key.  */
7012       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7013       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7014       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7015       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7016       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7017       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7018       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7019       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7020       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7021       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7022       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7023       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7024       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7025       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7026       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7027       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7028       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7029       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7030       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7031       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7032       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7033       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7034       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7035       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7036       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7037       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7038       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7039     };
7040   bfd_reloc_code_real_type r;
7041   size_t i;
7042
7043   if (!mips_opts.micromips)
7044     return reloc;
7045   for (i = 0; i < ARRAY_SIZE (relocs); i++)
7046     {
7047       r = relocs[i][0];
7048       if (r > reloc)
7049         return reloc;
7050       if (r == reloc)
7051         return relocs[i][1];
7052     }
7053   return reloc;
7054 }
7055
7056 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7057    Return true on success, storing the resolved value in RESULT.  */
7058
7059 static bfd_boolean
7060 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7061                  offsetT *result)
7062 {
7063   switch (reloc)
7064     {
7065     case BFD_RELOC_MIPS_HIGHEST:
7066     case BFD_RELOC_MICROMIPS_HIGHEST:
7067       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7068       return TRUE;
7069
7070     case BFD_RELOC_MIPS_HIGHER:
7071     case BFD_RELOC_MICROMIPS_HIGHER:
7072       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7073       return TRUE;
7074
7075     case BFD_RELOC_HI16_S:
7076     case BFD_RELOC_HI16_S_PCREL:
7077     case BFD_RELOC_MICROMIPS_HI16_S:
7078     case BFD_RELOC_MIPS16_HI16_S:
7079       *result = ((operand + 0x8000) >> 16) & 0xffff;
7080       return TRUE;
7081
7082     case BFD_RELOC_HI16:
7083     case BFD_RELOC_MICROMIPS_HI16:
7084     case BFD_RELOC_MIPS16_HI16:
7085       *result = (operand >> 16) & 0xffff;
7086       return TRUE;
7087
7088     case BFD_RELOC_LO16:
7089     case BFD_RELOC_LO16_PCREL:
7090     case BFD_RELOC_MICROMIPS_LO16:
7091     case BFD_RELOC_MIPS16_LO16:
7092       *result = operand & 0xffff;
7093       return TRUE;
7094
7095     case BFD_RELOC_UNUSED:
7096       *result = operand;
7097       return TRUE;
7098
7099     default:
7100       return FALSE;
7101     }
7102 }
7103
7104 /* Output an instruction.  IP is the instruction information.
7105    ADDRESS_EXPR is an operand of the instruction to be used with
7106    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7107    a macro expansion.  */
7108
7109 static void
7110 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7111              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7112 {
7113   unsigned long prev_pinfo2, pinfo;
7114   bfd_boolean relaxed_branch = FALSE;
7115   enum append_method method;
7116   bfd_boolean relax32;
7117   int branch_disp;
7118
7119   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7120     fix_loongson2f (ip);
7121
7122   file_ase_mips16 |= mips_opts.mips16;
7123   file_ase_micromips |= mips_opts.micromips;
7124
7125   prev_pinfo2 = history[0].insn_mo->pinfo2;
7126   pinfo = ip->insn_mo->pinfo;
7127
7128   /* Don't raise alarm about `nods' frags as they'll fill in the right
7129      kind of nop in relaxation if required.  */
7130   if (mips_opts.micromips
7131       && !expansionp
7132       && !(history[0].frag
7133            && history[0].frag->fr_type == rs_machine_dependent
7134            && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7135            && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7136       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7137            && micromips_insn_length (ip->insn_mo) != 2)
7138           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7139               && micromips_insn_length (ip->insn_mo) != 4)))
7140     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7141              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7142
7143   if (address_expr == NULL)
7144     ip->complete_p = 1;
7145   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7146            && reloc_type[1] == BFD_RELOC_UNUSED
7147            && reloc_type[2] == BFD_RELOC_UNUSED
7148            && address_expr->X_op == O_constant)
7149     {
7150       switch (*reloc_type)
7151         {
7152         case BFD_RELOC_MIPS_JMP:
7153           {
7154             int shift;
7155
7156             /* Shift is 2, unusually, for microMIPS JALX.  */
7157             shift = (mips_opts.micromips
7158                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7159             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7160               as_bad (_("jump to misaligned address (0x%lx)"),
7161                       (unsigned long) address_expr->X_add_number);
7162             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7163                                 & 0x3ffffff);
7164             ip->complete_p = 1;
7165           }
7166           break;
7167
7168         case BFD_RELOC_MIPS16_JMP:
7169           if ((address_expr->X_add_number & 3) != 0)
7170             as_bad (_("jump to misaligned address (0x%lx)"),
7171                     (unsigned long) address_expr->X_add_number);
7172           ip->insn_opcode |=
7173             (((address_expr->X_add_number & 0x7c0000) << 3)
7174                | ((address_expr->X_add_number & 0xf800000) >> 7)
7175                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7176           ip->complete_p = 1;
7177           break;
7178
7179         case BFD_RELOC_16_PCREL_S2:
7180           {
7181             int shift;
7182
7183             shift = mips_opts.micromips ? 1 : 2;
7184             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7185               as_bad (_("branch to misaligned address (0x%lx)"),
7186                       (unsigned long) address_expr->X_add_number);
7187             if (!mips_relax_branch)
7188               {
7189                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7190                     & ~((1 << (shift + 16)) - 1))
7191                   as_bad (_("branch address range overflow (0x%lx)"),
7192                           (unsigned long) address_expr->X_add_number);
7193                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7194                                     & 0xffff);
7195               }
7196           }
7197           break;
7198
7199         case BFD_RELOC_MIPS_21_PCREL_S2:
7200           {
7201             int shift;
7202
7203             shift = 2;
7204             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7205               as_bad (_("branch to misaligned address (0x%lx)"),
7206                       (unsigned long) address_expr->X_add_number);
7207             if ((address_expr->X_add_number + (1 << (shift + 20)))
7208                 & ~((1 << (shift + 21)) - 1))
7209               as_bad (_("branch address range overflow (0x%lx)"),
7210                       (unsigned long) address_expr->X_add_number);
7211             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7212                                 & 0x1fffff);
7213           }
7214           break;
7215
7216         case BFD_RELOC_MIPS_26_PCREL_S2:
7217           {
7218             int shift;
7219
7220             shift = 2;
7221             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7222               as_bad (_("branch to misaligned address (0x%lx)"),
7223                       (unsigned long) address_expr->X_add_number);
7224             if ((address_expr->X_add_number + (1 << (shift + 25)))
7225                 & ~((1 << (shift + 26)) - 1))
7226               as_bad (_("branch address range overflow (0x%lx)"),
7227                       (unsigned long) address_expr->X_add_number);
7228             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7229                                 & 0x3ffffff);
7230           }
7231           break;
7232
7233         default:
7234           {
7235             offsetT value;
7236
7237             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7238                                  &value))
7239               {
7240                 ip->insn_opcode |= value & 0xffff;
7241                 ip->complete_p = 1;
7242               }
7243           }
7244           break;
7245         }
7246     }
7247
7248   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7249     {
7250       /* There are a lot of optimizations we could do that we don't.
7251          In particular, we do not, in general, reorder instructions.
7252          If you use gcc with optimization, it will reorder
7253          instructions and generally do much more optimization then we
7254          do here; repeating all that work in the assembler would only
7255          benefit hand written assembly code, and does not seem worth
7256          it.  */
7257       int nops = (mips_optimize == 0
7258                   ? nops_for_insn (0, history, NULL)
7259                   : nops_for_insn_or_target (0, history, ip));
7260       if (nops > 0)
7261         {
7262           fragS *old_frag;
7263           unsigned long old_frag_offset;
7264           int i;
7265
7266           old_frag = frag_now;
7267           old_frag_offset = frag_now_fix ();
7268
7269           for (i = 0; i < nops; i++)
7270             add_fixed_insn (NOP_INSN);
7271           insert_into_history (0, nops, NOP_INSN);
7272
7273           if (listing)
7274             {
7275               listing_prev_line ();
7276               /* We may be at the start of a variant frag.  In case we
7277                  are, make sure there is enough space for the frag
7278                  after the frags created by listing_prev_line.  The
7279                  argument to frag_grow here must be at least as large
7280                  as the argument to all other calls to frag_grow in
7281                  this file.  We don't have to worry about being in the
7282                  middle of a variant frag, because the variants insert
7283                  all needed nop instructions themselves.  */
7284               frag_grow (40);
7285             }
7286
7287           mips_move_text_labels ();
7288
7289 #ifndef NO_ECOFF_DEBUGGING
7290           if (ECOFF_DEBUGGING)
7291             ecoff_fix_loc (old_frag, old_frag_offset);
7292 #endif
7293         }
7294     }
7295   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7296     {
7297       int nops;
7298
7299       /* Work out how many nops in prev_nop_frag are needed by IP,
7300          ignoring hazards generated by the first prev_nop_frag_since
7301          instructions.  */
7302       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7303       gas_assert (nops <= prev_nop_frag_holds);
7304
7305       /* Enforce NOPS as a minimum.  */
7306       if (nops > prev_nop_frag_required)
7307         prev_nop_frag_required = nops;
7308
7309       if (prev_nop_frag_holds == prev_nop_frag_required)
7310         {
7311           /* Settle for the current number of nops.  Update the history
7312              accordingly (for the benefit of any future .set reorder code).  */
7313           prev_nop_frag = NULL;
7314           insert_into_history (prev_nop_frag_since,
7315                                prev_nop_frag_holds, NOP_INSN);
7316         }
7317       else
7318         {
7319           /* Allow this instruction to replace one of the nops that was
7320              tentatively added to prev_nop_frag.  */
7321           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7322           prev_nop_frag_holds--;
7323           prev_nop_frag_since++;
7324         }
7325     }
7326
7327   method = get_append_method (ip, address_expr, reloc_type);
7328   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7329
7330   dwarf2_emit_insn (0);
7331   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7332      so "move" the instruction address accordingly.
7333
7334      Also, it doesn't seem appropriate for the assembler to reorder .loc
7335      entries.  If this instruction is a branch that we are going to swap
7336      with the previous instruction, the two instructions should be
7337      treated as a unit, and the debug information for both instructions
7338      should refer to the start of the branch sequence.  Using the
7339      current position is certainly wrong when swapping a 32-bit branch
7340      and a 16-bit delay slot, since the current position would then be
7341      in the middle of a branch.  */
7342   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7343
7344   relax32 = (mips_relax_branch
7345              /* Don't try branch relaxation within .set nomacro, or within
7346                 .set noat if we use $at for PIC computations.  If it turns
7347                 out that the branch was out-of-range, we'll get an error.  */
7348              && !mips_opts.warn_about_macros
7349              && (mips_opts.at || mips_pic == NO_PIC)
7350              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7351                 as they have no complementing branches.  */
7352              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7353
7354   if (!HAVE_CODE_COMPRESSION
7355       && address_expr
7356       && relax32
7357       && *reloc_type == BFD_RELOC_16_PCREL_S2
7358       && delayed_branch_p (ip))
7359     {
7360       relaxed_branch = TRUE;
7361       add_relaxed_insn (ip, (relaxed_branch_length
7362                              (NULL, NULL,
7363                               uncond_branch_p (ip) ? -1
7364                               : branch_likely_p (ip) ? 1
7365                               : 0)), 4,
7366                         RELAX_BRANCH_ENCODE
7367                         (AT, mips_pic != NO_PIC,
7368                          uncond_branch_p (ip),
7369                          branch_likely_p (ip),
7370                          pinfo & INSN_WRITE_GPR_31,
7371                          0),
7372                         address_expr->X_add_symbol,
7373                         address_expr->X_add_number);
7374       *reloc_type = BFD_RELOC_UNUSED;
7375     }
7376   else if (mips_opts.micromips
7377            && address_expr
7378            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7379                || *reloc_type > BFD_RELOC_UNUSED)
7380            && (delayed_branch_p (ip) || compact_branch_p (ip))
7381            /* Don't try branch relaxation when users specify
7382               16-bit/32-bit instructions.  */
7383            && !forced_insn_length)
7384     {
7385       bfd_boolean relax16 = (method != APPEND_ADD_COMPACT
7386                              && *reloc_type > BFD_RELOC_UNUSED);
7387       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7388       int uncond = uncond_branch_p (ip) ? -1 : 0;
7389       int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7390       int nods = method == APPEND_ADD_WITH_NOP;
7391       int al = pinfo & INSN_WRITE_GPR_31;
7392       int length32 = nods ? 8 : 4;
7393
7394       gas_assert (address_expr != NULL);
7395       gas_assert (!mips_relax.sequence);
7396
7397       relaxed_branch = TRUE;
7398       if (nods)
7399         method = APPEND_ADD;
7400       if (relax32)
7401         length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7402       add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7403                         RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7404                                                 mips_pic != NO_PIC,
7405                                                 uncond, compact, al, nods,
7406                                                 relax32, 0, 0),
7407                         address_expr->X_add_symbol,
7408                         address_expr->X_add_number);
7409       *reloc_type = BFD_RELOC_UNUSED;
7410     }
7411   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7412     {
7413       bfd_boolean require_unextended;
7414       bfd_boolean require_extended;
7415       symbolS *symbol;
7416       offsetT offset;
7417
7418       if (forced_insn_length != 0)
7419         {
7420           require_unextended = forced_insn_length == 2;
7421           require_extended = forced_insn_length == 4;
7422         }
7423       else
7424         {
7425           require_unextended = (mips_opts.noautoextend
7426                                 && !mips_opcode_32bit_p (ip->insn_mo));
7427           require_extended = 0;
7428         }
7429
7430       /* We need to set up a variant frag.  */
7431       gas_assert (address_expr != NULL);
7432       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7433          symbol created by `make_expr_symbol' may not get a necessary
7434          external relocation produced.  */
7435       if (address_expr->X_op == O_symbol)
7436         {
7437           symbol = address_expr->X_add_symbol;
7438           offset = address_expr->X_add_number;
7439         }
7440       else
7441         {
7442           symbol = make_expr_symbol (address_expr);
7443           symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7444           offset = 0;
7445         }
7446       add_relaxed_insn (ip, 12, 0,
7447                         RELAX_MIPS16_ENCODE
7448                         (*reloc_type - BFD_RELOC_UNUSED,
7449                          mips_pic != NO_PIC,
7450                          HAVE_32BIT_SYMBOLS,
7451                          mips_opts.warn_about_macros,
7452                          require_unextended, require_extended,
7453                          delayed_branch_p (&history[0]),
7454                          history[0].mips16_absolute_jump_p),
7455                         symbol, offset);
7456     }
7457   else if (mips_opts.mips16 && insn_length (ip) == 2)
7458     {
7459       if (!delayed_branch_p (ip))
7460         /* Make sure there is enough room to swap this instruction with
7461            a following jump instruction.  */
7462         frag_grow (6);
7463       add_fixed_insn (ip);
7464     }
7465   else
7466     {
7467       if (mips_opts.mips16
7468           && mips_opts.noreorder
7469           && delayed_branch_p (&history[0]))
7470         as_warn (_("extended instruction in delay slot"));
7471
7472       if (mips_relax.sequence)
7473         {
7474           /* If we've reached the end of this frag, turn it into a variant
7475              frag and record the information for the instructions we've
7476              written so far.  */
7477           if (frag_room () < 4)
7478             relax_close_frag ();
7479           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7480         }
7481
7482       if (mips_relax.sequence != 2)
7483         {
7484           if (mips_macro_warning.first_insn_sizes[0] == 0)
7485             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7486           mips_macro_warning.sizes[0] += insn_length (ip);
7487           mips_macro_warning.insns[0]++;
7488         }
7489       if (mips_relax.sequence != 1)
7490         {
7491           if (mips_macro_warning.first_insn_sizes[1] == 0)
7492             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7493           mips_macro_warning.sizes[1] += insn_length (ip);
7494           mips_macro_warning.insns[1]++;
7495         }
7496
7497       if (mips_opts.mips16)
7498         {
7499           ip->fixed_p = 1;
7500           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7501         }
7502       add_fixed_insn (ip);
7503     }
7504
7505   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7506     {
7507       bfd_reloc_code_real_type final_type[3];
7508       reloc_howto_type *howto0;
7509       reloc_howto_type *howto;
7510       int i;
7511
7512       /* Perform any necessary conversion to microMIPS relocations
7513          and find out how many relocations there actually are.  */
7514       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7515         final_type[i] = micromips_map_reloc (reloc_type[i]);
7516
7517       /* In a compound relocation, it is the final (outermost)
7518          operator that determines the relocated field.  */
7519       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7520       if (!howto)
7521         abort ();
7522
7523       if (i > 1)
7524         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7525       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7526                                  bfd_get_reloc_size (howto),
7527                                  address_expr,
7528                                  howto0 && howto0->pc_relative,
7529                                  final_type[0]);
7530       /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7531       ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7532
7533       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7534       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7535         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7536
7537       /* These relocations can have an addend that won't fit in
7538          4 octets for 64bit assembly.  */
7539       if (GPR_SIZE == 64
7540           && ! howto->partial_inplace
7541           && (reloc_type[0] == BFD_RELOC_16
7542               || reloc_type[0] == BFD_RELOC_32
7543               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7544               || reloc_type[0] == BFD_RELOC_GPREL16
7545               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7546               || reloc_type[0] == BFD_RELOC_GPREL32
7547               || reloc_type[0] == BFD_RELOC_64
7548               || reloc_type[0] == BFD_RELOC_CTOR
7549               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7550               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7551               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7552               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7553               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7554               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7555               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7556               || hi16_reloc_p (reloc_type[0])
7557               || lo16_reloc_p (reloc_type[0])))
7558         ip->fixp[0]->fx_no_overflow = 1;
7559
7560       /* These relocations can have an addend that won't fit in 2 octets.  */
7561       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7562           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7563         ip->fixp[0]->fx_no_overflow = 1;
7564
7565       if (mips_relax.sequence)
7566         {
7567           if (mips_relax.first_fixup == 0)
7568             mips_relax.first_fixup = ip->fixp[0];
7569         }
7570       else if (reloc_needs_lo_p (*reloc_type))
7571         {
7572           struct mips_hi_fixup *hi_fixup;
7573
7574           /* Reuse the last entry if it already has a matching %lo.  */
7575           hi_fixup = mips_hi_fixup_list;
7576           if (hi_fixup == 0
7577               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7578             {
7579               hi_fixup = XNEW (struct mips_hi_fixup);
7580               hi_fixup->next = mips_hi_fixup_list;
7581               mips_hi_fixup_list = hi_fixup;
7582             }
7583           hi_fixup->fixp = ip->fixp[0];
7584           hi_fixup->seg = now_seg;
7585         }
7586
7587       /* Add fixups for the second and third relocations, if given.
7588          Note that the ABI allows the second relocation to be
7589          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7590          moment we only use RSS_UNDEF, but we could add support
7591          for the others if it ever becomes necessary.  */
7592       for (i = 1; i < 3; i++)
7593         if (reloc_type[i] != BFD_RELOC_UNUSED)
7594           {
7595             ip->fixp[i] = fix_new (ip->frag, ip->where,
7596                                    ip->fixp[0]->fx_size, NULL, 0,
7597                                    FALSE, final_type[i]);
7598
7599             /* Use fx_tcbit to mark compound relocs.  */
7600             ip->fixp[0]->fx_tcbit = 1;
7601             ip->fixp[i]->fx_tcbit = 1;
7602           }
7603     }
7604
7605   /* Update the register mask information.  */
7606   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7607   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7608
7609   switch (method)
7610     {
7611     case APPEND_ADD:
7612       insert_into_history (0, 1, ip);
7613       break;
7614
7615     case APPEND_ADD_WITH_NOP:
7616       {
7617         struct mips_cl_insn *nop;
7618
7619         insert_into_history (0, 1, ip);
7620         nop = get_delay_slot_nop (ip);
7621         add_fixed_insn (nop);
7622         insert_into_history (0, 1, nop);
7623         if (mips_relax.sequence)
7624           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7625       }
7626       break;
7627
7628     case APPEND_ADD_COMPACT:
7629       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7630       if (mips_opts.mips16)
7631         {
7632           ip->insn_opcode |= 0x0080;
7633           find_altered_mips16_opcode (ip);
7634         }
7635       /* Convert microMIPS instructions.  */
7636       else if (mips_opts.micromips)
7637         {
7638           /* jr16->jrc */
7639           if ((ip->insn_opcode & 0xffe0) == 0x4580)
7640             ip->insn_opcode |= 0x0020;
7641           /* b16->bc */
7642           else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
7643             ip->insn_opcode = 0x40e00000;
7644           /* beqz16->beqzc, bnez16->bnezc */
7645           else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
7646             {
7647               unsigned long regno;
7648
7649               regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
7650               regno &= MICROMIPSOP_MASK_MD;
7651               regno = micromips_to_32_reg_d_map[regno];
7652               ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
7653                                  | (regno << MICROMIPSOP_SH_RS)
7654                                  | 0x40a00000) ^ 0x00400000;
7655             }
7656           /* beqz->beqzc, bnez->bnezc */
7657           else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
7658             ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
7659                                | ((ip->insn_opcode >> 7) & 0x00400000)
7660                                | 0x40a00000) ^ 0x00400000;
7661           /* beq $0->beqzc, bne $0->bnezc */
7662           else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
7663             ip->insn_opcode = (((ip->insn_opcode >>
7664                                  (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
7665                                 & (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
7666                                | ((ip->insn_opcode >> 7) & 0x00400000)
7667                                | 0x40a00000) ^ 0x00400000;
7668           else
7669             abort ();
7670           find_altered_micromips_opcode (ip);
7671         }
7672       else
7673         abort ();
7674       install_insn (ip);
7675       insert_into_history (0, 1, ip);
7676       break;
7677
7678     case APPEND_SWAP:
7679       {
7680         struct mips_cl_insn delay = history[0];
7681
7682         if (relaxed_branch || delay.frag != ip->frag)
7683           {
7684             /* Add the delay slot instruction to the end of the
7685                current frag and shrink the fixed part of the
7686                original frag.  If the branch occupies the tail of
7687                the latter, move it backwards to cover the gap.  */
7688             delay.frag->fr_fix -= branch_disp;
7689             if (delay.frag == ip->frag)
7690               move_insn (ip, ip->frag, ip->where - branch_disp);
7691             add_fixed_insn (&delay);
7692           }
7693         else
7694           {
7695             /* If this is not a relaxed branch and we are in the
7696                same frag, then just swap the instructions.  */
7697             move_insn (ip, delay.frag, delay.where);
7698             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7699           }
7700         history[0] = *ip;
7701         delay.fixed_p = 1;
7702         insert_into_history (0, 1, &delay);
7703       }
7704       break;
7705     }
7706
7707   /* If we have just completed an unconditional branch, clear the history.  */
7708   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7709       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7710     {
7711       unsigned int i;
7712
7713       mips_no_prev_insn ();
7714
7715       for (i = 0; i < ARRAY_SIZE (history); i++)
7716         history[i].cleared_p = 1;
7717     }
7718
7719   /* We need to emit a label at the end of branch-likely macros.  */
7720   if (emit_branch_likely_macro)
7721     {
7722       emit_branch_likely_macro = FALSE;
7723       micromips_add_label ();
7724     }
7725
7726   /* We just output an insn, so the next one doesn't have a label.  */
7727   mips_clear_insn_labels ();
7728 }
7729
7730 /* Forget that there was any previous instruction or label.
7731    When BRANCH is true, the branch history is also flushed.  */
7732
7733 static void
7734 mips_no_prev_insn (void)
7735 {
7736   prev_nop_frag = NULL;
7737   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7738   mips_clear_insn_labels ();
7739 }
7740
7741 /* This function must be called before we emit something other than
7742    instructions.  It is like mips_no_prev_insn except that it inserts
7743    any NOPS that might be needed by previous instructions.  */
7744
7745 void
7746 mips_emit_delays (void)
7747 {
7748   if (! mips_opts.noreorder)
7749     {
7750       int nops = nops_for_insn (0, history, NULL);
7751       if (nops > 0)
7752         {
7753           while (nops-- > 0)
7754             add_fixed_insn (NOP_INSN);
7755           mips_move_text_labels ();
7756         }
7757     }
7758   mips_no_prev_insn ();
7759 }
7760
7761 /* Start a (possibly nested) noreorder block.  */
7762
7763 static void
7764 start_noreorder (void)
7765 {
7766   if (mips_opts.noreorder == 0)
7767     {
7768       unsigned int i;
7769       int nops;
7770
7771       /* None of the instructions before the .set noreorder can be moved.  */
7772       for (i = 0; i < ARRAY_SIZE (history); i++)
7773         history[i].fixed_p = 1;
7774
7775       /* Insert any nops that might be needed between the .set noreorder
7776          block and the previous instructions.  We will later remove any
7777          nops that turn out not to be needed.  */
7778       nops = nops_for_insn (0, history, NULL);
7779       if (nops > 0)
7780         {
7781           if (mips_optimize != 0)
7782             {
7783               /* Record the frag which holds the nop instructions, so
7784                  that we can remove them if we don't need them.  */
7785               frag_grow (nops * NOP_INSN_SIZE);
7786               prev_nop_frag = frag_now;
7787               prev_nop_frag_holds = nops;
7788               prev_nop_frag_required = 0;
7789               prev_nop_frag_since = 0;
7790             }
7791
7792           for (; nops > 0; --nops)
7793             add_fixed_insn (NOP_INSN);
7794
7795           /* Move on to a new frag, so that it is safe to simply
7796              decrease the size of prev_nop_frag.  */
7797           frag_wane (frag_now);
7798           frag_new (0);
7799           mips_move_text_labels ();
7800         }
7801       mips_mark_labels ();
7802       mips_clear_insn_labels ();
7803     }
7804   mips_opts.noreorder++;
7805   mips_any_noreorder = 1;
7806 }
7807
7808 /* End a nested noreorder block.  */
7809
7810 static void
7811 end_noreorder (void)
7812 {
7813   mips_opts.noreorder--;
7814   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7815     {
7816       /* Commit to inserting prev_nop_frag_required nops and go back to
7817          handling nop insertion the .set reorder way.  */
7818       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7819                                 * NOP_INSN_SIZE);
7820       insert_into_history (prev_nop_frag_since,
7821                            prev_nop_frag_required, NOP_INSN);
7822       prev_nop_frag = NULL;
7823     }
7824 }
7825
7826 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7827    higher bits unset.  */
7828
7829 static void
7830 normalize_constant_expr (expressionS *ex)
7831 {
7832   if (ex->X_op == O_constant
7833       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7834     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7835                         - 0x80000000);
7836 }
7837
7838 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7839    all higher bits unset.  */
7840
7841 static void
7842 normalize_address_expr (expressionS *ex)
7843 {
7844   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7845         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7846       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7847     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7848                         - 0x80000000);
7849 }
7850
7851 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7852    Return true if the match was successful.
7853
7854    OPCODE_EXTRA is a value that should be ORed into the opcode
7855    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7856    there are more alternatives after OPCODE and SOFT_MATCH is
7857    as for mips_arg_info.  */
7858
7859 static bfd_boolean
7860 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7861             struct mips_operand_token *tokens, unsigned int opcode_extra,
7862             bfd_boolean lax_match, bfd_boolean complete_p)
7863 {
7864   const char *args;
7865   struct mips_arg_info arg;
7866   const struct mips_operand *operand;
7867   char c;
7868
7869   imm_expr.X_op = O_absent;
7870   offset_expr.X_op = O_absent;
7871   offset_reloc[0] = BFD_RELOC_UNUSED;
7872   offset_reloc[1] = BFD_RELOC_UNUSED;
7873   offset_reloc[2] = BFD_RELOC_UNUSED;
7874
7875   create_insn (insn, opcode);
7876   /* When no opcode suffix is specified, assume ".xyzw". */
7877   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7878     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7879   else
7880     insn->insn_opcode |= opcode_extra;
7881   memset (&arg, 0, sizeof (arg));
7882   arg.insn = insn;
7883   arg.token = tokens;
7884   arg.argnum = 1;
7885   arg.last_regno = ILLEGAL_REG;
7886   arg.dest_regno = ILLEGAL_REG;
7887   arg.lax_match = lax_match;
7888   for (args = opcode->args;; ++args)
7889     {
7890       if (arg.token->type == OT_END)
7891         {
7892           /* Handle unary instructions in which only one operand is given.
7893              The source is then the same as the destination.  */
7894           if (arg.opnum == 1 && *args == ',')
7895             {
7896               operand = (mips_opts.micromips
7897                          ? decode_micromips_operand (args + 1)
7898                          : decode_mips_operand (args + 1));
7899               if (operand && mips_optional_operand_p (operand))
7900                 {
7901                   arg.token = tokens;
7902                   arg.argnum = 1;
7903                   continue;
7904                 }
7905             }
7906
7907           /* Treat elided base registers as $0.  */
7908           if (strcmp (args, "(b)") == 0)
7909             args += 3;
7910
7911           if (args[0] == '+')
7912             switch (args[1])
7913               {
7914               case 'K':
7915               case 'N':
7916                 /* The register suffix is optional. */
7917                 args += 2;
7918                 break;
7919               }
7920
7921           /* Fail the match if there were too few operands.  */
7922           if (*args)
7923             return FALSE;
7924
7925           /* Successful match.  */
7926           if (!complete_p)
7927             return TRUE;
7928           clear_insn_error ();
7929           if (arg.dest_regno == arg.last_regno
7930               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7931             {
7932               if (arg.opnum == 2)
7933                 set_insn_error
7934                   (0, _("source and destination must be different"));
7935               else if (arg.last_regno == 31)
7936                 set_insn_error
7937                   (0, _("a destination register must be supplied"));
7938             }
7939           else if (arg.last_regno == 31
7940                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7941                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7942             set_insn_error (0, _("the source register must not be $31"));
7943           check_completed_insn (&arg);
7944           return TRUE;
7945         }
7946
7947       /* Fail the match if the line has too many operands.   */
7948       if (*args == 0)
7949         return FALSE;
7950
7951       /* Handle characters that need to match exactly.  */
7952       if (*args == '(' || *args == ')' || *args == ',')
7953         {
7954           if (match_char (&arg, *args))
7955             continue;
7956           return FALSE;
7957         }
7958       if (*args == '#')
7959         {
7960           ++args;
7961           if (arg.token->type == OT_DOUBLE_CHAR
7962               && arg.token->u.ch == *args)
7963             {
7964               ++arg.token;
7965               continue;
7966             }
7967           return FALSE;
7968         }
7969
7970       /* Handle special macro operands.  Work out the properties of
7971          other operands.  */
7972       arg.opnum += 1;
7973       switch (*args)
7974         {
7975         case '-':
7976           switch (args[1])
7977             {
7978             case 'A':
7979               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
7980               break;
7981
7982             case 'B':
7983               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
7984               break;
7985             }
7986           break;
7987
7988         case '+':
7989           switch (args[1])
7990             {
7991             case 'i':
7992               *offset_reloc = BFD_RELOC_MIPS_JMP;
7993               break;
7994
7995             case '\'':
7996               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
7997               break;
7998
7999             case '\"':
8000               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
8001               break;
8002             }
8003           break;
8004
8005         case 'I':
8006           if (!match_const_int (&arg, &imm_expr.X_add_number))
8007             return FALSE;
8008           imm_expr.X_op = O_constant;
8009           if (GPR_SIZE == 32)
8010             normalize_constant_expr (&imm_expr);
8011           continue;
8012
8013         case 'A':
8014           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8015             {
8016               /* Assume that the offset has been elided and that what
8017                  we saw was a base register.  The match will fail later
8018                  if that assumption turns out to be wrong.  */
8019               offset_expr.X_op = O_constant;
8020               offset_expr.X_add_number = 0;
8021             }
8022           else
8023             {
8024               if (!match_expression (&arg, &offset_expr, offset_reloc))
8025                 return FALSE;
8026               normalize_address_expr (&offset_expr);
8027             }
8028           continue;
8029
8030         case 'F':
8031           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8032                                      8, TRUE))
8033             return FALSE;
8034           continue;
8035
8036         case 'L':
8037           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8038                                      8, FALSE))
8039             return FALSE;
8040           continue;
8041
8042         case 'f':
8043           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8044                                      4, TRUE))
8045             return FALSE;
8046           continue;
8047
8048         case 'l':
8049           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8050                                      4, FALSE))
8051             return FALSE;
8052           continue;
8053
8054         case 'p':
8055           *offset_reloc = BFD_RELOC_16_PCREL_S2;
8056           break;
8057
8058         case 'a':
8059           *offset_reloc = BFD_RELOC_MIPS_JMP;
8060           break;
8061
8062         case 'm':
8063           gas_assert (mips_opts.micromips);
8064           c = args[1];
8065           switch (c)
8066             {
8067             case 'D':
8068             case 'E':
8069               if (!forced_insn_length)
8070                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
8071               else if (c == 'D')
8072                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8073               else
8074                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8075               break;
8076             }
8077           break;
8078         }
8079
8080       operand = (mips_opts.micromips
8081                  ? decode_micromips_operand (args)
8082                  : decode_mips_operand (args));
8083       if (!operand)
8084         abort ();
8085
8086       /* Skip prefixes.  */
8087       if (*args == '+' || *args == 'm' || *args == '-')
8088         args++;
8089
8090       if (mips_optional_operand_p (operand)
8091           && args[1] == ','
8092           && (arg.token[0].type != OT_REG
8093               || arg.token[1].type == OT_END))
8094         {
8095           /* Assume that the register has been elided and is the
8096              same as the first operand.  */
8097           arg.token = tokens;
8098           arg.argnum = 1;
8099         }
8100
8101       if (!match_operand (&arg, operand))
8102         return FALSE;
8103     }
8104 }
8105
8106 /* Like match_insn, but for MIPS16.  */
8107
8108 static bfd_boolean
8109 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8110                    struct mips_operand_token *tokens)
8111 {
8112   const char *args;
8113   const struct mips_operand *operand;
8114   const struct mips_operand *ext_operand;
8115   bfd_boolean pcrel = FALSE;
8116   int required_insn_length;
8117   struct mips_arg_info arg;
8118   int relax_char;
8119
8120   if (forced_insn_length)
8121     required_insn_length = forced_insn_length;
8122   else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8123     required_insn_length = 2;
8124   else
8125     required_insn_length = 0;
8126
8127   create_insn (insn, opcode);
8128   imm_expr.X_op = O_absent;
8129   offset_expr.X_op = O_absent;
8130   offset_reloc[0] = BFD_RELOC_UNUSED;
8131   offset_reloc[1] = BFD_RELOC_UNUSED;
8132   offset_reloc[2] = BFD_RELOC_UNUSED;
8133   relax_char = 0;
8134
8135   memset (&arg, 0, sizeof (arg));
8136   arg.insn = insn;
8137   arg.token = tokens;
8138   arg.argnum = 1;
8139   arg.last_regno = ILLEGAL_REG;
8140   arg.dest_regno = ILLEGAL_REG;
8141   relax_char = 0;
8142   for (args = opcode->args;; ++args)
8143     {
8144       int c;
8145
8146       if (arg.token->type == OT_END)
8147         {
8148           offsetT value;
8149
8150           /* Handle unary instructions in which only one operand is given.
8151              The source is then the same as the destination.  */
8152           if (arg.opnum == 1 && *args == ',')
8153             {
8154               operand = decode_mips16_operand (args[1], FALSE);
8155               if (operand && mips_optional_operand_p (operand))
8156                 {
8157                   arg.token = tokens;
8158                   arg.argnum = 1;
8159                   continue;
8160                 }
8161             }
8162
8163           /* Fail the match if there were too few operands.  */
8164           if (*args)
8165             return FALSE;
8166
8167           /* Successful match.  Stuff the immediate value in now, if
8168              we can.  */
8169           clear_insn_error ();
8170           if (opcode->pinfo == INSN_MACRO)
8171             {
8172               gas_assert (relax_char == 0 || relax_char == 'p');
8173               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8174             }
8175           else if (relax_char
8176                    && offset_expr.X_op == O_constant
8177                    && !pcrel
8178                    && calculate_reloc (*offset_reloc,
8179                                        offset_expr.X_add_number,
8180                                        &value))
8181             {
8182               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8183                             required_insn_length, &insn->insn_opcode);
8184               offset_expr.X_op = O_absent;
8185               *offset_reloc = BFD_RELOC_UNUSED;
8186             }
8187           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8188             {
8189               if (required_insn_length == 2)
8190                 set_insn_error (0, _("invalid unextended operand value"));
8191               else
8192                 {
8193                   forced_insn_length = 4;
8194                   insn->insn_opcode |= MIPS16_EXTEND;
8195                 }
8196             }
8197           else if (relax_char)
8198             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8199
8200           check_completed_insn (&arg);
8201           return TRUE;
8202         }
8203
8204       /* Fail the match if the line has too many operands.   */
8205       if (*args == 0)
8206         return FALSE;
8207
8208       /* Handle characters that need to match exactly.  */
8209       if (*args == '(' || *args == ')' || *args == ',')
8210         {
8211           if (match_char (&arg, *args))
8212             continue;
8213           return FALSE;
8214         }
8215
8216       arg.opnum += 1;
8217       c = *args;
8218       switch (c)
8219         {
8220         case 'p':
8221         case 'q':
8222         case 'A':
8223         case 'B':
8224         case 'E':
8225           relax_char = c;
8226           break;
8227
8228         case 'I':
8229           if (!match_const_int (&arg, &imm_expr.X_add_number))
8230             return FALSE;
8231           imm_expr.X_op = O_constant;
8232           if (GPR_SIZE == 32)
8233             normalize_constant_expr (&imm_expr);
8234           continue;
8235
8236         case 'a':
8237         case 'i':
8238           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8239           break;
8240         }
8241
8242       operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8243       if (!operand)
8244         abort ();
8245
8246       if (operand->type == OP_PCREL)
8247         pcrel = TRUE;
8248       else
8249         {
8250           ext_operand = decode_mips16_operand (c, TRUE);
8251           if (operand != ext_operand)
8252             {
8253               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8254                 {
8255                   offset_expr.X_op = O_constant;
8256                   offset_expr.X_add_number = 0;
8257                   relax_char = c;
8258                   continue;
8259                 }
8260
8261               if (!match_expression (&arg, &offset_expr, offset_reloc))
8262                 return FALSE;
8263
8264               /* '8' is used for SLTI(U) and has traditionally not
8265                  been allowed to take relocation operators.  */
8266               if (offset_reloc[0] != BFD_RELOC_UNUSED
8267                   && (ext_operand->size != 16 || c == '8'))
8268                 {
8269                   match_not_constant (&arg);
8270                   return FALSE;
8271                 }
8272
8273               if (offset_expr.X_op == O_big)
8274                 {
8275                   match_out_of_range (&arg);
8276                   return FALSE;
8277                 }
8278
8279               relax_char = c;
8280               continue;
8281             }
8282         }
8283
8284       if (mips_optional_operand_p (operand)
8285           && args[1] == ','
8286           && (arg.token[0].type != OT_REG
8287               || arg.token[1].type == OT_END))
8288         {
8289           /* Assume that the register has been elided and is the
8290              same as the first operand.  */
8291           arg.token = tokens;
8292           arg.argnum = 1;
8293         }
8294
8295       if (!match_operand (&arg, operand))
8296         return FALSE;
8297     }
8298 }
8299
8300 /* Record that the current instruction is invalid for the current ISA.  */
8301
8302 static void
8303 match_invalid_for_isa (void)
8304 {
8305   set_insn_error_ss
8306     (0, _("opcode not supported on this processor: %s (%s)"),
8307      mips_cpu_info_from_arch (mips_opts.arch)->name,
8308      mips_cpu_info_from_isa (mips_opts.isa)->name);
8309 }
8310
8311 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8312    Return true if a definite match or failure was found, storing any match
8313    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8314    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8315    tried and failed to match under normal conditions and now want to try a
8316    more relaxed match.  */
8317
8318 static bfd_boolean
8319 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8320              const struct mips_opcode *past, struct mips_operand_token *tokens,
8321              int opcode_extra, bfd_boolean lax_match)
8322 {
8323   const struct mips_opcode *opcode;
8324   const struct mips_opcode *invalid_delay_slot;
8325   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8326
8327   /* Search for a match, ignoring alternatives that don't satisfy the
8328      current ISA or forced_length.  */
8329   invalid_delay_slot = 0;
8330   seen_valid_for_isa = FALSE;
8331   seen_valid_for_size = FALSE;
8332   opcode = first;
8333   do
8334     {
8335       gas_assert (strcmp (opcode->name, first->name) == 0);
8336       if (is_opcode_valid (opcode))
8337         {
8338           seen_valid_for_isa = TRUE;
8339           if (is_size_valid (opcode))
8340             {
8341               bfd_boolean delay_slot_ok;
8342
8343               seen_valid_for_size = TRUE;
8344               delay_slot_ok = is_delay_slot_valid (opcode);
8345               if (match_insn (insn, opcode, tokens, opcode_extra,
8346                               lax_match, delay_slot_ok))
8347                 {
8348                   if (!delay_slot_ok)
8349                     {
8350                       if (!invalid_delay_slot)
8351                         invalid_delay_slot = opcode;
8352                     }
8353                   else
8354                     return TRUE;
8355                 }
8356             }
8357         }
8358       ++opcode;
8359     }
8360   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8361
8362   /* If the only matches we found had the wrong length for the delay slot,
8363      pick the first such match.  We'll issue an appropriate warning later.  */
8364   if (invalid_delay_slot)
8365     {
8366       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8367                       lax_match, TRUE))
8368         return TRUE;
8369       abort ();
8370     }
8371
8372   /* Handle the case where we didn't try to match an instruction because
8373      all the alternatives were incompatible with the current ISA.  */
8374   if (!seen_valid_for_isa)
8375     {
8376       match_invalid_for_isa ();
8377       return TRUE;
8378     }
8379
8380   /* Handle the case where we didn't try to match an instruction because
8381      all the alternatives were of the wrong size.  */
8382   if (!seen_valid_for_size)
8383     {
8384       if (mips_opts.insn32)
8385         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8386       else
8387         set_insn_error_i
8388           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8389            8 * forced_insn_length);
8390       return TRUE;
8391     }
8392
8393   return FALSE;
8394 }
8395
8396 /* Like match_insns, but for MIPS16.  */
8397
8398 static bfd_boolean
8399 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8400                     struct mips_operand_token *tokens)
8401 {
8402   const struct mips_opcode *opcode;
8403   bfd_boolean seen_valid_for_isa;
8404   bfd_boolean seen_valid_for_size;
8405
8406   /* Search for a match, ignoring alternatives that don't satisfy the
8407      current ISA.  There are no separate entries for extended forms so
8408      we deal with forced_length later.  */
8409   seen_valid_for_isa = FALSE;
8410   seen_valid_for_size = FALSE;
8411   opcode = first;
8412   do
8413     {
8414       gas_assert (strcmp (opcode->name, first->name) == 0);
8415       if (is_opcode_valid_16 (opcode))
8416         {
8417           seen_valid_for_isa = TRUE;
8418           if (is_size_valid_16 (opcode))
8419             {
8420               seen_valid_for_size = TRUE;
8421               if (match_mips16_insn (insn, opcode, tokens))
8422                 return TRUE;
8423             }
8424         }
8425       ++opcode;
8426     }
8427   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8428          && strcmp (opcode->name, first->name) == 0);
8429
8430   /* Handle the case where we didn't try to match an instruction because
8431      all the alternatives were incompatible with the current ISA.  */
8432   if (!seen_valid_for_isa)
8433     {
8434       match_invalid_for_isa ();
8435       return TRUE;
8436     }
8437
8438   /* Handle the case where we didn't try to match an instruction because
8439      all the alternatives were of the wrong size.  */
8440   if (!seen_valid_for_size)
8441     {
8442       if (forced_insn_length == 2)
8443         set_insn_error
8444           (0, _("unrecognized unextended version of MIPS16 opcode"));
8445       else
8446         set_insn_error
8447           (0, _("unrecognized extended version of MIPS16 opcode"));
8448       return TRUE;
8449     }
8450
8451   return FALSE;
8452 }
8453
8454 /* Set up global variables for the start of a new macro.  */
8455
8456 static void
8457 macro_start (void)
8458 {
8459   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8460   memset (&mips_macro_warning.first_insn_sizes, 0,
8461           sizeof (mips_macro_warning.first_insn_sizes));
8462   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8463   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8464                                      && delayed_branch_p (&history[0]));
8465   if (history[0].frag
8466       && history[0].frag->fr_type == rs_machine_dependent
8467       && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8468       && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8469     mips_macro_warning.delay_slot_length = 0;
8470   else
8471     switch (history[0].insn_mo->pinfo2
8472             & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8473       {
8474       case INSN2_BRANCH_DELAY_32BIT:
8475         mips_macro_warning.delay_slot_length = 4;
8476         break;
8477       case INSN2_BRANCH_DELAY_16BIT:
8478         mips_macro_warning.delay_slot_length = 2;
8479         break;
8480       default:
8481         mips_macro_warning.delay_slot_length = 0;
8482         break;
8483       }
8484   mips_macro_warning.first_frag = NULL;
8485 }
8486
8487 /* Given that a macro is longer than one instruction or of the wrong size,
8488    return the appropriate warning for it.  Return null if no warning is
8489    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8490    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8491    and RELAX_NOMACRO.  */
8492
8493 static const char *
8494 macro_warning (relax_substateT subtype)
8495 {
8496   if (subtype & RELAX_DELAY_SLOT)
8497     return _("macro instruction expanded into multiple instructions"
8498              " in a branch delay slot");
8499   else if (subtype & RELAX_NOMACRO)
8500     return _("macro instruction expanded into multiple instructions");
8501   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8502                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8503     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8504             ? _("macro instruction expanded into a wrong size instruction"
8505                 " in a 16-bit branch delay slot")
8506             : _("macro instruction expanded into a wrong size instruction"
8507                 " in a 32-bit branch delay slot"));
8508   else
8509     return 0;
8510 }
8511
8512 /* Finish up a macro.  Emit warnings as appropriate.  */
8513
8514 static void
8515 macro_end (void)
8516 {
8517   /* Relaxation warning flags.  */
8518   relax_substateT subtype = 0;
8519
8520   /* Check delay slot size requirements.  */
8521   if (mips_macro_warning.delay_slot_length == 2)
8522     subtype |= RELAX_DELAY_SLOT_16BIT;
8523   if (mips_macro_warning.delay_slot_length != 0)
8524     {
8525       if (mips_macro_warning.delay_slot_length
8526           != mips_macro_warning.first_insn_sizes[0])
8527         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8528       if (mips_macro_warning.delay_slot_length
8529           != mips_macro_warning.first_insn_sizes[1])
8530         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8531     }
8532
8533   /* Check instruction count requirements.  */
8534   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8535     {
8536       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8537         subtype |= RELAX_SECOND_LONGER;
8538       if (mips_opts.warn_about_macros)
8539         subtype |= RELAX_NOMACRO;
8540       if (mips_macro_warning.delay_slot_p)
8541         subtype |= RELAX_DELAY_SLOT;
8542     }
8543
8544   /* If both alternatives fail to fill a delay slot correctly,
8545      emit the warning now.  */
8546   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8547       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8548     {
8549       relax_substateT s;
8550       const char *msg;
8551
8552       s = subtype & (RELAX_DELAY_SLOT_16BIT
8553                      | RELAX_DELAY_SLOT_SIZE_FIRST
8554                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8555       msg = macro_warning (s);
8556       if (msg != NULL)
8557         as_warn ("%s", msg);
8558       subtype &= ~s;
8559     }
8560
8561   /* If both implementations are longer than 1 instruction, then emit the
8562      warning now.  */
8563   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8564     {
8565       relax_substateT s;
8566       const char *msg;
8567
8568       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8569       msg = macro_warning (s);
8570       if (msg != NULL)
8571         as_warn ("%s", msg);
8572       subtype &= ~s;
8573     }
8574
8575   /* If any flags still set, then one implementation might need a warning
8576      and the other either will need one of a different kind or none at all.
8577      Pass any remaining flags over to relaxation.  */
8578   if (mips_macro_warning.first_frag != NULL)
8579     mips_macro_warning.first_frag->fr_subtype |= subtype;
8580 }
8581
8582 /* Instruction operand formats used in macros that vary between
8583    standard MIPS and microMIPS code.  */
8584
8585 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8586 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8587 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8588 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8589 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8590 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8591 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8592 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8593
8594 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8595 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8596                                              : cop12_fmt[mips_opts.micromips])
8597 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8598 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8599 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8600 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8601                                              : mem12_fmt[mips_opts.micromips])
8602 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8603 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8604 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8605
8606 /* Read a macro's relocation codes from *ARGS and store them in *R.
8607    The first argument in *ARGS will be either the code for a single
8608    relocation or -1 followed by the three codes that make up a
8609    composite relocation.  */
8610
8611 static void
8612 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8613 {
8614   int i, next;
8615
8616   next = va_arg (*args, int);
8617   if (next >= 0)
8618     r[0] = (bfd_reloc_code_real_type) next;
8619   else
8620     {
8621       for (i = 0; i < 3; i++)
8622         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8623       /* This function is only used for 16-bit relocation fields.
8624          To make the macro code simpler, treat an unrelocated value
8625          in the same way as BFD_RELOC_LO16.  */
8626       if (r[0] == BFD_RELOC_UNUSED)
8627         r[0] = BFD_RELOC_LO16;
8628     }
8629 }
8630
8631 /* Build an instruction created by a macro expansion.  This is passed
8632    a pointer to the count of instructions created so far, an
8633    expression, the name of the instruction to build, an operand format
8634    string, and corresponding arguments.  */
8635
8636 static void
8637 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8638 {
8639   const struct mips_opcode *mo = NULL;
8640   bfd_reloc_code_real_type r[3];
8641   const struct mips_opcode *amo;
8642   const struct mips_operand *operand;
8643   struct hash_control *hash;
8644   struct mips_cl_insn insn;
8645   va_list args;
8646   unsigned int uval;
8647
8648   va_start (args, fmt);
8649
8650   if (mips_opts.mips16)
8651     {
8652       mips16_macro_build (ep, name, fmt, &args);
8653       va_end (args);
8654       return;
8655     }
8656
8657   r[0] = BFD_RELOC_UNUSED;
8658   r[1] = BFD_RELOC_UNUSED;
8659   r[2] = BFD_RELOC_UNUSED;
8660   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8661   amo = (struct mips_opcode *) hash_find (hash, name);
8662   gas_assert (amo);
8663   gas_assert (strcmp (name, amo->name) == 0);
8664
8665   do
8666     {
8667       /* Search until we get a match for NAME.  It is assumed here that
8668          macros will never generate MDMX, MIPS-3D, or MT instructions.
8669          We try to match an instruction that fulfills the branch delay
8670          slot instruction length requirement (if any) of the previous
8671          instruction.  While doing this we record the first instruction
8672          seen that matches all the other conditions and use it anyway
8673          if the requirement cannot be met; we will issue an appropriate
8674          warning later on.  */
8675       if (strcmp (fmt, amo->args) == 0
8676           && amo->pinfo != INSN_MACRO
8677           && is_opcode_valid (amo)
8678           && is_size_valid (amo))
8679         {
8680           if (is_delay_slot_valid (amo))
8681             {
8682               mo = amo;
8683               break;
8684             }
8685           else if (!mo)
8686             mo = amo;
8687         }
8688
8689       ++amo;
8690       gas_assert (amo->name);
8691     }
8692   while (strcmp (name, amo->name) == 0);
8693
8694   gas_assert (mo);
8695   create_insn (&insn, mo);
8696   for (; *fmt; ++fmt)
8697     {
8698       switch (*fmt)
8699         {
8700         case ',':
8701         case '(':
8702         case ')':
8703         case 'z':
8704           break;
8705
8706         case 'i':
8707         case 'j':
8708           macro_read_relocs (&args, r);
8709           gas_assert (*r == BFD_RELOC_GPREL16
8710                       || *r == BFD_RELOC_MIPS_HIGHER
8711                       || *r == BFD_RELOC_HI16_S
8712                       || *r == BFD_RELOC_LO16
8713                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8714           break;
8715
8716         case 'o':
8717           macro_read_relocs (&args, r);
8718           break;
8719
8720         case 'u':
8721           macro_read_relocs (&args, r);
8722           gas_assert (ep != NULL
8723                       && (ep->X_op == O_constant
8724                           || (ep->X_op == O_symbol
8725                               && (*r == BFD_RELOC_MIPS_HIGHEST
8726                                   || *r == BFD_RELOC_HI16_S
8727                                   || *r == BFD_RELOC_HI16
8728                                   || *r == BFD_RELOC_GPREL16
8729                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8730                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8731           break;
8732
8733         case 'p':
8734           gas_assert (ep != NULL);
8735
8736           /*
8737            * This allows macro() to pass an immediate expression for
8738            * creating short branches without creating a symbol.
8739            *
8740            * We don't allow branch relaxation for these branches, as
8741            * they should only appear in ".set nomacro" anyway.
8742            */
8743           if (ep->X_op == O_constant)
8744             {
8745               /* For microMIPS we always use relocations for branches.
8746                  So we should not resolve immediate values.  */
8747               gas_assert (!mips_opts.micromips);
8748
8749               if ((ep->X_add_number & 3) != 0)
8750                 as_bad (_("branch to misaligned address (0x%lx)"),
8751                         (unsigned long) ep->X_add_number);
8752               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8753                 as_bad (_("branch address range overflow (0x%lx)"),
8754                         (unsigned long) ep->X_add_number);
8755               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8756               ep = NULL;
8757             }
8758           else
8759             *r = BFD_RELOC_16_PCREL_S2;
8760           break;
8761
8762         case 'a':
8763           gas_assert (ep != NULL);
8764           *r = BFD_RELOC_MIPS_JMP;
8765           break;
8766
8767         default:
8768           operand = (mips_opts.micromips
8769                      ? decode_micromips_operand (fmt)
8770                      : decode_mips_operand (fmt));
8771           if (!operand)
8772             abort ();
8773
8774           uval = va_arg (args, int);
8775           if (operand->type == OP_CLO_CLZ_DEST)
8776             uval |= (uval << 5);
8777           insn_insert_operand (&insn, operand, uval);
8778
8779           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8780             ++fmt;
8781           break;
8782         }
8783     }
8784   va_end (args);
8785   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8786
8787   append_insn (&insn, ep, r, TRUE);
8788 }
8789
8790 static void
8791 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8792                     va_list *args)
8793 {
8794   struct mips_opcode *mo;
8795   struct mips_cl_insn insn;
8796   const struct mips_operand *operand;
8797   bfd_reloc_code_real_type r[3]
8798     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8799
8800   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8801   gas_assert (mo);
8802   gas_assert (strcmp (name, mo->name) == 0);
8803
8804   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8805     {
8806       ++mo;
8807       gas_assert (mo->name);
8808       gas_assert (strcmp (name, mo->name) == 0);
8809     }
8810
8811   create_insn (&insn, mo);
8812   for (; *fmt; ++fmt)
8813     {
8814       int c;
8815
8816       c = *fmt;
8817       switch (c)
8818         {
8819         case ',':
8820         case '(':
8821         case ')':
8822           break;
8823
8824         case '.':
8825         case 'S':
8826         case 'P':
8827         case 'R':
8828           break;
8829
8830         case '<':
8831         case '5':
8832         case 'F':
8833         case 'H':
8834         case 'W':
8835         case 'D':
8836         case 'j':
8837         case '8':
8838         case 'V':
8839         case 'C':
8840         case 'U':
8841         case 'k':
8842         case 'K':
8843         case 'p':
8844         case 'q':
8845           {
8846             offsetT value;
8847
8848             gas_assert (ep != NULL);
8849
8850             if (ep->X_op != O_constant)
8851               *r = (int) BFD_RELOC_UNUSED + c;
8852             else if (calculate_reloc (*r, ep->X_add_number, &value))
8853               {
8854                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8855                 ep = NULL;
8856                 *r = BFD_RELOC_UNUSED;
8857               }
8858           }
8859           break;
8860
8861         default:
8862           operand = decode_mips16_operand (c, FALSE);
8863           if (!operand)
8864             abort ();
8865
8866           insn_insert_operand (&insn, operand, va_arg (*args, int));
8867           break;
8868         }
8869     }
8870
8871   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8872
8873   append_insn (&insn, ep, r, TRUE);
8874 }
8875
8876 /*
8877  * Generate a "jalr" instruction with a relocation hint to the called
8878  * function.  This occurs in NewABI PIC code.
8879  */
8880 static void
8881 macro_build_jalr (expressionS *ep, int cprestore)
8882 {
8883   static const bfd_reloc_code_real_type jalr_relocs[2]
8884     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8885   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8886   const char *jalr;
8887   char *f = NULL;
8888
8889   if (MIPS_JALR_HINT_P (ep))
8890     {
8891       frag_grow (8);
8892       f = frag_more (0);
8893     }
8894   if (mips_opts.micromips)
8895     {
8896       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8897               ? "jalr" : "jalrs");
8898       if (MIPS_JALR_HINT_P (ep)
8899           || mips_opts.insn32
8900           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8901         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8902       else
8903         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8904     }
8905   else
8906     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8907   if (MIPS_JALR_HINT_P (ep))
8908     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8909 }
8910
8911 /*
8912  * Generate a "lui" instruction.
8913  */
8914 static void
8915 macro_build_lui (expressionS *ep, int regnum)
8916 {
8917   gas_assert (! mips_opts.mips16);
8918
8919   if (ep->X_op != O_constant)
8920     {
8921       gas_assert (ep->X_op == O_symbol);
8922       /* _gp_disp is a special case, used from s_cpload.
8923          __gnu_local_gp is used if mips_no_shared.  */
8924       gas_assert (mips_pic == NO_PIC
8925               || (! HAVE_NEWABI
8926                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8927               || (! mips_in_shared
8928                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8929                              "__gnu_local_gp") == 0));
8930     }
8931
8932   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8933 }
8934
8935 /* Generate a sequence of instructions to do a load or store from a constant
8936    offset off of a base register (breg) into/from a target register (treg),
8937    using AT if necessary.  */
8938 static void
8939 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8940                               int treg, int breg, int dbl)
8941 {
8942   gas_assert (ep->X_op == O_constant);
8943
8944   /* Sign-extending 32-bit constants makes their handling easier.  */
8945   if (!dbl)
8946     normalize_constant_expr (ep);
8947
8948   /* Right now, this routine can only handle signed 32-bit constants.  */
8949   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8950     as_warn (_("operand overflow"));
8951
8952   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8953     {
8954       /* Signed 16-bit offset will fit in the op.  Easy!  */
8955       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8956     }
8957   else
8958     {
8959       /* 32-bit offset, need multiple instructions and AT, like:
8960            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8961            addu     $tempreg,$tempreg,$breg
8962            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8963          to handle the complete offset.  */
8964       macro_build_lui (ep, AT);
8965       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8966       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8967
8968       if (!mips_opts.at)
8969         as_bad (_("macro used $at after \".set noat\""));
8970     }
8971 }
8972
8973 /*                      set_at()
8974  * Generates code to set the $at register to true (one)
8975  * if reg is less than the immediate expression.
8976  */
8977 static void
8978 set_at (int reg, int unsignedp)
8979 {
8980   if (imm_expr.X_add_number >= -0x8000
8981       && imm_expr.X_add_number < 0x8000)
8982     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8983                  AT, reg, BFD_RELOC_LO16);
8984   else
8985     {
8986       load_register (AT, &imm_expr, GPR_SIZE == 64);
8987       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8988     }
8989 }
8990
8991 /* Count the leading zeroes by performing a binary chop. This is a
8992    bulky bit of source, but performance is a LOT better for the
8993    majority of values than a simple loop to count the bits:
8994        for (lcnt = 0; (lcnt < 32); lcnt++)
8995          if ((v) & (1 << (31 - lcnt)))
8996            break;
8997   However it is not code size friendly, and the gain will drop a bit
8998   on certain cached systems.
8999 */
9000 #define COUNT_TOP_ZEROES(v)             \
9001   (((v) & ~0xffff) == 0                 \
9002    ? ((v) & ~0xff) == 0                 \
9003      ? ((v) & ~0xf) == 0                \
9004        ? ((v) & ~0x3) == 0              \
9005          ? ((v) & ~0x1) == 0            \
9006            ? !(v)                       \
9007              ? 32                       \
9008              : 31                       \
9009            : 30                         \
9010          : ((v) & ~0x7) == 0            \
9011            ? 29                         \
9012            : 28                         \
9013        : ((v) & ~0x3f) == 0             \
9014          ? ((v) & ~0x1f) == 0           \
9015            ? 27                         \
9016            : 26                         \
9017          : ((v) & ~0x7f) == 0           \
9018            ? 25                         \
9019            : 24                         \
9020      : ((v) & ~0xfff) == 0              \
9021        ? ((v) & ~0x3ff) == 0            \
9022          ? ((v) & ~0x1ff) == 0          \
9023            ? 23                         \
9024            : 22                         \
9025          : ((v) & ~0x7ff) == 0          \
9026            ? 21                         \
9027            : 20                         \
9028        : ((v) & ~0x3fff) == 0           \
9029          ? ((v) & ~0x1fff) == 0         \
9030            ? 19                         \
9031            : 18                         \
9032          : ((v) & ~0x7fff) == 0         \
9033            ? 17                         \
9034            : 16                         \
9035    : ((v) & ~0xffffff) == 0             \
9036      ? ((v) & ~0xfffff) == 0            \
9037        ? ((v) & ~0x3ffff) == 0          \
9038          ? ((v) & ~0x1ffff) == 0        \
9039            ? 15                         \
9040            : 14                         \
9041          : ((v) & ~0x7ffff) == 0        \
9042            ? 13                         \
9043            : 12                         \
9044        : ((v) & ~0x3fffff) == 0         \
9045          ? ((v) & ~0x1fffff) == 0       \
9046            ? 11                         \
9047            : 10                         \
9048          : ((v) & ~0x7fffff) == 0       \
9049            ? 9                          \
9050            : 8                          \
9051      : ((v) & ~0xfffffff) == 0          \
9052        ? ((v) & ~0x3ffffff) == 0        \
9053          ? ((v) & ~0x1ffffff) == 0      \
9054            ? 7                          \
9055            : 6                          \
9056          : ((v) & ~0x7ffffff) == 0      \
9057            ? 5                          \
9058            : 4                          \
9059        : ((v) & ~0x3fffffff) == 0       \
9060          ? ((v) & ~0x1fffffff) == 0     \
9061            ? 3                          \
9062            : 2                          \
9063          : ((v) & ~0x7fffffff) == 0     \
9064            ? 1                          \
9065            : 0)
9066
9067 /*                      load_register()
9068  *  This routine generates the least number of instructions necessary to load
9069  *  an absolute expression value into a register.
9070  */
9071 static void
9072 load_register (int reg, expressionS *ep, int dbl)
9073 {
9074   int freg;
9075   expressionS hi32, lo32;
9076
9077   if (ep->X_op != O_big)
9078     {
9079       gas_assert (ep->X_op == O_constant);
9080
9081       /* Sign-extending 32-bit constants makes their handling easier.  */
9082       if (!dbl)
9083         normalize_constant_expr (ep);
9084
9085       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9086         {
9087           /* We can handle 16 bit signed values with an addiu to
9088              $zero.  No need to ever use daddiu here, since $zero and
9089              the result are always correct in 32 bit mode.  */
9090           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9091           return;
9092         }
9093       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9094         {
9095           /* We can handle 16 bit unsigned values with an ori to
9096              $zero.  */
9097           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9098           return;
9099         }
9100       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9101         {
9102           /* 32 bit values require an lui.  */
9103           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9104           if ((ep->X_add_number & 0xffff) != 0)
9105             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9106           return;
9107         }
9108     }
9109
9110   /* The value is larger than 32 bits.  */
9111
9112   if (!dbl || GPR_SIZE == 32)
9113     {
9114       char value[32];
9115
9116       sprintf_vma (value, ep->X_add_number);
9117       as_bad (_("number (0x%s) larger than 32 bits"), value);
9118       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9119       return;
9120     }
9121
9122   if (ep->X_op != O_big)
9123     {
9124       hi32 = *ep;
9125       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9126       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9127       hi32.X_add_number &= 0xffffffff;
9128       lo32 = *ep;
9129       lo32.X_add_number &= 0xffffffff;
9130     }
9131   else
9132     {
9133       gas_assert (ep->X_add_number > 2);
9134       if (ep->X_add_number == 3)
9135         generic_bignum[3] = 0;
9136       else if (ep->X_add_number > 4)
9137         as_bad (_("number larger than 64 bits"));
9138       lo32.X_op = O_constant;
9139       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9140       hi32.X_op = O_constant;
9141       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9142     }
9143
9144   if (hi32.X_add_number == 0)
9145     freg = 0;
9146   else
9147     {
9148       int shift, bit;
9149       unsigned long hi, lo;
9150
9151       if (hi32.X_add_number == (offsetT) 0xffffffff)
9152         {
9153           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9154             {
9155               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9156               return;
9157             }
9158           if (lo32.X_add_number & 0x80000000)
9159             {
9160               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9161               if (lo32.X_add_number & 0xffff)
9162                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9163               return;
9164             }
9165         }
9166
9167       /* Check for 16bit shifted constant.  We know that hi32 is
9168          non-zero, so start the mask on the first bit of the hi32
9169          value.  */
9170       shift = 17;
9171       do
9172         {
9173           unsigned long himask, lomask;
9174
9175           if (shift < 32)
9176             {
9177               himask = 0xffff >> (32 - shift);
9178               lomask = (0xffff << shift) & 0xffffffff;
9179             }
9180           else
9181             {
9182               himask = 0xffff << (shift - 32);
9183               lomask = 0;
9184             }
9185           if ((hi32.X_add_number & ~(offsetT) himask) == 0
9186               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9187             {
9188               expressionS tmp;
9189
9190               tmp.X_op = O_constant;
9191               if (shift < 32)
9192                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9193                                     | (lo32.X_add_number >> shift));
9194               else
9195                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9196               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9197               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9198                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9199               return;
9200             }
9201           ++shift;
9202         }
9203       while (shift <= (64 - 16));
9204
9205       /* Find the bit number of the lowest one bit, and store the
9206          shifted value in hi/lo.  */
9207       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9208       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9209       if (lo != 0)
9210         {
9211           bit = 0;
9212           while ((lo & 1) == 0)
9213             {
9214               lo >>= 1;
9215               ++bit;
9216             }
9217           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9218           hi >>= bit;
9219         }
9220       else
9221         {
9222           bit = 32;
9223           while ((hi & 1) == 0)
9224             {
9225               hi >>= 1;
9226               ++bit;
9227             }
9228           lo = hi;
9229           hi = 0;
9230         }
9231
9232       /* Optimize if the shifted value is a (power of 2) - 1.  */
9233       if ((hi == 0 && ((lo + 1) & lo) == 0)
9234           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9235         {
9236           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9237           if (shift != 0)
9238             {
9239               expressionS tmp;
9240
9241               /* This instruction will set the register to be all
9242                  ones.  */
9243               tmp.X_op = O_constant;
9244               tmp.X_add_number = (offsetT) -1;
9245               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9246               if (bit != 0)
9247                 {
9248                   bit += shift;
9249                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9250                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9251                 }
9252               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9253                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9254               return;
9255             }
9256         }
9257
9258       /* Sign extend hi32 before calling load_register, because we can
9259          generally get better code when we load a sign extended value.  */
9260       if ((hi32.X_add_number & 0x80000000) != 0)
9261         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9262       load_register (reg, &hi32, 0);
9263       freg = reg;
9264     }
9265   if ((lo32.X_add_number & 0xffff0000) == 0)
9266     {
9267       if (freg != 0)
9268         {
9269           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9270           freg = reg;
9271         }
9272     }
9273   else
9274     {
9275       expressionS mid16;
9276
9277       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9278         {
9279           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9280           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9281           return;
9282         }
9283
9284       if (freg != 0)
9285         {
9286           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9287           freg = reg;
9288         }
9289       mid16 = lo32;
9290       mid16.X_add_number >>= 16;
9291       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9292       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9293       freg = reg;
9294     }
9295   if ((lo32.X_add_number & 0xffff) != 0)
9296     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9297 }
9298
9299 static inline void
9300 load_delay_nop (void)
9301 {
9302   if (!gpr_interlocks)
9303     macro_build (NULL, "nop", "");
9304 }
9305
9306 /* Load an address into a register.  */
9307
9308 static void
9309 load_address (int reg, expressionS *ep, int *used_at)
9310 {
9311   if (ep->X_op != O_constant
9312       && ep->X_op != O_symbol)
9313     {
9314       as_bad (_("expression too complex"));
9315       ep->X_op = O_constant;
9316     }
9317
9318   if (ep->X_op == O_constant)
9319     {
9320       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9321       return;
9322     }
9323
9324   if (mips_pic == NO_PIC)
9325     {
9326       /* If this is a reference to a GP relative symbol, we want
9327            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9328          Otherwise we want
9329            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9330            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9331          If we have an addend, we always use the latter form.
9332
9333          With 64bit address space and a usable $at we want
9334            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9335            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9336            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9337            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9338            dsll32       $reg,0
9339            daddu        $reg,$reg,$at
9340
9341          If $at is already in use, we use a path which is suboptimal
9342          on superscalar processors.
9343            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9344            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9345            dsll         $reg,16
9346            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9347            dsll         $reg,16
9348            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9349
9350          For GP relative symbols in 64bit address space we can use
9351          the same sequence as in 32bit address space.  */
9352       if (HAVE_64BIT_SYMBOLS)
9353         {
9354           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9355               && !nopic_need_relax (ep->X_add_symbol, 1))
9356             {
9357               relax_start (ep->X_add_symbol);
9358               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9359                            mips_gp_register, BFD_RELOC_GPREL16);
9360               relax_switch ();
9361             }
9362
9363           if (*used_at == 0 && mips_opts.at)
9364             {
9365               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9366               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9367               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9368                            BFD_RELOC_MIPS_HIGHER);
9369               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9370               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9371               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9372               *used_at = 1;
9373             }
9374           else
9375             {
9376               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9377               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9378                            BFD_RELOC_MIPS_HIGHER);
9379               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9380               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9381               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9382               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9383             }
9384
9385           if (mips_relax.sequence)
9386             relax_end ();
9387         }
9388       else
9389         {
9390           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9391               && !nopic_need_relax (ep->X_add_symbol, 1))
9392             {
9393               relax_start (ep->X_add_symbol);
9394               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9395                            mips_gp_register, BFD_RELOC_GPREL16);
9396               relax_switch ();
9397             }
9398           macro_build_lui (ep, reg);
9399           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9400                        reg, reg, BFD_RELOC_LO16);
9401           if (mips_relax.sequence)
9402             relax_end ();
9403         }
9404     }
9405   else if (!mips_big_got)
9406     {
9407       expressionS ex;
9408
9409       /* If this is a reference to an external symbol, we want
9410            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9411          Otherwise we want
9412            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9413            nop
9414            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9415          If there is a constant, it must be added in after.
9416
9417          If we have NewABI, we want
9418            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9419          unless we're referencing a global symbol with a non-zero
9420          offset, in which case cst must be added separately.  */
9421       if (HAVE_NEWABI)
9422         {
9423           if (ep->X_add_number)
9424             {
9425               ex.X_add_number = ep->X_add_number;
9426               ep->X_add_number = 0;
9427               relax_start (ep->X_add_symbol);
9428               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9429                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9430               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9431                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9432               ex.X_op = O_constant;
9433               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9434                            reg, reg, BFD_RELOC_LO16);
9435               ep->X_add_number = ex.X_add_number;
9436               relax_switch ();
9437             }
9438           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9439                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9440           if (mips_relax.sequence)
9441             relax_end ();
9442         }
9443       else
9444         {
9445           ex.X_add_number = ep->X_add_number;
9446           ep->X_add_number = 0;
9447           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9448                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9449           load_delay_nop ();
9450           relax_start (ep->X_add_symbol);
9451           relax_switch ();
9452           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9453                        BFD_RELOC_LO16);
9454           relax_end ();
9455
9456           if (ex.X_add_number != 0)
9457             {
9458               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9459                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9460               ex.X_op = O_constant;
9461               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9462                            reg, reg, BFD_RELOC_LO16);
9463             }
9464         }
9465     }
9466   else if (mips_big_got)
9467     {
9468       expressionS ex;
9469
9470       /* This is the large GOT case.  If this is a reference to an
9471          external symbol, we want
9472            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9473            addu         $reg,$reg,$gp
9474            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9475
9476          Otherwise, for a reference to a local symbol in old ABI, we want
9477            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9478            nop
9479            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9480          If there is a constant, it must be added in after.
9481
9482          In the NewABI, for local symbols, with or without offsets, we want:
9483            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9484            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9485       */
9486       if (HAVE_NEWABI)
9487         {
9488           ex.X_add_number = ep->X_add_number;
9489           ep->X_add_number = 0;
9490           relax_start (ep->X_add_symbol);
9491           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9492           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9493                        reg, reg, mips_gp_register);
9494           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9495                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9496           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9497             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9498           else if (ex.X_add_number)
9499             {
9500               ex.X_op = O_constant;
9501               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9502                            BFD_RELOC_LO16);
9503             }
9504
9505           ep->X_add_number = ex.X_add_number;
9506           relax_switch ();
9507           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9508                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9509           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9510                        BFD_RELOC_MIPS_GOT_OFST);
9511           relax_end ();
9512         }
9513       else
9514         {
9515           ex.X_add_number = ep->X_add_number;
9516           ep->X_add_number = 0;
9517           relax_start (ep->X_add_symbol);
9518           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9519           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9520                        reg, reg, mips_gp_register);
9521           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9522                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9523           relax_switch ();
9524           if (reg_needs_delay (mips_gp_register))
9525             {
9526               /* We need a nop before loading from $gp.  This special
9527                  check is required because the lui which starts the main
9528                  instruction stream does not refer to $gp, and so will not
9529                  insert the nop which may be required.  */
9530               macro_build (NULL, "nop", "");
9531             }
9532           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9533                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9534           load_delay_nop ();
9535           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9536                        BFD_RELOC_LO16);
9537           relax_end ();
9538
9539           if (ex.X_add_number != 0)
9540             {
9541               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9542                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9543               ex.X_op = O_constant;
9544               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9545                            BFD_RELOC_LO16);
9546             }
9547         }
9548     }
9549   else
9550     abort ();
9551
9552   if (!mips_opts.at && *used_at == 1)
9553     as_bad (_("macro used $at after \".set noat\""));
9554 }
9555
9556 /* Move the contents of register SOURCE into register DEST.  */
9557
9558 static void
9559 move_register (int dest, int source)
9560 {
9561   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9562      instruction specifically requires a 32-bit one.  */
9563   if (mips_opts.micromips
9564       && !mips_opts.insn32
9565       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9566     macro_build (NULL, "move", "mp,mj", dest, source);
9567   else
9568     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9569 }
9570
9571 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9572    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9573    The two alternatives are:
9574
9575    Global symbol                Local symbol
9576    -------------                ------------
9577    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9578    ...                          ...
9579    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9580
9581    load_got_offset emits the first instruction and add_got_offset
9582    emits the second for a 16-bit offset or add_got_offset_hilo emits
9583    a sequence to add a 32-bit offset using a scratch register.  */
9584
9585 static void
9586 load_got_offset (int dest, expressionS *local)
9587 {
9588   expressionS global;
9589
9590   global = *local;
9591   global.X_add_number = 0;
9592
9593   relax_start (local->X_add_symbol);
9594   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9595                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9596   relax_switch ();
9597   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9598                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9599   relax_end ();
9600 }
9601
9602 static void
9603 add_got_offset (int dest, expressionS *local)
9604 {
9605   expressionS global;
9606
9607   global.X_op = O_constant;
9608   global.X_op_symbol = NULL;
9609   global.X_add_symbol = NULL;
9610   global.X_add_number = local->X_add_number;
9611
9612   relax_start (local->X_add_symbol);
9613   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9614                dest, dest, BFD_RELOC_LO16);
9615   relax_switch ();
9616   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9617   relax_end ();
9618 }
9619
9620 static void
9621 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9622 {
9623   expressionS global;
9624   int hold_mips_optimize;
9625
9626   global.X_op = O_constant;
9627   global.X_op_symbol = NULL;
9628   global.X_add_symbol = NULL;
9629   global.X_add_number = local->X_add_number;
9630
9631   relax_start (local->X_add_symbol);
9632   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9633   relax_switch ();
9634   /* Set mips_optimize around the lui instruction to avoid
9635      inserting an unnecessary nop after the lw.  */
9636   hold_mips_optimize = mips_optimize;
9637   mips_optimize = 2;
9638   macro_build_lui (&global, tmp);
9639   mips_optimize = hold_mips_optimize;
9640   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9641   relax_end ();
9642
9643   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9644 }
9645
9646 /* Emit a sequence of instructions to emulate a branch likely operation.
9647    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9648    is its complementing branch with the original condition negated.
9649    CALL is set if the original branch specified the link operation.
9650    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9651
9652    Code like this is produced in the noreorder mode:
9653
9654         BRNEG   <args>, 1f
9655          nop
9656         b       <sym>
9657          delay slot (executed only if branch taken)
9658     1:
9659
9660    or, if CALL is set:
9661
9662         BRNEG   <args>, 1f
9663          nop
9664         bal     <sym>
9665          delay slot (executed only if branch taken)
9666     1:
9667
9668    In the reorder mode the delay slot would be filled with a nop anyway,
9669    so code produced is simply:
9670
9671         BR      <args>, <sym>
9672          nop
9673
9674    This function is used when producing code for the microMIPS ASE that
9675    does not implement branch likely instructions in hardware.  */
9676
9677 static void
9678 macro_build_branch_likely (const char *br, const char *brneg,
9679                            int call, expressionS *ep, const char *fmt,
9680                            unsigned int sreg, unsigned int treg)
9681 {
9682   int noreorder = mips_opts.noreorder;
9683   expressionS expr1;
9684
9685   gas_assert (mips_opts.micromips);
9686   start_noreorder ();
9687   if (noreorder)
9688     {
9689       micromips_label_expr (&expr1);
9690       macro_build (&expr1, brneg, fmt, sreg, treg);
9691       macro_build (NULL, "nop", "");
9692       macro_build (ep, call ? "bal" : "b", "p");
9693
9694       /* Set to true so that append_insn adds a label.  */
9695       emit_branch_likely_macro = TRUE;
9696     }
9697   else
9698     {
9699       macro_build (ep, br, fmt, sreg, treg);
9700       macro_build (NULL, "nop", "");
9701     }
9702   end_noreorder ();
9703 }
9704
9705 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9706    the condition code tested.  EP specifies the branch target.  */
9707
9708 static void
9709 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9710 {
9711   const int call = 0;
9712   const char *brneg;
9713   const char *br;
9714
9715   switch (type)
9716     {
9717     case M_BC1FL:
9718       br = "bc1f";
9719       brneg = "bc1t";
9720       break;
9721     case M_BC1TL:
9722       br = "bc1t";
9723       brneg = "bc1f";
9724       break;
9725     case M_BC2FL:
9726       br = "bc2f";
9727       brneg = "bc2t";
9728       break;
9729     case M_BC2TL:
9730       br = "bc2t";
9731       brneg = "bc2f";
9732       break;
9733     default:
9734       abort ();
9735     }
9736   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9737 }
9738
9739 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9740    the register tested.  EP specifies the branch target.  */
9741
9742 static void
9743 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9744 {
9745   const char *brneg = NULL;
9746   const char *br;
9747   int call = 0;
9748
9749   switch (type)
9750     {
9751     case M_BGEZ:
9752       br = "bgez";
9753       break;
9754     case M_BGEZL:
9755       br = mips_opts.micromips ? "bgez" : "bgezl";
9756       brneg = "bltz";
9757       break;
9758     case M_BGEZALL:
9759       gas_assert (mips_opts.micromips);
9760       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9761       brneg = "bltz";
9762       call = 1;
9763       break;
9764     case M_BGTZ:
9765       br = "bgtz";
9766       break;
9767     case M_BGTZL:
9768       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9769       brneg = "blez";
9770       break;
9771     case M_BLEZ:
9772       br = "blez";
9773       break;
9774     case M_BLEZL:
9775       br = mips_opts.micromips ? "blez" : "blezl";
9776       brneg = "bgtz";
9777       break;
9778     case M_BLTZ:
9779       br = "bltz";
9780       break;
9781     case M_BLTZL:
9782       br = mips_opts.micromips ? "bltz" : "bltzl";
9783       brneg = "bgez";
9784       break;
9785     case M_BLTZALL:
9786       gas_assert (mips_opts.micromips);
9787       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9788       brneg = "bgez";
9789       call = 1;
9790       break;
9791     default:
9792       abort ();
9793     }
9794   if (mips_opts.micromips && brneg)
9795     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9796   else
9797     macro_build (ep, br, "s,p", sreg);
9798 }
9799
9800 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9801    TREG as the registers tested.  EP specifies the branch target.  */
9802
9803 static void
9804 macro_build_branch_rsrt (int type, expressionS *ep,
9805                          unsigned int sreg, unsigned int treg)
9806 {
9807   const char *brneg = NULL;
9808   const int call = 0;
9809   const char *br;
9810
9811   switch (type)
9812     {
9813     case M_BEQ:
9814     case M_BEQ_I:
9815       br = "beq";
9816       break;
9817     case M_BEQL:
9818     case M_BEQL_I:
9819       br = mips_opts.micromips ? "beq" : "beql";
9820       brneg = "bne";
9821       break;
9822     case M_BNE:
9823     case M_BNE_I:
9824       br = "bne";
9825       break;
9826     case M_BNEL:
9827     case M_BNEL_I:
9828       br = mips_opts.micromips ? "bne" : "bnel";
9829       brneg = "beq";
9830       break;
9831     default:
9832       abort ();
9833     }
9834   if (mips_opts.micromips && brneg)
9835     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9836   else
9837     macro_build (ep, br, "s,t,p", sreg, treg);
9838 }
9839
9840 /* Return the high part that should be loaded in order to make the low
9841    part of VALUE accessible using an offset of OFFBITS bits.  */
9842
9843 static offsetT
9844 offset_high_part (offsetT value, unsigned int offbits)
9845 {
9846   offsetT bias;
9847   addressT low_mask;
9848
9849   if (offbits == 0)
9850     return value;
9851   bias = 1 << (offbits - 1);
9852   low_mask = bias * 2 - 1;
9853   return (value + bias) & ~low_mask;
9854 }
9855
9856 /* Return true if the value stored in offset_expr and offset_reloc
9857    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9858    amount that the caller wants to add without inducing overflow
9859    and ALIGN is the known alignment of the value in bytes.  */
9860
9861 static bfd_boolean
9862 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9863 {
9864   if (offbits == 16)
9865     {
9866       /* Accept any relocation operator if overflow isn't a concern.  */
9867       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9868         return TRUE;
9869
9870       /* These relocations are guaranteed not to overflow in correct links.  */
9871       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9872           || gprel16_reloc_p (*offset_reloc))
9873         return TRUE;
9874     }
9875   if (offset_expr.X_op == O_constant
9876       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9877       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9878     return TRUE;
9879   return FALSE;
9880 }
9881
9882 /*
9883  *                      Build macros
9884  *   This routine implements the seemingly endless macro or synthesized
9885  * instructions and addressing modes in the mips assembly language. Many
9886  * of these macros are simple and are similar to each other. These could
9887  * probably be handled by some kind of table or grammar approach instead of
9888  * this verbose method. Others are not simple macros but are more like
9889  * optimizing code generation.
9890  *   One interesting optimization is when several store macros appear
9891  * consecutively that would load AT with the upper half of the same address.
9892  * The ensuing load upper instructions are omitted. This implies some kind
9893  * of global optimization. We currently only optimize within a single macro.
9894  *   For many of the load and store macros if the address is specified as a
9895  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9896  * first load register 'at' with zero and use it as the base register. The
9897  * mips assembler simply uses register $zero. Just one tiny optimization
9898  * we're missing.
9899  */
9900 static void
9901 macro (struct mips_cl_insn *ip, char *str)
9902 {
9903   const struct mips_operand_array *operands;
9904   unsigned int breg, i;
9905   unsigned int tempreg;
9906   int mask;
9907   int used_at = 0;
9908   expressionS label_expr;
9909   expressionS expr1;
9910   expressionS *ep;
9911   const char *s;
9912   const char *s2;
9913   const char *fmt;
9914   int likely = 0;
9915   int coproc = 0;
9916   int offbits = 16;
9917   int call = 0;
9918   int jals = 0;
9919   int dbl = 0;
9920   int imm = 0;
9921   int ust = 0;
9922   int lp = 0;
9923   bfd_boolean large_offset;
9924   int off;
9925   int hold_mips_optimize;
9926   unsigned int align;
9927   unsigned int op[MAX_OPERANDS];
9928
9929   gas_assert (! mips_opts.mips16);
9930
9931   operands = insn_operands (ip);
9932   for (i = 0; i < MAX_OPERANDS; i++)
9933     if (operands->operand[i])
9934       op[i] = insn_extract_operand (ip, operands->operand[i]);
9935     else
9936       op[i] = -1;
9937
9938   mask = ip->insn_mo->mask;
9939
9940   label_expr.X_op = O_constant;
9941   label_expr.X_op_symbol = NULL;
9942   label_expr.X_add_symbol = NULL;
9943   label_expr.X_add_number = 0;
9944
9945   expr1.X_op = O_constant;
9946   expr1.X_op_symbol = NULL;
9947   expr1.X_add_symbol = NULL;
9948   expr1.X_add_number = 1;
9949   align = 1;
9950
9951   switch (mask)
9952     {
9953     case M_DABS:
9954       dbl = 1;
9955       /* Fall through.  */
9956     case M_ABS:
9957       /*    bgez    $a0,1f
9958             move    v0,$a0
9959             sub     v0,$zero,$a0
9960          1:
9961        */
9962
9963       start_noreorder ();
9964
9965       if (mips_opts.micromips)
9966         micromips_label_expr (&label_expr);
9967       else
9968         label_expr.X_add_number = 8;
9969       macro_build (&label_expr, "bgez", "s,p", op[1]);
9970       if (op[0] == op[1])
9971         macro_build (NULL, "nop", "");
9972       else
9973         move_register (op[0], op[1]);
9974       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9975       if (mips_opts.micromips)
9976         micromips_add_label ();
9977
9978       end_noreorder ();
9979       break;
9980
9981     case M_ADD_I:
9982       s = "addi";
9983       s2 = "add";
9984       goto do_addi;
9985     case M_ADDU_I:
9986       s = "addiu";
9987       s2 = "addu";
9988       goto do_addi;
9989     case M_DADD_I:
9990       dbl = 1;
9991       s = "daddi";
9992       s2 = "dadd";
9993       if (!mips_opts.micromips)
9994         goto do_addi;
9995       if (imm_expr.X_add_number >= -0x200
9996           && imm_expr.X_add_number < 0x200)
9997         {
9998           macro_build (NULL, s, "t,r,.", op[0], op[1],
9999                        (int) imm_expr.X_add_number);
10000           break;
10001         }
10002       goto do_addi_i;
10003     case M_DADDU_I:
10004       dbl = 1;
10005       s = "daddiu";
10006       s2 = "daddu";
10007     do_addi:
10008       if (imm_expr.X_add_number >= -0x8000
10009           && imm_expr.X_add_number < 0x8000)
10010         {
10011           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
10012           break;
10013         }
10014     do_addi_i:
10015       used_at = 1;
10016       load_register (AT, &imm_expr, dbl);
10017       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10018       break;
10019
10020     case M_AND_I:
10021       s = "andi";
10022       s2 = "and";
10023       goto do_bit;
10024     case M_OR_I:
10025       s = "ori";
10026       s2 = "or";
10027       goto do_bit;
10028     case M_NOR_I:
10029       s = "";
10030       s2 = "nor";
10031       goto do_bit;
10032     case M_XOR_I:
10033       s = "xori";
10034       s2 = "xor";
10035     do_bit:
10036       if (imm_expr.X_add_number >= 0
10037           && imm_expr.X_add_number < 0x10000)
10038         {
10039           if (mask != M_NOR_I)
10040             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10041           else
10042             {
10043               macro_build (&imm_expr, "ori", "t,r,i",
10044                            op[0], op[1], BFD_RELOC_LO16);
10045               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10046             }
10047           break;
10048         }
10049
10050       used_at = 1;
10051       load_register (AT, &imm_expr, GPR_SIZE == 64);
10052       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10053       break;
10054
10055     case M_BALIGN:
10056       switch (imm_expr.X_add_number)
10057         {
10058         case 0:
10059           macro_build (NULL, "nop", "");
10060           break;
10061         case 2:
10062           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10063           break;
10064         case 1:
10065         case 3:
10066           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10067                        (int) imm_expr.X_add_number);
10068           break;
10069         default:
10070           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10071                   (unsigned long) imm_expr.X_add_number);
10072           break;
10073         }
10074       break;
10075
10076     case M_BC1FL:
10077     case M_BC1TL:
10078     case M_BC2FL:
10079     case M_BC2TL:
10080       gas_assert (mips_opts.micromips);
10081       macro_build_branch_ccl (mask, &offset_expr,
10082                               EXTRACT_OPERAND (1, BCC, *ip));
10083       break;
10084
10085     case M_BEQ_I:
10086     case M_BEQL_I:
10087     case M_BNE_I:
10088     case M_BNEL_I:
10089       if (imm_expr.X_add_number == 0)
10090         op[1] = 0;
10091       else
10092         {
10093           op[1] = AT;
10094           used_at = 1;
10095           load_register (op[1], &imm_expr, GPR_SIZE == 64);
10096         }
10097       /* Fall through.  */
10098     case M_BEQL:
10099     case M_BNEL:
10100       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10101       break;
10102
10103     case M_BGEL:
10104       likely = 1;
10105       /* Fall through.  */
10106     case M_BGE:
10107       if (op[1] == 0)
10108         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10109       else if (op[0] == 0)
10110         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10111       else
10112         {
10113           used_at = 1;
10114           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10115           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10116                                    &offset_expr, AT, ZERO);
10117         }
10118       break;
10119
10120     case M_BGEZL:
10121     case M_BGEZALL:
10122     case M_BGTZL:
10123     case M_BLEZL:
10124     case M_BLTZL:
10125     case M_BLTZALL:
10126       macro_build_branch_rs (mask, &offset_expr, op[0]);
10127       break;
10128
10129     case M_BGTL_I:
10130       likely = 1;
10131       /* Fall through.  */
10132     case M_BGT_I:
10133       /* Check for > max integer.  */
10134       if (imm_expr.X_add_number >= GPR_SMAX)
10135         {
10136         do_false:
10137           /* Result is always false.  */
10138           if (! likely)
10139             macro_build (NULL, "nop", "");
10140           else
10141             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10142           break;
10143         }
10144       ++imm_expr.X_add_number;
10145       /* FALLTHROUGH */
10146     case M_BGE_I:
10147     case M_BGEL_I:
10148       if (mask == M_BGEL_I)
10149         likely = 1;
10150       if (imm_expr.X_add_number == 0)
10151         {
10152           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10153                                  &offset_expr, op[0]);
10154           break;
10155         }
10156       if (imm_expr.X_add_number == 1)
10157         {
10158           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10159                                  &offset_expr, op[0]);
10160           break;
10161         }
10162       if (imm_expr.X_add_number <= GPR_SMIN)
10163         {
10164         do_true:
10165           /* result is always true */
10166           as_warn (_("branch %s is always true"), ip->insn_mo->name);
10167           macro_build (&offset_expr, "b", "p");
10168           break;
10169         }
10170       used_at = 1;
10171       set_at (op[0], 0);
10172       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10173                                &offset_expr, AT, ZERO);
10174       break;
10175
10176     case M_BGEUL:
10177       likely = 1;
10178       /* Fall through.  */
10179     case M_BGEU:
10180       if (op[1] == 0)
10181         goto do_true;
10182       else if (op[0] == 0)
10183         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10184                                  &offset_expr, ZERO, op[1]);
10185       else
10186         {
10187           used_at = 1;
10188           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10189           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10190                                    &offset_expr, AT, ZERO);
10191         }
10192       break;
10193
10194     case M_BGTUL_I:
10195       likely = 1;
10196       /* Fall through.  */
10197     case M_BGTU_I:
10198       if (op[0] == 0
10199           || (GPR_SIZE == 32
10200               && imm_expr.X_add_number == -1))
10201         goto do_false;
10202       ++imm_expr.X_add_number;
10203       /* FALLTHROUGH */
10204     case M_BGEU_I:
10205     case M_BGEUL_I:
10206       if (mask == M_BGEUL_I)
10207         likely = 1;
10208       if (imm_expr.X_add_number == 0)
10209         goto do_true;
10210       else if (imm_expr.X_add_number == 1)
10211         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10212                                  &offset_expr, op[0], ZERO);
10213       else
10214         {
10215           used_at = 1;
10216           set_at (op[0], 1);
10217           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10218                                    &offset_expr, AT, ZERO);
10219         }
10220       break;
10221
10222     case M_BGTL:
10223       likely = 1;
10224       /* Fall through.  */
10225     case M_BGT:
10226       if (op[1] == 0)
10227         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10228       else if (op[0] == 0)
10229         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10230       else
10231         {
10232           used_at = 1;
10233           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10234           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10235                                    &offset_expr, AT, ZERO);
10236         }
10237       break;
10238
10239     case M_BGTUL:
10240       likely = 1;
10241       /* Fall through.  */
10242     case M_BGTU:
10243       if (op[1] == 0)
10244         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10245                                  &offset_expr, op[0], ZERO);
10246       else if (op[0] == 0)
10247         goto do_false;
10248       else
10249         {
10250           used_at = 1;
10251           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10252           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10253                                    &offset_expr, AT, ZERO);
10254         }
10255       break;
10256
10257     case M_BLEL:
10258       likely = 1;
10259       /* Fall through.  */
10260     case M_BLE:
10261       if (op[1] == 0)
10262         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10263       else if (op[0] == 0)
10264         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10265       else
10266         {
10267           used_at = 1;
10268           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10269           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10270                                    &offset_expr, AT, ZERO);
10271         }
10272       break;
10273
10274     case M_BLEL_I:
10275       likely = 1;
10276       /* Fall through.  */
10277     case M_BLE_I:
10278       if (imm_expr.X_add_number >= GPR_SMAX)
10279         goto do_true;
10280       ++imm_expr.X_add_number;
10281       /* FALLTHROUGH */
10282     case M_BLT_I:
10283     case M_BLTL_I:
10284       if (mask == M_BLTL_I)
10285         likely = 1;
10286       if (imm_expr.X_add_number == 0)
10287         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10288       else if (imm_expr.X_add_number == 1)
10289         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10290       else
10291         {
10292           used_at = 1;
10293           set_at (op[0], 0);
10294           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10295                                    &offset_expr, AT, ZERO);
10296         }
10297       break;
10298
10299     case M_BLEUL:
10300       likely = 1;
10301       /* Fall through.  */
10302     case M_BLEU:
10303       if (op[1] == 0)
10304         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10305                                  &offset_expr, op[0], ZERO);
10306       else if (op[0] == 0)
10307         goto do_true;
10308       else
10309         {
10310           used_at = 1;
10311           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10312           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10313                                    &offset_expr, AT, ZERO);
10314         }
10315       break;
10316
10317     case M_BLEUL_I:
10318       likely = 1;
10319       /* Fall through.  */
10320     case M_BLEU_I:
10321       if (op[0] == 0
10322           || (GPR_SIZE == 32
10323               && imm_expr.X_add_number == -1))
10324         goto do_true;
10325       ++imm_expr.X_add_number;
10326       /* FALLTHROUGH */
10327     case M_BLTU_I:
10328     case M_BLTUL_I:
10329       if (mask == M_BLTUL_I)
10330         likely = 1;
10331       if (imm_expr.X_add_number == 0)
10332         goto do_false;
10333       else if (imm_expr.X_add_number == 1)
10334         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10335                                  &offset_expr, op[0], ZERO);
10336       else
10337         {
10338           used_at = 1;
10339           set_at (op[0], 1);
10340           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10341                                    &offset_expr, AT, ZERO);
10342         }
10343       break;
10344
10345     case M_BLTL:
10346       likely = 1;
10347       /* Fall through.  */
10348     case M_BLT:
10349       if (op[1] == 0)
10350         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10351       else if (op[0] == 0)
10352         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10353       else
10354         {
10355           used_at = 1;
10356           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10357           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10358                                    &offset_expr, AT, ZERO);
10359         }
10360       break;
10361
10362     case M_BLTUL:
10363       likely = 1;
10364       /* Fall through.  */
10365     case M_BLTU:
10366       if (op[1] == 0)
10367         goto do_false;
10368       else if (op[0] == 0)
10369         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10370                                  &offset_expr, ZERO, op[1]);
10371       else
10372         {
10373           used_at = 1;
10374           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10375           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10376                                    &offset_expr, AT, ZERO);
10377         }
10378       break;
10379
10380     case M_DDIV_3:
10381       dbl = 1;
10382       /* Fall through.  */
10383     case M_DIV_3:
10384       s = "mflo";
10385       goto do_div3;
10386     case M_DREM_3:
10387       dbl = 1;
10388       /* Fall through.  */
10389     case M_REM_3:
10390       s = "mfhi";
10391     do_div3:
10392       if (op[2] == 0)
10393         {
10394           as_warn (_("divide by zero"));
10395           if (mips_trap)
10396             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10397           else
10398             macro_build (NULL, "break", BRK_FMT, 7);
10399           break;
10400         }
10401
10402       start_noreorder ();
10403       if (mips_trap)
10404         {
10405           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10406           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10407         }
10408       else
10409         {
10410           if (mips_opts.micromips)
10411             micromips_label_expr (&label_expr);
10412           else
10413             label_expr.X_add_number = 8;
10414           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10415           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10416           macro_build (NULL, "break", BRK_FMT, 7);
10417           if (mips_opts.micromips)
10418             micromips_add_label ();
10419         }
10420       expr1.X_add_number = -1;
10421       used_at = 1;
10422       load_register (AT, &expr1, dbl);
10423       if (mips_opts.micromips)
10424         micromips_label_expr (&label_expr);
10425       else
10426         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10427       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10428       if (dbl)
10429         {
10430           expr1.X_add_number = 1;
10431           load_register (AT, &expr1, dbl);
10432           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10433         }
10434       else
10435         {
10436           expr1.X_add_number = 0x80000000;
10437           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10438         }
10439       if (mips_trap)
10440         {
10441           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10442           /* We want to close the noreorder block as soon as possible, so
10443              that later insns are available for delay slot filling.  */
10444           end_noreorder ();
10445         }
10446       else
10447         {
10448           if (mips_opts.micromips)
10449             micromips_label_expr (&label_expr);
10450           else
10451             label_expr.X_add_number = 8;
10452           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10453           macro_build (NULL, "nop", "");
10454
10455           /* We want to close the noreorder block as soon as possible, so
10456              that later insns are available for delay slot filling.  */
10457           end_noreorder ();
10458
10459           macro_build (NULL, "break", BRK_FMT, 6);
10460         }
10461       if (mips_opts.micromips)
10462         micromips_add_label ();
10463       macro_build (NULL, s, MFHL_FMT, op[0]);
10464       break;
10465
10466     case M_DIV_3I:
10467       s = "div";
10468       s2 = "mflo";
10469       goto do_divi;
10470     case M_DIVU_3I:
10471       s = "divu";
10472       s2 = "mflo";
10473       goto do_divi;
10474     case M_REM_3I:
10475       s = "div";
10476       s2 = "mfhi";
10477       goto do_divi;
10478     case M_REMU_3I:
10479       s = "divu";
10480       s2 = "mfhi";
10481       goto do_divi;
10482     case M_DDIV_3I:
10483       dbl = 1;
10484       s = "ddiv";
10485       s2 = "mflo";
10486       goto do_divi;
10487     case M_DDIVU_3I:
10488       dbl = 1;
10489       s = "ddivu";
10490       s2 = "mflo";
10491       goto do_divi;
10492     case M_DREM_3I:
10493       dbl = 1;
10494       s = "ddiv";
10495       s2 = "mfhi";
10496       goto do_divi;
10497     case M_DREMU_3I:
10498       dbl = 1;
10499       s = "ddivu";
10500       s2 = "mfhi";
10501     do_divi:
10502       if (imm_expr.X_add_number == 0)
10503         {
10504           as_warn (_("divide by zero"));
10505           if (mips_trap)
10506             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10507           else
10508             macro_build (NULL, "break", BRK_FMT, 7);
10509           break;
10510         }
10511       if (imm_expr.X_add_number == 1)
10512         {
10513           if (strcmp (s2, "mflo") == 0)
10514             move_register (op[0], op[1]);
10515           else
10516             move_register (op[0], ZERO);
10517           break;
10518         }
10519       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10520         {
10521           if (strcmp (s2, "mflo") == 0)
10522             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10523           else
10524             move_register (op[0], ZERO);
10525           break;
10526         }
10527
10528       used_at = 1;
10529       load_register (AT, &imm_expr, dbl);
10530       macro_build (NULL, s, "z,s,t", op[1], AT);
10531       macro_build (NULL, s2, MFHL_FMT, op[0]);
10532       break;
10533
10534     case M_DIVU_3:
10535       s = "divu";
10536       s2 = "mflo";
10537       goto do_divu3;
10538     case M_REMU_3:
10539       s = "divu";
10540       s2 = "mfhi";
10541       goto do_divu3;
10542     case M_DDIVU_3:
10543       s = "ddivu";
10544       s2 = "mflo";
10545       goto do_divu3;
10546     case M_DREMU_3:
10547       s = "ddivu";
10548       s2 = "mfhi";
10549     do_divu3:
10550       start_noreorder ();
10551       if (mips_trap)
10552         {
10553           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10554           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10555           /* We want to close the noreorder block as soon as possible, so
10556              that later insns are available for delay slot filling.  */
10557           end_noreorder ();
10558         }
10559       else
10560         {
10561           if (mips_opts.micromips)
10562             micromips_label_expr (&label_expr);
10563           else
10564             label_expr.X_add_number = 8;
10565           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10566           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10567
10568           /* We want to close the noreorder block as soon as possible, so
10569              that later insns are available for delay slot filling.  */
10570           end_noreorder ();
10571           macro_build (NULL, "break", BRK_FMT, 7);
10572           if (mips_opts.micromips)
10573             micromips_add_label ();
10574         }
10575       macro_build (NULL, s2, MFHL_FMT, op[0]);
10576       break;
10577
10578     case M_DLCA_AB:
10579       dbl = 1;
10580       /* Fall through.  */
10581     case M_LCA_AB:
10582       call = 1;
10583       goto do_la;
10584     case M_DLA_AB:
10585       dbl = 1;
10586       /* Fall through.  */
10587     case M_LA_AB:
10588     do_la:
10589       /* Load the address of a symbol into a register.  If breg is not
10590          zero, we then add a base register to it.  */
10591
10592       breg = op[2];
10593       if (dbl && GPR_SIZE == 32)
10594         as_warn (_("dla used to load 32-bit register; recommend using la "
10595                    "instead"));
10596
10597       if (!dbl && HAVE_64BIT_OBJECTS)
10598         as_warn (_("la used to load 64-bit address; recommend using dla "
10599                    "instead"));
10600
10601       if (small_offset_p (0, align, 16))
10602         {
10603           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10604                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10605           break;
10606         }
10607
10608       if (mips_opts.at && (op[0] == breg))
10609         {
10610           tempreg = AT;
10611           used_at = 1;
10612         }
10613       else
10614         tempreg = op[0];
10615
10616       if (offset_expr.X_op != O_symbol
10617           && offset_expr.X_op != O_constant)
10618         {
10619           as_bad (_("expression too complex"));
10620           offset_expr.X_op = O_constant;
10621         }
10622
10623       if (offset_expr.X_op == O_constant)
10624         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10625       else if (mips_pic == NO_PIC)
10626         {
10627           /* If this is a reference to a GP relative symbol, we want
10628                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10629              Otherwise we want
10630                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10631                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10632              If we have a constant, we need two instructions anyhow,
10633              so we may as well always use the latter form.
10634
10635              With 64bit address space and a usable $at we want
10636                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10637                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10638                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10639                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10640                dsll32   $tempreg,0
10641                daddu    $tempreg,$tempreg,$at
10642
10643              If $at is already in use, we use a path which is suboptimal
10644              on superscalar processors.
10645                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10646                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10647                dsll     $tempreg,16
10648                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10649                dsll     $tempreg,16
10650                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10651
10652              For GP relative symbols in 64bit address space we can use
10653              the same sequence as in 32bit address space.  */
10654           if (HAVE_64BIT_SYMBOLS)
10655             {
10656               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10657                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10658                 {
10659                   relax_start (offset_expr.X_add_symbol);
10660                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10661                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10662                   relax_switch ();
10663                 }
10664
10665               if (used_at == 0 && mips_opts.at)
10666                 {
10667                   macro_build (&offset_expr, "lui", LUI_FMT,
10668                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10669                   macro_build (&offset_expr, "lui", LUI_FMT,
10670                                AT, BFD_RELOC_HI16_S);
10671                   macro_build (&offset_expr, "daddiu", "t,r,j",
10672                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10673                   macro_build (&offset_expr, "daddiu", "t,r,j",
10674                                AT, AT, BFD_RELOC_LO16);
10675                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10676                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10677                   used_at = 1;
10678                 }
10679               else
10680                 {
10681                   macro_build (&offset_expr, "lui", LUI_FMT,
10682                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10683                   macro_build (&offset_expr, "daddiu", "t,r,j",
10684                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10685                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10686                   macro_build (&offset_expr, "daddiu", "t,r,j",
10687                                tempreg, tempreg, BFD_RELOC_HI16_S);
10688                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10689                   macro_build (&offset_expr, "daddiu", "t,r,j",
10690                                tempreg, tempreg, BFD_RELOC_LO16);
10691                 }
10692
10693               if (mips_relax.sequence)
10694                 relax_end ();
10695             }
10696           else
10697             {
10698               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10699                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10700                 {
10701                   relax_start (offset_expr.X_add_symbol);
10702                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10703                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10704                   relax_switch ();
10705                 }
10706               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10707                 as_bad (_("offset too large"));
10708               macro_build_lui (&offset_expr, tempreg);
10709               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10710                            tempreg, tempreg, BFD_RELOC_LO16);
10711               if (mips_relax.sequence)
10712                 relax_end ();
10713             }
10714         }
10715       else if (!mips_big_got && !HAVE_NEWABI)
10716         {
10717           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10718
10719           /* If this is a reference to an external symbol, and there
10720              is no constant, we want
10721                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10722              or for lca or if tempreg is PIC_CALL_REG
10723                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10724              For a local symbol, we want
10725                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10726                nop
10727                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10728
10729              If we have a small constant, and this is a reference to
10730              an external symbol, we want
10731                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10732                nop
10733                addiu    $tempreg,$tempreg,<constant>
10734              For a local symbol, we want the same instruction
10735              sequence, but we output a BFD_RELOC_LO16 reloc on the
10736              addiu instruction.
10737
10738              If we have a large constant, and this is a reference to
10739              an external symbol, we want
10740                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10741                lui      $at,<hiconstant>
10742                addiu    $at,$at,<loconstant>
10743                addu     $tempreg,$tempreg,$at
10744              For a local symbol, we want the same instruction
10745              sequence, but we output a BFD_RELOC_LO16 reloc on the
10746              addiu instruction.
10747            */
10748
10749           if (offset_expr.X_add_number == 0)
10750             {
10751               if (mips_pic == SVR4_PIC
10752                   && breg == 0
10753                   && (call || tempreg == PIC_CALL_REG))
10754                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10755
10756               relax_start (offset_expr.X_add_symbol);
10757               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10758                            lw_reloc_type, mips_gp_register);
10759               if (breg != 0)
10760                 {
10761                   /* We're going to put in an addu instruction using
10762                      tempreg, so we may as well insert the nop right
10763                      now.  */
10764                   load_delay_nop ();
10765                 }
10766               relax_switch ();
10767               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10768                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10769               load_delay_nop ();
10770               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10771                            tempreg, tempreg, BFD_RELOC_LO16);
10772               relax_end ();
10773               /* FIXME: If breg == 0, and the next instruction uses
10774                  $tempreg, then if this variant case is used an extra
10775                  nop will be generated.  */
10776             }
10777           else if (offset_expr.X_add_number >= -0x8000
10778                    && offset_expr.X_add_number < 0x8000)
10779             {
10780               load_got_offset (tempreg, &offset_expr);
10781               load_delay_nop ();
10782               add_got_offset (tempreg, &offset_expr);
10783             }
10784           else
10785             {
10786               expr1.X_add_number = offset_expr.X_add_number;
10787               offset_expr.X_add_number =
10788                 SEXT_16BIT (offset_expr.X_add_number);
10789               load_got_offset (tempreg, &offset_expr);
10790               offset_expr.X_add_number = expr1.X_add_number;
10791               /* If we are going to add in a base register, and the
10792                  target register and the base register are the same,
10793                  then we are using AT as a temporary register.  Since
10794                  we want to load the constant into AT, we add our
10795                  current AT (from the global offset table) and the
10796                  register into the register now, and pretend we were
10797                  not using a base register.  */
10798               if (breg == op[0])
10799                 {
10800                   load_delay_nop ();
10801                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10802                                op[0], AT, breg);
10803                   breg = 0;
10804                   tempreg = op[0];
10805                 }
10806               add_got_offset_hilo (tempreg, &offset_expr, AT);
10807               used_at = 1;
10808             }
10809         }
10810       else if (!mips_big_got && HAVE_NEWABI)
10811         {
10812           int add_breg_early = 0;
10813
10814           /* If this is a reference to an external, and there is no
10815              constant, or local symbol (*), with or without a
10816              constant, we want
10817                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10818              or for lca or if tempreg is PIC_CALL_REG
10819                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10820
10821              If we have a small constant, and this is a reference to
10822              an external symbol, we want
10823                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10824                addiu    $tempreg,$tempreg,<constant>
10825
10826              If we have a large constant, and this is a reference to
10827              an external symbol, we want
10828                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10829                lui      $at,<hiconstant>
10830                addiu    $at,$at,<loconstant>
10831                addu     $tempreg,$tempreg,$at
10832
10833              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10834              local symbols, even though it introduces an additional
10835              instruction.  */
10836
10837           if (offset_expr.X_add_number)
10838             {
10839               expr1.X_add_number = offset_expr.X_add_number;
10840               offset_expr.X_add_number = 0;
10841
10842               relax_start (offset_expr.X_add_symbol);
10843               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10844                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10845
10846               if (expr1.X_add_number >= -0x8000
10847                   && expr1.X_add_number < 0x8000)
10848                 {
10849                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10850                                tempreg, tempreg, BFD_RELOC_LO16);
10851                 }
10852               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10853                 {
10854                   unsigned int dreg;
10855
10856                   /* If we are going to add in a base register, and the
10857                      target register and the base register are the same,
10858                      then we are using AT as a temporary register.  Since
10859                      we want to load the constant into AT, we add our
10860                      current AT (from the global offset table) and the
10861                      register into the register now, and pretend we were
10862                      not using a base register.  */
10863                   if (breg != op[0])
10864                     dreg = tempreg;
10865                   else
10866                     {
10867                       gas_assert (tempreg == AT);
10868                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10869                                    op[0], AT, breg);
10870                       dreg = op[0];
10871                       add_breg_early = 1;
10872                     }
10873
10874                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10875                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10876                                dreg, dreg, AT);
10877
10878                   used_at = 1;
10879                 }
10880               else
10881                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10882
10883               relax_switch ();
10884               offset_expr.X_add_number = expr1.X_add_number;
10885
10886               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10887                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10888               if (add_breg_early)
10889                 {
10890                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10891                                op[0], tempreg, breg);
10892                   breg = 0;
10893                   tempreg = op[0];
10894                 }
10895               relax_end ();
10896             }
10897           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10898             {
10899               relax_start (offset_expr.X_add_symbol);
10900               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10901                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10902               relax_switch ();
10903               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10904                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10905               relax_end ();
10906             }
10907           else
10908             {
10909               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10910                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10911             }
10912         }
10913       else if (mips_big_got && !HAVE_NEWABI)
10914         {
10915           int gpdelay;
10916           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10917           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10918           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10919
10920           /* This is the large GOT case.  If this is a reference to an
10921              external symbol, and there is no constant, we want
10922                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10923                addu     $tempreg,$tempreg,$gp
10924                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10925              or for lca or if tempreg is PIC_CALL_REG
10926                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10927                addu     $tempreg,$tempreg,$gp
10928                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10929              For a local symbol, we want
10930                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10931                nop
10932                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10933
10934              If we have a small constant, and this is a reference to
10935              an external symbol, we want
10936                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10937                addu     $tempreg,$tempreg,$gp
10938                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10939                nop
10940                addiu    $tempreg,$tempreg,<constant>
10941              For a local symbol, we want
10942                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10943                nop
10944                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10945
10946              If we have a large constant, and this is a reference to
10947              an external symbol, we want
10948                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10949                addu     $tempreg,$tempreg,$gp
10950                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10951                lui      $at,<hiconstant>
10952                addiu    $at,$at,<loconstant>
10953                addu     $tempreg,$tempreg,$at
10954              For a local symbol, we want
10955                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10956                lui      $at,<hiconstant>
10957                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10958                addu     $tempreg,$tempreg,$at
10959           */
10960
10961           expr1.X_add_number = offset_expr.X_add_number;
10962           offset_expr.X_add_number = 0;
10963           relax_start (offset_expr.X_add_symbol);
10964           gpdelay = reg_needs_delay (mips_gp_register);
10965           if (expr1.X_add_number == 0 && breg == 0
10966               && (call || tempreg == PIC_CALL_REG))
10967             {
10968               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10969               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10970             }
10971           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10972           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10973                        tempreg, tempreg, mips_gp_register);
10974           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10975                        tempreg, lw_reloc_type, tempreg);
10976           if (expr1.X_add_number == 0)
10977             {
10978               if (breg != 0)
10979                 {
10980                   /* We're going to put in an addu instruction using
10981                      tempreg, so we may as well insert the nop right
10982                      now.  */
10983                   load_delay_nop ();
10984                 }
10985             }
10986           else if (expr1.X_add_number >= -0x8000
10987                    && expr1.X_add_number < 0x8000)
10988             {
10989               load_delay_nop ();
10990               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10991                            tempreg, tempreg, BFD_RELOC_LO16);
10992             }
10993           else
10994             {
10995               unsigned int dreg;
10996
10997               /* If we are going to add in a base register, and the
10998                  target register and the base register are the same,
10999                  then we are using AT as a temporary register.  Since
11000                  we want to load the constant into AT, we add our
11001                  current AT (from the global offset table) and the
11002                  register into the register now, and pretend we were
11003                  not using a base register.  */
11004               if (breg != op[0])
11005                 dreg = tempreg;
11006               else
11007                 {
11008                   gas_assert (tempreg == AT);
11009                   load_delay_nop ();
11010                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11011                                op[0], AT, breg);
11012                   dreg = op[0];
11013                 }
11014
11015               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11016               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11017
11018               used_at = 1;
11019             }
11020           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11021           relax_switch ();
11022
11023           if (gpdelay)
11024             {
11025               /* This is needed because this instruction uses $gp, but
11026                  the first instruction on the main stream does not.  */
11027               macro_build (NULL, "nop", "");
11028             }
11029
11030           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11031                        local_reloc_type, mips_gp_register);
11032           if (expr1.X_add_number >= -0x8000
11033               && expr1.X_add_number < 0x8000)
11034             {
11035               load_delay_nop ();
11036               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11037                            tempreg, tempreg, BFD_RELOC_LO16);
11038               /* FIXME: If add_number is 0, and there was no base
11039                  register, the external symbol case ended with a load,
11040                  so if the symbol turns out to not be external, and
11041                  the next instruction uses tempreg, an unnecessary nop
11042                  will be inserted.  */
11043             }
11044           else
11045             {
11046               if (breg == op[0])
11047                 {
11048                   /* We must add in the base register now, as in the
11049                      external symbol case.  */
11050                   gas_assert (tempreg == AT);
11051                   load_delay_nop ();
11052                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11053                                op[0], AT, breg);
11054                   tempreg = op[0];
11055                   /* We set breg to 0 because we have arranged to add
11056                      it in in both cases.  */
11057                   breg = 0;
11058                 }
11059
11060               macro_build_lui (&expr1, AT);
11061               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11062                            AT, AT, BFD_RELOC_LO16);
11063               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11064                            tempreg, tempreg, AT);
11065               used_at = 1;
11066             }
11067           relax_end ();
11068         }
11069       else if (mips_big_got && HAVE_NEWABI)
11070         {
11071           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11072           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11073           int add_breg_early = 0;
11074
11075           /* This is the large GOT case.  If this is a reference to an
11076              external symbol, and there is no constant, we want
11077                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11078                add      $tempreg,$tempreg,$gp
11079                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11080              or for lca or if tempreg is PIC_CALL_REG
11081                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11082                add      $tempreg,$tempreg,$gp
11083                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11084
11085              If we have a small constant, and this is a reference to
11086              an external symbol, we want
11087                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11088                add      $tempreg,$tempreg,$gp
11089                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11090                addi     $tempreg,$tempreg,<constant>
11091
11092              If we have a large constant, and this is a reference to
11093              an external symbol, we want
11094                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11095                addu     $tempreg,$tempreg,$gp
11096                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11097                lui      $at,<hiconstant>
11098                addi     $at,$at,<loconstant>
11099                add      $tempreg,$tempreg,$at
11100
11101              If we have NewABI, and we know it's a local symbol, we want
11102                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
11103                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
11104              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11105
11106           relax_start (offset_expr.X_add_symbol);
11107
11108           expr1.X_add_number = offset_expr.X_add_number;
11109           offset_expr.X_add_number = 0;
11110
11111           if (expr1.X_add_number == 0 && breg == 0
11112               && (call || tempreg == PIC_CALL_REG))
11113             {
11114               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11115               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11116             }
11117           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11118           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11119                        tempreg, tempreg, mips_gp_register);
11120           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11121                        tempreg, lw_reloc_type, tempreg);
11122
11123           if (expr1.X_add_number == 0)
11124             ;
11125           else if (expr1.X_add_number >= -0x8000
11126                    && expr1.X_add_number < 0x8000)
11127             {
11128               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11129                            tempreg, tempreg, BFD_RELOC_LO16);
11130             }
11131           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11132             {
11133               unsigned int dreg;
11134
11135               /* If we are going to add in a base register, and the
11136                  target register and the base register are the same,
11137                  then we are using AT as a temporary register.  Since
11138                  we want to load the constant into AT, we add our
11139                  current AT (from the global offset table) and the
11140                  register into the register now, and pretend we were
11141                  not using a base register.  */
11142               if (breg != op[0])
11143                 dreg = tempreg;
11144               else
11145                 {
11146                   gas_assert (tempreg == AT);
11147                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11148                                op[0], AT, breg);
11149                   dreg = op[0];
11150                   add_breg_early = 1;
11151                 }
11152
11153               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11154               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11155
11156               used_at = 1;
11157             }
11158           else
11159             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11160
11161           relax_switch ();
11162           offset_expr.X_add_number = expr1.X_add_number;
11163           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11164                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11165           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11166                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
11167           if (add_breg_early)
11168             {
11169               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11170                            op[0], tempreg, breg);
11171               breg = 0;
11172               tempreg = op[0];
11173             }
11174           relax_end ();
11175         }
11176       else
11177         abort ();
11178
11179       if (breg != 0)
11180         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11181       break;
11182
11183     case M_MSGSND:
11184       gas_assert (!mips_opts.micromips);
11185       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11186       break;
11187
11188     case M_MSGLD:
11189       gas_assert (!mips_opts.micromips);
11190       macro_build (NULL, "c2", "C", 0x02);
11191       break;
11192
11193     case M_MSGLD_T:
11194       gas_assert (!mips_opts.micromips);
11195       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11196       break;
11197
11198     case M_MSGWAIT:
11199       gas_assert (!mips_opts.micromips);
11200       macro_build (NULL, "c2", "C", 3);
11201       break;
11202
11203     case M_MSGWAIT_T:
11204       gas_assert (!mips_opts.micromips);
11205       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11206       break;
11207
11208     case M_J_A:
11209       /* The j instruction may not be used in PIC code, since it
11210          requires an absolute address.  We convert it to a b
11211          instruction.  */
11212       if (mips_pic == NO_PIC)
11213         macro_build (&offset_expr, "j", "a");
11214       else
11215         macro_build (&offset_expr, "b", "p");
11216       break;
11217
11218       /* The jal instructions must be handled as macros because when
11219          generating PIC code they expand to multi-instruction
11220          sequences.  Normally they are simple instructions.  */
11221     case M_JALS_1:
11222       op[1] = op[0];
11223       op[0] = RA;
11224       /* Fall through.  */
11225     case M_JALS_2:
11226       gas_assert (mips_opts.micromips);
11227       if (mips_opts.insn32)
11228         {
11229           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11230           break;
11231         }
11232       jals = 1;
11233       goto jal;
11234     case M_JAL_1:
11235       op[1] = op[0];
11236       op[0] = RA;
11237       /* Fall through.  */
11238     case M_JAL_2:
11239     jal:
11240       if (mips_pic == NO_PIC)
11241         {
11242           s = jals ? "jalrs" : "jalr";
11243           if (mips_opts.micromips
11244               && !mips_opts.insn32
11245               && op[0] == RA
11246               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11247             macro_build (NULL, s, "mj", op[1]);
11248           else
11249             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11250         }
11251       else
11252         {
11253           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11254                            && mips_cprestore_offset >= 0);
11255
11256           if (op[1] != PIC_CALL_REG)
11257             as_warn (_("MIPS PIC call to register other than $25"));
11258
11259           s = ((mips_opts.micromips
11260                 && !mips_opts.insn32
11261                 && (!mips_opts.noreorder || cprestore))
11262                ? "jalrs" : "jalr");
11263           if (mips_opts.micromips
11264               && !mips_opts.insn32
11265               && op[0] == RA
11266               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11267             macro_build (NULL, s, "mj", op[1]);
11268           else
11269             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11270           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11271             {
11272               if (mips_cprestore_offset < 0)
11273                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11274               else
11275                 {
11276                   if (!mips_frame_reg_valid)
11277                     {
11278                       as_warn (_("no .frame pseudo-op used in PIC code"));
11279                       /* Quiet this warning.  */
11280                       mips_frame_reg_valid = 1;
11281                     }
11282                   if (!mips_cprestore_valid)
11283                     {
11284                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11285                       /* Quiet this warning.  */
11286                       mips_cprestore_valid = 1;
11287                     }
11288                   if (mips_opts.noreorder)
11289                     macro_build (NULL, "nop", "");
11290                   expr1.X_add_number = mips_cprestore_offset;
11291                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11292                                                 mips_gp_register,
11293                                                 mips_frame_reg,
11294                                                 HAVE_64BIT_ADDRESSES);
11295                 }
11296             }
11297         }
11298
11299       break;
11300
11301     case M_JALS_A:
11302       gas_assert (mips_opts.micromips);
11303       if (mips_opts.insn32)
11304         {
11305           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11306           break;
11307         }
11308       jals = 1;
11309       /* Fall through.  */
11310     case M_JAL_A:
11311       if (mips_pic == NO_PIC)
11312         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11313       else if (mips_pic == SVR4_PIC)
11314         {
11315           /* If this is a reference to an external symbol, and we are
11316              using a small GOT, we want
11317                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11318                nop
11319                jalr     $ra,$25
11320                nop
11321                lw       $gp,cprestore($sp)
11322              The cprestore value is set using the .cprestore
11323              pseudo-op.  If we are using a big GOT, we want
11324                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11325                addu     $25,$25,$gp
11326                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11327                nop
11328                jalr     $ra,$25
11329                nop
11330                lw       $gp,cprestore($sp)
11331              If the symbol is not external, we want
11332                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11333                nop
11334                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11335                jalr     $ra,$25
11336                nop
11337                lw $gp,cprestore($sp)
11338
11339              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11340              sequences above, minus nops, unless the symbol is local,
11341              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11342              GOT_DISP.  */
11343           if (HAVE_NEWABI)
11344             {
11345               if (!mips_big_got)
11346                 {
11347                   relax_start (offset_expr.X_add_symbol);
11348                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11349                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11350                                mips_gp_register);
11351                   relax_switch ();
11352                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11353                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11354                                mips_gp_register);
11355                   relax_end ();
11356                 }
11357               else
11358                 {
11359                   relax_start (offset_expr.X_add_symbol);
11360                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11361                                BFD_RELOC_MIPS_CALL_HI16);
11362                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11363                                PIC_CALL_REG, mips_gp_register);
11364                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11365                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11366                                PIC_CALL_REG);
11367                   relax_switch ();
11368                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11369                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11370                                mips_gp_register);
11371                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11372                                PIC_CALL_REG, PIC_CALL_REG,
11373                                BFD_RELOC_MIPS_GOT_OFST);
11374                   relax_end ();
11375                 }
11376
11377               macro_build_jalr (&offset_expr, 0);
11378             }
11379           else
11380             {
11381               relax_start (offset_expr.X_add_symbol);
11382               if (!mips_big_got)
11383                 {
11384                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11385                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11386                                mips_gp_register);
11387                   load_delay_nop ();
11388                   relax_switch ();
11389                 }
11390               else
11391                 {
11392                   int gpdelay;
11393
11394                   gpdelay = reg_needs_delay (mips_gp_register);
11395                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11396                                BFD_RELOC_MIPS_CALL_HI16);
11397                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11398                                PIC_CALL_REG, mips_gp_register);
11399                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11400                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11401                                PIC_CALL_REG);
11402                   load_delay_nop ();
11403                   relax_switch ();
11404                   if (gpdelay)
11405                     macro_build (NULL, "nop", "");
11406                 }
11407               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11408                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11409                            mips_gp_register);
11410               load_delay_nop ();
11411               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11412                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11413               relax_end ();
11414               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11415
11416               if (mips_cprestore_offset < 0)
11417                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11418               else
11419                 {
11420                   if (!mips_frame_reg_valid)
11421                     {
11422                       as_warn (_("no .frame pseudo-op used in PIC code"));
11423                       /* Quiet this warning.  */
11424                       mips_frame_reg_valid = 1;
11425                     }
11426                   if (!mips_cprestore_valid)
11427                     {
11428                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11429                       /* Quiet this warning.  */
11430                       mips_cprestore_valid = 1;
11431                     }
11432                   if (mips_opts.noreorder)
11433                     macro_build (NULL, "nop", "");
11434                   expr1.X_add_number = mips_cprestore_offset;
11435                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11436                                                 mips_gp_register,
11437                                                 mips_frame_reg,
11438                                                 HAVE_64BIT_ADDRESSES);
11439                 }
11440             }
11441         }
11442       else if (mips_pic == VXWORKS_PIC)
11443         as_bad (_("non-PIC jump used in PIC library"));
11444       else
11445         abort ();
11446
11447       break;
11448
11449     case M_LBUE_AB:
11450       s = "lbue";
11451       fmt = "t,+j(b)";
11452       offbits = 9;
11453       goto ld_st;
11454     case M_LHUE_AB:
11455       s = "lhue";
11456       fmt = "t,+j(b)";
11457       offbits = 9;
11458       goto ld_st;
11459     case M_LBE_AB:
11460       s = "lbe";
11461       fmt = "t,+j(b)";
11462       offbits = 9;
11463       goto ld_st;
11464     case M_LHE_AB:
11465       s = "lhe";
11466       fmt = "t,+j(b)";
11467       offbits = 9;
11468       goto ld_st;
11469     case M_LLE_AB:
11470       s = "lle";
11471       fmt = "t,+j(b)";
11472       offbits = 9;
11473       goto ld_st;
11474     case M_LWE_AB:
11475       s = "lwe";
11476       fmt = "t,+j(b)";
11477       offbits = 9;
11478       goto ld_st;
11479     case M_LWLE_AB:
11480       s = "lwle";
11481       fmt = "t,+j(b)";
11482       offbits = 9;
11483       goto ld_st;
11484     case M_LWRE_AB:
11485       s = "lwre";
11486       fmt = "t,+j(b)";
11487       offbits = 9;
11488       goto ld_st;
11489     case M_SBE_AB:
11490       s = "sbe";
11491       fmt = "t,+j(b)";
11492       offbits = 9;
11493       goto ld_st;
11494     case M_SCE_AB:
11495       s = "sce";
11496       fmt = "t,+j(b)";
11497       offbits = 9;
11498       goto ld_st;
11499     case M_SHE_AB:
11500       s = "she";
11501       fmt = "t,+j(b)";
11502       offbits = 9;
11503       goto ld_st;
11504     case M_SWE_AB:
11505       s = "swe";
11506       fmt = "t,+j(b)";
11507       offbits = 9;
11508       goto ld_st;
11509     case M_SWLE_AB:
11510       s = "swle";
11511       fmt = "t,+j(b)";
11512       offbits = 9;
11513       goto ld_st;
11514     case M_SWRE_AB:
11515       s = "swre";
11516       fmt = "t,+j(b)";
11517       offbits = 9;
11518       goto ld_st;
11519     case M_ACLR_AB:
11520       s = "aclr";
11521       fmt = "\\,~(b)";
11522       offbits = 12;
11523       goto ld_st;
11524     case M_ASET_AB:
11525       s = "aset";
11526       fmt = "\\,~(b)";
11527       offbits = 12;
11528       goto ld_st;
11529     case M_LB_AB:
11530       s = "lb";
11531       fmt = "t,o(b)";
11532       goto ld;
11533     case M_LBU_AB:
11534       s = "lbu";
11535       fmt = "t,o(b)";
11536       goto ld;
11537     case M_LH_AB:
11538       s = "lh";
11539       fmt = "t,o(b)";
11540       goto ld;
11541     case M_LHU_AB:
11542       s = "lhu";
11543       fmt = "t,o(b)";
11544       goto ld;
11545     case M_LW_AB:
11546       s = "lw";
11547       fmt = "t,o(b)";
11548       goto ld;
11549     case M_LWC0_AB:
11550       gas_assert (!mips_opts.micromips);
11551       s = "lwc0";
11552       fmt = "E,o(b)";
11553       /* Itbl support may require additional care here.  */
11554       coproc = 1;
11555       goto ld_st;
11556     case M_LWC1_AB:
11557       s = "lwc1";
11558       fmt = "T,o(b)";
11559       /* Itbl support may require additional care here.  */
11560       coproc = 1;
11561       goto ld_st;
11562     case M_LWC2_AB:
11563       s = "lwc2";
11564       fmt = COP12_FMT;
11565       offbits = (mips_opts.micromips ? 12
11566                  : ISA_IS_R6 (mips_opts.isa) ? 11
11567                  : 16);
11568       /* Itbl support may require additional care here.  */
11569       coproc = 1;
11570       goto ld_st;
11571     case M_LWC3_AB:
11572       gas_assert (!mips_opts.micromips);
11573       s = "lwc3";
11574       fmt = "E,o(b)";
11575       /* Itbl support may require additional care here.  */
11576       coproc = 1;
11577       goto ld_st;
11578     case M_LWL_AB:
11579       s = "lwl";
11580       fmt = MEM12_FMT;
11581       offbits = (mips_opts.micromips ? 12 : 16);
11582       goto ld_st;
11583     case M_LWR_AB:
11584       s = "lwr";
11585       fmt = MEM12_FMT;
11586       offbits = (mips_opts.micromips ? 12 : 16);
11587       goto ld_st;
11588     case M_LDC1_AB:
11589       s = "ldc1";
11590       fmt = "T,o(b)";
11591       /* Itbl support may require additional care here.  */
11592       coproc = 1;
11593       goto ld_st;
11594     case M_LDC2_AB:
11595       s = "ldc2";
11596       fmt = COP12_FMT;
11597       offbits = (mips_opts.micromips ? 12
11598                  : ISA_IS_R6 (mips_opts.isa) ? 11
11599                  : 16);
11600       /* Itbl support may require additional care here.  */
11601       coproc = 1;
11602       goto ld_st;
11603     case M_LQC2_AB:
11604       s = "lqc2";
11605       fmt = "+7,o(b)";
11606       /* Itbl support may require additional care here.  */
11607       coproc = 1;
11608       goto ld_st;
11609     case M_LDC3_AB:
11610       s = "ldc3";
11611       fmt = "E,o(b)";
11612       /* Itbl support may require additional care here.  */
11613       coproc = 1;
11614       goto ld_st;
11615     case M_LDL_AB:
11616       s = "ldl";
11617       fmt = MEM12_FMT;
11618       offbits = (mips_opts.micromips ? 12 : 16);
11619       goto ld_st;
11620     case M_LDR_AB:
11621       s = "ldr";
11622       fmt = MEM12_FMT;
11623       offbits = (mips_opts.micromips ? 12 : 16);
11624       goto ld_st;
11625     case M_LL_AB:
11626       s = "ll";
11627       fmt = LL_SC_FMT;
11628       offbits = (mips_opts.micromips ? 12
11629                  : ISA_IS_R6 (mips_opts.isa) ? 9
11630                  : 16);
11631       goto ld;
11632     case M_LLD_AB:
11633       s = "lld";
11634       fmt = LL_SC_FMT;
11635       offbits = (mips_opts.micromips ? 12
11636                  : ISA_IS_R6 (mips_opts.isa) ? 9
11637                  : 16);
11638       goto ld;
11639     case M_LWU_AB:
11640       s = "lwu";
11641       fmt = MEM12_FMT;
11642       offbits = (mips_opts.micromips ? 12 : 16);
11643       goto ld;
11644     case M_LWP_AB:
11645       gas_assert (mips_opts.micromips);
11646       s = "lwp";
11647       fmt = "t,~(b)";
11648       offbits = 12;
11649       lp = 1;
11650       goto ld;
11651     case M_LDP_AB:
11652       gas_assert (mips_opts.micromips);
11653       s = "ldp";
11654       fmt = "t,~(b)";
11655       offbits = 12;
11656       lp = 1;
11657       goto ld;
11658     case M_LWM_AB:
11659       gas_assert (mips_opts.micromips);
11660       s = "lwm";
11661       fmt = "n,~(b)";
11662       offbits = 12;
11663       goto ld_st;
11664     case M_LDM_AB:
11665       gas_assert (mips_opts.micromips);
11666       s = "ldm";
11667       fmt = "n,~(b)";
11668       offbits = 12;
11669       goto ld_st;
11670
11671     ld:
11672       /* We don't want to use $0 as tempreg.  */
11673       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11674         goto ld_st;
11675       else
11676         tempreg = op[0] + lp;
11677       goto ld_noat;
11678
11679     case M_SB_AB:
11680       s = "sb";
11681       fmt = "t,o(b)";
11682       goto ld_st;
11683     case M_SH_AB:
11684       s = "sh";
11685       fmt = "t,o(b)";
11686       goto ld_st;
11687     case M_SW_AB:
11688       s = "sw";
11689       fmt = "t,o(b)";
11690       goto ld_st;
11691     case M_SWC0_AB:
11692       gas_assert (!mips_opts.micromips);
11693       s = "swc0";
11694       fmt = "E,o(b)";
11695       /* Itbl support may require additional care here.  */
11696       coproc = 1;
11697       goto ld_st;
11698     case M_SWC1_AB:
11699       s = "swc1";
11700       fmt = "T,o(b)";
11701       /* Itbl support may require additional care here.  */
11702       coproc = 1;
11703       goto ld_st;
11704     case M_SWC2_AB:
11705       s = "swc2";
11706       fmt = COP12_FMT;
11707       offbits = (mips_opts.micromips ? 12
11708                  : ISA_IS_R6 (mips_opts.isa) ? 11
11709                  : 16);
11710       /* Itbl support may require additional care here.  */
11711       coproc = 1;
11712       goto ld_st;
11713     case M_SWC3_AB:
11714       gas_assert (!mips_opts.micromips);
11715       s = "swc3";
11716       fmt = "E,o(b)";
11717       /* Itbl support may require additional care here.  */
11718       coproc = 1;
11719       goto ld_st;
11720     case M_SWL_AB:
11721       s = "swl";
11722       fmt = MEM12_FMT;
11723       offbits = (mips_opts.micromips ? 12 : 16);
11724       goto ld_st;
11725     case M_SWR_AB:
11726       s = "swr";
11727       fmt = MEM12_FMT;
11728       offbits = (mips_opts.micromips ? 12 : 16);
11729       goto ld_st;
11730     case M_SC_AB:
11731       s = "sc";
11732       fmt = LL_SC_FMT;
11733       offbits = (mips_opts.micromips ? 12
11734                  : ISA_IS_R6 (mips_opts.isa) ? 9
11735                  : 16);
11736       goto ld_st;
11737     case M_SCD_AB:
11738       s = "scd";
11739       fmt = LL_SC_FMT;
11740       offbits = (mips_opts.micromips ? 12
11741                  : ISA_IS_R6 (mips_opts.isa) ? 9
11742                  : 16);
11743       goto ld_st;
11744     case M_CACHE_AB:
11745       s = "cache";
11746       fmt = (mips_opts.micromips ? "k,~(b)"
11747              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11748              : "k,o(b)");
11749       offbits = (mips_opts.micromips ? 12
11750                  : ISA_IS_R6 (mips_opts.isa) ? 9
11751                  : 16);
11752       goto ld_st;
11753     case M_CACHEE_AB:
11754       s = "cachee";
11755       fmt = "k,+j(b)";
11756       offbits = 9;
11757       goto ld_st;
11758     case M_PREF_AB:
11759       s = "pref";
11760       fmt = (mips_opts.micromips ? "k,~(b)"
11761              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11762              : "k,o(b)");
11763       offbits = (mips_opts.micromips ? 12
11764                  : ISA_IS_R6 (mips_opts.isa) ? 9
11765                  : 16);
11766       goto ld_st;
11767     case M_PREFE_AB:
11768       s = "prefe";
11769       fmt = "k,+j(b)";
11770       offbits = 9;
11771       goto ld_st;
11772     case M_SDC1_AB:
11773       s = "sdc1";
11774       fmt = "T,o(b)";
11775       coproc = 1;
11776       /* Itbl support may require additional care here.  */
11777       goto ld_st;
11778     case M_SDC2_AB:
11779       s = "sdc2";
11780       fmt = COP12_FMT;
11781       offbits = (mips_opts.micromips ? 12
11782                  : ISA_IS_R6 (mips_opts.isa) ? 11
11783                  : 16);
11784       /* Itbl support may require additional care here.  */
11785       coproc = 1;
11786       goto ld_st;
11787     case M_SQC2_AB:
11788       s = "sqc2";
11789       fmt = "+7,o(b)";
11790       /* Itbl support may require additional care here.  */
11791       coproc = 1;
11792       goto ld_st;
11793     case M_SDC3_AB:
11794       gas_assert (!mips_opts.micromips);
11795       s = "sdc3";
11796       fmt = "E,o(b)";
11797       /* Itbl support may require additional care here.  */
11798       coproc = 1;
11799       goto ld_st;
11800     case M_SDL_AB:
11801       s = "sdl";
11802       fmt = MEM12_FMT;
11803       offbits = (mips_opts.micromips ? 12 : 16);
11804       goto ld_st;
11805     case M_SDR_AB:
11806       s = "sdr";
11807       fmt = MEM12_FMT;
11808       offbits = (mips_opts.micromips ? 12 : 16);
11809       goto ld_st;
11810     case M_SWP_AB:
11811       gas_assert (mips_opts.micromips);
11812       s = "swp";
11813       fmt = "t,~(b)";
11814       offbits = 12;
11815       goto ld_st;
11816     case M_SDP_AB:
11817       gas_assert (mips_opts.micromips);
11818       s = "sdp";
11819       fmt = "t,~(b)";
11820       offbits = 12;
11821       goto ld_st;
11822     case M_SWM_AB:
11823       gas_assert (mips_opts.micromips);
11824       s = "swm";
11825       fmt = "n,~(b)";
11826       offbits = 12;
11827       goto ld_st;
11828     case M_SDM_AB:
11829       gas_assert (mips_opts.micromips);
11830       s = "sdm";
11831       fmt = "n,~(b)";
11832       offbits = 12;
11833
11834     ld_st:
11835       tempreg = AT;
11836     ld_noat:
11837       breg = op[2];
11838       if (small_offset_p (0, align, 16))
11839         {
11840           /* The first case exists for M_LD_AB and M_SD_AB, which are
11841              macros for o32 but which should act like normal instructions
11842              otherwise.  */
11843           if (offbits == 16)
11844             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11845                          offset_reloc[1], offset_reloc[2], breg);
11846           else if (small_offset_p (0, align, offbits))
11847             {
11848               if (offbits == 0)
11849                 macro_build (NULL, s, fmt, op[0], breg);
11850               else
11851                 macro_build (NULL, s, fmt, op[0],
11852                              (int) offset_expr.X_add_number, breg);
11853             }
11854           else
11855             {
11856               if (tempreg == AT)
11857                 used_at = 1;
11858               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11859                            tempreg, breg, -1, offset_reloc[0],
11860                            offset_reloc[1], offset_reloc[2]);
11861               if (offbits == 0)
11862                 macro_build (NULL, s, fmt, op[0], tempreg);
11863               else
11864                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11865             }
11866           break;
11867         }
11868
11869       if (tempreg == AT)
11870         used_at = 1;
11871
11872       if (offset_expr.X_op != O_constant
11873           && offset_expr.X_op != O_symbol)
11874         {
11875           as_bad (_("expression too complex"));
11876           offset_expr.X_op = O_constant;
11877         }
11878
11879       if (HAVE_32BIT_ADDRESSES
11880           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11881         {
11882           char value [32];
11883
11884           sprintf_vma (value, offset_expr.X_add_number);
11885           as_bad (_("number (0x%s) larger than 32 bits"), value);
11886         }
11887
11888       /* A constant expression in PIC code can be handled just as it
11889          is in non PIC code.  */
11890       if (offset_expr.X_op == O_constant)
11891         {
11892           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11893                                                  offbits == 0 ? 16 : offbits);
11894           offset_expr.X_add_number -= expr1.X_add_number;
11895
11896           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11897           if (breg != 0)
11898             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11899                          tempreg, tempreg, breg);
11900           if (offbits == 0)
11901             {
11902               if (offset_expr.X_add_number != 0)
11903                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11904                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11905               macro_build (NULL, s, fmt, op[0], tempreg);
11906             }
11907           else if (offbits == 16)
11908             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11909           else
11910             macro_build (NULL, s, fmt, op[0],
11911                          (int) offset_expr.X_add_number, tempreg);
11912         }
11913       else if (offbits != 16)
11914         {
11915           /* The offset field is too narrow to be used for a low-part
11916              relocation, so load the whole address into the auxiliary
11917              register.  */
11918           load_address (tempreg, &offset_expr, &used_at);
11919           if (breg != 0)
11920             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11921                          tempreg, tempreg, breg);
11922           if (offbits == 0)
11923             macro_build (NULL, s, fmt, op[0], tempreg);
11924           else
11925             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11926         }
11927       else if (mips_pic == NO_PIC)
11928         {
11929           /* If this is a reference to a GP relative symbol, and there
11930              is no base register, we want
11931                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11932              Otherwise, if there is no base register, we want
11933                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11934                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11935              If we have a constant, we need two instructions anyhow,
11936              so we always use the latter form.
11937
11938              If we have a base register, and this is a reference to a
11939              GP relative symbol, we want
11940                addu     $tempreg,$breg,$gp
11941                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11942              Otherwise we want
11943                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11944                addu     $tempreg,$tempreg,$breg
11945                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11946              With a constant we always use the latter case.
11947
11948              With 64bit address space and no base register and $at usable,
11949              we want
11950                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11951                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11952                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11953                dsll32   $tempreg,0
11954                daddu    $tempreg,$at
11955                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11956              If we have a base register, we want
11957                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11958                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11959                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11960                daddu    $at,$breg
11961                dsll32   $tempreg,0
11962                daddu    $tempreg,$at
11963                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11964
11965              Without $at we can't generate the optimal path for superscalar
11966              processors here since this would require two temporary registers.
11967                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11968                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11969                dsll     $tempreg,16
11970                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11971                dsll     $tempreg,16
11972                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11973              If we have a base register, we want
11974                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11975                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11976                dsll     $tempreg,16
11977                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11978                dsll     $tempreg,16
11979                daddu    $tempreg,$tempreg,$breg
11980                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11981
11982              For GP relative symbols in 64bit address space we can use
11983              the same sequence as in 32bit address space.  */
11984           if (HAVE_64BIT_SYMBOLS)
11985             {
11986               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11987                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11988                 {
11989                   relax_start (offset_expr.X_add_symbol);
11990                   if (breg == 0)
11991                     {
11992                       macro_build (&offset_expr, s, fmt, op[0],
11993                                    BFD_RELOC_GPREL16, mips_gp_register);
11994                     }
11995                   else
11996                     {
11997                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11998                                    tempreg, breg, mips_gp_register);
11999                       macro_build (&offset_expr, s, fmt, op[0],
12000                                    BFD_RELOC_GPREL16, tempreg);
12001                     }
12002                   relax_switch ();
12003                 }
12004
12005               if (used_at == 0 && mips_opts.at)
12006                 {
12007                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12008                                BFD_RELOC_MIPS_HIGHEST);
12009                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
12010                                BFD_RELOC_HI16_S);
12011                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12012                                tempreg, BFD_RELOC_MIPS_HIGHER);
12013                   if (breg != 0)
12014                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12015                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12016                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12017                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12018                                tempreg);
12019                   used_at = 1;
12020                 }
12021               else
12022                 {
12023                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12024                                BFD_RELOC_MIPS_HIGHEST);
12025                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12026                                tempreg, BFD_RELOC_MIPS_HIGHER);
12027                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12028                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12029                                tempreg, BFD_RELOC_HI16_S);
12030                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12031                   if (breg != 0)
12032                     macro_build (NULL, "daddu", "d,v,t",
12033                                  tempreg, tempreg, breg);
12034                   macro_build (&offset_expr, s, fmt, op[0],
12035                                BFD_RELOC_LO16, tempreg);
12036                 }
12037
12038               if (mips_relax.sequence)
12039                 relax_end ();
12040               break;
12041             }
12042
12043           if (breg == 0)
12044             {
12045               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12046                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12047                 {
12048                   relax_start (offset_expr.X_add_symbol);
12049                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12050                                mips_gp_register);
12051                   relax_switch ();
12052                 }
12053               macro_build_lui (&offset_expr, tempreg);
12054               macro_build (&offset_expr, s, fmt, op[0],
12055                            BFD_RELOC_LO16, tempreg);
12056               if (mips_relax.sequence)
12057                 relax_end ();
12058             }
12059           else
12060             {
12061               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12062                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12063                 {
12064                   relax_start (offset_expr.X_add_symbol);
12065                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12066                                tempreg, breg, mips_gp_register);
12067                   macro_build (&offset_expr, s, fmt, op[0],
12068                                BFD_RELOC_GPREL16, tempreg);
12069                   relax_switch ();
12070                 }
12071               macro_build_lui (&offset_expr, tempreg);
12072               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12073                            tempreg, tempreg, breg);
12074               macro_build (&offset_expr, s, fmt, op[0],
12075                            BFD_RELOC_LO16, tempreg);
12076               if (mips_relax.sequence)
12077                 relax_end ();
12078             }
12079         }
12080       else if (!mips_big_got)
12081         {
12082           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12083
12084           /* If this is a reference to an external symbol, we want
12085                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12086                nop
12087                <op>     op[0],0($tempreg)
12088              Otherwise we want
12089                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12090                nop
12091                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12092                <op>     op[0],0($tempreg)
12093
12094              For NewABI, we want
12095                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12096                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12097
12098              If there is a base register, we add it to $tempreg before
12099              the <op>.  If there is a constant, we stick it in the
12100              <op> instruction.  We don't handle constants larger than
12101              16 bits, because we have no way to load the upper 16 bits
12102              (actually, we could handle them for the subset of cases
12103              in which we are not using $at).  */
12104           gas_assert (offset_expr.X_op == O_symbol);
12105           if (HAVE_NEWABI)
12106             {
12107               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12108                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12109               if (breg != 0)
12110                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12111                              tempreg, tempreg, breg);
12112               macro_build (&offset_expr, s, fmt, op[0],
12113                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
12114               break;
12115             }
12116           expr1.X_add_number = offset_expr.X_add_number;
12117           offset_expr.X_add_number = 0;
12118           if (expr1.X_add_number < -0x8000
12119               || expr1.X_add_number >= 0x8000)
12120             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12121           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12122                        lw_reloc_type, mips_gp_register);
12123           load_delay_nop ();
12124           relax_start (offset_expr.X_add_symbol);
12125           relax_switch ();
12126           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12127                        tempreg, BFD_RELOC_LO16);
12128           relax_end ();
12129           if (breg != 0)
12130             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12131                          tempreg, tempreg, breg);
12132           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12133         }
12134       else if (mips_big_got && !HAVE_NEWABI)
12135         {
12136           int gpdelay;
12137
12138           /* If this is a reference to an external symbol, we want
12139                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12140                addu     $tempreg,$tempreg,$gp
12141                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12142                <op>     op[0],0($tempreg)
12143              Otherwise we want
12144                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12145                nop
12146                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12147                <op>     op[0],0($tempreg)
12148              If there is a base register, we add it to $tempreg before
12149              the <op>.  If there is a constant, we stick it in the
12150              <op> instruction.  We don't handle constants larger than
12151              16 bits, because we have no way to load the upper 16 bits
12152              (actually, we could handle them for the subset of cases
12153              in which we are not using $at).  */
12154           gas_assert (offset_expr.X_op == O_symbol);
12155           expr1.X_add_number = offset_expr.X_add_number;
12156           offset_expr.X_add_number = 0;
12157           if (expr1.X_add_number < -0x8000
12158               || expr1.X_add_number >= 0x8000)
12159             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12160           gpdelay = reg_needs_delay (mips_gp_register);
12161           relax_start (offset_expr.X_add_symbol);
12162           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12163                        BFD_RELOC_MIPS_GOT_HI16);
12164           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12165                        mips_gp_register);
12166           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12167                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12168           relax_switch ();
12169           if (gpdelay)
12170             macro_build (NULL, "nop", "");
12171           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12172                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12173           load_delay_nop ();
12174           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12175                        tempreg, BFD_RELOC_LO16);
12176           relax_end ();
12177
12178           if (breg != 0)
12179             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12180                          tempreg, tempreg, breg);
12181           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12182         }
12183       else if (mips_big_got && HAVE_NEWABI)
12184         {
12185           /* If this is a reference to an external symbol, we want
12186                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12187                add      $tempreg,$tempreg,$gp
12188                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12189                <op>     op[0],<ofst>($tempreg)
12190              Otherwise, for local symbols, we want:
12191                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12192                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12193           gas_assert (offset_expr.X_op == O_symbol);
12194           expr1.X_add_number = offset_expr.X_add_number;
12195           offset_expr.X_add_number = 0;
12196           if (expr1.X_add_number < -0x8000
12197               || expr1.X_add_number >= 0x8000)
12198             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12199           relax_start (offset_expr.X_add_symbol);
12200           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12201                        BFD_RELOC_MIPS_GOT_HI16);
12202           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12203                        mips_gp_register);
12204           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12205                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12206           if (breg != 0)
12207             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12208                          tempreg, tempreg, breg);
12209           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12210
12211           relax_switch ();
12212           offset_expr.X_add_number = expr1.X_add_number;
12213           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12214                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12215           if (breg != 0)
12216             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12217                          tempreg, tempreg, breg);
12218           macro_build (&offset_expr, s, fmt, op[0],
12219                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12220           relax_end ();
12221         }
12222       else
12223         abort ();
12224
12225       break;
12226
12227     case M_JRADDIUSP:
12228       gas_assert (mips_opts.micromips);
12229       gas_assert (mips_opts.insn32);
12230       start_noreorder ();
12231       macro_build (NULL, "jr", "s", RA);
12232       expr1.X_add_number = op[0] << 2;
12233       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12234       end_noreorder ();
12235       break;
12236
12237     case M_JRC:
12238       gas_assert (mips_opts.micromips);
12239       gas_assert (mips_opts.insn32);
12240       macro_build (NULL, "jr", "s", op[0]);
12241       if (mips_opts.noreorder)
12242         macro_build (NULL, "nop", "");
12243       break;
12244
12245     case M_LI:
12246     case M_LI_S:
12247       load_register (op[0], &imm_expr, 0);
12248       break;
12249
12250     case M_DLI:
12251       load_register (op[0], &imm_expr, 1);
12252       break;
12253
12254     case M_LI_SS:
12255       if (imm_expr.X_op == O_constant)
12256         {
12257           used_at = 1;
12258           load_register (AT, &imm_expr, 0);
12259           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12260           break;
12261         }
12262       else
12263         {
12264           gas_assert (imm_expr.X_op == O_absent
12265                       && offset_expr.X_op == O_symbol
12266                       && strcmp (segment_name (S_GET_SEGMENT
12267                                                (offset_expr.X_add_symbol)),
12268                                  ".lit4") == 0
12269                       && offset_expr.X_add_number == 0);
12270           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12271                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12272           break;
12273         }
12274
12275     case M_LI_D:
12276       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12277          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12278          order 32 bits of the value and the low order 32 bits are either
12279          zero or in OFFSET_EXPR.  */
12280       if (imm_expr.X_op == O_constant)
12281         {
12282           if (GPR_SIZE == 64)
12283             load_register (op[0], &imm_expr, 1);
12284           else
12285             {
12286               int hreg, lreg;
12287
12288               if (target_big_endian)
12289                 {
12290                   hreg = op[0];
12291                   lreg = op[0] + 1;
12292                 }
12293               else
12294                 {
12295                   hreg = op[0] + 1;
12296                   lreg = op[0];
12297                 }
12298
12299               if (hreg <= 31)
12300                 load_register (hreg, &imm_expr, 0);
12301               if (lreg <= 31)
12302                 {
12303                   if (offset_expr.X_op == O_absent)
12304                     move_register (lreg, 0);
12305                   else
12306                     {
12307                       gas_assert (offset_expr.X_op == O_constant);
12308                       load_register (lreg, &offset_expr, 0);
12309                     }
12310                 }
12311             }
12312           break;
12313         }
12314       gas_assert (imm_expr.X_op == O_absent);
12315
12316       /* We know that sym is in the .rdata section.  First we get the
12317          upper 16 bits of the address.  */
12318       if (mips_pic == NO_PIC)
12319         {
12320           macro_build_lui (&offset_expr, AT);
12321           used_at = 1;
12322         }
12323       else
12324         {
12325           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12326                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12327           used_at = 1;
12328         }
12329
12330       /* Now we load the register(s).  */
12331       if (GPR_SIZE == 64)
12332         {
12333           used_at = 1;
12334           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12335                        BFD_RELOC_LO16, AT);
12336         }
12337       else
12338         {
12339           used_at = 1;
12340           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12341                        BFD_RELOC_LO16, AT);
12342           if (op[0] != RA)
12343             {
12344               /* FIXME: How in the world do we deal with the possible
12345                  overflow here?  */
12346               offset_expr.X_add_number += 4;
12347               macro_build (&offset_expr, "lw", "t,o(b)",
12348                            op[0] + 1, BFD_RELOC_LO16, AT);
12349             }
12350         }
12351       break;
12352
12353     case M_LI_DD:
12354       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12355          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12356          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12357          the value and the low order 32 bits are either zero or in
12358          OFFSET_EXPR.  */
12359       if (imm_expr.X_op == O_constant)
12360         {
12361           used_at = 1;
12362           load_register (AT, &imm_expr, FPR_SIZE == 64);
12363           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12364             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12365           else
12366             {
12367               if (ISA_HAS_MXHC1 (mips_opts.isa))
12368                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12369               else if (FPR_SIZE != 32)
12370                 as_bad (_("Unable to generate `%s' compliant code "
12371                           "without mthc1"),
12372                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12373               else
12374                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12375               if (offset_expr.X_op == O_absent)
12376                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12377               else
12378                 {
12379                   gas_assert (offset_expr.X_op == O_constant);
12380                   load_register (AT, &offset_expr, 0);
12381                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12382                 }
12383             }
12384           break;
12385         }
12386
12387       gas_assert (imm_expr.X_op == O_absent
12388                   && offset_expr.X_op == O_symbol
12389                   && offset_expr.X_add_number == 0);
12390       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12391       if (strcmp (s, ".lit8") == 0)
12392         {
12393           op[2] = mips_gp_register;
12394           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12395           offset_reloc[1] = BFD_RELOC_UNUSED;
12396           offset_reloc[2] = BFD_RELOC_UNUSED;
12397         }
12398       else
12399         {
12400           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12401           used_at = 1;
12402           if (mips_pic != NO_PIC)
12403             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12404                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12405           else
12406             {
12407               /* FIXME: This won't work for a 64 bit address.  */
12408               macro_build_lui (&offset_expr, AT);
12409             }
12410
12411           op[2] = AT;
12412           offset_reloc[0] = BFD_RELOC_LO16;
12413           offset_reloc[1] = BFD_RELOC_UNUSED;
12414           offset_reloc[2] = BFD_RELOC_UNUSED;
12415         }
12416       align = 8;
12417       /* Fall through */
12418
12419     case M_L_DAB:
12420       /*
12421        * The MIPS assembler seems to check for X_add_number not
12422        * being double aligned and generating:
12423        *        lui     at,%hi(foo+1)
12424        *        addu    at,at,v1
12425        *        addiu   at,at,%lo(foo+1)
12426        *        lwc1    f2,0(at)
12427        *        lwc1    f3,4(at)
12428        * But, the resulting address is the same after relocation so why
12429        * generate the extra instruction?
12430        */
12431       /* Itbl support may require additional care here.  */
12432       coproc = 1;
12433       fmt = "T,o(b)";
12434       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12435         {
12436           s = "ldc1";
12437           goto ld_st;
12438         }
12439       s = "lwc1";
12440       goto ldd_std;
12441
12442     case M_S_DAB:
12443       gas_assert (!mips_opts.micromips);
12444       /* Itbl support may require additional care here.  */
12445       coproc = 1;
12446       fmt = "T,o(b)";
12447       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12448         {
12449           s = "sdc1";
12450           goto ld_st;
12451         }
12452       s = "swc1";
12453       goto ldd_std;
12454
12455     case M_LQ_AB:
12456       fmt = "t,o(b)";
12457       s = "lq";
12458       goto ld;
12459
12460     case M_SQ_AB:
12461       fmt = "t,o(b)";
12462       s = "sq";
12463       goto ld_st;
12464
12465     case M_LD_AB:
12466       fmt = "t,o(b)";
12467       if (GPR_SIZE == 64)
12468         {
12469           s = "ld";
12470           goto ld;
12471         }
12472       s = "lw";
12473       goto ldd_std;
12474
12475     case M_SD_AB:
12476       fmt = "t,o(b)";
12477       if (GPR_SIZE == 64)
12478         {
12479           s = "sd";
12480           goto ld_st;
12481         }
12482       s = "sw";
12483
12484     ldd_std:
12485       /* Even on a big endian machine $fn comes before $fn+1.  We have
12486          to adjust when loading from memory.  We set coproc if we must
12487          load $fn+1 first.  */
12488       /* Itbl support may require additional care here.  */
12489       if (!target_big_endian)
12490         coproc = 0;
12491
12492       breg = op[2];
12493       if (small_offset_p (0, align, 16))
12494         {
12495           ep = &offset_expr;
12496           if (!small_offset_p (4, align, 16))
12497             {
12498               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12499                            -1, offset_reloc[0], offset_reloc[1],
12500                            offset_reloc[2]);
12501               expr1.X_add_number = 0;
12502               ep = &expr1;
12503               breg = AT;
12504               used_at = 1;
12505               offset_reloc[0] = BFD_RELOC_LO16;
12506               offset_reloc[1] = BFD_RELOC_UNUSED;
12507               offset_reloc[2] = BFD_RELOC_UNUSED;
12508             }
12509           if (strcmp (s, "lw") == 0 && op[0] == breg)
12510             {
12511               ep->X_add_number += 4;
12512               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12513                            offset_reloc[1], offset_reloc[2], breg);
12514               ep->X_add_number -= 4;
12515               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12516                            offset_reloc[1], offset_reloc[2], breg);
12517             }
12518           else
12519             {
12520               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12521                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12522                            breg);
12523               ep->X_add_number += 4;
12524               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12525                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12526                            breg);
12527             }
12528           break;
12529         }
12530
12531       if (offset_expr.X_op != O_symbol
12532           && offset_expr.X_op != O_constant)
12533         {
12534           as_bad (_("expression too complex"));
12535           offset_expr.X_op = O_constant;
12536         }
12537
12538       if (HAVE_32BIT_ADDRESSES
12539           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12540         {
12541           char value [32];
12542
12543           sprintf_vma (value, offset_expr.X_add_number);
12544           as_bad (_("number (0x%s) larger than 32 bits"), value);
12545         }
12546
12547       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12548         {
12549           /* If this is a reference to a GP relative symbol, we want
12550                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12551                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12552              If we have a base register, we use this
12553                addu     $at,$breg,$gp
12554                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12555                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12556              If this is not a GP relative symbol, we want
12557                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12558                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12559                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12560              If there is a base register, we add it to $at after the
12561              lui instruction.  If there is a constant, we always use
12562              the last case.  */
12563           if (offset_expr.X_op == O_symbol
12564               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12565               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12566             {
12567               relax_start (offset_expr.X_add_symbol);
12568               if (breg == 0)
12569                 {
12570                   tempreg = mips_gp_register;
12571                 }
12572               else
12573                 {
12574                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12575                                AT, breg, mips_gp_register);
12576                   tempreg = AT;
12577                   used_at = 1;
12578                 }
12579
12580               /* Itbl support may require additional care here.  */
12581               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12582                            BFD_RELOC_GPREL16, tempreg);
12583               offset_expr.X_add_number += 4;
12584
12585               /* Set mips_optimize to 2 to avoid inserting an
12586                  undesired nop.  */
12587               hold_mips_optimize = mips_optimize;
12588               mips_optimize = 2;
12589               /* Itbl support may require additional care here.  */
12590               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12591                            BFD_RELOC_GPREL16, tempreg);
12592               mips_optimize = hold_mips_optimize;
12593
12594               relax_switch ();
12595
12596               offset_expr.X_add_number -= 4;
12597             }
12598           used_at = 1;
12599           if (offset_high_part (offset_expr.X_add_number, 16)
12600               != offset_high_part (offset_expr.X_add_number + 4, 16))
12601             {
12602               load_address (AT, &offset_expr, &used_at);
12603               offset_expr.X_op = O_constant;
12604               offset_expr.X_add_number = 0;
12605             }
12606           else
12607             macro_build_lui (&offset_expr, AT);
12608           if (breg != 0)
12609             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12610           /* Itbl support may require additional care here.  */
12611           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12612                        BFD_RELOC_LO16, AT);
12613           /* FIXME: How do we handle overflow here?  */
12614           offset_expr.X_add_number += 4;
12615           /* Itbl support may require additional care here.  */
12616           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12617                        BFD_RELOC_LO16, AT);
12618           if (mips_relax.sequence)
12619             relax_end ();
12620         }
12621       else if (!mips_big_got)
12622         {
12623           /* If this is a reference to an external symbol, we want
12624                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12625                nop
12626                <op>     op[0],0($at)
12627                <op>     op[0]+1,4($at)
12628              Otherwise we want
12629                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12630                nop
12631                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12632                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12633              If there is a base register we add it to $at before the
12634              lwc1 instructions.  If there is a constant we include it
12635              in the lwc1 instructions.  */
12636           used_at = 1;
12637           expr1.X_add_number = offset_expr.X_add_number;
12638           if (expr1.X_add_number < -0x8000
12639               || expr1.X_add_number >= 0x8000 - 4)
12640             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12641           load_got_offset (AT, &offset_expr);
12642           load_delay_nop ();
12643           if (breg != 0)
12644             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12645
12646           /* Set mips_optimize to 2 to avoid inserting an undesired
12647              nop.  */
12648           hold_mips_optimize = mips_optimize;
12649           mips_optimize = 2;
12650
12651           /* Itbl support may require additional care here.  */
12652           relax_start (offset_expr.X_add_symbol);
12653           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12654                        BFD_RELOC_LO16, AT);
12655           expr1.X_add_number += 4;
12656           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12657                        BFD_RELOC_LO16, AT);
12658           relax_switch ();
12659           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12660                        BFD_RELOC_LO16, AT);
12661           offset_expr.X_add_number += 4;
12662           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12663                        BFD_RELOC_LO16, AT);
12664           relax_end ();
12665
12666           mips_optimize = hold_mips_optimize;
12667         }
12668       else if (mips_big_got)
12669         {
12670           int gpdelay;
12671
12672           /* If this is a reference to an external symbol, we want
12673                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12674                addu     $at,$at,$gp
12675                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12676                nop
12677                <op>     op[0],0($at)
12678                <op>     op[0]+1,4($at)
12679              Otherwise we want
12680                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12681                nop
12682                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12683                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12684              If there is a base register we add it to $at before the
12685              lwc1 instructions.  If there is a constant we include it
12686              in the lwc1 instructions.  */
12687           used_at = 1;
12688           expr1.X_add_number = offset_expr.X_add_number;
12689           offset_expr.X_add_number = 0;
12690           if (expr1.X_add_number < -0x8000
12691               || expr1.X_add_number >= 0x8000 - 4)
12692             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12693           gpdelay = reg_needs_delay (mips_gp_register);
12694           relax_start (offset_expr.X_add_symbol);
12695           macro_build (&offset_expr, "lui", LUI_FMT,
12696                        AT, BFD_RELOC_MIPS_GOT_HI16);
12697           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12698                        AT, AT, mips_gp_register);
12699           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12700                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12701           load_delay_nop ();
12702           if (breg != 0)
12703             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12704           /* Itbl support may require additional care here.  */
12705           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12706                        BFD_RELOC_LO16, AT);
12707           expr1.X_add_number += 4;
12708
12709           /* Set mips_optimize to 2 to avoid inserting an undesired
12710              nop.  */
12711           hold_mips_optimize = mips_optimize;
12712           mips_optimize = 2;
12713           /* Itbl support may require additional care here.  */
12714           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12715                        BFD_RELOC_LO16, AT);
12716           mips_optimize = hold_mips_optimize;
12717           expr1.X_add_number -= 4;
12718
12719           relax_switch ();
12720           offset_expr.X_add_number = expr1.X_add_number;
12721           if (gpdelay)
12722             macro_build (NULL, "nop", "");
12723           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12724                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12725           load_delay_nop ();
12726           if (breg != 0)
12727             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12728           /* Itbl support may require additional care here.  */
12729           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12730                        BFD_RELOC_LO16, AT);
12731           offset_expr.X_add_number += 4;
12732
12733           /* Set mips_optimize to 2 to avoid inserting an undesired
12734              nop.  */
12735           hold_mips_optimize = mips_optimize;
12736           mips_optimize = 2;
12737           /* Itbl support may require additional care here.  */
12738           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12739                        BFD_RELOC_LO16, AT);
12740           mips_optimize = hold_mips_optimize;
12741           relax_end ();
12742         }
12743       else
12744         abort ();
12745
12746       break;
12747
12748     case M_SAA_AB:
12749       s = "saa";
12750       goto saa_saad;
12751     case M_SAAD_AB:
12752       s = "saad";
12753     saa_saad:
12754       gas_assert (!mips_opts.micromips);
12755       offbits = 0;
12756       fmt = "t,(b)";
12757       goto ld_st;
12758
12759    /* New code added to support COPZ instructions.
12760       This code builds table entries out of the macros in mip_opcodes.
12761       R4000 uses interlocks to handle coproc delays.
12762       Other chips (like the R3000) require nops to be inserted for delays.
12763
12764       FIXME: Currently, we require that the user handle delays.
12765       In order to fill delay slots for non-interlocked chips,
12766       we must have a way to specify delays based on the coprocessor.
12767       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12768       What are the side-effects of the cop instruction?
12769       What cache support might we have and what are its effects?
12770       Both coprocessor & memory require delays. how long???
12771       What registers are read/set/modified?
12772
12773       If an itbl is provided to interpret cop instructions,
12774       this knowledge can be encoded in the itbl spec.  */
12775
12776     case M_COP0:
12777       s = "c0";
12778       goto copz;
12779     case M_COP1:
12780       s = "c1";
12781       goto copz;
12782     case M_COP2:
12783       s = "c2";
12784       goto copz;
12785     case M_COP3:
12786       s = "c3";
12787     copz:
12788       gas_assert (!mips_opts.micromips);
12789       /* For now we just do C (same as Cz).  The parameter will be
12790          stored in insn_opcode by mips_ip.  */
12791       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12792       break;
12793
12794     case M_MOVE:
12795       move_register (op[0], op[1]);
12796       break;
12797
12798     case M_MOVEP:
12799       gas_assert (mips_opts.micromips);
12800       gas_assert (mips_opts.insn32);
12801       move_register (micromips_to_32_reg_h_map1[op[0]],
12802                      micromips_to_32_reg_m_map[op[1]]);
12803       move_register (micromips_to_32_reg_h_map2[op[0]],
12804                      micromips_to_32_reg_n_map[op[2]]);
12805       break;
12806
12807     case M_DMUL:
12808       dbl = 1;
12809       /* Fall through.  */
12810     case M_MUL:
12811       if (mips_opts.arch == CPU_R5900)
12812         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12813                      op[2]);
12814       else
12815         {
12816           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12817           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12818         }
12819       break;
12820
12821     case M_DMUL_I:
12822       dbl = 1;
12823       /* Fall through.  */
12824     case M_MUL_I:
12825       /* The MIPS assembler some times generates shifts and adds.  I'm
12826          not trying to be that fancy. GCC should do this for us
12827          anyway.  */
12828       used_at = 1;
12829       load_register (AT, &imm_expr, dbl);
12830       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12831       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12832       break;
12833
12834     case M_DMULO_I:
12835       dbl = 1;
12836       /* Fall through.  */
12837     case M_MULO_I:
12838       imm = 1;
12839       goto do_mulo;
12840
12841     case M_DMULO:
12842       dbl = 1;
12843       /* Fall through.  */
12844     case M_MULO:
12845     do_mulo:
12846       start_noreorder ();
12847       used_at = 1;
12848       if (imm)
12849         load_register (AT, &imm_expr, dbl);
12850       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12851                    op[1], imm ? AT : op[2]);
12852       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12853       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12854       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12855       if (mips_trap)
12856         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12857       else
12858         {
12859           if (mips_opts.micromips)
12860             micromips_label_expr (&label_expr);
12861           else
12862             label_expr.X_add_number = 8;
12863           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12864           macro_build (NULL, "nop", "");
12865           macro_build (NULL, "break", BRK_FMT, 6);
12866           if (mips_opts.micromips)
12867             micromips_add_label ();
12868         }
12869       end_noreorder ();
12870       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12871       break;
12872
12873     case M_DMULOU_I:
12874       dbl = 1;
12875       /* Fall through.  */
12876     case M_MULOU_I:
12877       imm = 1;
12878       goto do_mulou;
12879
12880     case M_DMULOU:
12881       dbl = 1;
12882       /* Fall through.  */
12883     case M_MULOU:
12884     do_mulou:
12885       start_noreorder ();
12886       used_at = 1;
12887       if (imm)
12888         load_register (AT, &imm_expr, dbl);
12889       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12890                    op[1], imm ? AT : op[2]);
12891       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12892       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12893       if (mips_trap)
12894         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12895       else
12896         {
12897           if (mips_opts.micromips)
12898             micromips_label_expr (&label_expr);
12899           else
12900             label_expr.X_add_number = 8;
12901           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12902           macro_build (NULL, "nop", "");
12903           macro_build (NULL, "break", BRK_FMT, 6);
12904           if (mips_opts.micromips)
12905             micromips_add_label ();
12906         }
12907       end_noreorder ();
12908       break;
12909
12910     case M_DROL:
12911       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12912         {
12913           if (op[0] == op[1])
12914             {
12915               tempreg = AT;
12916               used_at = 1;
12917             }
12918           else
12919             tempreg = op[0];
12920           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12921           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12922           break;
12923         }
12924       used_at = 1;
12925       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12926       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12927       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12928       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12929       break;
12930
12931     case M_ROL:
12932       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12933         {
12934           if (op[0] == op[1])
12935             {
12936               tempreg = AT;
12937               used_at = 1;
12938             }
12939           else
12940             tempreg = op[0];
12941           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12942           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12943           break;
12944         }
12945       used_at = 1;
12946       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12947       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12948       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12949       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12950       break;
12951
12952     case M_DROL_I:
12953       {
12954         unsigned int rot;
12955         const char *l;
12956         const char *rr;
12957
12958         rot = imm_expr.X_add_number & 0x3f;
12959         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12960           {
12961             rot = (64 - rot) & 0x3f;
12962             if (rot >= 32)
12963               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12964             else
12965               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12966             break;
12967           }
12968         if (rot == 0)
12969           {
12970             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12971             break;
12972           }
12973         l = (rot < 0x20) ? "dsll" : "dsll32";
12974         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12975         rot &= 0x1f;
12976         used_at = 1;
12977         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12978         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12979         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12980       }
12981       break;
12982
12983     case M_ROL_I:
12984       {
12985         unsigned int rot;
12986
12987         rot = imm_expr.X_add_number & 0x1f;
12988         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12989           {
12990             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12991                          (32 - rot) & 0x1f);
12992             break;
12993           }
12994         if (rot == 0)
12995           {
12996             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12997             break;
12998           }
12999         used_at = 1;
13000         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
13001         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13002         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13003       }
13004       break;
13005
13006     case M_DROR:
13007       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13008         {
13009           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
13010           break;
13011         }
13012       used_at = 1;
13013       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13014       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13015       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13016       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13017       break;
13018
13019     case M_ROR:
13020       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13021         {
13022           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13023           break;
13024         }
13025       used_at = 1;
13026       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13027       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13028       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13029       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13030       break;
13031
13032     case M_DROR_I:
13033       {
13034         unsigned int rot;
13035         const char *l;
13036         const char *rr;
13037
13038         rot = imm_expr.X_add_number & 0x3f;
13039         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13040           {
13041             if (rot >= 32)
13042               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13043             else
13044               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13045             break;
13046           }
13047         if (rot == 0)
13048           {
13049             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13050             break;
13051           }
13052         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13053         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13054         rot &= 0x1f;
13055         used_at = 1;
13056         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13057         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13058         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13059       }
13060       break;
13061
13062     case M_ROR_I:
13063       {
13064         unsigned int rot;
13065
13066         rot = imm_expr.X_add_number & 0x1f;
13067         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13068           {
13069             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13070             break;
13071           }
13072         if (rot == 0)
13073           {
13074             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13075             break;
13076           }
13077         used_at = 1;
13078         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13079         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13080         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13081       }
13082       break;
13083
13084     case M_SEQ:
13085       if (op[1] == 0)
13086         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13087       else if (op[2] == 0)
13088         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13089       else
13090         {
13091           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13092           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13093         }
13094       break;
13095
13096     case M_SEQ_I:
13097       if (imm_expr.X_add_number == 0)
13098         {
13099           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13100           break;
13101         }
13102       if (op[1] == 0)
13103         {
13104           as_warn (_("instruction %s: result is always false"),
13105                    ip->insn_mo->name);
13106           move_register (op[0], 0);
13107           break;
13108         }
13109       if (CPU_HAS_SEQ (mips_opts.arch)
13110           && -512 <= imm_expr.X_add_number
13111           && imm_expr.X_add_number < 512)
13112         {
13113           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13114                        (int) imm_expr.X_add_number);
13115           break;
13116         }
13117       if (imm_expr.X_add_number >= 0
13118           && imm_expr.X_add_number < 0x10000)
13119         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13120       else if (imm_expr.X_add_number > -0x8000
13121                && imm_expr.X_add_number < 0)
13122         {
13123           imm_expr.X_add_number = -imm_expr.X_add_number;
13124           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13125                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13126         }
13127       else if (CPU_HAS_SEQ (mips_opts.arch))
13128         {
13129           used_at = 1;
13130           load_register (AT, &imm_expr, GPR_SIZE == 64);
13131           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13132           break;
13133         }
13134       else
13135         {
13136           load_register (AT, &imm_expr, GPR_SIZE == 64);
13137           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13138           used_at = 1;
13139         }
13140       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13141       break;
13142
13143     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
13144       s = "slt";
13145       goto sge;
13146     case M_SGEU:
13147       s = "sltu";
13148     sge:
13149       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13150       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13151       break;
13152
13153     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
13154     case M_SGEU_I:
13155       if (imm_expr.X_add_number >= -0x8000
13156           && imm_expr.X_add_number < 0x8000)
13157         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13158                      op[0], op[1], BFD_RELOC_LO16);
13159       else
13160         {
13161           load_register (AT, &imm_expr, GPR_SIZE == 64);
13162           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13163                        op[0], op[1], AT);
13164           used_at = 1;
13165         }
13166       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13167       break;
13168
13169     case M_SGT:         /* X > Y  <==>  Y < X */
13170       s = "slt";
13171       goto sgt;
13172     case M_SGTU:
13173       s = "sltu";
13174     sgt:
13175       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13176       break;
13177
13178     case M_SGT_I:       /* X > I  <==>  I < X */
13179       s = "slt";
13180       goto sgti;
13181     case M_SGTU_I:
13182       s = "sltu";
13183     sgti:
13184       used_at = 1;
13185       load_register (AT, &imm_expr, GPR_SIZE == 64);
13186       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13187       break;
13188
13189     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
13190       s = "slt";
13191       goto sle;
13192     case M_SLEU:
13193       s = "sltu";
13194     sle:
13195       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13196       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13197       break;
13198
13199     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
13200       s = "slt";
13201       goto slei;
13202     case M_SLEU_I:
13203       s = "sltu";
13204     slei:
13205       used_at = 1;
13206       load_register (AT, &imm_expr, GPR_SIZE == 64);
13207       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13208       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13209       break;
13210
13211     case M_SLT_I:
13212       if (imm_expr.X_add_number >= -0x8000
13213           && imm_expr.X_add_number < 0x8000)
13214         {
13215           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13216                        BFD_RELOC_LO16);
13217           break;
13218         }
13219       used_at = 1;
13220       load_register (AT, &imm_expr, GPR_SIZE == 64);
13221       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13222       break;
13223
13224     case M_SLTU_I:
13225       if (imm_expr.X_add_number >= -0x8000
13226           && imm_expr.X_add_number < 0x8000)
13227         {
13228           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13229                        BFD_RELOC_LO16);
13230           break;
13231         }
13232       used_at = 1;
13233       load_register (AT, &imm_expr, GPR_SIZE == 64);
13234       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13235       break;
13236
13237     case M_SNE:
13238       if (op[1] == 0)
13239         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13240       else if (op[2] == 0)
13241         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13242       else
13243         {
13244           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13245           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13246         }
13247       break;
13248
13249     case M_SNE_I:
13250       if (imm_expr.X_add_number == 0)
13251         {
13252           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13253           break;
13254         }
13255       if (op[1] == 0)
13256         {
13257           as_warn (_("instruction %s: result is always true"),
13258                    ip->insn_mo->name);
13259           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13260                        op[0], 0, BFD_RELOC_LO16);
13261           break;
13262         }
13263       if (CPU_HAS_SEQ (mips_opts.arch)
13264           && -512 <= imm_expr.X_add_number
13265           && imm_expr.X_add_number < 512)
13266         {
13267           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13268                        (int) imm_expr.X_add_number);
13269           break;
13270         }
13271       if (imm_expr.X_add_number >= 0
13272           && imm_expr.X_add_number < 0x10000)
13273         {
13274           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13275                        BFD_RELOC_LO16);
13276         }
13277       else if (imm_expr.X_add_number > -0x8000
13278                && imm_expr.X_add_number < 0)
13279         {
13280           imm_expr.X_add_number = -imm_expr.X_add_number;
13281           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13282                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13283         }
13284       else if (CPU_HAS_SEQ (mips_opts.arch))
13285         {
13286           used_at = 1;
13287           load_register (AT, &imm_expr, GPR_SIZE == 64);
13288           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13289           break;
13290         }
13291       else
13292         {
13293           load_register (AT, &imm_expr, GPR_SIZE == 64);
13294           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13295           used_at = 1;
13296         }
13297       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13298       break;
13299
13300     case M_SUB_I:
13301       s = "addi";
13302       s2 = "sub";
13303       goto do_subi;
13304     case M_SUBU_I:
13305       s = "addiu";
13306       s2 = "subu";
13307       goto do_subi;
13308     case M_DSUB_I:
13309       dbl = 1;
13310       s = "daddi";
13311       s2 = "dsub";
13312       if (!mips_opts.micromips)
13313         goto do_subi;
13314       if (imm_expr.X_add_number > -0x200
13315           && imm_expr.X_add_number <= 0x200)
13316         {
13317           macro_build (NULL, s, "t,r,.", op[0], op[1],
13318                        (int) -imm_expr.X_add_number);
13319           break;
13320         }
13321       goto do_subi_i;
13322     case M_DSUBU_I:
13323       dbl = 1;
13324       s = "daddiu";
13325       s2 = "dsubu";
13326     do_subi:
13327       if (imm_expr.X_add_number > -0x8000
13328           && imm_expr.X_add_number <= 0x8000)
13329         {
13330           imm_expr.X_add_number = -imm_expr.X_add_number;
13331           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13332           break;
13333         }
13334     do_subi_i:
13335       used_at = 1;
13336       load_register (AT, &imm_expr, dbl);
13337       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13338       break;
13339
13340     case M_TEQ_I:
13341       s = "teq";
13342       goto trap;
13343     case M_TGE_I:
13344       s = "tge";
13345       goto trap;
13346     case M_TGEU_I:
13347       s = "tgeu";
13348       goto trap;
13349     case M_TLT_I:
13350       s = "tlt";
13351       goto trap;
13352     case M_TLTU_I:
13353       s = "tltu";
13354       goto trap;
13355     case M_TNE_I:
13356       s = "tne";
13357     trap:
13358       used_at = 1;
13359       load_register (AT, &imm_expr, GPR_SIZE == 64);
13360       macro_build (NULL, s, "s,t", op[0], AT);
13361       break;
13362
13363     case M_TRUNCWS:
13364     case M_TRUNCWD:
13365       gas_assert (!mips_opts.micromips);
13366       gas_assert (mips_opts.isa == ISA_MIPS1);
13367       used_at = 1;
13368
13369       /*
13370        * Is the double cfc1 instruction a bug in the mips assembler;
13371        * or is there a reason for it?
13372        */
13373       start_noreorder ();
13374       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13375       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13376       macro_build (NULL, "nop", "");
13377       expr1.X_add_number = 3;
13378       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13379       expr1.X_add_number = 2;
13380       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13381       macro_build (NULL, "ctc1", "t,G", AT, RA);
13382       macro_build (NULL, "nop", "");
13383       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13384                    op[0], op[1]);
13385       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13386       macro_build (NULL, "nop", "");
13387       end_noreorder ();
13388       break;
13389
13390     case M_ULH_AB:
13391       s = "lb";
13392       s2 = "lbu";
13393       off = 1;
13394       goto uld_st;
13395     case M_ULHU_AB:
13396       s = "lbu";
13397       s2 = "lbu";
13398       off = 1;
13399       goto uld_st;
13400     case M_ULW_AB:
13401       s = "lwl";
13402       s2 = "lwr";
13403       offbits = (mips_opts.micromips ? 12 : 16);
13404       off = 3;
13405       goto uld_st;
13406     case M_ULD_AB:
13407       s = "ldl";
13408       s2 = "ldr";
13409       offbits = (mips_opts.micromips ? 12 : 16);
13410       off = 7;
13411       goto uld_st;
13412     case M_USH_AB:
13413       s = "sb";
13414       s2 = "sb";
13415       off = 1;
13416       ust = 1;
13417       goto uld_st;
13418     case M_USW_AB:
13419       s = "swl";
13420       s2 = "swr";
13421       offbits = (mips_opts.micromips ? 12 : 16);
13422       off = 3;
13423       ust = 1;
13424       goto uld_st;
13425     case M_USD_AB:
13426       s = "sdl";
13427       s2 = "sdr";
13428       offbits = (mips_opts.micromips ? 12 : 16);
13429       off = 7;
13430       ust = 1;
13431
13432     uld_st:
13433       breg = op[2];
13434       large_offset = !small_offset_p (off, align, offbits);
13435       ep = &offset_expr;
13436       expr1.X_add_number = 0;
13437       if (large_offset)
13438         {
13439           used_at = 1;
13440           tempreg = AT;
13441           if (small_offset_p (0, align, 16))
13442             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13443                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13444           else
13445             {
13446               load_address (tempreg, ep, &used_at);
13447               if (breg != 0)
13448                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13449                              tempreg, tempreg, breg);
13450             }
13451           offset_reloc[0] = BFD_RELOC_LO16;
13452           offset_reloc[1] = BFD_RELOC_UNUSED;
13453           offset_reloc[2] = BFD_RELOC_UNUSED;
13454           breg = tempreg;
13455           tempreg = op[0];
13456           ep = &expr1;
13457         }
13458       else if (!ust && op[0] == breg)
13459         {
13460           used_at = 1;
13461           tempreg = AT;
13462         }
13463       else
13464         tempreg = op[0];
13465
13466       if (off == 1)
13467         goto ulh_sh;
13468
13469       if (!target_big_endian)
13470         ep->X_add_number += off;
13471       if (offbits == 12)
13472         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13473       else
13474         macro_build (ep, s, "t,o(b)", tempreg, -1,
13475                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13476
13477       if (!target_big_endian)
13478         ep->X_add_number -= off;
13479       else
13480         ep->X_add_number += off;
13481       if (offbits == 12)
13482         macro_build (NULL, s2, "t,~(b)",
13483                      tempreg, (int) ep->X_add_number, breg);
13484       else
13485         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13486                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13487
13488       /* If necessary, move the result in tempreg to the final destination.  */
13489       if (!ust && op[0] != tempreg)
13490         {
13491           /* Protect second load's delay slot.  */
13492           load_delay_nop ();
13493           move_register (op[0], tempreg);
13494         }
13495       break;
13496
13497     ulh_sh:
13498       used_at = 1;
13499       if (target_big_endian == ust)
13500         ep->X_add_number += off;
13501       tempreg = ust || large_offset ? op[0] : AT;
13502       macro_build (ep, s, "t,o(b)", tempreg, -1,
13503                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13504
13505       /* For halfword transfers we need a temporary register to shuffle
13506          bytes.  Unfortunately for M_USH_A we have none available before
13507          the next store as AT holds the base address.  We deal with this
13508          case by clobbering TREG and then restoring it as with ULH.  */
13509       tempreg = ust == large_offset ? op[0] : AT;
13510       if (ust)
13511         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13512
13513       if (target_big_endian == ust)
13514         ep->X_add_number -= off;
13515       else
13516         ep->X_add_number += off;
13517       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13518                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13519
13520       /* For M_USH_A re-retrieve the LSB.  */
13521       if (ust && large_offset)
13522         {
13523           if (target_big_endian)
13524             ep->X_add_number += off;
13525           else
13526             ep->X_add_number -= off;
13527           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13528                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13529         }
13530       /* For ULH and M_USH_A OR the LSB in.  */
13531       if (!ust || large_offset)
13532         {
13533           tempreg = !large_offset ? AT : op[0];
13534           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13535           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13536         }
13537       break;
13538
13539     default:
13540       /* FIXME: Check if this is one of the itbl macros, since they
13541          are added dynamically.  */
13542       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13543       break;
13544     }
13545   if (!mips_opts.at && used_at)
13546     as_bad (_("macro used $at after \".set noat\""));
13547 }
13548
13549 /* Implement macros in mips16 mode.  */
13550
13551 static void
13552 mips16_macro (struct mips_cl_insn *ip)
13553 {
13554   const struct mips_operand_array *operands;
13555   int mask;
13556   int tmp;
13557   expressionS expr1;
13558   int dbl;
13559   const char *s, *s2, *s3;
13560   unsigned int op[MAX_OPERANDS];
13561   unsigned int i;
13562
13563   mask = ip->insn_mo->mask;
13564
13565   operands = insn_operands (ip);
13566   for (i = 0; i < MAX_OPERANDS; i++)
13567     if (operands->operand[i])
13568       op[i] = insn_extract_operand (ip, operands->operand[i]);
13569     else
13570       op[i] = -1;
13571
13572   expr1.X_op = O_constant;
13573   expr1.X_op_symbol = NULL;
13574   expr1.X_add_symbol = NULL;
13575   expr1.X_add_number = 1;
13576
13577   dbl = 0;
13578
13579   switch (mask)
13580     {
13581     default:
13582       abort ();
13583
13584     case M_DDIV_3:
13585       dbl = 1;
13586       /* Fall through.  */
13587     case M_DIV_3:
13588       s = "mflo";
13589       goto do_div3;
13590     case M_DREM_3:
13591       dbl = 1;
13592       /* Fall through.  */
13593     case M_REM_3:
13594       s = "mfhi";
13595     do_div3:
13596       start_noreorder ();
13597       macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
13598       expr1.X_add_number = 2;
13599       macro_build (&expr1, "bnez", "x,p", op[2]);
13600       macro_build (NULL, "break", "6", 7);
13601
13602       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13603          since that causes an overflow.  We should do that as well,
13604          but I don't see how to do the comparisons without a temporary
13605          register.  */
13606       end_noreorder ();
13607       macro_build (NULL, s, "x", op[0]);
13608       break;
13609
13610     case M_DIVU_3:
13611       s = "divu";
13612       s2 = "mflo";
13613       goto do_divu3;
13614     case M_REMU_3:
13615       s = "divu";
13616       s2 = "mfhi";
13617       goto do_divu3;
13618     case M_DDIVU_3:
13619       s = "ddivu";
13620       s2 = "mflo";
13621       goto do_divu3;
13622     case M_DREMU_3:
13623       s = "ddivu";
13624       s2 = "mfhi";
13625     do_divu3:
13626       start_noreorder ();
13627       macro_build (NULL, s, ".,x,y", op[1], op[2]);
13628       expr1.X_add_number = 2;
13629       macro_build (&expr1, "bnez", "x,p", op[2]);
13630       macro_build (NULL, "break", "6", 7);
13631       end_noreorder ();
13632       macro_build (NULL, s2, "x", op[0]);
13633       break;
13634
13635     case M_DMUL:
13636       dbl = 1;
13637       /* Fall through.  */
13638     case M_MUL:
13639       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13640       macro_build (NULL, "mflo", "x", op[0]);
13641       break;
13642
13643     case M_DSUBU_I:
13644       dbl = 1;
13645       goto do_subu;
13646     case M_SUBU_I:
13647     do_subu:
13648       imm_expr.X_add_number = -imm_expr.X_add_number;
13649       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
13650       break;
13651
13652     case M_SUBU_I_2:
13653       imm_expr.X_add_number = -imm_expr.X_add_number;
13654       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13655       break;
13656
13657     case M_DSUBU_I_2:
13658       imm_expr.X_add_number = -imm_expr.X_add_number;
13659       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13660       break;
13661
13662     case M_BEQ:
13663       s = "cmp";
13664       s2 = "bteqz";
13665       goto do_branch;
13666     case M_BNE:
13667       s = "cmp";
13668       s2 = "btnez";
13669       goto do_branch;
13670     case M_BLT:
13671       s = "slt";
13672       s2 = "btnez";
13673       goto do_branch;
13674     case M_BLTU:
13675       s = "sltu";
13676       s2 = "btnez";
13677       goto do_branch;
13678     case M_BLE:
13679       s = "slt";
13680       s2 = "bteqz";
13681       goto do_reverse_branch;
13682     case M_BLEU:
13683       s = "sltu";
13684       s2 = "bteqz";
13685       goto do_reverse_branch;
13686     case M_BGE:
13687       s = "slt";
13688       s2 = "bteqz";
13689       goto do_branch;
13690     case M_BGEU:
13691       s = "sltu";
13692       s2 = "bteqz";
13693       goto do_branch;
13694     case M_BGT:
13695       s = "slt";
13696       s2 = "btnez";
13697       goto do_reverse_branch;
13698     case M_BGTU:
13699       s = "sltu";
13700       s2 = "btnez";
13701
13702     do_reverse_branch:
13703       tmp = op[1];
13704       op[1] = op[0];
13705       op[0] = tmp;
13706
13707     do_branch:
13708       macro_build (NULL, s, "x,y", op[0], op[1]);
13709       macro_build (&offset_expr, s2, "p");
13710       break;
13711
13712     case M_BEQ_I:
13713       s = "cmpi";
13714       s2 = "bteqz";
13715       s3 = "x,U";
13716       goto do_branch_i;
13717     case M_BNE_I:
13718       s = "cmpi";
13719       s2 = "btnez";
13720       s3 = "x,U";
13721       goto do_branch_i;
13722     case M_BLT_I:
13723       s = "slti";
13724       s2 = "btnez";
13725       s3 = "x,8";
13726       goto do_branch_i;
13727     case M_BLTU_I:
13728       s = "sltiu";
13729       s2 = "btnez";
13730       s3 = "x,8";
13731       goto do_branch_i;
13732     case M_BLE_I:
13733       s = "slti";
13734       s2 = "btnez";
13735       s3 = "x,8";
13736       goto do_addone_branch_i;
13737     case M_BLEU_I:
13738       s = "sltiu";
13739       s2 = "btnez";
13740       s3 = "x,8";
13741       goto do_addone_branch_i;
13742     case M_BGE_I:
13743       s = "slti";
13744       s2 = "bteqz";
13745       s3 = "x,8";
13746       goto do_branch_i;
13747     case M_BGEU_I:
13748       s = "sltiu";
13749       s2 = "bteqz";
13750       s3 = "x,8";
13751       goto do_branch_i;
13752     case M_BGT_I:
13753       s = "slti";
13754       s2 = "bteqz";
13755       s3 = "x,8";
13756       goto do_addone_branch_i;
13757     case M_BGTU_I:
13758       s = "sltiu";
13759       s2 = "bteqz";
13760       s3 = "x,8";
13761
13762     do_addone_branch_i:
13763       ++imm_expr.X_add_number;
13764
13765     do_branch_i:
13766       macro_build (&imm_expr, s, s3, op[0]);
13767       macro_build (&offset_expr, s2, "p");
13768       break;
13769
13770     case M_ABS:
13771       expr1.X_add_number = 0;
13772       macro_build (&expr1, "slti", "x,8", op[1]);
13773       if (op[0] != op[1])
13774         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13775       expr1.X_add_number = 2;
13776       macro_build (&expr1, "bteqz", "p");
13777       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13778       break;
13779     }
13780 }
13781
13782 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13783    opcode bits in *OPCODE_EXTRA.  */
13784
13785 static struct mips_opcode *
13786 mips_lookup_insn (struct hash_control *hash, const char *start,
13787                   ssize_t length, unsigned int *opcode_extra)
13788 {
13789   char *name, *dot, *p;
13790   unsigned int mask, suffix;
13791   ssize_t opend;
13792   struct mips_opcode *insn;
13793
13794   /* Make a copy of the instruction so that we can fiddle with it.  */
13795   name = xstrndup (start, length);
13796
13797   /* Look up the instruction as-is.  */
13798   insn = (struct mips_opcode *) hash_find (hash, name);
13799   if (insn)
13800     goto end;
13801
13802   dot = strchr (name, '.');
13803   if (dot && dot[1])
13804     {
13805       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13806       p = mips_parse_vu0_channels (dot + 1, &mask);
13807       if (*p == 0 && mask != 0)
13808         {
13809           *dot = 0;
13810           insn = (struct mips_opcode *) hash_find (hash, name);
13811           *dot = '.';
13812           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13813             {
13814               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13815               goto end;
13816             }
13817         }
13818     }
13819
13820   if (mips_opts.micromips)
13821     {
13822       /* See if there's an instruction size override suffix,
13823          either `16' or `32', at the end of the mnemonic proper,
13824          that defines the operation, i.e. before the first `.'
13825          character if any.  Strip it and retry.  */
13826       opend = dot != NULL ? dot - name : length;
13827       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13828         suffix = 2;
13829       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13830         suffix = 4;
13831       else
13832         suffix = 0;
13833       if (suffix)
13834         {
13835           memcpy (name + opend - 2, name + opend, length - opend + 1);
13836           insn = (struct mips_opcode *) hash_find (hash, name);
13837           if (insn)
13838             {
13839               forced_insn_length = suffix;
13840               goto end;
13841             }
13842         }
13843     }
13844
13845   insn = NULL;
13846  end:
13847   free (name);
13848   return insn;
13849 }
13850
13851 /* Assemble an instruction into its binary format.  If the instruction
13852    is a macro, set imm_expr and offset_expr to the values associated
13853    with "I" and "A" operands respectively.  Otherwise store the value
13854    of the relocatable field (if any) in offset_expr.  In both cases
13855    set offset_reloc to the relocation operators applied to offset_expr.  */
13856
13857 static void
13858 mips_ip (char *str, struct mips_cl_insn *insn)
13859 {
13860   const struct mips_opcode *first, *past;
13861   struct hash_control *hash;
13862   char format;
13863   size_t end;
13864   struct mips_operand_token *tokens;
13865   unsigned int opcode_extra;
13866
13867   if (mips_opts.micromips)
13868     {
13869       hash = micromips_op_hash;
13870       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13871     }
13872   else
13873     {
13874       hash = op_hash;
13875       past = &mips_opcodes[NUMOPCODES];
13876     }
13877   forced_insn_length = 0;
13878   opcode_extra = 0;
13879
13880   /* We first try to match an instruction up to a space or to the end.  */
13881   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13882     continue;
13883
13884   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13885   if (first == NULL)
13886     {
13887       set_insn_error (0, _("unrecognized opcode"));
13888       return;
13889     }
13890
13891   if (strcmp (first->name, "li.s") == 0)
13892     format = 'f';
13893   else if (strcmp (first->name, "li.d") == 0)
13894     format = 'd';
13895   else
13896     format = 0;
13897   tokens = mips_parse_arguments (str + end, format);
13898   if (!tokens)
13899     return;
13900
13901   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13902       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13903     set_insn_error (0, _("invalid operands"));
13904
13905   obstack_free (&mips_operand_tokens, tokens);
13906 }
13907
13908 /* As for mips_ip, but used when assembling MIPS16 code.
13909    Also set forced_insn_length to the resulting instruction size in
13910    bytes if the user explicitly requested a small or extended instruction.  */
13911
13912 static void
13913 mips16_ip (char *str, struct mips_cl_insn *insn)
13914 {
13915   char *end, *s, c;
13916   struct mips_opcode *first;
13917   struct mips_operand_token *tokens;
13918   unsigned int l;
13919
13920   for (s = str; ISLOWER (*s); ++s)
13921     ;
13922   end = s;
13923   c = *end;
13924
13925   l = 0;
13926   switch (c)
13927     {
13928     case '\0':
13929       break;
13930
13931     case ' ':
13932       s++;
13933       break;
13934
13935     case '.':
13936       s++;
13937       if (*s == 't')
13938         {
13939           l = 2;
13940           s++;
13941         }
13942       else if (*s == 'e')
13943         {
13944           l = 4;
13945           s++;
13946         }
13947       if (*s == '\0')
13948         break;
13949       else if (*s++ == ' ')
13950         break;
13951       /* Fall through.  */
13952     default:
13953       set_insn_error (0, _("unrecognized opcode"));
13954       return;
13955     }
13956   forced_insn_length = l;
13957
13958   *end = 0;
13959   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13960   *end = c;
13961
13962   if (!first)
13963     {
13964       set_insn_error (0, _("unrecognized opcode"));
13965       return;
13966     }
13967
13968   tokens = mips_parse_arguments (s, 0);
13969   if (!tokens)
13970     return;
13971
13972   if (!match_mips16_insns (insn, first, tokens))
13973     set_insn_error (0, _("invalid operands"));
13974
13975   obstack_free (&mips_operand_tokens, tokens);
13976 }
13977
13978 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13979    NBITS is the number of significant bits in VAL.  */
13980
13981 static unsigned long
13982 mips16_immed_extend (offsetT val, unsigned int nbits)
13983 {
13984   int extval;
13985   if (nbits == 16)
13986     {
13987       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13988       val &= 0x1f;
13989     }
13990   else if (nbits == 15)
13991     {
13992       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13993       val &= 0xf;
13994     }
13995   else
13996     {
13997       extval = ((val & 0x1f) << 6) | (val & 0x20);
13998       val = 0;
13999     }
14000   return (extval << 16) | val;
14001 }
14002
14003 /* Like decode_mips16_operand, but require the operand to be defined and
14004    require it to be an integer.  */
14005
14006 static const struct mips_int_operand *
14007 mips16_immed_operand (int type, bfd_boolean extended_p)
14008 {
14009   const struct mips_operand *operand;
14010
14011   operand = decode_mips16_operand (type, extended_p);
14012   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
14013     abort ();
14014   return (const struct mips_int_operand *) operand;
14015 }
14016
14017 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14018
14019 static bfd_boolean
14020 mips16_immed_in_range_p (const struct mips_int_operand *operand,
14021                          bfd_reloc_code_real_type reloc, offsetT sval)
14022 {
14023   int min_val, max_val;
14024
14025   min_val = mips_int_operand_min (operand);
14026   max_val = mips_int_operand_max (operand);
14027   if (reloc != BFD_RELOC_UNUSED)
14028     {
14029       if (min_val < 0)
14030         sval = SEXT_16BIT (sval);
14031       else
14032         sval &= 0xffff;
14033     }
14034
14035   return (sval >= min_val
14036           && sval <= max_val
14037           && (sval & ((1 << operand->shift) - 1)) == 0);
14038 }
14039
14040 /* Install immediate value VAL into MIPS16 instruction *INSN,
14041    extending it if necessary.  The instruction in *INSN may
14042    already be extended.
14043
14044    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14045    if none.  In the former case, VAL is a 16-bit number with no
14046    defined signedness.
14047
14048    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14049    is the length that the user requested, or 0 if none.  */
14050
14051 static void
14052 mips16_immed (const char *file, unsigned int line, int type,
14053               bfd_reloc_code_real_type reloc, offsetT val,
14054               unsigned int user_insn_length, unsigned long *insn)
14055 {
14056   const struct mips_int_operand *operand;
14057   unsigned int uval, length;
14058
14059   operand = mips16_immed_operand (type, FALSE);
14060   if (!mips16_immed_in_range_p (operand, reloc, val))
14061     {
14062       /* We need an extended instruction.  */
14063       if (user_insn_length == 2)
14064         as_bad_where (file, line, _("invalid unextended operand value"));
14065       else
14066         *insn |= MIPS16_EXTEND;
14067     }
14068   else if (user_insn_length == 4)
14069     {
14070       /* The operand doesn't force an unextended instruction to be extended.
14071          Warn if the user wanted an extended instruction anyway.  */
14072       *insn |= MIPS16_EXTEND;
14073       as_warn_where (file, line,
14074                      _("extended operand requested but not required"));
14075     }
14076
14077   length = mips16_opcode_length (*insn);
14078   if (length == 4)
14079     {
14080       operand = mips16_immed_operand (type, TRUE);
14081       if (!mips16_immed_in_range_p (operand, reloc, val))
14082         as_bad_where (file, line,
14083                       _("operand value out of range for instruction"));
14084     }
14085   uval = ((unsigned int) val >> operand->shift) - operand->bias;
14086   if (length == 2 || operand->root.lsb != 0)
14087     *insn = mips_insert_operand (&operand->root, *insn, uval);
14088   else
14089     *insn |= mips16_immed_extend (uval, operand->root.size);
14090 }
14091 \f
14092 struct percent_op_match
14093 {
14094   const char *str;
14095   bfd_reloc_code_real_type reloc;
14096 };
14097
14098 static const struct percent_op_match mips_percent_op[] =
14099 {
14100   {"%lo", BFD_RELOC_LO16},
14101   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14102   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14103   {"%call16", BFD_RELOC_MIPS_CALL16},
14104   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14105   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14106   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14107   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14108   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14109   {"%got", BFD_RELOC_MIPS_GOT16},
14110   {"%gp_rel", BFD_RELOC_GPREL16},
14111   {"%gprel", BFD_RELOC_GPREL16},
14112   {"%half", BFD_RELOC_16},
14113   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14114   {"%higher", BFD_RELOC_MIPS_HIGHER},
14115   {"%neg", BFD_RELOC_MIPS_SUB},
14116   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14117   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14118   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14119   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14120   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14121   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14122   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14123   {"%hi", BFD_RELOC_HI16_S},
14124   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14125   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14126 };
14127
14128 static const struct percent_op_match mips16_percent_op[] =
14129 {
14130   {"%lo", BFD_RELOC_MIPS16_LO16},
14131   {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14132   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14133   {"%got", BFD_RELOC_MIPS16_GOT16},
14134   {"%call16", BFD_RELOC_MIPS16_CALL16},
14135   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14136   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14137   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14138   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14139   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14140   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14141   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14142   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14143 };
14144
14145
14146 /* Return true if *STR points to a relocation operator.  When returning true,
14147    move *STR over the operator and store its relocation code in *RELOC.
14148    Leave both *STR and *RELOC alone when returning false.  */
14149
14150 static bfd_boolean
14151 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14152 {
14153   const struct percent_op_match *percent_op;
14154   size_t limit, i;
14155
14156   if (mips_opts.mips16)
14157     {
14158       percent_op = mips16_percent_op;
14159       limit = ARRAY_SIZE (mips16_percent_op);
14160     }
14161   else
14162     {
14163       percent_op = mips_percent_op;
14164       limit = ARRAY_SIZE (mips_percent_op);
14165     }
14166
14167   for (i = 0; i < limit; i++)
14168     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14169       {
14170         int len = strlen (percent_op[i].str);
14171
14172         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14173           continue;
14174
14175         *str += strlen (percent_op[i].str);
14176         *reloc = percent_op[i].reloc;
14177
14178         /* Check whether the output BFD supports this relocation.
14179            If not, issue an error and fall back on something safe.  */
14180         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14181           {
14182             as_bad (_("relocation %s isn't supported by the current ABI"),
14183                     percent_op[i].str);
14184             *reloc = BFD_RELOC_UNUSED;
14185           }
14186         return TRUE;
14187       }
14188   return FALSE;
14189 }
14190
14191
14192 /* Parse string STR as a 16-bit relocatable operand.  Store the
14193    expression in *EP and the relocations in the array starting
14194    at RELOC.  Return the number of relocation operators used.
14195
14196    On exit, EXPR_END points to the first character after the expression.  */
14197
14198 static size_t
14199 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14200                        char *str)
14201 {
14202   bfd_reloc_code_real_type reversed_reloc[3];
14203   size_t reloc_index, i;
14204   int crux_depth, str_depth;
14205   char *crux;
14206
14207   /* Search for the start of the main expression, recoding relocations
14208      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14209      of the main expression and with CRUX_DEPTH containing the number
14210      of open brackets at that point.  */
14211   reloc_index = -1;
14212   str_depth = 0;
14213   do
14214     {
14215       reloc_index++;
14216       crux = str;
14217       crux_depth = str_depth;
14218
14219       /* Skip over whitespace and brackets, keeping count of the number
14220          of brackets.  */
14221       while (*str == ' ' || *str == '\t' || *str == '(')
14222         if (*str++ == '(')
14223           str_depth++;
14224     }
14225   while (*str == '%'
14226          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14227          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14228
14229   my_getExpression (ep, crux);
14230   str = expr_end;
14231
14232   /* Match every open bracket.  */
14233   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14234     if (*str++ == ')')
14235       crux_depth--;
14236
14237   if (crux_depth > 0)
14238     as_bad (_("unclosed '('"));
14239
14240   expr_end = str;
14241
14242   if (reloc_index != 0)
14243     {
14244       prev_reloc_op_frag = frag_now;
14245       for (i = 0; i < reloc_index; i++)
14246         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14247     }
14248
14249   return reloc_index;
14250 }
14251
14252 static void
14253 my_getExpression (expressionS *ep, char *str)
14254 {
14255   char *save_in;
14256
14257   save_in = input_line_pointer;
14258   input_line_pointer = str;
14259   expression (ep);
14260   expr_end = input_line_pointer;
14261   input_line_pointer = save_in;
14262 }
14263
14264 const char *
14265 md_atof (int type, char *litP, int *sizeP)
14266 {
14267   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14268 }
14269
14270 void
14271 md_number_to_chars (char *buf, valueT val, int n)
14272 {
14273   if (target_big_endian)
14274     number_to_chars_bigendian (buf, val, n);
14275   else
14276     number_to_chars_littleendian (buf, val, n);
14277 }
14278 \f
14279 static int support_64bit_objects(void)
14280 {
14281   const char **list, **l;
14282   int yes;
14283
14284   list = bfd_target_list ();
14285   for (l = list; *l != NULL; l++)
14286     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14287         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14288       break;
14289   yes = (*l != NULL);
14290   free (list);
14291   return yes;
14292 }
14293
14294 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14295    NEW_VALUE.  Warn if another value was already specified.  Note:
14296    we have to defer parsing the -march and -mtune arguments in order
14297    to handle 'from-abi' correctly, since the ABI might be specified
14298    in a later argument.  */
14299
14300 static void
14301 mips_set_option_string (const char **string_ptr, const char *new_value)
14302 {
14303   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14304     as_warn (_("a different %s was already specified, is now %s"),
14305              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14306              new_value);
14307
14308   *string_ptr = new_value;
14309 }
14310
14311 int
14312 md_parse_option (int c, const char *arg)
14313 {
14314   unsigned int i;
14315
14316   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14317     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14318       {
14319         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14320                                            c == mips_ases[i].option_on);
14321         return 1;
14322       }
14323
14324   switch (c)
14325     {
14326     case OPTION_CONSTRUCT_FLOATS:
14327       mips_disable_float_construction = 0;
14328       break;
14329
14330     case OPTION_NO_CONSTRUCT_FLOATS:
14331       mips_disable_float_construction = 1;
14332       break;
14333
14334     case OPTION_TRAP:
14335       mips_trap = 1;
14336       break;
14337
14338     case OPTION_BREAK:
14339       mips_trap = 0;
14340       break;
14341
14342     case OPTION_EB:
14343       target_big_endian = 1;
14344       break;
14345
14346     case OPTION_EL:
14347       target_big_endian = 0;
14348       break;
14349
14350     case 'O':
14351       if (arg == NULL)
14352         mips_optimize = 1;
14353       else if (arg[0] == '0')
14354         mips_optimize = 0;
14355       else if (arg[0] == '1')
14356         mips_optimize = 1;
14357       else
14358         mips_optimize = 2;
14359       break;
14360
14361     case 'g':
14362       if (arg == NULL)
14363         mips_debug = 2;
14364       else
14365         mips_debug = atoi (arg);
14366       break;
14367
14368     case OPTION_MIPS1:
14369       file_mips_opts.isa = ISA_MIPS1;
14370       break;
14371
14372     case OPTION_MIPS2:
14373       file_mips_opts.isa = ISA_MIPS2;
14374       break;
14375
14376     case OPTION_MIPS3:
14377       file_mips_opts.isa = ISA_MIPS3;
14378       break;
14379
14380     case OPTION_MIPS4:
14381       file_mips_opts.isa = ISA_MIPS4;
14382       break;
14383
14384     case OPTION_MIPS5:
14385       file_mips_opts.isa = ISA_MIPS5;
14386       break;
14387
14388     case OPTION_MIPS32:
14389       file_mips_opts.isa = ISA_MIPS32;
14390       break;
14391
14392     case OPTION_MIPS32R2:
14393       file_mips_opts.isa = ISA_MIPS32R2;
14394       break;
14395
14396     case OPTION_MIPS32R3:
14397       file_mips_opts.isa = ISA_MIPS32R3;
14398       break;
14399
14400     case OPTION_MIPS32R5:
14401       file_mips_opts.isa = ISA_MIPS32R5;
14402       break;
14403
14404     case OPTION_MIPS32R6:
14405       file_mips_opts.isa = ISA_MIPS32R6;
14406       break;
14407
14408     case OPTION_MIPS64R2:
14409       file_mips_opts.isa = ISA_MIPS64R2;
14410       break;
14411
14412     case OPTION_MIPS64R3:
14413       file_mips_opts.isa = ISA_MIPS64R3;
14414       break;
14415
14416     case OPTION_MIPS64R5:
14417       file_mips_opts.isa = ISA_MIPS64R5;
14418       break;
14419
14420     case OPTION_MIPS64R6:
14421       file_mips_opts.isa = ISA_MIPS64R6;
14422       break;
14423
14424     case OPTION_MIPS64:
14425       file_mips_opts.isa = ISA_MIPS64;
14426       break;
14427
14428     case OPTION_MTUNE:
14429       mips_set_option_string (&mips_tune_string, arg);
14430       break;
14431
14432     case OPTION_MARCH:
14433       mips_set_option_string (&mips_arch_string, arg);
14434       break;
14435
14436     case OPTION_M4650:
14437       mips_set_option_string (&mips_arch_string, "4650");
14438       mips_set_option_string (&mips_tune_string, "4650");
14439       break;
14440
14441     case OPTION_NO_M4650:
14442       break;
14443
14444     case OPTION_M4010:
14445       mips_set_option_string (&mips_arch_string, "4010");
14446       mips_set_option_string (&mips_tune_string, "4010");
14447       break;
14448
14449     case OPTION_NO_M4010:
14450       break;
14451
14452     case OPTION_M4100:
14453       mips_set_option_string (&mips_arch_string, "4100");
14454       mips_set_option_string (&mips_tune_string, "4100");
14455       break;
14456
14457     case OPTION_NO_M4100:
14458       break;
14459
14460     case OPTION_M3900:
14461       mips_set_option_string (&mips_arch_string, "3900");
14462       mips_set_option_string (&mips_tune_string, "3900");
14463       break;
14464
14465     case OPTION_NO_M3900:
14466       break;
14467
14468     case OPTION_MICROMIPS:
14469       if (file_mips_opts.mips16 == 1)
14470         {
14471           as_bad (_("-mmicromips cannot be used with -mips16"));
14472           return 0;
14473         }
14474       file_mips_opts.micromips = 1;
14475       mips_no_prev_insn ();
14476       break;
14477
14478     case OPTION_NO_MICROMIPS:
14479       file_mips_opts.micromips = 0;
14480       mips_no_prev_insn ();
14481       break;
14482
14483     case OPTION_MIPS16:
14484       if (file_mips_opts.micromips == 1)
14485         {
14486           as_bad (_("-mips16 cannot be used with -micromips"));
14487           return 0;
14488         }
14489       file_mips_opts.mips16 = 1;
14490       mips_no_prev_insn ();
14491       break;
14492
14493     case OPTION_NO_MIPS16:
14494       file_mips_opts.mips16 = 0;
14495       mips_no_prev_insn ();
14496       break;
14497
14498     case OPTION_FIX_24K:
14499       mips_fix_24k = 1;
14500       break;
14501
14502     case OPTION_NO_FIX_24K:
14503       mips_fix_24k = 0;
14504       break;
14505
14506     case OPTION_FIX_RM7000:
14507       mips_fix_rm7000 = 1;
14508       break;
14509
14510     case OPTION_NO_FIX_RM7000:
14511       mips_fix_rm7000 = 0;
14512       break;
14513
14514     case OPTION_FIX_LOONGSON2F_JUMP:
14515       mips_fix_loongson2f_jump = TRUE;
14516       break;
14517
14518     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14519       mips_fix_loongson2f_jump = FALSE;
14520       break;
14521
14522     case OPTION_FIX_LOONGSON2F_NOP:
14523       mips_fix_loongson2f_nop = TRUE;
14524       break;
14525
14526     case OPTION_NO_FIX_LOONGSON2F_NOP:
14527       mips_fix_loongson2f_nop = FALSE;
14528       break;
14529
14530     case OPTION_FIX_VR4120:
14531       mips_fix_vr4120 = 1;
14532       break;
14533
14534     case OPTION_NO_FIX_VR4120:
14535       mips_fix_vr4120 = 0;
14536       break;
14537
14538     case OPTION_FIX_VR4130:
14539       mips_fix_vr4130 = 1;
14540       break;
14541
14542     case OPTION_NO_FIX_VR4130:
14543       mips_fix_vr4130 = 0;
14544       break;
14545
14546     case OPTION_FIX_CN63XXP1:
14547       mips_fix_cn63xxp1 = TRUE;
14548       break;
14549
14550     case OPTION_NO_FIX_CN63XXP1:
14551       mips_fix_cn63xxp1 = FALSE;
14552       break;
14553
14554     case OPTION_RELAX_BRANCH:
14555       mips_relax_branch = 1;
14556       break;
14557
14558     case OPTION_NO_RELAX_BRANCH:
14559       mips_relax_branch = 0;
14560       break;
14561
14562     case OPTION_IGNORE_BRANCH_ISA:
14563       mips_ignore_branch_isa = TRUE;
14564       break;
14565
14566     case OPTION_NO_IGNORE_BRANCH_ISA:
14567       mips_ignore_branch_isa = FALSE;
14568       break;
14569
14570     case OPTION_INSN32:
14571       file_mips_opts.insn32 = TRUE;
14572       break;
14573
14574     case OPTION_NO_INSN32:
14575       file_mips_opts.insn32 = FALSE;
14576       break;
14577
14578     case OPTION_MSHARED:
14579       mips_in_shared = TRUE;
14580       break;
14581
14582     case OPTION_MNO_SHARED:
14583       mips_in_shared = FALSE;
14584       break;
14585
14586     case OPTION_MSYM32:
14587       file_mips_opts.sym32 = TRUE;
14588       break;
14589
14590     case OPTION_MNO_SYM32:
14591       file_mips_opts.sym32 = FALSE;
14592       break;
14593
14594       /* When generating ELF code, we permit -KPIC and -call_shared to
14595          select SVR4_PIC, and -non_shared to select no PIC.  This is
14596          intended to be compatible with Irix 5.  */
14597     case OPTION_CALL_SHARED:
14598       mips_pic = SVR4_PIC;
14599       mips_abicalls = TRUE;
14600       break;
14601
14602     case OPTION_CALL_NONPIC:
14603       mips_pic = NO_PIC;
14604       mips_abicalls = TRUE;
14605       break;
14606
14607     case OPTION_NON_SHARED:
14608       mips_pic = NO_PIC;
14609       mips_abicalls = FALSE;
14610       break;
14611
14612       /* The -xgot option tells the assembler to use 32 bit offsets
14613          when accessing the got in SVR4_PIC mode.  It is for Irix
14614          compatibility.  */
14615     case OPTION_XGOT:
14616       mips_big_got = 1;
14617       break;
14618
14619     case 'G':
14620       g_switch_value = atoi (arg);
14621       g_switch_seen = 1;
14622       break;
14623
14624       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14625          and -mabi=64.  */
14626     case OPTION_32:
14627       mips_abi = O32_ABI;
14628       break;
14629
14630     case OPTION_N32:
14631       mips_abi = N32_ABI;
14632       break;
14633
14634     case OPTION_64:
14635       mips_abi = N64_ABI;
14636       if (!support_64bit_objects())
14637         as_fatal (_("no compiled in support for 64 bit object file format"));
14638       break;
14639
14640     case OPTION_GP32:
14641       file_mips_opts.gp = 32;
14642       break;
14643
14644     case OPTION_GP64:
14645       file_mips_opts.gp = 64;
14646       break;
14647
14648     case OPTION_FP32:
14649       file_mips_opts.fp = 32;
14650       break;
14651
14652     case OPTION_FPXX:
14653       file_mips_opts.fp = 0;
14654       break;
14655
14656     case OPTION_FP64:
14657       file_mips_opts.fp = 64;
14658       break;
14659
14660     case OPTION_ODD_SPREG:
14661       file_mips_opts.oddspreg = 1;
14662       break;
14663
14664     case OPTION_NO_ODD_SPREG:
14665       file_mips_opts.oddspreg = 0;
14666       break;
14667
14668     case OPTION_SINGLE_FLOAT:
14669       file_mips_opts.single_float = 1;
14670       break;
14671
14672     case OPTION_DOUBLE_FLOAT:
14673       file_mips_opts.single_float = 0;
14674       break;
14675
14676     case OPTION_SOFT_FLOAT:
14677       file_mips_opts.soft_float = 1;
14678       break;
14679
14680     case OPTION_HARD_FLOAT:
14681       file_mips_opts.soft_float = 0;
14682       break;
14683
14684     case OPTION_MABI:
14685       if (strcmp (arg, "32") == 0)
14686         mips_abi = O32_ABI;
14687       else if (strcmp (arg, "o64") == 0)
14688         mips_abi = O64_ABI;
14689       else if (strcmp (arg, "n32") == 0)
14690         mips_abi = N32_ABI;
14691       else if (strcmp (arg, "64") == 0)
14692         {
14693           mips_abi = N64_ABI;
14694           if (! support_64bit_objects())
14695             as_fatal (_("no compiled in support for 64 bit object file "
14696                         "format"));
14697         }
14698       else if (strcmp (arg, "eabi") == 0)
14699         mips_abi = EABI_ABI;
14700       else
14701         {
14702           as_fatal (_("invalid abi -mabi=%s"), arg);
14703           return 0;
14704         }
14705       break;
14706
14707     case OPTION_M7000_HILO_FIX:
14708       mips_7000_hilo_fix = TRUE;
14709       break;
14710
14711     case OPTION_MNO_7000_HILO_FIX:
14712       mips_7000_hilo_fix = FALSE;
14713       break;
14714
14715     case OPTION_MDEBUG:
14716       mips_flag_mdebug = TRUE;
14717       break;
14718
14719     case OPTION_NO_MDEBUG:
14720       mips_flag_mdebug = FALSE;
14721       break;
14722
14723     case OPTION_PDR:
14724       mips_flag_pdr = TRUE;
14725       break;
14726
14727     case OPTION_NO_PDR:
14728       mips_flag_pdr = FALSE;
14729       break;
14730
14731     case OPTION_MVXWORKS_PIC:
14732       mips_pic = VXWORKS_PIC;
14733       break;
14734
14735     case OPTION_NAN:
14736       if (strcmp (arg, "2008") == 0)
14737         mips_nan2008 = 1;
14738       else if (strcmp (arg, "legacy") == 0)
14739         mips_nan2008 = 0;
14740       else
14741         {
14742           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14743           return 0;
14744         }
14745       break;
14746
14747     default:
14748       return 0;
14749     }
14750
14751     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14752
14753   return 1;
14754 }
14755 \f
14756 /* Set up globals to tune for the ISA or processor described by INFO.  */
14757
14758 static void
14759 mips_set_tune (const struct mips_cpu_info *info)
14760 {
14761   if (info != 0)
14762     mips_tune = info->cpu;
14763 }
14764
14765
14766 void
14767 mips_after_parse_args (void)
14768 {
14769   const struct mips_cpu_info *arch_info = 0;
14770   const struct mips_cpu_info *tune_info = 0;
14771
14772   /* GP relative stuff not working for PE */
14773   if (strncmp (TARGET_OS, "pe", 2) == 0)
14774     {
14775       if (g_switch_seen && g_switch_value != 0)
14776         as_bad (_("-G not supported in this configuration"));
14777       g_switch_value = 0;
14778     }
14779
14780   if (mips_abi == NO_ABI)
14781     mips_abi = MIPS_DEFAULT_ABI;
14782
14783   /* The following code determines the architecture.
14784      Similar code was added to GCC 3.3 (see override_options() in
14785      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14786      as much as possible.  */
14787
14788   if (mips_arch_string != 0)
14789     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14790
14791   if (file_mips_opts.isa != ISA_UNKNOWN)
14792     {
14793       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14794          ISA level specified by -mipsN, while arch_info->isa contains
14795          the -march selection (if any).  */
14796       if (arch_info != 0)
14797         {
14798           /* -march takes precedence over -mipsN, since it is more descriptive.
14799              There's no harm in specifying both as long as the ISA levels
14800              are the same.  */
14801           if (file_mips_opts.isa != arch_info->isa)
14802             as_bad (_("-%s conflicts with the other architecture options,"
14803                       " which imply -%s"),
14804                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14805                     mips_cpu_info_from_isa (arch_info->isa)->name);
14806         }
14807       else
14808         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14809     }
14810
14811   if (arch_info == 0)
14812     {
14813       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14814       gas_assert (arch_info);
14815     }
14816
14817   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14818     as_bad (_("-march=%s is not compatible with the selected ABI"),
14819             arch_info->name);
14820
14821   file_mips_opts.arch = arch_info->cpu;
14822   file_mips_opts.isa = arch_info->isa;
14823
14824   /* Set up initial mips_opts state.  */
14825   mips_opts = file_mips_opts;
14826
14827   /* The register size inference code is now placed in
14828      file_mips_check_options.  */
14829
14830   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14831      processor.  */
14832   if (mips_tune_string != 0)
14833     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14834
14835   if (tune_info == 0)
14836     mips_set_tune (arch_info);
14837   else
14838     mips_set_tune (tune_info);
14839
14840   if (mips_flag_mdebug < 0)
14841     mips_flag_mdebug = 0;
14842 }
14843 \f
14844 void
14845 mips_init_after_args (void)
14846 {
14847   /* initialize opcodes */
14848   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14849   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14850 }
14851
14852 long
14853 md_pcrel_from (fixS *fixP)
14854 {
14855   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14856   switch (fixP->fx_r_type)
14857     {
14858     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14859     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14860       /* Return the address of the delay slot.  */
14861       return addr + 2;
14862
14863     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14864     case BFD_RELOC_MICROMIPS_JMP:
14865     case BFD_RELOC_MIPS16_16_PCREL_S1:
14866     case BFD_RELOC_16_PCREL_S2:
14867     case BFD_RELOC_MIPS_21_PCREL_S2:
14868     case BFD_RELOC_MIPS_26_PCREL_S2:
14869     case BFD_RELOC_MIPS_JMP:
14870       /* Return the address of the delay slot.  */
14871       return addr + 4;
14872
14873     case BFD_RELOC_MIPS_18_PCREL_S3:
14874       /* Return the aligned address of the doubleword containing
14875          the instruction.  */
14876       return addr & ~7;
14877
14878     default:
14879       return addr;
14880     }
14881 }
14882
14883 /* This is called before the symbol table is processed.  In order to
14884    work with gcc when using mips-tfile, we must keep all local labels.
14885    However, in other cases, we want to discard them.  If we were
14886    called with -g, but we didn't see any debugging information, it may
14887    mean that gcc is smuggling debugging information through to
14888    mips-tfile, in which case we must generate all local labels.  */
14889
14890 void
14891 mips_frob_file_before_adjust (void)
14892 {
14893 #ifndef NO_ECOFF_DEBUGGING
14894   if (ECOFF_DEBUGGING
14895       && mips_debug != 0
14896       && ! ecoff_debugging_seen)
14897     flag_keep_locals = 1;
14898 #endif
14899 }
14900
14901 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14902    the corresponding LO16 reloc.  This is called before md_apply_fix and
14903    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14904    relocation operators.
14905
14906    For our purposes, a %lo() expression matches a %got() or %hi()
14907    expression if:
14908
14909       (a) it refers to the same symbol; and
14910       (b) the offset applied in the %lo() expression is no lower than
14911           the offset applied in the %got() or %hi().
14912
14913    (b) allows us to cope with code like:
14914
14915         lui     $4,%hi(foo)
14916         lh      $4,%lo(foo+2)($4)
14917
14918    ...which is legal on RELA targets, and has a well-defined behaviour
14919    if the user knows that adding 2 to "foo" will not induce a carry to
14920    the high 16 bits.
14921
14922    When several %lo()s match a particular %got() or %hi(), we use the
14923    following rules to distinguish them:
14924
14925      (1) %lo()s with smaller offsets are a better match than %lo()s with
14926          higher offsets.
14927
14928      (2) %lo()s with no matching %got() or %hi() are better than those
14929          that already have a matching %got() or %hi().
14930
14931      (3) later %lo()s are better than earlier %lo()s.
14932
14933    These rules are applied in order.
14934
14935    (1) means, among other things, that %lo()s with identical offsets are
14936    chosen if they exist.
14937
14938    (2) means that we won't associate several high-part relocations with
14939    the same low-part relocation unless there's no alternative.  Having
14940    several high parts for the same low part is a GNU extension; this rule
14941    allows careful users to avoid it.
14942
14943    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14944    with the last high-part relocation being at the front of the list.
14945    It therefore makes sense to choose the last matching low-part
14946    relocation, all other things being equal.  It's also easier
14947    to code that way.  */
14948
14949 void
14950 mips_frob_file (void)
14951 {
14952   struct mips_hi_fixup *l;
14953   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14954
14955   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14956     {
14957       segment_info_type *seginfo;
14958       bfd_boolean matched_lo_p;
14959       fixS **hi_pos, **lo_pos, **pos;
14960
14961       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14962
14963       /* If a GOT16 relocation turns out to be against a global symbol,
14964          there isn't supposed to be a matching LO.  Ignore %gots against
14965          constants; we'll report an error for those later.  */
14966       if (got16_reloc_p (l->fixp->fx_r_type)
14967           && !(l->fixp->fx_addsy
14968                && pic_need_relax (l->fixp->fx_addsy)))
14969         continue;
14970
14971       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14972       if (fixup_has_matching_lo_p (l->fixp))
14973         continue;
14974
14975       seginfo = seg_info (l->seg);
14976
14977       /* Set HI_POS to the position of this relocation in the chain.
14978          Set LO_POS to the position of the chosen low-part relocation.
14979          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14980          relocation that matches an immediately-preceding high-part
14981          relocation.  */
14982       hi_pos = NULL;
14983       lo_pos = NULL;
14984       matched_lo_p = FALSE;
14985       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14986
14987       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14988         {
14989           if (*pos == l->fixp)
14990             hi_pos = pos;
14991
14992           if ((*pos)->fx_r_type == looking_for_rtype
14993               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14994               && (*pos)->fx_offset >= l->fixp->fx_offset
14995               && (lo_pos == NULL
14996                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14997                   || (!matched_lo_p
14998                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14999             lo_pos = pos;
15000
15001           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15002                           && fixup_has_matching_lo_p (*pos));
15003         }
15004
15005       /* If we found a match, remove the high-part relocation from its
15006          current position and insert it before the low-part relocation.
15007          Make the offsets match so that fixup_has_matching_lo_p()
15008          will return true.
15009
15010          We don't warn about unmatched high-part relocations since some
15011          versions of gcc have been known to emit dead "lui ...%hi(...)"
15012          instructions.  */
15013       if (lo_pos != NULL)
15014         {
15015           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15016           if (l->fixp->fx_next != *lo_pos)
15017             {
15018               *hi_pos = l->fixp->fx_next;
15019               l->fixp->fx_next = *lo_pos;
15020               *lo_pos = l->fixp;
15021             }
15022         }
15023     }
15024 }
15025
15026 int
15027 mips_force_relocation (fixS *fixp)
15028 {
15029   if (generic_force_reloc (fixp))
15030     return 1;
15031
15032   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15033      so that the linker relaxation can update targets.  */
15034   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15035       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15036       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15037     return 1;
15038
15039   /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15040      and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15041      microMIPS symbols so that we can do cross-mode branch diagnostics
15042      and BAL to JALX conversion by the linker.  */
15043   if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15044        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15045        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15046       && fixp->fx_addsy
15047       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15048     return 1;
15049
15050   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15051   if (ISA_IS_R6 (file_mips_opts.isa)
15052       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15053           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15054           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15055           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15056           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15057           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15058           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15059     return 1;
15060
15061   return 0;
15062 }
15063
15064 /* Implement TC_FORCE_RELOCATION_ABS.  */
15065
15066 bfd_boolean
15067 mips_force_relocation_abs (fixS *fixp)
15068 {
15069   if (generic_force_reloc (fixp))
15070     return TRUE;
15071
15072   /* These relocations do not have enough bits in the in-place addend
15073      to hold an arbitrary absolute section's offset.  */
15074   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15075     return TRUE;
15076
15077   return FALSE;
15078 }
15079
15080 /* Read the instruction associated with RELOC from BUF.  */
15081
15082 static unsigned int
15083 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15084 {
15085   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15086     return read_compressed_insn (buf, 4);
15087   else
15088     return read_insn (buf);
15089 }
15090
15091 /* Write instruction INSN to BUF, given that it has been relocated
15092    by RELOC.  */
15093
15094 static void
15095 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15096                   unsigned long insn)
15097 {
15098   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15099     write_compressed_insn (buf, insn, 4);
15100   else
15101     write_insn (buf, insn);
15102 }
15103
15104 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15105    to a symbol in another ISA mode, which cannot be converted to JALX.  */
15106
15107 static bfd_boolean
15108 fix_bad_cross_mode_jump_p (fixS *fixP)
15109 {
15110   unsigned long opcode;
15111   int other;
15112   char *buf;
15113
15114   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15115     return FALSE;
15116
15117   other = S_GET_OTHER (fixP->fx_addsy);
15118   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15119   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15120   switch (fixP->fx_r_type)
15121     {
15122     case BFD_RELOC_MIPS_JMP:
15123       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15124     case BFD_RELOC_MICROMIPS_JMP:
15125       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15126     default:
15127       return FALSE;
15128     }
15129 }
15130
15131 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15132    jump to a symbol in the same ISA mode.  */
15133
15134 static bfd_boolean
15135 fix_bad_same_mode_jalx_p (fixS *fixP)
15136 {
15137   unsigned long opcode;
15138   int other;
15139   char *buf;
15140
15141   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15142     return FALSE;
15143
15144   other = S_GET_OTHER (fixP->fx_addsy);
15145   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15146   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15147   switch (fixP->fx_r_type)
15148     {
15149     case BFD_RELOC_MIPS_JMP:
15150       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15151     case BFD_RELOC_MIPS16_JMP:
15152       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15153     case BFD_RELOC_MICROMIPS_JMP:
15154       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15155     default:
15156       return FALSE;
15157     }
15158 }
15159
15160 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15161    to a symbol whose value plus addend is not aligned according to the
15162    ultimate (after linker relaxation) jump instruction's immediate field
15163    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15164    regular MIPS code, to (1 << 2).  */
15165
15166 static bfd_boolean
15167 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15168 {
15169   bfd_boolean micro_to_mips_p;
15170   valueT val;
15171   int other;
15172
15173   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15174     return FALSE;
15175
15176   other = S_GET_OTHER (fixP->fx_addsy);
15177   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15178   val += fixP->fx_offset;
15179   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15180                      && !ELF_ST_IS_MICROMIPS (other));
15181   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15182           != ELF_ST_IS_COMPRESSED (other));
15183 }
15184
15185 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15186    to a symbol whose annotation indicates another ISA mode.  For absolute
15187    symbols check the ISA bit instead.
15188
15189    We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15190    symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15191    MIPS symbols and associated with BAL instructions as these instructions
15192    may be be converted to JALX by the linker.  */
15193
15194 static bfd_boolean
15195 fix_bad_cross_mode_branch_p (fixS *fixP)
15196 {
15197   bfd_boolean absolute_p;
15198   unsigned long opcode;
15199   asection *symsec;
15200   valueT val;
15201   int other;
15202   char *buf;
15203
15204   if (mips_ignore_branch_isa)
15205     return FALSE;
15206
15207   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15208     return FALSE;
15209
15210   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15211   absolute_p = bfd_is_abs_section (symsec);
15212
15213   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15214   other = S_GET_OTHER (fixP->fx_addsy);
15215
15216   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15217   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15218   switch (fixP->fx_r_type)
15219     {
15220     case BFD_RELOC_16_PCREL_S2:
15221       return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15222               && opcode != 0x0411);
15223     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15224       return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15225               && opcode != 0x4060);
15226     case BFD_RELOC_MIPS_21_PCREL_S2:
15227     case BFD_RELOC_MIPS_26_PCREL_S2:
15228       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15229     case BFD_RELOC_MIPS16_16_PCREL_S1:
15230       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15231     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15232     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15233       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15234     default:
15235       abort ();
15236     }
15237 }
15238
15239 /* Return TRUE if the symbol plus addend associated with a regular MIPS
15240    branch instruction pointed to by FIXP is not aligned according to the
15241    branch instruction's immediate field requirement.  We need the addend
15242    to preserve the ISA bit and also the sum must not have bit 2 set.  We
15243    must explicitly OR in the ISA bit from symbol annotation as the bit
15244    won't be set in the symbol's value then.  */
15245
15246 static bfd_boolean
15247 fix_bad_misaligned_branch_p (fixS *fixP)
15248 {
15249   bfd_boolean absolute_p;
15250   asection *symsec;
15251   valueT isa_bit;
15252   valueT val;
15253   valueT off;
15254   int other;
15255
15256   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15257     return FALSE;
15258
15259   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15260   absolute_p = bfd_is_abs_section (symsec);
15261
15262   val = S_GET_VALUE (fixP->fx_addsy);
15263   other = S_GET_OTHER (fixP->fx_addsy);
15264   off = fixP->fx_offset;
15265
15266   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15267   val |= ELF_ST_IS_COMPRESSED (other);
15268   val += off;
15269   return (val & 0x3) != isa_bit;
15270 }
15271
15272 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15273    and its calculated value VAL.  */
15274
15275 static void
15276 fix_validate_branch (fixS *fixP, valueT val)
15277 {
15278   if (fixP->fx_done && (val & 0x3) != 0)
15279     as_bad_where (fixP->fx_file, fixP->fx_line,
15280                   _("branch to misaligned address (0x%lx)"),
15281                   (long) (val + md_pcrel_from (fixP)));
15282   else if (fix_bad_cross_mode_branch_p (fixP))
15283     as_bad_where (fixP->fx_file, fixP->fx_line,
15284                   _("branch to a symbol in another ISA mode"));
15285   else if (fix_bad_misaligned_branch_p (fixP))
15286     as_bad_where (fixP->fx_file, fixP->fx_line,
15287                   _("branch to misaligned address (0x%lx)"),
15288                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15289   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15290     as_bad_where (fixP->fx_file, fixP->fx_line,
15291                   _("cannot encode misaligned addend "
15292                     "in the relocatable field (0x%lx)"),
15293                   (long) fixP->fx_offset);
15294 }
15295
15296 /* Apply a fixup to the object file.  */
15297
15298 void
15299 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15300 {
15301   char *buf;
15302   unsigned long insn;
15303   reloc_howto_type *howto;
15304
15305   if (fixP->fx_pcrel)
15306     switch (fixP->fx_r_type)
15307       {
15308       case BFD_RELOC_16_PCREL_S2:
15309       case BFD_RELOC_MIPS16_16_PCREL_S1:
15310       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15311       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15312       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15313       case BFD_RELOC_32_PCREL:
15314       case BFD_RELOC_MIPS_21_PCREL_S2:
15315       case BFD_RELOC_MIPS_26_PCREL_S2:
15316       case BFD_RELOC_MIPS_18_PCREL_S3:
15317       case BFD_RELOC_MIPS_19_PCREL_S2:
15318       case BFD_RELOC_HI16_S_PCREL:
15319       case BFD_RELOC_LO16_PCREL:
15320         break;
15321
15322       case BFD_RELOC_32:
15323         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15324         break;
15325
15326       default:
15327         as_bad_where (fixP->fx_file, fixP->fx_line,
15328                       _("PC-relative reference to a different section"));
15329         break;
15330       }
15331
15332   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15333      that have no MIPS ELF equivalent.  */
15334   if (fixP->fx_r_type != BFD_RELOC_8)
15335     {
15336       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15337       if (!howto)
15338         return;
15339     }
15340
15341   gas_assert (fixP->fx_size == 2
15342               || fixP->fx_size == 4
15343               || fixP->fx_r_type == BFD_RELOC_8
15344               || fixP->fx_r_type == BFD_RELOC_16
15345               || fixP->fx_r_type == BFD_RELOC_64
15346               || fixP->fx_r_type == BFD_RELOC_CTOR
15347               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15348               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15349               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15350               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15351               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15352               || fixP->fx_r_type == BFD_RELOC_NONE);
15353
15354   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15355
15356   /* Don't treat parts of a composite relocation as done.  There are two
15357      reasons for this:
15358
15359      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15360          should nevertheless be emitted if the first part is.
15361
15362      (2) In normal usage, composite relocations are never assembly-time
15363          constants.  The easiest way of dealing with the pathological
15364          exceptions is to generate a relocation against STN_UNDEF and
15365          leave everything up to the linker.  */
15366   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15367     fixP->fx_done = 1;
15368
15369   switch (fixP->fx_r_type)
15370     {
15371     case BFD_RELOC_MIPS_TLS_GD:
15372     case BFD_RELOC_MIPS_TLS_LDM:
15373     case BFD_RELOC_MIPS_TLS_DTPREL32:
15374     case BFD_RELOC_MIPS_TLS_DTPREL64:
15375     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15376     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15377     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15378     case BFD_RELOC_MIPS_TLS_TPREL32:
15379     case BFD_RELOC_MIPS_TLS_TPREL64:
15380     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15381     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15382     case BFD_RELOC_MICROMIPS_TLS_GD:
15383     case BFD_RELOC_MICROMIPS_TLS_LDM:
15384     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15385     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15386     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15387     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15388     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15389     case BFD_RELOC_MIPS16_TLS_GD:
15390     case BFD_RELOC_MIPS16_TLS_LDM:
15391     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15392     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15393     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15394     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15395     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15396       if (fixP->fx_addsy)
15397         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15398       else
15399         as_bad_where (fixP->fx_file, fixP->fx_line,
15400                       _("TLS relocation against a constant"));
15401       break;
15402
15403     case BFD_RELOC_MIPS_JMP:
15404     case BFD_RELOC_MIPS16_JMP:
15405     case BFD_RELOC_MICROMIPS_JMP:
15406       {
15407         int shift;
15408
15409         gas_assert (!fixP->fx_done);
15410
15411         /* Shift is 2, unusually, for microMIPS JALX.  */
15412         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15413             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15414           shift = 1;
15415         else
15416           shift = 2;
15417
15418         if (fix_bad_cross_mode_jump_p (fixP))
15419           as_bad_where (fixP->fx_file, fixP->fx_line,
15420                         _("jump to a symbol in another ISA mode"));
15421         else if (fix_bad_same_mode_jalx_p (fixP))
15422           as_bad_where (fixP->fx_file, fixP->fx_line,
15423                         _("JALX to a symbol in the same ISA mode"));
15424         else if (fix_bad_misaligned_jump_p (fixP, shift))
15425           as_bad_where (fixP->fx_file, fixP->fx_line,
15426                         _("jump to misaligned address (0x%lx)"),
15427                         (long) (S_GET_VALUE (fixP->fx_addsy)
15428                                 + fixP->fx_offset));
15429         else if (HAVE_IN_PLACE_ADDENDS
15430                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15431           as_bad_where (fixP->fx_file, fixP->fx_line,
15432                         _("cannot encode misaligned addend "
15433                           "in the relocatable field (0x%lx)"),
15434                         (long) fixP->fx_offset);
15435       }
15436       /* Fall through.  */
15437
15438     case BFD_RELOC_MIPS_SHIFT5:
15439     case BFD_RELOC_MIPS_SHIFT6:
15440     case BFD_RELOC_MIPS_GOT_DISP:
15441     case BFD_RELOC_MIPS_GOT_PAGE:
15442     case BFD_RELOC_MIPS_GOT_OFST:
15443     case BFD_RELOC_MIPS_SUB:
15444     case BFD_RELOC_MIPS_INSERT_A:
15445     case BFD_RELOC_MIPS_INSERT_B:
15446     case BFD_RELOC_MIPS_DELETE:
15447     case BFD_RELOC_MIPS_HIGHEST:
15448     case BFD_RELOC_MIPS_HIGHER:
15449     case BFD_RELOC_MIPS_SCN_DISP:
15450     case BFD_RELOC_MIPS_REL16:
15451     case BFD_RELOC_MIPS_RELGOT:
15452     case BFD_RELOC_MIPS_JALR:
15453     case BFD_RELOC_HI16:
15454     case BFD_RELOC_HI16_S:
15455     case BFD_RELOC_LO16:
15456     case BFD_RELOC_GPREL16:
15457     case BFD_RELOC_MIPS_LITERAL:
15458     case BFD_RELOC_MIPS_CALL16:
15459     case BFD_RELOC_MIPS_GOT16:
15460     case BFD_RELOC_GPREL32:
15461     case BFD_RELOC_MIPS_GOT_HI16:
15462     case BFD_RELOC_MIPS_GOT_LO16:
15463     case BFD_RELOC_MIPS_CALL_HI16:
15464     case BFD_RELOC_MIPS_CALL_LO16:
15465     case BFD_RELOC_HI16_S_PCREL:
15466     case BFD_RELOC_LO16_PCREL:
15467     case BFD_RELOC_MIPS16_GPREL:
15468     case BFD_RELOC_MIPS16_GOT16:
15469     case BFD_RELOC_MIPS16_CALL16:
15470     case BFD_RELOC_MIPS16_HI16:
15471     case BFD_RELOC_MIPS16_HI16_S:
15472     case BFD_RELOC_MIPS16_LO16:
15473     case BFD_RELOC_MICROMIPS_GOT_DISP:
15474     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15475     case BFD_RELOC_MICROMIPS_GOT_OFST:
15476     case BFD_RELOC_MICROMIPS_SUB:
15477     case BFD_RELOC_MICROMIPS_HIGHEST:
15478     case BFD_RELOC_MICROMIPS_HIGHER:
15479     case BFD_RELOC_MICROMIPS_SCN_DISP:
15480     case BFD_RELOC_MICROMIPS_JALR:
15481     case BFD_RELOC_MICROMIPS_HI16:
15482     case BFD_RELOC_MICROMIPS_HI16_S:
15483     case BFD_RELOC_MICROMIPS_LO16:
15484     case BFD_RELOC_MICROMIPS_GPREL16:
15485     case BFD_RELOC_MICROMIPS_LITERAL:
15486     case BFD_RELOC_MICROMIPS_CALL16:
15487     case BFD_RELOC_MICROMIPS_GOT16:
15488     case BFD_RELOC_MICROMIPS_GOT_HI16:
15489     case BFD_RELOC_MICROMIPS_GOT_LO16:
15490     case BFD_RELOC_MICROMIPS_CALL_HI16:
15491     case BFD_RELOC_MICROMIPS_CALL_LO16:
15492     case BFD_RELOC_MIPS_EH:
15493       if (fixP->fx_done)
15494         {
15495           offsetT value;
15496
15497           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15498             {
15499               insn = read_reloc_insn (buf, fixP->fx_r_type);
15500               if (mips16_reloc_p (fixP->fx_r_type))
15501                 insn |= mips16_immed_extend (value, 16);
15502               else
15503                 insn |= (value & 0xffff);
15504               write_reloc_insn (buf, fixP->fx_r_type, insn);
15505             }
15506           else
15507             as_bad_where (fixP->fx_file, fixP->fx_line,
15508                           _("unsupported constant in relocation"));
15509         }
15510       break;
15511
15512     case BFD_RELOC_64:
15513       /* This is handled like BFD_RELOC_32, but we output a sign
15514          extended value if we are only 32 bits.  */
15515       if (fixP->fx_done)
15516         {
15517           if (8 <= sizeof (valueT))
15518             md_number_to_chars (buf, *valP, 8);
15519           else
15520             {
15521               valueT hiv;
15522
15523               if ((*valP & 0x80000000) != 0)
15524                 hiv = 0xffffffff;
15525               else
15526                 hiv = 0;
15527               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15528               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15529             }
15530         }
15531       break;
15532
15533     case BFD_RELOC_RVA:
15534     case BFD_RELOC_32:
15535     case BFD_RELOC_32_PCREL:
15536     case BFD_RELOC_16:
15537     case BFD_RELOC_8:
15538       /* If we are deleting this reloc entry, we must fill in the
15539          value now.  This can happen if we have a .word which is not
15540          resolved when it appears but is later defined.  */
15541       if (fixP->fx_done)
15542         md_number_to_chars (buf, *valP, fixP->fx_size);
15543       break;
15544
15545     case BFD_RELOC_MIPS_21_PCREL_S2:
15546       fix_validate_branch (fixP, *valP);
15547       if (!fixP->fx_done)
15548         break;
15549
15550       if (*valP + 0x400000 <= 0x7fffff)
15551         {
15552           insn = read_insn (buf);
15553           insn |= (*valP >> 2) & 0x1fffff;
15554           write_insn (buf, insn);
15555         }
15556       else
15557         as_bad_where (fixP->fx_file, fixP->fx_line,
15558                       _("branch out of range"));
15559       break;
15560
15561     case BFD_RELOC_MIPS_26_PCREL_S2:
15562       fix_validate_branch (fixP, *valP);
15563       if (!fixP->fx_done)
15564         break;
15565
15566       if (*valP + 0x8000000 <= 0xfffffff)
15567         {
15568           insn = read_insn (buf);
15569           insn |= (*valP >> 2) & 0x3ffffff;
15570           write_insn (buf, insn);
15571         }
15572       else
15573         as_bad_where (fixP->fx_file, fixP->fx_line,
15574                       _("branch out of range"));
15575       break;
15576
15577     case BFD_RELOC_MIPS_18_PCREL_S3:
15578       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15579         as_bad_where (fixP->fx_file, fixP->fx_line,
15580                       _("PC-relative access using misaligned symbol (%lx)"),
15581                       (long) S_GET_VALUE (fixP->fx_addsy));
15582       if ((fixP->fx_offset & 0x7) != 0)
15583         as_bad_where (fixP->fx_file, fixP->fx_line,
15584                       _("PC-relative access using misaligned offset (%lx)"),
15585                       (long) fixP->fx_offset);
15586       if (!fixP->fx_done)
15587         break;
15588
15589       if (*valP + 0x100000 <= 0x1fffff)
15590         {
15591           insn = read_insn (buf);
15592           insn |= (*valP >> 3) & 0x3ffff;
15593           write_insn (buf, insn);
15594         }
15595       else
15596         as_bad_where (fixP->fx_file, fixP->fx_line,
15597                       _("PC-relative access out of range"));
15598       break;
15599
15600     case BFD_RELOC_MIPS_19_PCREL_S2:
15601       if ((*valP & 0x3) != 0)
15602         as_bad_where (fixP->fx_file, fixP->fx_line,
15603                       _("PC-relative access to misaligned address (%lx)"),
15604                       (long) *valP);
15605       if (!fixP->fx_done)
15606         break;
15607
15608       if (*valP + 0x100000 <= 0x1fffff)
15609         {
15610           insn = read_insn (buf);
15611           insn |= (*valP >> 2) & 0x7ffff;
15612           write_insn (buf, insn);
15613         }
15614       else
15615         as_bad_where (fixP->fx_file, fixP->fx_line,
15616                       _("PC-relative access out of range"));
15617       break;
15618
15619     case BFD_RELOC_16_PCREL_S2:
15620       fix_validate_branch (fixP, *valP);
15621
15622       /* We need to save the bits in the instruction since fixup_segment()
15623          might be deleting the relocation entry (i.e., a branch within
15624          the current segment).  */
15625       if (! fixP->fx_done)
15626         break;
15627
15628       /* Update old instruction data.  */
15629       insn = read_insn (buf);
15630
15631       if (*valP + 0x20000 <= 0x3ffff)
15632         {
15633           insn |= (*valP >> 2) & 0xffff;
15634           write_insn (buf, insn);
15635         }
15636       else if (fixP->fx_tcbit2
15637                && fixP->fx_done
15638                && fixP->fx_frag->fr_address >= text_section->vma
15639                && (fixP->fx_frag->fr_address
15640                    < text_section->vma + bfd_get_section_size (text_section))
15641                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15642                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15643                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15644         {
15645           /* The branch offset is too large.  If this is an
15646              unconditional branch, and we are not generating PIC code,
15647              we can convert it to an absolute jump instruction.  */
15648           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15649             insn = 0x0c000000;  /* jal */
15650           else
15651             insn = 0x08000000;  /* j */
15652           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15653           fixP->fx_done = 0;
15654           fixP->fx_addsy = section_symbol (text_section);
15655           *valP += md_pcrel_from (fixP);
15656           write_insn (buf, insn);
15657         }
15658       else
15659         {
15660           /* If we got here, we have branch-relaxation disabled,
15661              and there's nothing we can do to fix this instruction
15662              without turning it into a longer sequence.  */
15663           as_bad_where (fixP->fx_file, fixP->fx_line,
15664                         _("branch out of range"));
15665         }
15666       break;
15667
15668     case BFD_RELOC_MIPS16_16_PCREL_S1:
15669     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15670     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15671     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15672       gas_assert (!fixP->fx_done);
15673       if (fix_bad_cross_mode_branch_p (fixP))
15674         as_bad_where (fixP->fx_file, fixP->fx_line,
15675                       _("branch to a symbol in another ISA mode"));
15676       else if (fixP->fx_addsy
15677                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15678                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15679                && (fixP->fx_offset & 0x1) != 0)
15680         as_bad_where (fixP->fx_file, fixP->fx_line,
15681                       _("branch to misaligned address (0x%lx)"),
15682                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15683       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15684         as_bad_where (fixP->fx_file, fixP->fx_line,
15685                       _("cannot encode misaligned addend "
15686                         "in the relocatable field (0x%lx)"),
15687                       (long) fixP->fx_offset);
15688       break;
15689
15690     case BFD_RELOC_VTABLE_INHERIT:
15691       fixP->fx_done = 0;
15692       if (fixP->fx_addsy
15693           && !S_IS_DEFINED (fixP->fx_addsy)
15694           && !S_IS_WEAK (fixP->fx_addsy))
15695         S_SET_WEAK (fixP->fx_addsy);
15696       break;
15697
15698     case BFD_RELOC_NONE:
15699     case BFD_RELOC_VTABLE_ENTRY:
15700       fixP->fx_done = 0;
15701       break;
15702
15703     default:
15704       abort ();
15705     }
15706
15707   /* Remember value for tc_gen_reloc.  */
15708   fixP->fx_addnumber = *valP;
15709 }
15710
15711 static symbolS *
15712 get_symbol (void)
15713 {
15714   int c;
15715   char *name;
15716   symbolS *p;
15717
15718   c = get_symbol_name (&name);
15719   p = (symbolS *) symbol_find_or_make (name);
15720   (void) restore_line_pointer (c);
15721   return p;
15722 }
15723
15724 /* Align the current frag to a given power of two.  If a particular
15725    fill byte should be used, FILL points to an integer that contains
15726    that byte, otherwise FILL is null.
15727
15728    This function used to have the comment:
15729
15730       The MIPS assembler also automatically adjusts any preceding label.
15731
15732    The implementation therefore applied the adjustment to a maximum of
15733    one label.  However, other label adjustments are applied to batches
15734    of labels, and adjusting just one caused problems when new labels
15735    were added for the sake of debugging or unwind information.
15736    We therefore adjust all preceding labels (given as LABELS) instead.  */
15737
15738 static void
15739 mips_align (int to, int *fill, struct insn_label_list *labels)
15740 {
15741   mips_emit_delays ();
15742   mips_record_compressed_mode ();
15743   if (fill == NULL && subseg_text_p (now_seg))
15744     frag_align_code (to, 0);
15745   else
15746     frag_align (to, fill ? *fill : 0, 0);
15747   record_alignment (now_seg, to);
15748   mips_move_labels (labels, FALSE);
15749 }
15750
15751 /* Align to a given power of two.  .align 0 turns off the automatic
15752    alignment used by the data creating pseudo-ops.  */
15753
15754 static void
15755 s_align (int x ATTRIBUTE_UNUSED)
15756 {
15757   int temp, fill_value, *fill_ptr;
15758   long max_alignment = 28;
15759
15760   /* o Note that the assembler pulls down any immediately preceding label
15761        to the aligned address.
15762      o It's not documented but auto alignment is reinstated by
15763        a .align pseudo instruction.
15764      o Note also that after auto alignment is turned off the mips assembler
15765        issues an error on attempt to assemble an improperly aligned data item.
15766        We don't.  */
15767
15768   temp = get_absolute_expression ();
15769   if (temp > max_alignment)
15770     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15771   else if (temp < 0)
15772     {
15773       as_warn (_("alignment negative, 0 assumed"));
15774       temp = 0;
15775     }
15776   if (*input_line_pointer == ',')
15777     {
15778       ++input_line_pointer;
15779       fill_value = get_absolute_expression ();
15780       fill_ptr = &fill_value;
15781     }
15782   else
15783     fill_ptr = 0;
15784   if (temp)
15785     {
15786       segment_info_type *si = seg_info (now_seg);
15787       struct insn_label_list *l = si->label_list;
15788       /* Auto alignment should be switched on by next section change.  */
15789       auto_align = 1;
15790       mips_align (temp, fill_ptr, l);
15791     }
15792   else
15793     {
15794       auto_align = 0;
15795     }
15796
15797   demand_empty_rest_of_line ();
15798 }
15799
15800 static void
15801 s_change_sec (int sec)
15802 {
15803   segT seg;
15804
15805   /* The ELF backend needs to know that we are changing sections, so
15806      that .previous works correctly.  We could do something like check
15807      for an obj_section_change_hook macro, but that might be confusing
15808      as it would not be appropriate to use it in the section changing
15809      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15810      This should be cleaner, somehow.  */
15811   obj_elf_section_change_hook ();
15812
15813   mips_emit_delays ();
15814
15815   switch (sec)
15816     {
15817     case 't':
15818       s_text (0);
15819       break;
15820     case 'd':
15821       s_data (0);
15822       break;
15823     case 'b':
15824       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15825       demand_empty_rest_of_line ();
15826       break;
15827
15828     case 'r':
15829       seg = subseg_new (RDATA_SECTION_NAME,
15830                         (subsegT) get_absolute_expression ());
15831       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15832                                               | SEC_READONLY | SEC_RELOC
15833                                               | SEC_DATA));
15834       if (strncmp (TARGET_OS, "elf", 3) != 0)
15835         record_alignment (seg, 4);
15836       demand_empty_rest_of_line ();
15837       break;
15838
15839     case 's':
15840       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15841       bfd_set_section_flags (stdoutput, seg,
15842                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15843       if (strncmp (TARGET_OS, "elf", 3) != 0)
15844         record_alignment (seg, 4);
15845       demand_empty_rest_of_line ();
15846       break;
15847
15848     case 'B':
15849       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15850       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15851       if (strncmp (TARGET_OS, "elf", 3) != 0)
15852         record_alignment (seg, 4);
15853       demand_empty_rest_of_line ();
15854       break;
15855     }
15856
15857   auto_align = 1;
15858 }
15859
15860 void
15861 s_change_section (int ignore ATTRIBUTE_UNUSED)
15862 {
15863   char *saved_ilp;
15864   char *section_name;
15865   char c, endc;
15866   char next_c = 0;
15867   int section_type;
15868   int section_flag;
15869   int section_entry_size;
15870   int section_alignment;
15871
15872   saved_ilp = input_line_pointer;
15873   endc = get_symbol_name (&section_name);
15874   c = (endc == '"' ? input_line_pointer[1] : endc);
15875   if (c)
15876     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
15877
15878   /* Do we have .section Name<,"flags">?  */
15879   if (c != ',' || (c == ',' && next_c == '"'))
15880     {
15881       /* Just after name is now '\0'.  */
15882       (void) restore_line_pointer (endc);
15883       input_line_pointer = saved_ilp;
15884       obj_elf_section (ignore);
15885       return;
15886     }
15887
15888   section_name = xstrdup (section_name);
15889   c = restore_line_pointer (endc);
15890
15891   input_line_pointer++;
15892
15893   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15894   if (c == ',')
15895     section_type = get_absolute_expression ();
15896   else
15897     section_type = 0;
15898
15899   if (*input_line_pointer++ == ',')
15900     section_flag = get_absolute_expression ();
15901   else
15902     section_flag = 0;
15903
15904   if (*input_line_pointer++ == ',')
15905     section_entry_size = get_absolute_expression ();
15906   else
15907     section_entry_size = 0;
15908
15909   if (*input_line_pointer++ == ',')
15910     section_alignment = get_absolute_expression ();
15911   else
15912     section_alignment = 0;
15913
15914   /* FIXME: really ignore?  */
15915   (void) section_alignment;
15916
15917   /* When using the generic form of .section (as implemented by obj-elf.c),
15918      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15919      traditionally had to fall back on the more common @progbits instead.
15920
15921      There's nothing really harmful in this, since bfd will correct
15922      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15923      means that, for backwards compatibility, the special_section entries
15924      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15925
15926      Even so, we shouldn't force users of the MIPS .section syntax to
15927      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15928      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15929      generic type-checking code.  */
15930   if (section_type == SHT_MIPS_DWARF)
15931     section_type = SHT_PROGBITS;
15932
15933   obj_elf_change_section (section_name, section_type, 0, section_flag,
15934                           section_entry_size, 0, 0, 0);
15935
15936   if (now_seg->name != section_name)
15937     free (section_name);
15938 }
15939
15940 void
15941 mips_enable_auto_align (void)
15942 {
15943   auto_align = 1;
15944 }
15945
15946 static void
15947 s_cons (int log_size)
15948 {
15949   segment_info_type *si = seg_info (now_seg);
15950   struct insn_label_list *l = si->label_list;
15951
15952   mips_emit_delays ();
15953   if (log_size > 0 && auto_align)
15954     mips_align (log_size, 0, l);
15955   cons (1 << log_size);
15956   mips_clear_insn_labels ();
15957 }
15958
15959 static void
15960 s_float_cons (int type)
15961 {
15962   segment_info_type *si = seg_info (now_seg);
15963   struct insn_label_list *l = si->label_list;
15964
15965   mips_emit_delays ();
15966
15967   if (auto_align)
15968     {
15969       if (type == 'd')
15970         mips_align (3, 0, l);
15971       else
15972         mips_align (2, 0, l);
15973     }
15974
15975   float_cons (type);
15976   mips_clear_insn_labels ();
15977 }
15978
15979 /* Handle .globl.  We need to override it because on Irix 5 you are
15980    permitted to say
15981        .globl foo .text
15982    where foo is an undefined symbol, to mean that foo should be
15983    considered to be the address of a function.  */
15984
15985 static void
15986 s_mips_globl (int x ATTRIBUTE_UNUSED)
15987 {
15988   char *name;
15989   int c;
15990   symbolS *symbolP;
15991   flagword flag;
15992
15993   do
15994     {
15995       c = get_symbol_name (&name);
15996       symbolP = symbol_find_or_make (name);
15997       S_SET_EXTERNAL (symbolP);
15998
15999       *input_line_pointer = c;
16000       SKIP_WHITESPACE_AFTER_NAME ();
16001
16002       /* On Irix 5, every global symbol that is not explicitly labelled as
16003          being a function is apparently labelled as being an object.  */
16004       flag = BSF_OBJECT;
16005
16006       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16007           && (*input_line_pointer != ','))
16008         {
16009           char *secname;
16010           asection *sec;
16011
16012           c = get_symbol_name (&secname);
16013           sec = bfd_get_section_by_name (stdoutput, secname);
16014           if (sec == NULL)
16015             as_bad (_("%s: no such section"), secname);
16016           (void) restore_line_pointer (c);
16017
16018           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16019             flag = BSF_FUNCTION;
16020         }
16021
16022       symbol_get_bfdsym (symbolP)->flags |= flag;
16023
16024       c = *input_line_pointer;
16025       if (c == ',')
16026         {
16027           input_line_pointer++;
16028           SKIP_WHITESPACE ();
16029           if (is_end_of_line[(unsigned char) *input_line_pointer])
16030             c = '\n';
16031         }
16032     }
16033   while (c == ',');
16034
16035   demand_empty_rest_of_line ();
16036 }
16037
16038 static void
16039 s_option (int x ATTRIBUTE_UNUSED)
16040 {
16041   char *opt;
16042   char c;
16043
16044   c = get_symbol_name (&opt);
16045
16046   if (*opt == 'O')
16047     {
16048       /* FIXME: What does this mean?  */
16049     }
16050   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
16051     {
16052       int i;
16053
16054       i = atoi (opt + 3);
16055       if (i != 0 && i != 2)
16056         as_bad (_(".option pic%d not supported"), i);
16057       else if (mips_pic == VXWORKS_PIC)
16058         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16059       else if (i == 0)
16060         mips_pic = NO_PIC;
16061       else if (i == 2)
16062         {
16063           mips_pic = SVR4_PIC;
16064           mips_abicalls = TRUE;
16065         }
16066
16067       if (mips_pic == SVR4_PIC)
16068         {
16069           if (g_switch_seen && g_switch_value != 0)
16070             as_warn (_("-G may not be used with SVR4 PIC code"));
16071           g_switch_value = 0;
16072           bfd_set_gp_size (stdoutput, 0);
16073         }
16074     }
16075   else
16076     as_warn (_("unrecognized option \"%s\""), opt);
16077
16078   (void) restore_line_pointer (c);
16079   demand_empty_rest_of_line ();
16080 }
16081
16082 /* This structure is used to hold a stack of .set values.  */
16083
16084 struct mips_option_stack
16085 {
16086   struct mips_option_stack *next;
16087   struct mips_set_options options;
16088 };
16089
16090 static struct mips_option_stack *mips_opts_stack;
16091
16092 /* Return status for .set/.module option handling.  */
16093
16094 enum code_option_type
16095 {
16096   /* Unrecognized option.  */
16097   OPTION_TYPE_BAD = -1,
16098
16099   /* Ordinary option.  */
16100   OPTION_TYPE_NORMAL,
16101
16102   /* ISA changing option.  */
16103   OPTION_TYPE_ISA
16104 };
16105
16106 /* Handle common .set/.module options.  Return status indicating option
16107    type.  */
16108
16109 static enum code_option_type
16110 parse_code_option (char * name)
16111 {
16112   bfd_boolean isa_set = FALSE;
16113   const struct mips_ase *ase;
16114
16115   if (strncmp (name, "at=", 3) == 0)
16116     {
16117       char *s = name + 3;
16118
16119       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16120         as_bad (_("unrecognized register name `%s'"), s);
16121     }
16122   else if (strcmp (name, "at") == 0)
16123     mips_opts.at = ATREG;
16124   else if (strcmp (name, "noat") == 0)
16125     mips_opts.at = ZERO;
16126   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16127     mips_opts.nomove = 0;
16128   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16129     mips_opts.nomove = 1;
16130   else if (strcmp (name, "bopt") == 0)
16131     mips_opts.nobopt = 0;
16132   else if (strcmp (name, "nobopt") == 0)
16133     mips_opts.nobopt = 1;
16134   else if (strcmp (name, "gp=32") == 0)
16135     mips_opts.gp = 32;
16136   else if (strcmp (name, "gp=64") == 0)
16137     mips_opts.gp = 64;
16138   else if (strcmp (name, "fp=32") == 0)
16139     mips_opts.fp = 32;
16140   else if (strcmp (name, "fp=xx") == 0)
16141     mips_opts.fp = 0;
16142   else if (strcmp (name, "fp=64") == 0)
16143     mips_opts.fp = 64;
16144   else if (strcmp (name, "softfloat") == 0)
16145     mips_opts.soft_float = 1;
16146   else if (strcmp (name, "hardfloat") == 0)
16147     mips_opts.soft_float = 0;
16148   else if (strcmp (name, "singlefloat") == 0)
16149     mips_opts.single_float = 1;
16150   else if (strcmp (name, "doublefloat") == 0)
16151     mips_opts.single_float = 0;
16152   else if (strcmp (name, "nooddspreg") == 0)
16153     mips_opts.oddspreg = 0;
16154   else if (strcmp (name, "oddspreg") == 0)
16155     mips_opts.oddspreg = 1;
16156   else if (strcmp (name, "mips16") == 0
16157            || strcmp (name, "MIPS-16") == 0)
16158     mips_opts.mips16 = 1;
16159   else if (strcmp (name, "nomips16") == 0
16160            || strcmp (name, "noMIPS-16") == 0)
16161     mips_opts.mips16 = 0;
16162   else if (strcmp (name, "micromips") == 0)
16163     mips_opts.micromips = 1;
16164   else if (strcmp (name, "nomicromips") == 0)
16165     mips_opts.micromips = 0;
16166   else if (name[0] == 'n'
16167            && name[1] == 'o'
16168            && (ase = mips_lookup_ase (name + 2)))
16169     mips_set_ase (ase, &mips_opts, FALSE);
16170   else if ((ase = mips_lookup_ase (name)))
16171     mips_set_ase (ase, &mips_opts, TRUE);
16172   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16173     {
16174       /* Permit the user to change the ISA and architecture on the fly.
16175          Needless to say, misuse can cause serious problems.  */
16176       if (strncmp (name, "arch=", 5) == 0)
16177         {
16178           const struct mips_cpu_info *p;
16179
16180           p = mips_parse_cpu ("internal use", name + 5);
16181           if (!p)
16182             as_bad (_("unknown architecture %s"), name + 5);
16183           else
16184             {
16185               mips_opts.arch = p->cpu;
16186               mips_opts.isa = p->isa;
16187               isa_set = TRUE;
16188             }
16189         }
16190       else if (strncmp (name, "mips", 4) == 0)
16191         {
16192           const struct mips_cpu_info *p;
16193
16194           p = mips_parse_cpu ("internal use", name);
16195           if (!p)
16196             as_bad (_("unknown ISA level %s"), name + 4);
16197           else
16198             {
16199               mips_opts.arch = p->cpu;
16200               mips_opts.isa = p->isa;
16201               isa_set = TRUE;
16202             }
16203         }
16204       else
16205         as_bad (_("unknown ISA or architecture %s"), name);
16206     }
16207   else if (strcmp (name, "autoextend") == 0)
16208     mips_opts.noautoextend = 0;
16209   else if (strcmp (name, "noautoextend") == 0)
16210     mips_opts.noautoextend = 1;
16211   else if (strcmp (name, "insn32") == 0)
16212     mips_opts.insn32 = TRUE;
16213   else if (strcmp (name, "noinsn32") == 0)
16214     mips_opts.insn32 = FALSE;
16215   else if (strcmp (name, "sym32") == 0)
16216     mips_opts.sym32 = TRUE;
16217   else if (strcmp (name, "nosym32") == 0)
16218     mips_opts.sym32 = FALSE;
16219   else
16220     return OPTION_TYPE_BAD;
16221
16222   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16223 }
16224
16225 /* Handle the .set pseudo-op.  */
16226
16227 static void
16228 s_mipsset (int x ATTRIBUTE_UNUSED)
16229 {
16230   enum code_option_type type = OPTION_TYPE_NORMAL;
16231   char *name = input_line_pointer, ch;
16232
16233   file_mips_check_options ();
16234
16235   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16236     ++input_line_pointer;
16237   ch = *input_line_pointer;
16238   *input_line_pointer = '\0';
16239
16240   if (strchr (name, ','))
16241     {
16242       /* Generic ".set" directive; use the generic handler.  */
16243       *input_line_pointer = ch;
16244       input_line_pointer = name;
16245       s_set (0);
16246       return;
16247     }
16248
16249   if (strcmp (name, "reorder") == 0)
16250     {
16251       if (mips_opts.noreorder)
16252         end_noreorder ();
16253     }
16254   else if (strcmp (name, "noreorder") == 0)
16255     {
16256       if (!mips_opts.noreorder)
16257         start_noreorder ();
16258     }
16259   else if (strcmp (name, "macro") == 0)
16260     mips_opts.warn_about_macros = 0;
16261   else if (strcmp (name, "nomacro") == 0)
16262     {
16263       if (mips_opts.noreorder == 0)
16264         as_bad (_("`noreorder' must be set before `nomacro'"));
16265       mips_opts.warn_about_macros = 1;
16266     }
16267   else if (strcmp (name, "gp=default") == 0)
16268     mips_opts.gp = file_mips_opts.gp;
16269   else if (strcmp (name, "fp=default") == 0)
16270     mips_opts.fp = file_mips_opts.fp;
16271   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16272     {
16273       mips_opts.isa = file_mips_opts.isa;
16274       mips_opts.arch = file_mips_opts.arch;
16275       mips_opts.gp = file_mips_opts.gp;
16276       mips_opts.fp = file_mips_opts.fp;
16277     }
16278   else if (strcmp (name, "push") == 0)
16279     {
16280       struct mips_option_stack *s;
16281
16282       s = XNEW (struct mips_option_stack);
16283       s->next = mips_opts_stack;
16284       s->options = mips_opts;
16285       mips_opts_stack = s;
16286     }
16287   else if (strcmp (name, "pop") == 0)
16288     {
16289       struct mips_option_stack *s;
16290
16291       s = mips_opts_stack;
16292       if (s == NULL)
16293         as_bad (_(".set pop with no .set push"));
16294       else
16295         {
16296           /* If we're changing the reorder mode we need to handle
16297              delay slots correctly.  */
16298           if (s->options.noreorder && ! mips_opts.noreorder)
16299             start_noreorder ();
16300           else if (! s->options.noreorder && mips_opts.noreorder)
16301             end_noreorder ();
16302
16303           mips_opts = s->options;
16304           mips_opts_stack = s->next;
16305           free (s);
16306         }
16307     }
16308   else
16309     {
16310       type = parse_code_option (name);
16311       if (type == OPTION_TYPE_BAD)
16312         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16313     }
16314
16315   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16316      registers based on what is supported by the arch/cpu.  */
16317   if (type == OPTION_TYPE_ISA)
16318     {
16319       switch (mips_opts.isa)
16320         {
16321         case 0:
16322           break;
16323         case ISA_MIPS1:
16324           /* MIPS I cannot support FPXX.  */
16325           mips_opts.fp = 32;
16326           /* fall-through.  */
16327         case ISA_MIPS2:
16328         case ISA_MIPS32:
16329         case ISA_MIPS32R2:
16330         case ISA_MIPS32R3:
16331         case ISA_MIPS32R5:
16332           mips_opts.gp = 32;
16333           if (mips_opts.fp != 0)
16334             mips_opts.fp = 32;
16335           break;
16336         case ISA_MIPS32R6:
16337           mips_opts.gp = 32;
16338           mips_opts.fp = 64;
16339           break;
16340         case ISA_MIPS3:
16341         case ISA_MIPS4:
16342         case ISA_MIPS5:
16343         case ISA_MIPS64:
16344         case ISA_MIPS64R2:
16345         case ISA_MIPS64R3:
16346         case ISA_MIPS64R5:
16347         case ISA_MIPS64R6:
16348           mips_opts.gp = 64;
16349           if (mips_opts.fp != 0)
16350             {
16351               if (mips_opts.arch == CPU_R5900)
16352                 mips_opts.fp = 32;
16353               else
16354                 mips_opts.fp = 64;
16355             }
16356           break;
16357         default:
16358           as_bad (_("unknown ISA level %s"), name + 4);
16359           break;
16360         }
16361     }
16362
16363   mips_check_options (&mips_opts, FALSE);
16364
16365   mips_check_isa_supports_ases ();
16366   *input_line_pointer = ch;
16367   demand_empty_rest_of_line ();
16368 }
16369
16370 /* Handle the .module pseudo-op.  */
16371
16372 static void
16373 s_module (int ignore ATTRIBUTE_UNUSED)
16374 {
16375   char *name = input_line_pointer, ch;
16376
16377   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16378     ++input_line_pointer;
16379   ch = *input_line_pointer;
16380   *input_line_pointer = '\0';
16381
16382   if (!file_mips_opts_checked)
16383     {
16384       if (parse_code_option (name) == OPTION_TYPE_BAD)
16385         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16386
16387       /* Update module level settings from mips_opts.  */
16388       file_mips_opts = mips_opts;
16389     }
16390   else
16391     as_bad (_(".module is not permitted after generating code"));
16392
16393   *input_line_pointer = ch;
16394   demand_empty_rest_of_line ();
16395 }
16396
16397 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16398    .option pic2.  It means to generate SVR4 PIC calls.  */
16399
16400 static void
16401 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16402 {
16403   mips_pic = SVR4_PIC;
16404   mips_abicalls = TRUE;
16405
16406   if (g_switch_seen && g_switch_value != 0)
16407     as_warn (_("-G may not be used with SVR4 PIC code"));
16408   g_switch_value = 0;
16409
16410   bfd_set_gp_size (stdoutput, 0);
16411   demand_empty_rest_of_line ();
16412 }
16413
16414 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16415    PIC code.  It sets the $gp register for the function based on the
16416    function address, which is in the register named in the argument.
16417    This uses a relocation against _gp_disp, which is handled specially
16418    by the linker.  The result is:
16419         lui     $gp,%hi(_gp_disp)
16420         addiu   $gp,$gp,%lo(_gp_disp)
16421         addu    $gp,$gp,.cpload argument
16422    The .cpload argument is normally $25 == $t9.
16423
16424    The -mno-shared option changes this to:
16425         lui     $gp,%hi(__gnu_local_gp)
16426         addiu   $gp,$gp,%lo(__gnu_local_gp)
16427    and the argument is ignored.  This saves an instruction, but the
16428    resulting code is not position independent; it uses an absolute
16429    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16430    can go into an ordinary executable, but not into a shared library.  */
16431
16432 static void
16433 s_cpload (int ignore ATTRIBUTE_UNUSED)
16434 {
16435   expressionS ex;
16436   int reg;
16437   int in_shared;
16438
16439   file_mips_check_options ();
16440
16441   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16442      .cpload is ignored.  */
16443   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16444     {
16445       s_ignore (0);
16446       return;
16447     }
16448
16449   if (mips_opts.mips16)
16450     {
16451       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16452       ignore_rest_of_line ();
16453       return;
16454     }
16455
16456   /* .cpload should be in a .set noreorder section.  */
16457   if (mips_opts.noreorder == 0)
16458     as_warn (_(".cpload not in noreorder section"));
16459
16460   reg = tc_get_register (0);
16461
16462   /* If we need to produce a 64-bit address, we are better off using
16463      the default instruction sequence.  */
16464   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16465
16466   ex.X_op = O_symbol;
16467   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16468                                          "__gnu_local_gp");
16469   ex.X_op_symbol = NULL;
16470   ex.X_add_number = 0;
16471
16472   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16473   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16474
16475   mips_mark_labels ();
16476   mips_assembling_insn = TRUE;
16477
16478   macro_start ();
16479   macro_build_lui (&ex, mips_gp_register);
16480   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16481                mips_gp_register, BFD_RELOC_LO16);
16482   if (in_shared)
16483     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16484                  mips_gp_register, reg);
16485   macro_end ();
16486
16487   mips_assembling_insn = FALSE;
16488   demand_empty_rest_of_line ();
16489 }
16490
16491 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16492      .cpsetup $reg1, offset|$reg2, label
16493
16494    If offset is given, this results in:
16495      sd         $gp, offset($sp)
16496      lui        $gp, %hi(%neg(%gp_rel(label)))
16497      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16498      daddu      $gp, $gp, $reg1
16499
16500    If $reg2 is given, this results in:
16501      or         $reg2, $gp, $0
16502      lui        $gp, %hi(%neg(%gp_rel(label)))
16503      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16504      daddu      $gp, $gp, $reg1
16505    $reg1 is normally $25 == $t9.
16506
16507    The -mno-shared option replaces the last three instructions with
16508         lui     $gp,%hi(_gp)
16509         addiu   $gp,$gp,%lo(_gp)  */
16510
16511 static void
16512 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16513 {
16514   expressionS ex_off;
16515   expressionS ex_sym;
16516   int reg1;
16517
16518   file_mips_check_options ();
16519
16520   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16521      We also need NewABI support.  */
16522   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16523     {
16524       s_ignore (0);
16525       return;
16526     }
16527
16528   if (mips_opts.mips16)
16529     {
16530       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16531       ignore_rest_of_line ();
16532       return;
16533     }
16534
16535   reg1 = tc_get_register (0);
16536   SKIP_WHITESPACE ();
16537   if (*input_line_pointer != ',')
16538     {
16539       as_bad (_("missing argument separator ',' for .cpsetup"));
16540       return;
16541     }
16542   else
16543     ++input_line_pointer;
16544   SKIP_WHITESPACE ();
16545   if (*input_line_pointer == '$')
16546     {
16547       mips_cpreturn_register = tc_get_register (0);
16548       mips_cpreturn_offset = -1;
16549     }
16550   else
16551     {
16552       mips_cpreturn_offset = get_absolute_expression ();
16553       mips_cpreturn_register = -1;
16554     }
16555   SKIP_WHITESPACE ();
16556   if (*input_line_pointer != ',')
16557     {
16558       as_bad (_("missing argument separator ',' for .cpsetup"));
16559       return;
16560     }
16561   else
16562     ++input_line_pointer;
16563   SKIP_WHITESPACE ();
16564   expression (&ex_sym);
16565
16566   mips_mark_labels ();
16567   mips_assembling_insn = TRUE;
16568
16569   macro_start ();
16570   if (mips_cpreturn_register == -1)
16571     {
16572       ex_off.X_op = O_constant;
16573       ex_off.X_add_symbol = NULL;
16574       ex_off.X_op_symbol = NULL;
16575       ex_off.X_add_number = mips_cpreturn_offset;
16576
16577       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16578                    BFD_RELOC_LO16, SP);
16579     }
16580   else
16581     move_register (mips_cpreturn_register, mips_gp_register);
16582
16583   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16584     {
16585       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16586                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16587                    BFD_RELOC_HI16_S);
16588
16589       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16590                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16591                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16592
16593       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16594                    mips_gp_register, reg1);
16595     }
16596   else
16597     {
16598       expressionS ex;
16599
16600       ex.X_op = O_symbol;
16601       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16602       ex.X_op_symbol = NULL;
16603       ex.X_add_number = 0;
16604
16605       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16606       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16607
16608       macro_build_lui (&ex, mips_gp_register);
16609       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16610                    mips_gp_register, BFD_RELOC_LO16);
16611     }
16612
16613   macro_end ();
16614
16615   mips_assembling_insn = FALSE;
16616   demand_empty_rest_of_line ();
16617 }
16618
16619 static void
16620 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16621 {
16622   file_mips_check_options ();
16623
16624   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16625      .cplocal is ignored.  */
16626   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16627     {
16628       s_ignore (0);
16629       return;
16630     }
16631
16632   if (mips_opts.mips16)
16633     {
16634       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16635       ignore_rest_of_line ();
16636       return;
16637     }
16638
16639   mips_gp_register = tc_get_register (0);
16640   demand_empty_rest_of_line ();
16641 }
16642
16643 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16644    offset from $sp.  The offset is remembered, and after making a PIC
16645    call $gp is restored from that location.  */
16646
16647 static void
16648 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16649 {
16650   expressionS ex;
16651
16652   file_mips_check_options ();
16653
16654   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16655      .cprestore is ignored.  */
16656   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16657     {
16658       s_ignore (0);
16659       return;
16660     }
16661
16662   if (mips_opts.mips16)
16663     {
16664       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16665       ignore_rest_of_line ();
16666       return;
16667     }
16668
16669   mips_cprestore_offset = get_absolute_expression ();
16670   mips_cprestore_valid = 1;
16671
16672   ex.X_op = O_constant;
16673   ex.X_add_symbol = NULL;
16674   ex.X_op_symbol = NULL;
16675   ex.X_add_number = mips_cprestore_offset;
16676
16677   mips_mark_labels ();
16678   mips_assembling_insn = TRUE;
16679
16680   macro_start ();
16681   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16682                                 SP, HAVE_64BIT_ADDRESSES);
16683   macro_end ();
16684
16685   mips_assembling_insn = FALSE;
16686   demand_empty_rest_of_line ();
16687 }
16688
16689 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16690    was given in the preceding .cpsetup, it results in:
16691      ld         $gp, offset($sp)
16692
16693    If a register $reg2 was given there, it results in:
16694      or         $gp, $reg2, $0  */
16695
16696 static void
16697 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16698 {
16699   expressionS ex;
16700
16701   file_mips_check_options ();
16702
16703   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16704      We also need NewABI support.  */
16705   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16706     {
16707       s_ignore (0);
16708       return;
16709     }
16710
16711   if (mips_opts.mips16)
16712     {
16713       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16714       ignore_rest_of_line ();
16715       return;
16716     }
16717
16718   mips_mark_labels ();
16719   mips_assembling_insn = TRUE;
16720
16721   macro_start ();
16722   if (mips_cpreturn_register == -1)
16723     {
16724       ex.X_op = O_constant;
16725       ex.X_add_symbol = NULL;
16726       ex.X_op_symbol = NULL;
16727       ex.X_add_number = mips_cpreturn_offset;
16728
16729       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16730     }
16731   else
16732     move_register (mips_gp_register, mips_cpreturn_register);
16733
16734   macro_end ();
16735
16736   mips_assembling_insn = FALSE;
16737   demand_empty_rest_of_line ();
16738 }
16739
16740 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16741    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16742    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16743    debug information or MIPS16 TLS.  */
16744
16745 static void
16746 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16747                      bfd_reloc_code_real_type rtype)
16748 {
16749   expressionS ex;
16750   char *p;
16751
16752   expression (&ex);
16753
16754   if (ex.X_op != O_symbol)
16755     {
16756       as_bad (_("unsupported use of %s"), dirstr);
16757       ignore_rest_of_line ();
16758     }
16759
16760   p = frag_more (bytes);
16761   md_number_to_chars (p, 0, bytes);
16762   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16763   demand_empty_rest_of_line ();
16764   mips_clear_insn_labels ();
16765 }
16766
16767 /* Handle .dtprelword.  */
16768
16769 static void
16770 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16771 {
16772   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16773 }
16774
16775 /* Handle .dtpreldword.  */
16776
16777 static void
16778 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16779 {
16780   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16781 }
16782
16783 /* Handle .tprelword.  */
16784
16785 static void
16786 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16787 {
16788   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16789 }
16790
16791 /* Handle .tpreldword.  */
16792
16793 static void
16794 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16795 {
16796   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16797 }
16798
16799 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16800    code.  It sets the offset to use in gp_rel relocations.  */
16801
16802 static void
16803 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16804 {
16805   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16806      We also need NewABI support.  */
16807   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16808     {
16809       s_ignore (0);
16810       return;
16811     }
16812
16813   mips_gprel_offset = get_absolute_expression ();
16814
16815   demand_empty_rest_of_line ();
16816 }
16817
16818 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16819    code.  It generates a 32 bit GP relative reloc.  */
16820
16821 static void
16822 s_gpword (int ignore ATTRIBUTE_UNUSED)
16823 {
16824   segment_info_type *si;
16825   struct insn_label_list *l;
16826   expressionS ex;
16827   char *p;
16828
16829   /* When not generating PIC code, this is treated as .word.  */
16830   if (mips_pic != SVR4_PIC)
16831     {
16832       s_cons (2);
16833       return;
16834     }
16835
16836   si = seg_info (now_seg);
16837   l = si->label_list;
16838   mips_emit_delays ();
16839   if (auto_align)
16840     mips_align (2, 0, l);
16841
16842   expression (&ex);
16843   mips_clear_insn_labels ();
16844
16845   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16846     {
16847       as_bad (_("unsupported use of .gpword"));
16848       ignore_rest_of_line ();
16849     }
16850
16851   p = frag_more (4);
16852   md_number_to_chars (p, 0, 4);
16853   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16854                BFD_RELOC_GPREL32);
16855
16856   demand_empty_rest_of_line ();
16857 }
16858
16859 static void
16860 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16861 {
16862   segment_info_type *si;
16863   struct insn_label_list *l;
16864   expressionS ex;
16865   char *p;
16866
16867   /* When not generating PIC code, this is treated as .dword.  */
16868   if (mips_pic != SVR4_PIC)
16869     {
16870       s_cons (3);
16871       return;
16872     }
16873
16874   si = seg_info (now_seg);
16875   l = si->label_list;
16876   mips_emit_delays ();
16877   if (auto_align)
16878     mips_align (3, 0, l);
16879
16880   expression (&ex);
16881   mips_clear_insn_labels ();
16882
16883   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16884     {
16885       as_bad (_("unsupported use of .gpdword"));
16886       ignore_rest_of_line ();
16887     }
16888
16889   p = frag_more (8);
16890   md_number_to_chars (p, 0, 8);
16891   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16892                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16893
16894   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16895   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16896            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16897
16898   demand_empty_rest_of_line ();
16899 }
16900
16901 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
16902    tables.  It generates a R_MIPS_EH reloc.  */
16903
16904 static void
16905 s_ehword (int ignore ATTRIBUTE_UNUSED)
16906 {
16907   expressionS ex;
16908   char *p;
16909
16910   mips_emit_delays ();
16911
16912   expression (&ex);
16913   mips_clear_insn_labels ();
16914
16915   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16916     {
16917       as_bad (_("unsupported use of .ehword"));
16918       ignore_rest_of_line ();
16919     }
16920
16921   p = frag_more (4);
16922   md_number_to_chars (p, 0, 4);
16923   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16924                BFD_RELOC_32_PCREL);
16925
16926   demand_empty_rest_of_line ();
16927 }
16928
16929 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16930    tables in SVR4 PIC code.  */
16931
16932 static void
16933 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16934 {
16935   int reg;
16936
16937   file_mips_check_options ();
16938
16939   /* This is ignored when not generating SVR4 PIC code.  */
16940   if (mips_pic != SVR4_PIC)
16941     {
16942       s_ignore (0);
16943       return;
16944     }
16945
16946   mips_mark_labels ();
16947   mips_assembling_insn = TRUE;
16948
16949   /* Add $gp to the register named as an argument.  */
16950   macro_start ();
16951   reg = tc_get_register (0);
16952   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16953   macro_end ();
16954
16955   mips_assembling_insn = FALSE;
16956   demand_empty_rest_of_line ();
16957 }
16958
16959 /* Handle the .insn pseudo-op.  This marks instruction labels in
16960    mips16/micromips mode.  This permits the linker to handle them specially,
16961    such as generating jalx instructions when needed.  We also make
16962    them odd for the duration of the assembly, in order to generate the
16963    right sort of code.  We will make them even in the adjust_symtab
16964    routine, while leaving them marked.  This is convenient for the
16965    debugger and the disassembler.  The linker knows to make them odd
16966    again.  */
16967
16968 static void
16969 s_insn (int ignore ATTRIBUTE_UNUSED)
16970 {
16971   file_mips_check_options ();
16972   file_ase_mips16 |= mips_opts.mips16;
16973   file_ase_micromips |= mips_opts.micromips;
16974
16975   mips_mark_labels ();
16976
16977   demand_empty_rest_of_line ();
16978 }
16979
16980 /* Handle the .nan pseudo-op.  */
16981
16982 static void
16983 s_nan (int ignore ATTRIBUTE_UNUSED)
16984 {
16985   static const char str_legacy[] = "legacy";
16986   static const char str_2008[] = "2008";
16987   size_t i;
16988
16989   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16990
16991   if (i == sizeof (str_2008) - 1
16992       && memcmp (input_line_pointer, str_2008, i) == 0)
16993     mips_nan2008 = 1;
16994   else if (i == sizeof (str_legacy) - 1
16995            && memcmp (input_line_pointer, str_legacy, i) == 0)
16996     {
16997       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
16998         mips_nan2008 = 0;
16999       else
17000         as_bad (_("`%s' does not support legacy NaN"),
17001                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
17002     }
17003   else
17004     as_bad (_("bad .nan directive"));
17005
17006   input_line_pointer += i;
17007   demand_empty_rest_of_line ();
17008 }
17009
17010 /* Handle a .stab[snd] directive.  Ideally these directives would be
17011    implemented in a transparent way, so that removing them would not
17012    have any effect on the generated instructions.  However, s_stab
17013    internally changes the section, so in practice we need to decide
17014    now whether the preceding label marks compressed code.  We do not
17015    support changing the compression mode of a label after a .stab*
17016    directive, such as in:
17017
17018    foo:
17019         .stabs ...
17020         .set mips16
17021
17022    so the current mode wins.  */
17023
17024 static void
17025 s_mips_stab (int type)
17026 {
17027   mips_mark_labels ();
17028   s_stab (type);
17029 }
17030
17031 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17032
17033 static void
17034 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17035 {
17036   char *name;
17037   int c;
17038   symbolS *symbolP;
17039   expressionS exp;
17040
17041   c = get_symbol_name (&name);
17042   symbolP = symbol_find_or_make (name);
17043   S_SET_WEAK (symbolP);
17044   *input_line_pointer = c;
17045
17046   SKIP_WHITESPACE_AFTER_NAME ();
17047
17048   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17049     {
17050       if (S_IS_DEFINED (symbolP))
17051         {
17052           as_bad (_("ignoring attempt to redefine symbol %s"),
17053                   S_GET_NAME (symbolP));
17054           ignore_rest_of_line ();
17055           return;
17056         }
17057
17058       if (*input_line_pointer == ',')
17059         {
17060           ++input_line_pointer;
17061           SKIP_WHITESPACE ();
17062         }
17063
17064       expression (&exp);
17065       if (exp.X_op != O_symbol)
17066         {
17067           as_bad (_("bad .weakext directive"));
17068           ignore_rest_of_line ();
17069           return;
17070         }
17071       symbol_set_value_expression (symbolP, &exp);
17072     }
17073
17074   demand_empty_rest_of_line ();
17075 }
17076
17077 /* Parse a register string into a number.  Called from the ECOFF code
17078    to parse .frame.  The argument is non-zero if this is the frame
17079    register, so that we can record it in mips_frame_reg.  */
17080
17081 int
17082 tc_get_register (int frame)
17083 {
17084   unsigned int reg;
17085
17086   SKIP_WHITESPACE ();
17087   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17088     reg = 0;
17089   if (frame)
17090     {
17091       mips_frame_reg = reg != 0 ? reg : SP;
17092       mips_frame_reg_valid = 1;
17093       mips_cprestore_valid = 0;
17094     }
17095   return reg;
17096 }
17097
17098 valueT
17099 md_section_align (asection *seg, valueT addr)
17100 {
17101   int align = bfd_get_section_alignment (stdoutput, seg);
17102
17103   /* We don't need to align ELF sections to the full alignment.
17104      However, Irix 5 may prefer that we align them at least to a 16
17105      byte boundary.  We don't bother to align the sections if we
17106      are targeted for an embedded system.  */
17107   if (strncmp (TARGET_OS, "elf", 3) == 0)
17108     return addr;
17109   if (align > 4)
17110     align = 4;
17111
17112   return ((addr + (1 << align) - 1) & -(1 << align));
17113 }
17114
17115 /* Utility routine, called from above as well.  If called while the
17116    input file is still being read, it's only an approximation.  (For
17117    example, a symbol may later become defined which appeared to be
17118    undefined earlier.)  */
17119
17120 static int
17121 nopic_need_relax (symbolS *sym, int before_relaxing)
17122 {
17123   if (sym == 0)
17124     return 0;
17125
17126   if (g_switch_value > 0)
17127     {
17128       const char *symname;
17129       int change;
17130
17131       /* Find out whether this symbol can be referenced off the $gp
17132          register.  It can be if it is smaller than the -G size or if
17133          it is in the .sdata or .sbss section.  Certain symbols can
17134          not be referenced off the $gp, although it appears as though
17135          they can.  */
17136       symname = S_GET_NAME (sym);
17137       if (symname != (const char *) NULL
17138           && (strcmp (symname, "eprol") == 0
17139               || strcmp (symname, "etext") == 0
17140               || strcmp (symname, "_gp") == 0
17141               || strcmp (symname, "edata") == 0
17142               || strcmp (symname, "_fbss") == 0
17143               || strcmp (symname, "_fdata") == 0
17144               || strcmp (symname, "_ftext") == 0
17145               || strcmp (symname, "end") == 0
17146               || strcmp (symname, "_gp_disp") == 0))
17147         change = 1;
17148       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17149                && (0
17150 #ifndef NO_ECOFF_DEBUGGING
17151                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17152                        && (symbol_get_obj (sym)->ecoff_extern_size
17153                            <= g_switch_value))
17154 #endif
17155                    /* We must defer this decision until after the whole
17156                       file has been read, since there might be a .extern
17157                       after the first use of this symbol.  */
17158                    || (before_relaxing
17159 #ifndef NO_ECOFF_DEBUGGING
17160                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17161 #endif
17162                        && S_GET_VALUE (sym) == 0)
17163                    || (S_GET_VALUE (sym) != 0
17164                        && S_GET_VALUE (sym) <= g_switch_value)))
17165         change = 0;
17166       else
17167         {
17168           const char *segname;
17169
17170           segname = segment_name (S_GET_SEGMENT (sym));
17171           gas_assert (strcmp (segname, ".lit8") != 0
17172                   && strcmp (segname, ".lit4") != 0);
17173           change = (strcmp (segname, ".sdata") != 0
17174                     && strcmp (segname, ".sbss") != 0
17175                     && strncmp (segname, ".sdata.", 7) != 0
17176                     && strncmp (segname, ".sbss.", 6) != 0
17177                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17178                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17179         }
17180       return change;
17181     }
17182   else
17183     /* We are not optimizing for the $gp register.  */
17184     return 1;
17185 }
17186
17187
17188 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17189
17190 static bfd_boolean
17191 pic_need_relax (symbolS *sym)
17192 {
17193   asection *symsec;
17194
17195   /* Handle the case of a symbol equated to another symbol.  */
17196   while (symbol_equated_reloc_p (sym))
17197     {
17198       symbolS *n;
17199
17200       /* It's possible to get a loop here in a badly written program.  */
17201       n = symbol_get_value_expression (sym)->X_add_symbol;
17202       if (n == sym)
17203         break;
17204       sym = n;
17205     }
17206
17207   if (symbol_section_p (sym))
17208     return TRUE;
17209
17210   symsec = S_GET_SEGMENT (sym);
17211
17212   /* This must duplicate the test in adjust_reloc_syms.  */
17213   return (!bfd_is_und_section (symsec)
17214           && !bfd_is_abs_section (symsec)
17215           && !bfd_is_com_section (symsec)
17216           /* A global or weak symbol is treated as external.  */
17217           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17218 }
17219 \f
17220 /* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17221    convert a section-relative value VAL to the equivalent PC-relative
17222    value.  */
17223
17224 static offsetT
17225 mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17226                   offsetT val, long stretch)
17227 {
17228   fragS *sym_frag;
17229   addressT addr;
17230
17231   gas_assert (pcrel_op->root.root.type == OP_PCREL);
17232
17233   sym_frag = symbol_get_frag (fragp->fr_symbol);
17234
17235   /* If the relax_marker of the symbol fragment differs from the
17236      relax_marker of this fragment, we have not yet adjusted the
17237      symbol fragment fr_address.  We want to add in STRETCH in
17238      order to get a better estimate of the address.  This
17239      particularly matters because of the shift bits.  */
17240   if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17241     {
17242       fragS *f;
17243
17244       /* Adjust stretch for any alignment frag.  Note that if have
17245          been expanding the earlier code, the symbol may be
17246          defined in what appears to be an earlier frag.  FIXME:
17247          This doesn't handle the fr_subtype field, which specifies
17248          a maximum number of bytes to skip when doing an
17249          alignment.  */
17250       for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17251         {
17252           if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17253             {
17254               if (stretch < 0)
17255                 stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17256               else
17257                 stretch &= ~((1 << (int) f->fr_offset) - 1);
17258               if (stretch == 0)
17259                 break;
17260             }
17261         }
17262       if (f != NULL)
17263         val += stretch;
17264     }
17265
17266   addr = fragp->fr_address + fragp->fr_fix;
17267
17268   /* The base address rules are complicated.  The base address of
17269      a branch is the following instruction.  The base address of a
17270      PC relative load or add is the instruction itself, but if it
17271      is in a delay slot (in which case it can not be extended) use
17272      the address of the instruction whose delay slot it is in.  */
17273   if (pcrel_op->include_isa_bit)
17274     {
17275       addr += 2;
17276
17277       /* If we are currently assuming that this frag should be
17278          extended, then the current address is two bytes higher.  */
17279       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17280         addr += 2;
17281
17282       /* Ignore the low bit in the target, since it will be set
17283          for a text label.  */
17284       val &= -2;
17285     }
17286   else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17287     addr -= 4;
17288   else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17289     addr -= 2;
17290
17291   val -= addr & -(1 << pcrel_op->align_log2);
17292
17293   return val;
17294 }
17295
17296 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17297    extended opcode.  SEC is the section the frag is in.  */
17298
17299 static int
17300 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17301 {
17302   const struct mips_int_operand *operand;
17303   offsetT val;
17304   segT symsec;
17305   int type;
17306
17307   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17308     return 0;
17309   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17310     return 1;
17311
17312   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17313   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17314   operand = mips16_immed_operand (type, FALSE);
17315   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
17316       || (operand->root.type == OP_PCREL
17317           ? sec != symsec
17318           : !bfd_is_abs_section (symsec)))
17319     return 1;
17320
17321   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17322
17323   if (operand->root.type == OP_PCREL)
17324     {
17325       const struct mips_pcrel_operand *pcrel_op;
17326       offsetT maxtiny;
17327
17328       if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17329         return 1;
17330
17331       pcrel_op = (const struct mips_pcrel_operand *) operand;
17332       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17333
17334       /* If any of the shifted bits are set, we must use an extended
17335          opcode.  If the address depends on the size of this
17336          instruction, this can lead to a loop, so we arrange to always
17337          use an extended opcode.  */
17338       if ((val & ((1 << operand->shift) - 1)) != 0)
17339         {
17340           fragp->fr_subtype =
17341             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17342           return 1;
17343         }
17344
17345       /* If we are about to mark a frag as extended because the value
17346          is precisely the next value above maxtiny, then there is a
17347          chance of an infinite loop as in the following code:
17348              la $4,foo
17349              .skip      1020
17350              .align     2
17351            foo:
17352          In this case when the la is extended, foo is 0x3fc bytes
17353          away, so the la can be shrunk, but then foo is 0x400 away, so
17354          the la must be extended.  To avoid this loop, we mark the
17355          frag as extended if it was small, and is about to become
17356          extended with the next value above maxtiny.  */
17357       maxtiny = mips_int_operand_max (operand);
17358       if (val == maxtiny + (1 << operand->shift)
17359           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17360         {
17361           fragp->fr_subtype =
17362             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17363           return 1;
17364         }
17365     }
17366
17367   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17368 }
17369
17370 /* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
17371    macro expansion.  SEC is the section the frag is in.  We only
17372    support PC-relative instructions (LA, DLA, LW, LD) here, in
17373    non-PIC code using 32-bit addressing.  */
17374
17375 static int
17376 mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
17377 {
17378   const struct mips_pcrel_operand *pcrel_op;
17379   const struct mips_int_operand *operand;
17380   offsetT val;
17381   segT symsec;
17382   int type;
17383
17384   gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
17385
17386   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17387     return 0;
17388   if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
17389     return 0;
17390
17391   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17392   switch (type)
17393     {
17394     case 'A':
17395     case 'B':
17396     case 'E':
17397       symsec = S_GET_SEGMENT (fragp->fr_symbol);
17398       if (bfd_is_abs_section (symsec))
17399         return 1;
17400       if (RELAX_MIPS16_PIC (fragp->fr_subtype))
17401         return 0;
17402       if (S_FORCE_RELOC (fragp->fr_symbol, TRUE) || sec != symsec)
17403         return 1;
17404
17405       operand = mips16_immed_operand (type, TRUE);
17406       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17407       pcrel_op = (const struct mips_pcrel_operand *) operand;
17408       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17409
17410       return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17411
17412     default:
17413       return 0;
17414     }
17415 }
17416
17417 /* Compute the length of a branch sequence, and adjust the
17418    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17419    worst-case length is computed, with UPDATE being used to indicate
17420    whether an unconditional (-1), branch-likely (+1) or regular (0)
17421    branch is to be computed.  */
17422 static int
17423 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17424 {
17425   bfd_boolean toofar;
17426   int length;
17427
17428   if (fragp
17429       && S_IS_DEFINED (fragp->fr_symbol)
17430       && !S_IS_WEAK (fragp->fr_symbol)
17431       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17432     {
17433       addressT addr;
17434       offsetT val;
17435
17436       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17437
17438       addr = fragp->fr_address + fragp->fr_fix + 4;
17439
17440       val -= addr;
17441
17442       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17443     }
17444   else
17445     /* If the symbol is not defined or it's in a different segment,
17446        we emit the long sequence.  */
17447     toofar = TRUE;
17448
17449   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17450     fragp->fr_subtype
17451       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17452                              RELAX_BRANCH_PIC (fragp->fr_subtype),
17453                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17454                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17455                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17456                              toofar);
17457
17458   length = 4;
17459   if (toofar)
17460     {
17461       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17462         length += 8;
17463
17464       if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
17465         {
17466           /* Additional space for PIC loading of target address.  */
17467           length += 8;
17468           if (mips_opts.isa == ISA_MIPS1)
17469             /* Additional space for $at-stabilizing nop.  */
17470             length += 4;
17471         }
17472
17473       /* If branch is conditional.  */
17474       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17475         length += 8;
17476     }
17477
17478   return length;
17479 }
17480
17481 /* Get a FRAG's branch instruction delay slot size, either from the
17482    short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
17483    or SHORT_INSN_SIZE otherwise.  */
17484
17485 static int
17486 frag_branch_delay_slot_size (fragS *fragp, bfd_boolean al, int short_insn_size)
17487 {
17488   char *buf = fragp->fr_literal + fragp->fr_fix;
17489
17490   if (al)
17491     return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
17492   else
17493     return short_insn_size;
17494 }
17495
17496 /* Compute the length of a branch sequence, and adjust the
17497    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17498    worst-case length is computed, with UPDATE being used to indicate
17499    whether an unconditional (-1), or regular (0) branch is to be
17500    computed.  */
17501
17502 static int
17503 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17504 {
17505   bfd_boolean insn32 = TRUE;
17506   bfd_boolean nods = TRUE;
17507   bfd_boolean pic = TRUE;
17508   bfd_boolean al = TRUE;
17509   int short_insn_size;
17510   bfd_boolean toofar;
17511   int length;
17512
17513   if (fragp)
17514     {
17515       insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
17516       nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
17517       pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
17518       al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17519     }
17520   short_insn_size = insn32 ? 4 : 2;
17521
17522   if (fragp
17523       && S_IS_DEFINED (fragp->fr_symbol)
17524       && !S_IS_WEAK (fragp->fr_symbol)
17525       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17526     {
17527       addressT addr;
17528       offsetT val;
17529
17530       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17531       /* Ignore the low bit in the target, since it will be set
17532          for a text label.  */
17533       if ((val & 1) != 0)
17534         --val;
17535
17536       addr = fragp->fr_address + fragp->fr_fix + 4;
17537
17538       val -= addr;
17539
17540       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17541     }
17542   else
17543     /* If the symbol is not defined or it's in a different segment,
17544        we emit the long sequence.  */
17545     toofar = TRUE;
17546
17547   if (fragp && update
17548       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17549     fragp->fr_subtype = (toofar
17550                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17551                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17552
17553   length = 4;
17554   if (toofar)
17555     {
17556       bfd_boolean compact_known = fragp != NULL;
17557       bfd_boolean compact = FALSE;
17558       bfd_boolean uncond;
17559
17560       if (fragp)
17561         {
17562           compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17563           uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17564         }
17565       else
17566         uncond = update < 0;
17567
17568       /* If label is out of range, we turn branch <br>:
17569
17570                 <br>    label                   # 4 bytes
17571             0:
17572
17573          into:
17574
17575                 j       label                   # 4 bytes
17576                 nop                             # 2/4 bytes if
17577                                                 #  compact && (!PIC || insn32)
17578             0:
17579        */
17580       if ((!pic || insn32) && (!compact_known || compact))
17581         length += short_insn_size;
17582
17583       /* If assembling PIC code, we further turn:
17584
17585                         j       label                   # 4 bytes
17586
17587          into:
17588
17589                         lw/ld   at, %got(label)(gp)     # 4 bytes
17590                         d/addiu at, %lo(label)          # 4 bytes
17591                         jr/c    at                      # 2/4 bytes
17592        */
17593       if (pic)
17594         length += 4 + short_insn_size;
17595
17596       /* Add an extra nop if the jump has no compact form and we need
17597          to fill the delay slot.  */
17598       if ((!pic || al) && nods)
17599         length += (fragp
17600                    ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
17601                    : short_insn_size);
17602
17603       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17604
17605                         <brneg> 0f                      # 4 bytes
17606                         nop                             # 2/4 bytes if !compact
17607        */
17608       if (!uncond)
17609         length += (compact_known && compact) ? 4 : 4 + short_insn_size;
17610     }
17611   else if (nods)
17612     {
17613       /* Add an extra nop to fill the delay slot.  */
17614       gas_assert (fragp);
17615       length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
17616     }
17617
17618   return length;
17619 }
17620
17621 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17622    bit accordingly.  */
17623
17624 static int
17625 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17626 {
17627   bfd_boolean toofar;
17628
17629   if (fragp
17630       && S_IS_DEFINED (fragp->fr_symbol)
17631       && !S_IS_WEAK (fragp->fr_symbol)
17632       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17633     {
17634       addressT addr;
17635       offsetT val;
17636       int type;
17637
17638       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17639       /* Ignore the low bit in the target, since it will be set
17640          for a text label.  */
17641       if ((val & 1) != 0)
17642         --val;
17643
17644       /* Assume this is a 2-byte branch.  */
17645       addr = fragp->fr_address + fragp->fr_fix + 2;
17646
17647       /* We try to avoid the infinite loop by not adding 2 more bytes for
17648          long branches.  */
17649
17650       val -= addr;
17651
17652       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17653       if (type == 'D')
17654         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17655       else if (type == 'E')
17656         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17657       else
17658         abort ();
17659     }
17660   else
17661     /* If the symbol is not defined or it's in a different segment,
17662        we emit a normal 32-bit branch.  */
17663     toofar = TRUE;
17664
17665   if (fragp && update
17666       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17667     fragp->fr_subtype
17668       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17669                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17670
17671   if (toofar)
17672     return 4;
17673
17674   return 2;
17675 }
17676
17677 /* Estimate the size of a frag before relaxing.  Unless this is the
17678    mips16, we are not really relaxing here, and the final size is
17679    encoded in the subtype information.  For the mips16, we have to
17680    decide whether we are using an extended opcode or not.  */
17681
17682 int
17683 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17684 {
17685   int change;
17686
17687   if (RELAX_BRANCH_P (fragp->fr_subtype))
17688     {
17689
17690       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17691
17692       return fragp->fr_var;
17693     }
17694
17695   if (RELAX_MIPS16_P (fragp->fr_subtype))
17696     {
17697       /* We don't want to modify the EXTENDED bit here; it might get us
17698          into infinite loops.  We change it only in mips_relax_frag().  */
17699       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17700         return 12;
17701       else
17702         return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
17703     }
17704
17705   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17706     {
17707       int length = 4;
17708
17709       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17710         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17711       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17712         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17713       fragp->fr_var = length;
17714
17715       return length;
17716     }
17717
17718   if (mips_pic == VXWORKS_PIC)
17719     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17720     change = 0;
17721   else if (RELAX_PIC (fragp->fr_subtype))
17722     change = pic_need_relax (fragp->fr_symbol);
17723   else
17724     change = nopic_need_relax (fragp->fr_symbol, 0);
17725
17726   if (change)
17727     {
17728       fragp->fr_subtype |= RELAX_USE_SECOND;
17729       return -RELAX_FIRST (fragp->fr_subtype);
17730     }
17731   else
17732     return -RELAX_SECOND (fragp->fr_subtype);
17733 }
17734
17735 /* This is called to see whether a reloc against a defined symbol
17736    should be converted into a reloc against a section.  */
17737
17738 int
17739 mips_fix_adjustable (fixS *fixp)
17740 {
17741   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17742       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17743     return 0;
17744
17745   if (fixp->fx_addsy == NULL)
17746     return 1;
17747
17748   /* Allow relocs used for EH tables.  */
17749   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17750     return 1;
17751
17752   /* If symbol SYM is in a mergeable section, relocations of the form
17753      SYM + 0 can usually be made section-relative.  The mergeable data
17754      is then identified by the section offset rather than by the symbol.
17755
17756      However, if we're generating REL LO16 relocations, the offset is split
17757      between the LO16 and partnering high part relocation.  The linker will
17758      need to recalculate the complete offset in order to correctly identify
17759      the merge data.
17760
17761      The linker has traditionally not looked for the partnering high part
17762      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17763      placed anywhere.  Rather than break backwards compatibility by changing
17764      this, it seems better not to force the issue, and instead keep the
17765      original symbol.  This will work with either linker behavior.  */
17766   if ((lo16_reloc_p (fixp->fx_r_type)
17767        || reloc_needs_lo_p (fixp->fx_r_type))
17768       && HAVE_IN_PLACE_ADDENDS
17769       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17770     return 0;
17771
17772   /* There is no place to store an in-place offset for JALR relocations.  */
17773   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17774     return 0;
17775
17776   /* Likewise an in-range offset of limited PC-relative relocations may
17777      overflow the in-place relocatable field if recalculated against the
17778      start address of the symbol's containing section.
17779
17780      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17781      section relative to allow linker relaxations to be performed later on.  */
17782   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17783       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17784     return 0;
17785
17786   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17787      to a floating-point stub.  The same is true for non-R_MIPS16_26
17788      relocations against MIPS16 functions; in this case, the stub becomes
17789      the function's canonical address.
17790
17791      Floating-point stubs are stored in unique .mips16.call.* or
17792      .mips16.fn.* sections.  If a stub T for function F is in section S,
17793      the first relocation in section S must be against F; this is how the
17794      linker determines the target function.  All relocations that might
17795      resolve to T must also be against F.  We therefore have the following
17796      restrictions, which are given in an intentionally-redundant way:
17797
17798        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17799           symbols.
17800
17801        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17802           if that stub might be used.
17803
17804        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17805           symbols.
17806
17807        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17808           that stub might be used.
17809
17810      There is a further restriction:
17811
17812        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17813           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
17814           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
17815           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
17816           against MIPS16 or microMIPS symbols because we need to keep the
17817           MIPS16 or microMIPS symbol for the purpose of mode mismatch
17818           detection and JAL or BAL to JALX instruction conversion in the
17819           linker.
17820
17821      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17822      against a MIPS16 symbol.  We deal with (5) by additionally leaving
17823      alone any jump and branch relocations against a microMIPS symbol.
17824
17825      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17826      relocation against some symbol R, no relocation against R may be
17827      reduced.  (Note that this deals with (2) as well as (1) because
17828      relocations against global symbols will never be reduced on ELF
17829      targets.)  This approach is a little simpler than trying to detect
17830      stub sections, and gives the "all or nothing" per-symbol consistency
17831      that we have for MIPS16 symbols.  */
17832   if (fixp->fx_subsy == NULL
17833       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17834           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17835               && (jmp_reloc_p (fixp->fx_r_type)
17836                   || b_reloc_p (fixp->fx_r_type)))
17837           || *symbol_get_tc (fixp->fx_addsy)))
17838     return 0;
17839
17840   return 1;
17841 }
17842
17843 /* Translate internal representation of relocation info to BFD target
17844    format.  */
17845
17846 arelent **
17847 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17848 {
17849   static arelent *retval[4];
17850   arelent *reloc;
17851   bfd_reloc_code_real_type code;
17852
17853   memset (retval, 0, sizeof(retval));
17854   reloc = retval[0] = XCNEW (arelent);
17855   reloc->sym_ptr_ptr = XNEW (asymbol *);
17856   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17857   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17858
17859   if (fixp->fx_pcrel)
17860     {
17861       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17862                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
17863                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17864                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17865                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17866                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
17867                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
17868                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
17869                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
17870                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
17871                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
17872                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
17873
17874       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17875          Relocations want only the symbol offset.  */
17876       switch (fixp->fx_r_type)
17877         {
17878         case BFD_RELOC_MIPS_18_PCREL_S3:
17879           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
17880           break;
17881         default:
17882           reloc->addend = fixp->fx_addnumber + reloc->address;
17883           break;
17884         }
17885     }
17886   else if (HAVE_IN_PLACE_ADDENDS
17887            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
17888            && (read_compressed_insn (fixp->fx_frag->fr_literal
17889                                      + fixp->fx_where, 4) >> 26) == 0x3c)
17890     {
17891       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
17892          addend accordingly.  */
17893       reloc->addend = fixp->fx_addnumber >> 1;
17894     }
17895   else
17896     reloc->addend = fixp->fx_addnumber;
17897
17898   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17899      entry to be used in the relocation's section offset.  */
17900   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17901     {
17902       reloc->address = reloc->addend;
17903       reloc->addend = 0;
17904     }
17905
17906   code = fixp->fx_r_type;
17907
17908   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17909   if (reloc->howto == NULL)
17910     {
17911       as_bad_where (fixp->fx_file, fixp->fx_line,
17912                     _("cannot represent %s relocation in this object file"
17913                       " format"),
17914                     bfd_get_reloc_code_name (code));
17915       retval[0] = NULL;
17916     }
17917
17918   return retval;
17919 }
17920
17921 /* Relax a machine dependent frag.  This returns the amount by which
17922    the current size of the frag should change.  */
17923
17924 int
17925 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17926 {
17927   if (RELAX_BRANCH_P (fragp->fr_subtype))
17928     {
17929       offsetT old_var = fragp->fr_var;
17930
17931       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17932
17933       return fragp->fr_var - old_var;
17934     }
17935
17936   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17937     {
17938       offsetT old_var = fragp->fr_var;
17939       offsetT new_var = 4;
17940
17941       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17942         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17943       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17944         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17945       fragp->fr_var = new_var;
17946
17947       return new_var - old_var;
17948     }
17949
17950   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17951     return 0;
17952
17953   if (!mips16_extended_frag (fragp, sec, stretch))
17954     {
17955       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17956         {
17957           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
17958           return -10;
17959         }
17960       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17961         {
17962           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17963           return -2;
17964         }
17965       else
17966         return 0;
17967     }
17968   else if (!mips16_macro_frag (fragp, sec, stretch))
17969     {
17970       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17971         {
17972           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
17973           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17974           return -8;
17975         }
17976       else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17977         {
17978           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17979           return 2;
17980         }
17981       else
17982         return 0;
17983     }
17984   else
17985     {
17986       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17987         return 0;
17988       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17989         {
17990           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17991           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
17992           return 8;
17993         }
17994       else
17995         {
17996           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
17997           return 10;
17998         }
17999     }
18000
18001   return 0;
18002 }
18003
18004 /* Convert a machine dependent frag.  */
18005
18006 void
18007 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18008 {
18009   if (RELAX_BRANCH_P (fragp->fr_subtype))
18010     {
18011       char *buf;
18012       unsigned long insn;
18013       expressionS exp;
18014       fixS *fixp;
18015
18016       buf = fragp->fr_literal + fragp->fr_fix;
18017       insn = read_insn (buf);
18018
18019       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18020         {
18021           /* We generate a fixup instead of applying it right now
18022              because, if there are linker relaxations, we're going to
18023              need the relocations.  */
18024           exp.X_op = O_symbol;
18025           exp.X_add_symbol = fragp->fr_symbol;
18026           exp.X_add_number = fragp->fr_offset;
18027
18028           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18029                               BFD_RELOC_16_PCREL_S2);
18030           fixp->fx_file = fragp->fr_file;
18031           fixp->fx_line = fragp->fr_line;
18032
18033           buf = write_insn (buf, insn);
18034         }
18035       else
18036         {
18037           int i;
18038
18039           as_warn_where (fragp->fr_file, fragp->fr_line,
18040                          _("relaxed out-of-range branch into a jump"));
18041
18042           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18043             goto uncond;
18044
18045           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18046             {
18047               /* Reverse the branch.  */
18048               switch ((insn >> 28) & 0xf)
18049                 {
18050                 case 4:
18051                   if ((insn & 0xff000000) == 0x47000000
18052                       || (insn & 0xff600000) == 0x45600000)
18053                     {
18054                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18055                          reversed by tweaking bit 23.  */
18056                       insn ^= 0x00800000;
18057                     }
18058                   else
18059                     {
18060                       /* bc[0-3][tf]l? instructions can have the condition
18061                          reversed by tweaking a single TF bit, and their
18062                          opcodes all have 0x4???????.  */
18063                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
18064                       insn ^= 0x00010000;
18065                     }
18066                   break;
18067
18068                 case 0:
18069                   /* bltz       0x04000000      bgez    0x04010000
18070                      bltzal     0x04100000      bgezal  0x04110000  */
18071                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18072                   insn ^= 0x00010000;
18073                   break;
18074
18075                 case 1:
18076                   /* beq        0x10000000      bne     0x14000000
18077                      blez       0x18000000      bgtz    0x1c000000  */
18078                   insn ^= 0x04000000;
18079                   break;
18080
18081                 default:
18082                   abort ();
18083                 }
18084             }
18085
18086           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18087             {
18088               /* Clear the and-link bit.  */
18089               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18090
18091               /* bltzal         0x04100000      bgezal  0x04110000
18092                  bltzall        0x04120000      bgezall 0x04130000  */
18093               insn &= ~0x00100000;
18094             }
18095
18096           /* Branch over the branch (if the branch was likely) or the
18097              full jump (not likely case).  Compute the offset from the
18098              current instruction to branch to.  */
18099           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18100             i = 16;
18101           else
18102             {
18103               /* How many bytes in instructions we've already emitted?  */
18104               i = buf - fragp->fr_literal - fragp->fr_fix;
18105               /* How many bytes in instructions from here to the end?  */
18106               i = fragp->fr_var - i;
18107             }
18108           /* Convert to instruction count.  */
18109           i >>= 2;
18110           /* Branch counts from the next instruction.  */
18111           i--;
18112           insn |= i;
18113           /* Branch over the jump.  */
18114           buf = write_insn (buf, insn);
18115
18116           /* nop */
18117           buf = write_insn (buf, 0);
18118
18119           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18120             {
18121               /* beql $0, $0, 2f */
18122               insn = 0x50000000;
18123               /* Compute the PC offset from the current instruction to
18124                  the end of the variable frag.  */
18125               /* How many bytes in instructions we've already emitted?  */
18126               i = buf - fragp->fr_literal - fragp->fr_fix;
18127               /* How many bytes in instructions from here to the end?  */
18128               i = fragp->fr_var - i;
18129               /* Convert to instruction count.  */
18130               i >>= 2;
18131               /* Don't decrement i, because we want to branch over the
18132                  delay slot.  */
18133               insn |= i;
18134
18135               buf = write_insn (buf, insn);
18136               buf = write_insn (buf, 0);
18137             }
18138
18139         uncond:
18140           if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18141             {
18142               /* j or jal.  */
18143               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18144                       ? 0x0c000000 : 0x08000000);
18145               exp.X_op = O_symbol;
18146               exp.X_add_symbol = fragp->fr_symbol;
18147               exp.X_add_number = fragp->fr_offset;
18148
18149               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18150                                   FALSE, BFD_RELOC_MIPS_JMP);
18151               fixp->fx_file = fragp->fr_file;
18152               fixp->fx_line = fragp->fr_line;
18153
18154               buf = write_insn (buf, insn);
18155             }
18156           else
18157             {
18158               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18159
18160               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18161               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18162               insn |= at << OP_SH_RT;
18163               exp.X_op = O_symbol;
18164               exp.X_add_symbol = fragp->fr_symbol;
18165               exp.X_add_number = fragp->fr_offset;
18166
18167               if (fragp->fr_offset)
18168                 {
18169                   exp.X_add_symbol = make_expr_symbol (&exp);
18170                   exp.X_add_number = 0;
18171                 }
18172
18173               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18174                                   FALSE, BFD_RELOC_MIPS_GOT16);
18175               fixp->fx_file = fragp->fr_file;
18176               fixp->fx_line = fragp->fr_line;
18177
18178               buf = write_insn (buf, insn);
18179
18180               if (mips_opts.isa == ISA_MIPS1)
18181                 /* nop */
18182                 buf = write_insn (buf, 0);
18183
18184               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18185               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18186               insn |= at << OP_SH_RS | at << OP_SH_RT;
18187
18188               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18189                                   FALSE, BFD_RELOC_LO16);
18190               fixp->fx_file = fragp->fr_file;
18191               fixp->fx_line = fragp->fr_line;
18192
18193               buf = write_insn (buf, insn);
18194
18195               /* j(al)r $at.  */
18196               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18197                 insn = 0x0000f809;
18198               else
18199                 insn = 0x00000008;
18200               insn |= at << OP_SH_RS;
18201
18202               buf = write_insn (buf, insn);
18203             }
18204         }
18205
18206       fragp->fr_fix += fragp->fr_var;
18207       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18208       return;
18209     }
18210
18211   /* Relax microMIPS branches.  */
18212   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18213     {
18214       char *buf = fragp->fr_literal + fragp->fr_fix;
18215       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18216       bfd_boolean insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18217       bfd_boolean nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18218       bfd_boolean pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18219       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18220       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18221       bfd_boolean short_ds;
18222       unsigned long insn;
18223       expressionS exp;
18224       fixS *fixp;
18225
18226       exp.X_op = O_symbol;
18227       exp.X_add_symbol = fragp->fr_symbol;
18228       exp.X_add_number = fragp->fr_offset;
18229
18230       fragp->fr_fix += fragp->fr_var;
18231
18232       /* Handle 16-bit branches that fit or are forced to fit.  */
18233       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18234         {
18235           /* We generate a fixup instead of applying it right now,
18236              because if there is linker relaxation, we're going to
18237              need the relocations.  */
18238           if (type == 'D')
18239             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18240                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18241           else if (type == 'E')
18242             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18243                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18244           else
18245             abort ();
18246
18247           fixp->fx_file = fragp->fr_file;
18248           fixp->fx_line = fragp->fr_line;
18249
18250           /* These relocations can have an addend that won't fit in
18251              2 octets.  */
18252           fixp->fx_no_overflow = 1;
18253
18254           return;
18255         }
18256
18257       /* Handle 32-bit branches that fit or are forced to fit.  */
18258       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18259           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18260         {
18261           /* We generate a fixup instead of applying it right now,
18262              because if there is linker relaxation, we're going to
18263              need the relocations.  */
18264           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18265                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18266           fixp->fx_file = fragp->fr_file;
18267           fixp->fx_line = fragp->fr_line;
18268
18269           if (type == 0)
18270             {
18271               insn = read_compressed_insn (buf, 4);
18272               buf += 4;
18273
18274               if (nods)
18275                 {
18276                   /* Check the short-delay-slot bit.  */
18277                   if (!al || (insn & 0x02000000) != 0)
18278                     buf = write_compressed_insn (buf, 0x0c00, 2);
18279                   else
18280                     buf = write_compressed_insn (buf, 0x00000000, 4);
18281                 }
18282
18283               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18284               return;
18285             }
18286         }
18287
18288       /* Relax 16-bit branches to 32-bit branches.  */
18289       if (type != 0)
18290         {
18291           insn = read_compressed_insn (buf, 2);
18292
18293           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18294             insn = 0x94000000;                          /* beq  */
18295           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18296             {
18297               unsigned long regno;
18298
18299               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18300               regno = micromips_to_32_reg_d_map [regno];
18301               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18302               insn |= regno << MICROMIPSOP_SH_RS;
18303             }
18304           else
18305             abort ();
18306
18307           /* Nothing else to do, just write it out.  */
18308           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18309               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18310             {
18311               buf = write_compressed_insn (buf, insn, 4);
18312               if (nods)
18313                 buf = write_compressed_insn (buf, 0x0c00, 2);
18314               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18315               return;
18316             }
18317         }
18318       else
18319         insn = read_compressed_insn (buf, 4);
18320
18321       /* Relax 32-bit branches to a sequence of instructions.  */
18322       as_warn_where (fragp->fr_file, fragp->fr_line,
18323                      _("relaxed out-of-range branch into a jump"));
18324
18325       /* Set the short-delay-slot bit.  */
18326       short_ds = !al || (insn & 0x02000000) != 0;
18327
18328       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18329         {
18330           symbolS *l;
18331
18332           /* Reverse the branch.  */
18333           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18334               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18335             insn ^= 0x20000000;
18336           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18337                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18338                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18339                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18340                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18341                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18342                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18343                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18344                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18345                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18346             insn ^= 0x00400000;
18347           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18348                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18349                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18350                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18351             insn ^= 0x00200000;
18352           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
18353                                                                    BNZ.df  */
18354                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
18355                                                                    BNZ.V */
18356             insn ^= 0x00800000;
18357           else
18358             abort ();
18359
18360           if (al)
18361             {
18362               /* Clear the and-link and short-delay-slot bits.  */
18363               gas_assert ((insn & 0xfda00000) == 0x40200000);
18364
18365               /* bltzal  0x40200000     bgezal  0x40600000  */
18366               /* bltzals 0x42200000     bgezals 0x42600000  */
18367               insn &= ~0x02200000;
18368             }
18369
18370           /* Make a label at the end for use with the branch.  */
18371           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18372           micromips_label_inc ();
18373           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18374
18375           /* Refer to it.  */
18376           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18377                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18378           fixp->fx_file = fragp->fr_file;
18379           fixp->fx_line = fragp->fr_line;
18380
18381           /* Branch over the jump.  */
18382           buf = write_compressed_insn (buf, insn, 4);
18383
18384           if (!compact)
18385             {
18386               /* nop  */
18387               if (insn32)
18388                 buf = write_compressed_insn (buf, 0x00000000, 4);
18389               else
18390                 buf = write_compressed_insn (buf, 0x0c00, 2);
18391             }
18392         }
18393
18394       if (!pic)
18395         {
18396           unsigned long jal = (short_ds || nods
18397                                ? 0x74000000 : 0xf4000000);      /* jal/s  */
18398
18399           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18400           insn = al ? jal : 0xd4000000;
18401
18402           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18403                               BFD_RELOC_MICROMIPS_JMP);
18404           fixp->fx_file = fragp->fr_file;
18405           fixp->fx_line = fragp->fr_line;
18406
18407           buf = write_compressed_insn (buf, insn, 4);
18408
18409           if (compact || nods)
18410             {
18411               /* nop  */
18412               if (insn32)
18413                 buf = write_compressed_insn (buf, 0x00000000, 4);
18414               else
18415                 buf = write_compressed_insn (buf, 0x0c00, 2);
18416             }
18417         }
18418       else
18419         {
18420           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18421
18422           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18423           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18424           insn |= at << MICROMIPSOP_SH_RT;
18425
18426           if (exp.X_add_number)
18427             {
18428               exp.X_add_symbol = make_expr_symbol (&exp);
18429               exp.X_add_number = 0;
18430             }
18431
18432           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18433                               BFD_RELOC_MICROMIPS_GOT16);
18434           fixp->fx_file = fragp->fr_file;
18435           fixp->fx_line = fragp->fr_line;
18436
18437           buf = write_compressed_insn (buf, insn, 4);
18438
18439           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18440           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18441           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18442
18443           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18444                               BFD_RELOC_MICROMIPS_LO16);
18445           fixp->fx_file = fragp->fr_file;
18446           fixp->fx_line = fragp->fr_line;
18447
18448           buf = write_compressed_insn (buf, insn, 4);
18449
18450           if (insn32)
18451             {
18452               /* jr/jalr $at  */
18453               insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
18454               insn |= at << MICROMIPSOP_SH_RS;
18455
18456               buf = write_compressed_insn (buf, insn, 4);
18457
18458               if (compact || nods)
18459                 /* nop  */
18460                 buf = write_compressed_insn (buf, 0x00000000, 4);
18461             }
18462           else
18463             {
18464               /* jr/jrc/jalr/jalrs $at  */
18465               unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;  /* jalr/s  */
18466               unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
18467
18468               insn = al ? jalr : jr;
18469               insn |= at << MICROMIPSOP_SH_MJ;
18470
18471               buf = write_compressed_insn (buf, insn, 2);
18472               if (al && nods)
18473                 {
18474                   /* nop  */
18475                   if (short_ds)
18476                     buf = write_compressed_insn (buf, 0x0c00, 2);
18477                   else
18478                     buf = write_compressed_insn (buf, 0x00000000, 4);
18479                 }
18480             }
18481         }
18482
18483       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18484       return;
18485     }
18486
18487   if (RELAX_MIPS16_P (fragp->fr_subtype))
18488     {
18489       int type;
18490       const struct mips_int_operand *operand;
18491       offsetT val;
18492       char *buf;
18493       unsigned int user_length;
18494       bfd_boolean need_reloc;
18495       unsigned long insn;
18496       bfd_boolean mac;
18497       bfd_boolean ext;
18498       segT symsec;
18499
18500       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18501       operand = mips16_immed_operand (type, FALSE);
18502
18503       mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
18504       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18505       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18506
18507       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18508       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18509                     || (operand->root.type == OP_PCREL && !mac
18510                         ? asec != symsec
18511                         : !bfd_is_abs_section (symsec)));
18512
18513       if (operand->root.type == OP_PCREL && !mac)
18514         {
18515           const struct mips_pcrel_operand *pcrel_op;
18516
18517           pcrel_op = (const struct mips_pcrel_operand *) operand;
18518
18519           if (pcrel_op->include_isa_bit && !need_reloc)
18520             {
18521               if (!ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18522                 as_bad_where (fragp->fr_file, fragp->fr_line,
18523                               _("branch to a symbol in another ISA mode"));
18524               else if ((fragp->fr_offset & 0x1) != 0)
18525                 as_bad_where (fragp->fr_file, fragp->fr_line,
18526                               _("branch to misaligned address (0x%lx)"),
18527                               (long) val);
18528             }
18529
18530           val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
18531
18532           /* Make sure the section winds up with the alignment we have
18533              assumed.  */
18534           if (operand->shift > 0)
18535             record_alignment (asec, operand->shift);
18536         }
18537
18538       if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18539           || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18540         {
18541           if (mac)
18542             as_warn_where (fragp->fr_file, fragp->fr_line,
18543                            _("macro instruction expanded into multiple "
18544                              "instructions in a branch delay slot"));
18545           else if (ext)
18546             as_warn_where (fragp->fr_file, fragp->fr_line,
18547                            _("extended instruction in a branch delay slot"));
18548         }
18549       else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
18550         as_warn_where (fragp->fr_file, fragp->fr_line,
18551                        _("macro instruction expanded into multiple "
18552                          "instructions"));
18553
18554       buf = fragp->fr_literal + fragp->fr_fix;
18555
18556       insn = read_compressed_insn (buf, 2);
18557       if (ext)
18558         insn |= MIPS16_EXTEND;
18559
18560       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18561         user_length = 4;
18562       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18563         user_length = 2;
18564       else
18565         user_length = 0;
18566
18567       if (mac)
18568         {
18569           unsigned long reg;
18570           unsigned long new;
18571           unsigned long op;
18572
18573           gas_assert (type == 'A' || type == 'B' || type == 'E');
18574           gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
18575
18576           if (need_reloc)
18577             {
18578               fixS *fixp;
18579
18580               gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
18581
18582               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18583                               fragp->fr_symbol, fragp->fr_offset,
18584                               FALSE, BFD_RELOC_MIPS16_HI16_S);
18585               fixp->fx_file = fragp->fr_file;
18586               fixp->fx_line = fragp->fr_line;
18587
18588               fixp = fix_new (fragp, buf - fragp->fr_literal + 8, 4,
18589                               fragp->fr_symbol, fragp->fr_offset,
18590                               FALSE, BFD_RELOC_MIPS16_LO16);
18591               fixp->fx_file = fragp->fr_file;
18592               fixp->fx_line = fragp->fr_line;
18593
18594               val = 0;
18595             }
18596
18597           switch (insn & 0xf800)
18598             {
18599             case 0x0800:                                        /* ADDIU */
18600               reg = (insn >> 8) & 0x7;
18601               op = 0xf0004800 | (reg << 8);
18602               break;
18603             case 0xb000:                                        /* LW */
18604               reg = (insn >> 8) & 0x7;
18605               op = 0xf0009800 | (reg << 8) | (reg << 5);
18606               break;
18607             case 0xf800:                                        /* I64 */
18608               reg = (insn >> 5) & 0x7;
18609               switch (insn & 0x0700)
18610                 {
18611                 case 0x0400:                                    /* LD */
18612                   op = 0xf0003800 | (reg << 8) | (reg << 5);
18613                   break;
18614                 case 0x0600:                                    /* DADDIU */
18615                   op = 0xf000fd00 | (reg << 5);
18616                   break;
18617                 default:
18618                   abort ();
18619                 }
18620               break;
18621             default:
18622               abort ();
18623             }
18624
18625           new = 0xf0006800 | (reg << 8);                        /* LI */
18626           new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
18627           buf = write_compressed_insn (buf, new, 4);
18628           new = 0xf4003000 | (reg << 8) | (reg << 5);           /* SLL */
18629           buf = write_compressed_insn (buf, new, 4);
18630           op |= mips16_immed_extend (val, 16);
18631           buf = write_compressed_insn (buf, op, 4);
18632
18633           fragp->fr_fix += 12;
18634         }
18635       else
18636         {
18637           unsigned int length = ext ? 4 : 2;
18638
18639           if (need_reloc)
18640             {
18641               bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18642               expressionS exp;
18643               fixS *fixp;
18644
18645               switch (type)
18646                 {
18647                 case 'p':
18648                 case 'q':
18649                   reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18650                   break;
18651                 default:
18652                   break;
18653                 }
18654               if (mac || reloc == BFD_RELOC_NONE)
18655                 as_bad_where (fragp->fr_file, fragp->fr_line,
18656                               _("unsupported relocation"));
18657               else if (ext)
18658                 {
18659                   exp.X_op = O_symbol;
18660                   exp.X_add_symbol = fragp->fr_symbol;
18661                   exp.X_add_number = fragp->fr_offset;
18662
18663                   fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18664                                       TRUE, reloc);
18665
18666                   fixp->fx_file = fragp->fr_file;
18667                   fixp->fx_line = fragp->fr_line;
18668                 }
18669               else
18670                 as_bad_where (fragp->fr_file, fragp->fr_line,
18671                               _("invalid unextended operand value"));
18672             }
18673           else
18674             mips16_immed (fragp->fr_file, fragp->fr_line, type,
18675                           BFD_RELOC_UNUSED, val, user_length, &insn);
18676
18677           gas_assert (mips16_opcode_length (insn) == length);
18678           write_compressed_insn (buf, insn, length);
18679           fragp->fr_fix += length;
18680         }
18681     }
18682   else
18683     {
18684       relax_substateT subtype = fragp->fr_subtype;
18685       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18686       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18687       int first, second;
18688       fixS *fixp;
18689
18690       first = RELAX_FIRST (subtype);
18691       second = RELAX_SECOND (subtype);
18692       fixp = (fixS *) fragp->fr_opcode;
18693
18694       /* If the delay slot chosen does not match the size of the instruction,
18695          then emit a warning.  */
18696       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18697            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18698         {
18699           relax_substateT s;
18700           const char *msg;
18701
18702           s = subtype & (RELAX_DELAY_SLOT_16BIT
18703                          | RELAX_DELAY_SLOT_SIZE_FIRST
18704                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18705           msg = macro_warning (s);
18706           if (msg != NULL)
18707             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18708           subtype &= ~s;
18709         }
18710
18711       /* Possibly emit a warning if we've chosen the longer option.  */
18712       if (use_second == second_longer)
18713         {
18714           relax_substateT s;
18715           const char *msg;
18716
18717           s = (subtype
18718                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18719           msg = macro_warning (s);
18720           if (msg != NULL)
18721             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18722           subtype &= ~s;
18723         }
18724
18725       /* Go through all the fixups for the first sequence.  Disable them
18726          (by marking them as done) if we're going to use the second
18727          sequence instead.  */
18728       while (fixp
18729              && fixp->fx_frag == fragp
18730              && fixp->fx_where < fragp->fr_fix - second)
18731         {
18732           if (subtype & RELAX_USE_SECOND)
18733             fixp->fx_done = 1;
18734           fixp = fixp->fx_next;
18735         }
18736
18737       /* Go through the fixups for the second sequence.  Disable them if
18738          we're going to use the first sequence, otherwise adjust their
18739          addresses to account for the relaxation.  */
18740       while (fixp && fixp->fx_frag == fragp)
18741         {
18742           if (subtype & RELAX_USE_SECOND)
18743             fixp->fx_where -= first;
18744           else
18745             fixp->fx_done = 1;
18746           fixp = fixp->fx_next;
18747         }
18748
18749       /* Now modify the frag contents.  */
18750       if (subtype & RELAX_USE_SECOND)
18751         {
18752           char *start;
18753
18754           start = fragp->fr_literal + fragp->fr_fix - first - second;
18755           memmove (start, start + first, second);
18756           fragp->fr_fix -= first;
18757         }
18758       else
18759         fragp->fr_fix -= second;
18760     }
18761 }
18762
18763 /* This function is called after the relocs have been generated.
18764    We've been storing mips16 text labels as odd.  Here we convert them
18765    back to even for the convenience of the debugger.  */
18766
18767 void
18768 mips_frob_file_after_relocs (void)
18769 {
18770   asymbol **syms;
18771   unsigned int count, i;
18772
18773   syms = bfd_get_outsymbols (stdoutput);
18774   count = bfd_get_symcount (stdoutput);
18775   for (i = 0; i < count; i++, syms++)
18776     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18777         && ((*syms)->value & 1) != 0)
18778       {
18779         (*syms)->value &= ~1;
18780         /* If the symbol has an odd size, it was probably computed
18781            incorrectly, so adjust that as well.  */
18782         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18783           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18784       }
18785 }
18786
18787 /* This function is called whenever a label is defined, including fake
18788    labels instantiated off the dot special symbol.  It is used when
18789    handling branch delays; if a branch has a label, we assume we cannot
18790    move it.  This also bumps the value of the symbol by 1 in compressed
18791    code.  */
18792
18793 static void
18794 mips_record_label (symbolS *sym)
18795 {
18796   segment_info_type *si = seg_info (now_seg);
18797   struct insn_label_list *l;
18798
18799   if (free_insn_labels == NULL)
18800     l = XNEW (struct insn_label_list);
18801   else
18802     {
18803       l = free_insn_labels;
18804       free_insn_labels = l->next;
18805     }
18806
18807   l->label = sym;
18808   l->next = si->label_list;
18809   si->label_list = l;
18810 }
18811
18812 /* This function is called as tc_frob_label() whenever a label is defined
18813    and adds a DWARF-2 record we only want for true labels.  */
18814
18815 void
18816 mips_define_label (symbolS *sym)
18817 {
18818   mips_record_label (sym);
18819   dwarf2_emit_label (sym);
18820 }
18821
18822 /* This function is called by tc_new_dot_label whenever a new dot symbol
18823    is defined.  */
18824
18825 void
18826 mips_add_dot_label (symbolS *sym)
18827 {
18828   mips_record_label (sym);
18829   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18830     mips_compressed_mark_label (sym);
18831 }
18832 \f
18833 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
18834 static unsigned int
18835 mips_convert_ase_flags (int ase)
18836 {
18837   unsigned int ext_ases = 0;
18838
18839   if (ase & ASE_DSP)
18840     ext_ases |= AFL_ASE_DSP;
18841   if (ase & ASE_DSPR2)
18842     ext_ases |= AFL_ASE_DSPR2;
18843   if (ase & ASE_DSPR3)
18844     ext_ases |= AFL_ASE_DSPR3;
18845   if (ase & ASE_EVA)
18846     ext_ases |= AFL_ASE_EVA;
18847   if (ase & ASE_MCU)
18848     ext_ases |= AFL_ASE_MCU;
18849   if (ase & ASE_MDMX)
18850     ext_ases |= AFL_ASE_MDMX;
18851   if (ase & ASE_MIPS3D)
18852     ext_ases |= AFL_ASE_MIPS3D;
18853   if (ase & ASE_MT)
18854     ext_ases |= AFL_ASE_MT;
18855   if (ase & ASE_SMARTMIPS)
18856     ext_ases |= AFL_ASE_SMARTMIPS;
18857   if (ase & ASE_VIRT)
18858     ext_ases |= AFL_ASE_VIRT;
18859   if (ase & ASE_MSA)
18860     ext_ases |= AFL_ASE_MSA;
18861   if (ase & ASE_XPA)
18862     ext_ases |= AFL_ASE_XPA;
18863
18864   return ext_ases;
18865 }
18866 /* Some special processing for a MIPS ELF file.  */
18867
18868 void
18869 mips_elf_final_processing (void)
18870 {
18871   int fpabi;
18872   Elf_Internal_ABIFlags_v0 flags;
18873
18874   flags.version = 0;
18875   flags.isa_rev = 0;
18876   switch (file_mips_opts.isa)
18877     {
18878     case INSN_ISA1:
18879       flags.isa_level = 1;
18880       break;
18881     case INSN_ISA2:
18882       flags.isa_level = 2;
18883       break;
18884     case INSN_ISA3:
18885       flags.isa_level = 3;
18886       break;
18887     case INSN_ISA4:
18888       flags.isa_level = 4;
18889       break;
18890     case INSN_ISA5:
18891       flags.isa_level = 5;
18892       break;
18893     case INSN_ISA32:
18894       flags.isa_level = 32;
18895       flags.isa_rev = 1;
18896       break;
18897     case INSN_ISA32R2:
18898       flags.isa_level = 32;
18899       flags.isa_rev = 2;
18900       break;
18901     case INSN_ISA32R3:
18902       flags.isa_level = 32;
18903       flags.isa_rev = 3;
18904       break;
18905     case INSN_ISA32R5:
18906       flags.isa_level = 32;
18907       flags.isa_rev = 5;
18908       break;
18909     case INSN_ISA32R6:
18910       flags.isa_level = 32;
18911       flags.isa_rev = 6;
18912       break;
18913     case INSN_ISA64:
18914       flags.isa_level = 64;
18915       flags.isa_rev = 1;
18916       break;
18917     case INSN_ISA64R2:
18918       flags.isa_level = 64;
18919       flags.isa_rev = 2;
18920       break;
18921     case INSN_ISA64R3:
18922       flags.isa_level = 64;
18923       flags.isa_rev = 3;
18924       break;
18925     case INSN_ISA64R5:
18926       flags.isa_level = 64;
18927       flags.isa_rev = 5;
18928       break;
18929     case INSN_ISA64R6:
18930       flags.isa_level = 64;
18931       flags.isa_rev = 6;
18932       break;
18933     }
18934
18935   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
18936   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
18937                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
18938                     : (file_mips_opts.fp == 64) ? AFL_REG_64
18939                     : AFL_REG_32;
18940   flags.cpr2_size = AFL_REG_NONE;
18941   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18942                                            Tag_GNU_MIPS_ABI_FP);
18943   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
18944   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
18945   if (file_ase_mips16)
18946     flags.ases |= AFL_ASE_MIPS16;
18947   if (file_ase_micromips)
18948     flags.ases |= AFL_ASE_MICROMIPS;
18949   flags.flags1 = 0;
18950   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
18951        || file_mips_opts.fp == 64)
18952       && file_mips_opts.oddspreg)
18953     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
18954   flags.flags2 = 0;
18955
18956   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
18957                                      ((Elf_External_ABIFlags_v0 *)
18958                                      mips_flags_frag));
18959
18960   /* Write out the register information.  */
18961   if (mips_abi != N64_ABI)
18962     {
18963       Elf32_RegInfo s;
18964
18965       s.ri_gprmask = mips_gprmask;
18966       s.ri_cprmask[0] = mips_cprmask[0];
18967       s.ri_cprmask[1] = mips_cprmask[1];
18968       s.ri_cprmask[2] = mips_cprmask[2];
18969       s.ri_cprmask[3] = mips_cprmask[3];
18970       /* The gp_value field is set by the MIPS ELF backend.  */
18971
18972       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18973                                        ((Elf32_External_RegInfo *)
18974                                         mips_regmask_frag));
18975     }
18976   else
18977     {
18978       Elf64_Internal_RegInfo s;
18979
18980       s.ri_gprmask = mips_gprmask;
18981       s.ri_pad = 0;
18982       s.ri_cprmask[0] = mips_cprmask[0];
18983       s.ri_cprmask[1] = mips_cprmask[1];
18984       s.ri_cprmask[2] = mips_cprmask[2];
18985       s.ri_cprmask[3] = mips_cprmask[3];
18986       /* The gp_value field is set by the MIPS ELF backend.  */
18987
18988       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18989                                        ((Elf64_External_RegInfo *)
18990                                         mips_regmask_frag));
18991     }
18992
18993   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18994      sort of BFD interface for this.  */
18995   if (mips_any_noreorder)
18996     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18997   if (mips_pic != NO_PIC)
18998     {
18999       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19000       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19001     }
19002   if (mips_abicalls)
19003     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19004
19005   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19006      defined at present; this might need to change in future.  */
19007   if (file_ase_mips16)
19008     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19009   if (file_ase_micromips)
19010     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19011   if (file_mips_opts.ase & ASE_MDMX)
19012     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19013
19014   /* Set the MIPS ELF ABI flags.  */
19015   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19016     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19017   else if (mips_abi == O64_ABI)
19018     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19019   else if (mips_abi == EABI_ABI)
19020     {
19021       if (file_mips_opts.gp == 64)
19022         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19023       else
19024         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19025     }
19026   else if (mips_abi == N32_ABI)
19027     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
19028
19029   /* Nothing to do for N64_ABI.  */
19030
19031   if (mips_32bitmode)
19032     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19033
19034   if (mips_nan2008 == 1)
19035     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19036
19037   /* 32 bit code with 64 bit FP registers.  */
19038   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19039                                     Tag_GNU_MIPS_ABI_FP);
19040   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19041     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19042 }
19043 \f
19044 typedef struct proc {
19045   symbolS *func_sym;
19046   symbolS *func_end_sym;
19047   unsigned long reg_mask;
19048   unsigned long reg_offset;
19049   unsigned long fpreg_mask;
19050   unsigned long fpreg_offset;
19051   unsigned long frame_offset;
19052   unsigned long frame_reg;
19053   unsigned long pc_reg;
19054 } procS;
19055
19056 static procS cur_proc;
19057 static procS *cur_proc_ptr;
19058 static int numprocs;
19059
19060 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19061    as "2", and a normal nop as "0".  */
19062
19063 #define NOP_OPCODE_MIPS         0
19064 #define NOP_OPCODE_MIPS16       1
19065 #define NOP_OPCODE_MICROMIPS    2
19066
19067 char
19068 mips_nop_opcode (void)
19069 {
19070   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19071     return NOP_OPCODE_MICROMIPS;
19072   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19073     return NOP_OPCODE_MIPS16;
19074   else
19075     return NOP_OPCODE_MIPS;
19076 }
19077
19078 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19079    32-bit microMIPS NOPs here (if applicable).  */
19080
19081 void
19082 mips_handle_align (fragS *fragp)
19083 {
19084   char nop_opcode;
19085   char *p;
19086   int bytes, size, excess;
19087   valueT opcode;
19088
19089   if (fragp->fr_type != rs_align_code)
19090     return;
19091
19092   p = fragp->fr_literal + fragp->fr_fix;
19093   nop_opcode = *p;
19094   switch (nop_opcode)
19095     {
19096     case NOP_OPCODE_MICROMIPS:
19097       opcode = micromips_nop32_insn.insn_opcode;
19098       size = 4;
19099       break;
19100     case NOP_OPCODE_MIPS16:
19101       opcode = mips16_nop_insn.insn_opcode;
19102       size = 2;
19103       break;
19104     case NOP_OPCODE_MIPS:
19105     default:
19106       opcode = nop_insn.insn_opcode;
19107       size = 4;
19108       break;
19109     }
19110
19111   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19112   excess = bytes % size;
19113
19114   /* Handle the leading part if we're not inserting a whole number of
19115      instructions, and make it the end of the fixed part of the frag.
19116      Try to fit in a short microMIPS NOP if applicable and possible,
19117      and use zeroes otherwise.  */
19118   gas_assert (excess < 4);
19119   fragp->fr_fix += excess;
19120   switch (excess)
19121     {
19122     case 3:
19123       *p++ = '\0';
19124       /* Fall through.  */
19125     case 2:
19126       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19127         {
19128           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19129           break;
19130         }
19131       *p++ = '\0';
19132       /* Fall through.  */
19133     case 1:
19134       *p++ = '\0';
19135       /* Fall through.  */
19136     case 0:
19137       break;
19138     }
19139
19140   md_number_to_chars (p, opcode, size);
19141   fragp->fr_var = size;
19142 }
19143
19144 static long
19145 get_number (void)
19146 {
19147   int negative = 0;
19148   long val = 0;
19149
19150   if (*input_line_pointer == '-')
19151     {
19152       ++input_line_pointer;
19153       negative = 1;
19154     }
19155   if (!ISDIGIT (*input_line_pointer))
19156     as_bad (_("expected simple number"));
19157   if (input_line_pointer[0] == '0')
19158     {
19159       if (input_line_pointer[1] == 'x')
19160         {
19161           input_line_pointer += 2;
19162           while (ISXDIGIT (*input_line_pointer))
19163             {
19164               val <<= 4;
19165               val |= hex_value (*input_line_pointer++);
19166             }
19167           return negative ? -val : val;
19168         }
19169       else
19170         {
19171           ++input_line_pointer;
19172           while (ISDIGIT (*input_line_pointer))
19173             {
19174               val <<= 3;
19175               val |= *input_line_pointer++ - '0';
19176             }
19177           return negative ? -val : val;
19178         }
19179     }
19180   if (!ISDIGIT (*input_line_pointer))
19181     {
19182       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19183               *input_line_pointer, *input_line_pointer);
19184       as_warn (_("invalid number"));
19185       return -1;
19186     }
19187   while (ISDIGIT (*input_line_pointer))
19188     {
19189       val *= 10;
19190       val += *input_line_pointer++ - '0';
19191     }
19192   return negative ? -val : val;
19193 }
19194
19195 /* The .file directive; just like the usual .file directive, but there
19196    is an initial number which is the ECOFF file index.  In the non-ECOFF
19197    case .file implies DWARF-2.  */
19198
19199 static void
19200 s_mips_file (int x ATTRIBUTE_UNUSED)
19201 {
19202   static int first_file_directive = 0;
19203
19204   if (ECOFF_DEBUGGING)
19205     {
19206       get_number ();
19207       s_app_file (0);
19208     }
19209   else
19210     {
19211       char *filename;
19212
19213       filename = dwarf2_directive_file (0);
19214
19215       /* Versions of GCC up to 3.1 start files with a ".file"
19216          directive even for stabs output.  Make sure that this
19217          ".file" is handled.  Note that you need a version of GCC
19218          after 3.1 in order to support DWARF-2 on MIPS.  */
19219       if (filename != NULL && ! first_file_directive)
19220         {
19221           (void) new_logical_line (filename, -1);
19222           s_app_file_string (filename, 0);
19223         }
19224       first_file_directive = 1;
19225     }
19226 }
19227
19228 /* The .loc directive, implying DWARF-2.  */
19229
19230 static void
19231 s_mips_loc (int x ATTRIBUTE_UNUSED)
19232 {
19233   if (!ECOFF_DEBUGGING)
19234     dwarf2_directive_loc (0);
19235 }
19236
19237 /* The .end directive.  */
19238
19239 static void
19240 s_mips_end (int x ATTRIBUTE_UNUSED)
19241 {
19242   symbolS *p;
19243
19244   /* Following functions need their own .frame and .cprestore directives.  */
19245   mips_frame_reg_valid = 0;
19246   mips_cprestore_valid = 0;
19247
19248   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19249     {
19250       p = get_symbol ();
19251       demand_empty_rest_of_line ();
19252     }
19253   else
19254     p = NULL;
19255
19256   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19257     as_warn (_(".end not in text section"));
19258
19259   if (!cur_proc_ptr)
19260     {
19261       as_warn (_(".end directive without a preceding .ent directive"));
19262       demand_empty_rest_of_line ();
19263       return;
19264     }
19265
19266   if (p != NULL)
19267     {
19268       gas_assert (S_GET_NAME (p));
19269       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19270         as_warn (_(".end symbol does not match .ent symbol"));
19271
19272       if (debug_type == DEBUG_STABS)
19273         stabs_generate_asm_endfunc (S_GET_NAME (p),
19274                                     S_GET_NAME (p));
19275     }
19276   else
19277     as_warn (_(".end directive missing or unknown symbol"));
19278
19279   /* Create an expression to calculate the size of the function.  */
19280   if (p && cur_proc_ptr)
19281     {
19282       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19283       expressionS *exp = XNEW (expressionS);
19284
19285       obj->size = exp;
19286       exp->X_op = O_subtract;
19287       exp->X_add_symbol = symbol_temp_new_now ();
19288       exp->X_op_symbol = p;
19289       exp->X_add_number = 0;
19290
19291       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19292     }
19293
19294 #ifdef md_flush_pending_output
19295   md_flush_pending_output ();
19296 #endif
19297
19298   /* Generate a .pdr section.  */
19299   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19300     {
19301       segT saved_seg = now_seg;
19302       subsegT saved_subseg = now_subseg;
19303       expressionS exp;
19304       char *fragp;
19305
19306       gas_assert (pdr_seg);
19307       subseg_set (pdr_seg, 0);
19308
19309       /* Write the symbol.  */
19310       exp.X_op = O_symbol;
19311       exp.X_add_symbol = p;
19312       exp.X_add_number = 0;
19313       emit_expr (&exp, 4);
19314
19315       fragp = frag_more (7 * 4);
19316
19317       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19318       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19319       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19320       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19321       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19322       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19323       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19324
19325       subseg_set (saved_seg, saved_subseg);
19326     }
19327
19328   cur_proc_ptr = NULL;
19329 }
19330
19331 /* The .aent and .ent directives.  */
19332
19333 static void
19334 s_mips_ent (int aent)
19335 {
19336   symbolS *symbolP;
19337
19338   symbolP = get_symbol ();
19339   if (*input_line_pointer == ',')
19340     ++input_line_pointer;
19341   SKIP_WHITESPACE ();
19342   if (ISDIGIT (*input_line_pointer)
19343       || *input_line_pointer == '-')
19344     get_number ();
19345
19346   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19347     as_warn (_(".ent or .aent not in text section"));
19348
19349   if (!aent && cur_proc_ptr)
19350     as_warn (_("missing .end"));
19351
19352   if (!aent)
19353     {
19354       /* This function needs its own .frame and .cprestore directives.  */
19355       mips_frame_reg_valid = 0;
19356       mips_cprestore_valid = 0;
19357
19358       cur_proc_ptr = &cur_proc;
19359       memset (cur_proc_ptr, '\0', sizeof (procS));
19360
19361       cur_proc_ptr->func_sym = symbolP;
19362
19363       ++numprocs;
19364
19365       if (debug_type == DEBUG_STABS)
19366         stabs_generate_asm_func (S_GET_NAME (symbolP),
19367                                  S_GET_NAME (symbolP));
19368     }
19369
19370   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19371
19372   demand_empty_rest_of_line ();
19373 }
19374
19375 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19376    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19377    s_mips_frame is used so that we can set the PDR information correctly.
19378    We can't use the ecoff routines because they make reference to the ecoff
19379    symbol table (in the mdebug section).  */
19380
19381 static void
19382 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19383 {
19384   if (ECOFF_DEBUGGING)
19385     s_ignore (ignore);
19386   else
19387     {
19388       long val;
19389
19390       if (cur_proc_ptr == (procS *) NULL)
19391         {
19392           as_warn (_(".frame outside of .ent"));
19393           demand_empty_rest_of_line ();
19394           return;
19395         }
19396
19397       cur_proc_ptr->frame_reg = tc_get_register (1);
19398
19399       SKIP_WHITESPACE ();
19400       if (*input_line_pointer++ != ','
19401           || get_absolute_expression_and_terminator (&val) != ',')
19402         {
19403           as_warn (_("bad .frame directive"));
19404           --input_line_pointer;
19405           demand_empty_rest_of_line ();
19406           return;
19407         }
19408
19409       cur_proc_ptr->frame_offset = val;
19410       cur_proc_ptr->pc_reg = tc_get_register (0);
19411
19412       demand_empty_rest_of_line ();
19413     }
19414 }
19415
19416 /* The .fmask and .mask directives. If the mdebug section is present
19417    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19418    embedded targets, s_mips_mask is used so that we can set the PDR
19419    information correctly. We can't use the ecoff routines because they
19420    make reference to the ecoff symbol table (in the mdebug section).  */
19421
19422 static void
19423 s_mips_mask (int reg_type)
19424 {
19425   if (ECOFF_DEBUGGING)
19426     s_ignore (reg_type);
19427   else
19428     {
19429       long mask, off;
19430
19431       if (cur_proc_ptr == (procS *) NULL)
19432         {
19433           as_warn (_(".mask/.fmask outside of .ent"));
19434           demand_empty_rest_of_line ();
19435           return;
19436         }
19437
19438       if (get_absolute_expression_and_terminator (&mask) != ',')
19439         {
19440           as_warn (_("bad .mask/.fmask directive"));
19441           --input_line_pointer;
19442           demand_empty_rest_of_line ();
19443           return;
19444         }
19445
19446       off = get_absolute_expression ();
19447
19448       if (reg_type == 'F')
19449         {
19450           cur_proc_ptr->fpreg_mask = mask;
19451           cur_proc_ptr->fpreg_offset = off;
19452         }
19453       else
19454         {
19455           cur_proc_ptr->reg_mask = mask;
19456           cur_proc_ptr->reg_offset = off;
19457         }
19458
19459       demand_empty_rest_of_line ();
19460     }
19461 }
19462
19463 /* A table describing all the processors gas knows about.  Names are
19464    matched in the order listed.
19465
19466    To ease comparison, please keep this table in the same order as
19467    gcc's mips_cpu_info_table[].  */
19468 static const struct mips_cpu_info mips_cpu_info_table[] =
19469 {
19470   /* Entries for generic ISAs */
19471   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19472   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19473   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19474   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19475   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19476   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19477   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19478   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
19479   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
19480   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
19481   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19482   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19483   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
19484   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
19485   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
19486
19487   /* MIPS I */
19488   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19489   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19490   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19491
19492   /* MIPS II */
19493   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19494
19495   /* MIPS III */
19496   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19497   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19498   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19499   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19500   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19501   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19502   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19503   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19504   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19505   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19506   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19507   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19508   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19509   /* ST Microelectronics Loongson 2E and 2F cores */
19510   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19511   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19512
19513   /* MIPS IV */
19514   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19515   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19516   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19517   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19518   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19519   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19520   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19521   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19522   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19523   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19524   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19525   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19526   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19527   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19528   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19529
19530   /* MIPS 32 */
19531   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19532   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19533   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19534   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19535
19536   /* MIPS 32 Release 2 */
19537   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19538   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19539   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19540   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19541   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19542   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19543   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19544   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19545   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19546                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19547   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19548                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19549   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19550   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19551   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19552   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19553   /* Deprecated forms of the above.  */
19554   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19555   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19556   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19557   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19558   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19559   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19560   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19561   /* Deprecated forms of the above.  */
19562   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19563   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19564   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19565   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19566   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19567   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19568   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19569   /* Deprecated forms of the above.  */
19570   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19571   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19572   /* 34Kn is a 34kc without DSP.  */
19573   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19574   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19575   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19576   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19577   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19578   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19579   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19580   /* Deprecated forms of the above.  */
19581   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19582   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19583   /* 1004K cores are multiprocessor versions of the 34K.  */
19584   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19585   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19586   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19587   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19588   /* interaptiv is the new name for 1004kf */
19589   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19590   /* M5100 family */
19591   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19592   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19593   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19594   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19595
19596   /* MIPS 64 */
19597   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19598   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19599   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19600   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19601
19602   /* Broadcom SB-1 CPU core */
19603   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19604   /* Broadcom SB-1A CPU core */
19605   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19606
19607   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
19608
19609   /* MIPS 64 Release 2 */
19610
19611   /* Cavium Networks Octeon CPU core */
19612   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19613   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19614   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19615   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19616
19617   /* RMI Xlr */
19618   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19619
19620   /* Broadcom XLP.
19621      XLP is mostly like XLR, with the prominent exception that it is
19622      MIPS64R2 rather than MIPS64.  */
19623   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19624
19625   /* MIPS 64 Release 6 */
19626   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19627   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19628
19629   /* End marker */
19630   { NULL, 0, 0, 0, 0 }
19631 };
19632
19633
19634 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19635    with a final "000" replaced by "k".  Ignore case.
19636
19637    Note: this function is shared between GCC and GAS.  */
19638
19639 static bfd_boolean
19640 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19641 {
19642   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19643     given++, canonical++;
19644
19645   return ((*given == 0 && *canonical == 0)
19646           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19647 }
19648
19649
19650 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19651    CPU name.  We've traditionally allowed a lot of variation here.
19652
19653    Note: this function is shared between GCC and GAS.  */
19654
19655 static bfd_boolean
19656 mips_matching_cpu_name_p (const char *canonical, const char *given)
19657 {
19658   /* First see if the name matches exactly, or with a final "000"
19659      turned into "k".  */
19660   if (mips_strict_matching_cpu_name_p (canonical, given))
19661     return TRUE;
19662
19663   /* If not, try comparing based on numerical designation alone.
19664      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19665   if (TOLOWER (*given) == 'r')
19666     given++;
19667   if (!ISDIGIT (*given))
19668     return FALSE;
19669
19670   /* Skip over some well-known prefixes in the canonical name,
19671      hoping to find a number there too.  */
19672   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19673     canonical += 2;
19674   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19675     canonical += 2;
19676   else if (TOLOWER (canonical[0]) == 'r')
19677     canonical += 1;
19678
19679   return mips_strict_matching_cpu_name_p (canonical, given);
19680 }
19681
19682
19683 /* Parse an option that takes the name of a processor as its argument.
19684    OPTION is the name of the option and CPU_STRING is the argument.
19685    Return the corresponding processor enumeration if the CPU_STRING is
19686    recognized, otherwise report an error and return null.
19687
19688    A similar function exists in GCC.  */
19689
19690 static const struct mips_cpu_info *
19691 mips_parse_cpu (const char *option, const char *cpu_string)
19692 {
19693   const struct mips_cpu_info *p;
19694
19695   /* 'from-abi' selects the most compatible architecture for the given
19696      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19697      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19698      version.  Look first at the -mgp options, if given, otherwise base
19699      the choice on MIPS_DEFAULT_64BIT.
19700
19701      Treat NO_ABI like the EABIs.  One reason to do this is that the
19702      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19703      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19704      'mips64', just as we did in the days before 'from-abi'.  */
19705   if (strcasecmp (cpu_string, "from-abi") == 0)
19706     {
19707       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19708         return mips_cpu_info_from_isa (ISA_MIPS1);
19709
19710       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19711         return mips_cpu_info_from_isa (ISA_MIPS3);
19712
19713       if (file_mips_opts.gp >= 0)
19714         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19715                                        ? ISA_MIPS1 : ISA_MIPS3);
19716
19717       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19718                                      ? ISA_MIPS3
19719                                      : ISA_MIPS1);
19720     }
19721
19722   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19723   if (strcasecmp (cpu_string, "default") == 0)
19724     return 0;
19725
19726   for (p = mips_cpu_info_table; p->name != 0; p++)
19727     if (mips_matching_cpu_name_p (p->name, cpu_string))
19728       return p;
19729
19730   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19731   return 0;
19732 }
19733
19734 /* Return the canonical processor information for ISA (a member of the
19735    ISA_MIPS* enumeration).  */
19736
19737 static const struct mips_cpu_info *
19738 mips_cpu_info_from_isa (int isa)
19739 {
19740   int i;
19741
19742   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19743     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19744         && isa == mips_cpu_info_table[i].isa)
19745       return (&mips_cpu_info_table[i]);
19746
19747   return NULL;
19748 }
19749
19750 static const struct mips_cpu_info *
19751 mips_cpu_info_from_arch (int arch)
19752 {
19753   int i;
19754
19755   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19756     if (arch == mips_cpu_info_table[i].cpu)
19757       return (&mips_cpu_info_table[i]);
19758
19759   return NULL;
19760 }
19761 \f
19762 static void
19763 show (FILE *stream, const char *string, int *col_p, int *first_p)
19764 {
19765   if (*first_p)
19766     {
19767       fprintf (stream, "%24s", "");
19768       *col_p = 24;
19769     }
19770   else
19771     {
19772       fprintf (stream, ", ");
19773       *col_p += 2;
19774     }
19775
19776   if (*col_p + strlen (string) > 72)
19777     {
19778       fprintf (stream, "\n%24s", "");
19779       *col_p = 24;
19780     }
19781
19782   fprintf (stream, "%s", string);
19783   *col_p += strlen (string);
19784
19785   *first_p = 0;
19786 }
19787
19788 void
19789 md_show_usage (FILE *stream)
19790 {
19791   int column, first;
19792   size_t i;
19793
19794   fprintf (stream, _("\
19795 MIPS options:\n\
19796 -EB                     generate big endian output\n\
19797 -EL                     generate little endian output\n\
19798 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19799 -G NUM                  allow referencing objects up to NUM bytes\n\
19800                         implicitly with the gp register [default 8]\n"));
19801   fprintf (stream, _("\
19802 -mips1                  generate MIPS ISA I instructions\n\
19803 -mips2                  generate MIPS ISA II instructions\n\
19804 -mips3                  generate MIPS ISA III instructions\n\
19805 -mips4                  generate MIPS ISA IV instructions\n\
19806 -mips5                  generate MIPS ISA V instructions\n\
19807 -mips32                 generate MIPS32 ISA instructions\n\
19808 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19809 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
19810 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
19811 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
19812 -mips64                 generate MIPS64 ISA instructions\n\
19813 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19814 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
19815 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
19816 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
19817 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19818
19819   first = 1;
19820
19821   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19822     show (stream, mips_cpu_info_table[i].name, &column, &first);
19823   show (stream, "from-abi", &column, &first);
19824   fputc ('\n', stream);
19825
19826   fprintf (stream, _("\
19827 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19828 -no-mCPU                don't generate code specific to CPU.\n\
19829                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19830
19831   first = 1;
19832
19833   show (stream, "3900", &column, &first);
19834   show (stream, "4010", &column, &first);
19835   show (stream, "4100", &column, &first);
19836   show (stream, "4650", &column, &first);
19837   fputc ('\n', stream);
19838
19839   fprintf (stream, _("\
19840 -mips16                 generate mips16 instructions\n\
19841 -no-mips16              do not generate mips16 instructions\n"));
19842   fprintf (stream, _("\
19843 -mmicromips             generate microMIPS instructions\n\
19844 -mno-micromips          do not generate microMIPS instructions\n"));
19845   fprintf (stream, _("\
19846 -msmartmips             generate smartmips instructions\n\
19847 -mno-smartmips          do not generate smartmips instructions\n"));
19848   fprintf (stream, _("\
19849 -mdsp                   generate DSP instructions\n\
19850 -mno-dsp                do not generate DSP instructions\n"));
19851   fprintf (stream, _("\
19852 -mdspr2                 generate DSP R2 instructions\n\
19853 -mno-dspr2              do not generate DSP R2 instructions\n"));
19854   fprintf (stream, _("\
19855 -mdspr3                 generate DSP R3 instructions\n\
19856 -mno-dspr3              do not generate DSP R3 instructions\n"));
19857   fprintf (stream, _("\
19858 -mmt                    generate MT instructions\n\
19859 -mno-mt                 do not generate MT instructions\n"));
19860   fprintf (stream, _("\
19861 -mmcu                   generate MCU instructions\n\
19862 -mno-mcu                do not generate MCU instructions\n"));
19863   fprintf (stream, _("\
19864 -mmsa                   generate MSA instructions\n\
19865 -mno-msa                do not generate MSA instructions\n"));
19866   fprintf (stream, _("\
19867 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
19868 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
19869   fprintf (stream, _("\
19870 -mvirt                  generate Virtualization instructions\n\
19871 -mno-virt               do not generate Virtualization instructions\n"));
19872   fprintf (stream, _("\
19873 -minsn32                only generate 32-bit microMIPS instructions\n\
19874 -mno-insn32             generate all microMIPS instructions\n"));
19875   fprintf (stream, _("\
19876 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19877 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19878 -mfix-vr4120            work around certain VR4120 errata\n\
19879 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19880 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19881 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19882 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19883 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19884 -msym32                 assume all symbols have 32-bit values\n\
19885 -O0                     remove unneeded NOPs, do not swap branches\n\
19886 -O                      remove unneeded NOPs and swap branches\n\
19887 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19888 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19889   fprintf (stream, _("\
19890 -mhard-float            allow floating-point instructions\n\
19891 -msoft-float            do not allow floating-point instructions\n\
19892 -msingle-float          only allow 32-bit floating-point operations\n\
19893 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19894 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19895 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19896 -mignore-branch-isa     accept invalid branches requiring an ISA mode switch\n\
19897 -mno-ignore-branch-isa  reject invalid branches requiring an ISA mode switch\n\
19898 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19899
19900   first = 1;
19901
19902   show (stream, "legacy", &column, &first);
19903   show (stream, "2008", &column, &first);
19904
19905   fputc ('\n', stream);
19906
19907   fprintf (stream, _("\
19908 -KPIC, -call_shared     generate SVR4 position independent code\n\
19909 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19910 -mvxworks-pic           generate VxWorks position independent code\n\
19911 -non_shared             do not generate code that can operate with DSOs\n\
19912 -xgot                   assume a 32 bit GOT\n\
19913 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19914 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19915                         position dependent (non shared) code\n\
19916 -mabi=ABI               create ABI conformant object file for:\n"));
19917
19918   first = 1;
19919
19920   show (stream, "32", &column, &first);
19921   show (stream, "o64", &column, &first);
19922   show (stream, "n32", &column, &first);
19923   show (stream, "64", &column, &first);
19924   show (stream, "eabi", &column, &first);
19925
19926   fputc ('\n', stream);
19927
19928   fprintf (stream, _("\
19929 -32                     create o32 ABI object file (default)\n\
19930 -n32                    create n32 ABI object file\n\
19931 -64                     create 64 ABI object file\n"));
19932 }
19933
19934 #ifdef TE_IRIX
19935 enum dwarf2_format
19936 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19937 {
19938   if (HAVE_64BIT_SYMBOLS)
19939     return dwarf2_format_64bit_irix;
19940   else
19941     return dwarf2_format_32bit;
19942 }
19943 #endif
19944
19945 int
19946 mips_dwarf2_addr_size (void)
19947 {
19948   if (HAVE_64BIT_OBJECTS)
19949     return 8;
19950   else
19951     return 4;
19952 }
19953
19954 /* Standard calling conventions leave the CFA at SP on entry.  */
19955 void
19956 mips_cfi_frame_initial_instructions (void)
19957 {
19958   cfi_add_CFA_def_cfa_register (SP);
19959 }
19960
19961 int
19962 tc_mips_regname_to_dw2regnum (char *regname)
19963 {
19964   unsigned int regnum = -1;
19965   unsigned int reg;
19966
19967   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19968     regnum = reg;
19969
19970   return regnum;
19971 }
19972
19973 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
19974    Given a symbolic attribute NAME, return the proper integer value.
19975    Returns -1 if the attribute is not known.  */
19976
19977 int
19978 mips_convert_symbolic_attribute (const char *name)
19979 {
19980   static const struct
19981   {
19982     const char * name;
19983     const int    tag;
19984   }
19985   attribute_table[] =
19986     {
19987 #define T(tag) {#tag, tag}
19988       T (Tag_GNU_MIPS_ABI_FP),
19989       T (Tag_GNU_MIPS_ABI_MSA),
19990 #undef T
19991     };
19992   unsigned int i;
19993
19994   if (name == NULL)
19995     return -1;
19996
19997   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
19998     if (streq (name, attribute_table[i].name))
19999       return attribute_table[i].tag;
20000
20001   return -1;
20002 }
20003
20004 void
20005 md_mips_end (void)
20006 {
20007   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
20008
20009   mips_emit_delays ();
20010   if (cur_proc_ptr)
20011     as_warn (_("missing .end at end of assembly"));
20012
20013   /* Just in case no code was emitted, do the consistency check.  */
20014   file_mips_check_options ();
20015
20016   /* Set a floating-point ABI if the user did not.  */
20017   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20018     {
20019       /* Perform consistency checks on the floating-point ABI.  */
20020       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20021                                         Tag_GNU_MIPS_ABI_FP);
20022       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20023         check_fpabi (fpabi);
20024     }
20025   else
20026     {
20027       /* Soft-float gets precedence over single-float, the two options should
20028          not be used together so this should not matter.  */
20029       if (file_mips_opts.soft_float == 1)
20030         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20031       /* Single-float gets precedence over all double_float cases.  */
20032       else if (file_mips_opts.single_float == 1)
20033         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20034       else
20035         {
20036           switch (file_mips_opts.fp)
20037             {
20038             case 32:
20039               if (file_mips_opts.gp == 32)
20040                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20041               break;
20042             case 0:
20043               fpabi = Val_GNU_MIPS_ABI_FP_XX;
20044               break;
20045             case 64:
20046               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20047                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
20048               else if (file_mips_opts.gp == 32)
20049                 fpabi = Val_GNU_MIPS_ABI_FP_64;
20050               else
20051                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20052               break;
20053             }
20054         }
20055
20056       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20057                                 Tag_GNU_MIPS_ABI_FP, fpabi);
20058     }
20059 }
20060
20061 /*  Returns the relocation type required for a particular CFI encoding.  */
20062
20063 bfd_reloc_code_real_type
20064 mips_cfi_reloc_for_encoding (int encoding)
20065 {
20066   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20067     return BFD_RELOC_32_PCREL;
20068   else return BFD_RELOC_NONE;
20069 }