gas/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Contributed by the OSF and Ralph Campbell.
6    Written by Keith Knowles and Ralph Campbell, working independently.
7    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
8    Support.
9
10    This file is part of GAS.
11
12    GAS is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GAS is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with GAS; see the file COPYING.  If not, write to the Free
24    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
25    02110-1301, USA.  */
26
27 #include "as.h"
28 #include "config.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31
32 #include "opcode/mips.h"
33 #include "itbl-ops.h"
34 #include "dwarf2dbg.h"
35 #include "dw2gencfi.h"
36
37 #ifdef DEBUG
38 #define DBG(x) printf x
39 #else
40 #define DBG(x)
41 #endif
42
43 #ifdef OBJ_MAYBE_ELF
44 /* Clean up namespace so we can include obj-elf.h too.  */
45 static int mips_output_flavor (void);
46 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
47 #undef OBJ_PROCESS_STAB
48 #undef OUTPUT_FLAVOR
49 #undef S_GET_ALIGN
50 #undef S_GET_SIZE
51 #undef S_SET_ALIGN
52 #undef S_SET_SIZE
53 #undef obj_frob_file
54 #undef obj_frob_file_after_relocs
55 #undef obj_frob_symbol
56 #undef obj_pop_insert
57 #undef obj_sec_sym_ok_for_reloc
58 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
59
60 #include "obj-elf.h"
61 /* Fix any of them that we actually care about.  */
62 #undef OUTPUT_FLAVOR
63 #define OUTPUT_FLAVOR mips_output_flavor()
64 #endif
65
66 #if defined (OBJ_ELF)
67 #include "elf/mips.h"
68 #endif
69
70 #ifndef ECOFF_DEBUGGING
71 #define NO_ECOFF_DEBUGGING
72 #define ECOFF_DEBUGGING 0
73 #endif
74
75 int mips_flag_mdebug = -1;
76
77 /* Control generation of .pdr sections.  Off by default on IRIX: the native
78    linker doesn't know about and discards them, but relocations against them
79    remain, leading to rld crashes.  */
80 #ifdef TE_IRIX
81 int mips_flag_pdr = FALSE;
82 #else
83 int mips_flag_pdr = TRUE;
84 #endif
85
86 #include "ecoff.h"
87
88 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
89 static char *mips_regmask_frag;
90 #endif
91
92 #define ZERO 0
93 #define ATREG 1
94 #define S0  16
95 #define S7  23
96 #define TREG 24
97 #define PIC_CALL_REG 25
98 #define KT0 26
99 #define KT1 27
100 #define GP  28
101 #define SP  29
102 #define FP  30
103 #define RA  31
104
105 #define ILLEGAL_REG (32)
106
107 #define AT  mips_opts.at
108
109 /* Allow override of standard little-endian ECOFF format.  */
110
111 #ifndef ECOFF_LITTLE_FORMAT
112 #define ECOFF_LITTLE_FORMAT "ecoff-littlemips"
113 #endif
114
115 extern int target_big_endian;
116
117 /* The name of the readonly data section.  */
118 #define RDATA_SECTION_NAME (OUTPUT_FLAVOR == bfd_target_ecoff_flavour \
119                             ? ".rdata" \
120                             : OUTPUT_FLAVOR == bfd_target_coff_flavour \
121                             ? ".rdata" \
122                             : OUTPUT_FLAVOR == bfd_target_elf_flavour \
123                             ? ".rodata" \
124                             : (abort (), ""))
125
126 /* Ways in which an instruction can be "appended" to the output.  */
127 enum append_method {
128   /* Just add it normally.  */
129   APPEND_ADD,
130
131   /* Add it normally and then add a nop.  */
132   APPEND_ADD_WITH_NOP,
133
134   /* Turn an instruction with a delay slot into a "compact" version.  */
135   APPEND_ADD_COMPACT,
136
137   /* Insert the instruction before the last one.  */
138   APPEND_SWAP
139 };
140
141 /* Information about an instruction, including its format, operands
142    and fixups.  */
143 struct mips_cl_insn
144 {
145   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
146   const struct mips_opcode *insn_mo;
147
148   /* True if this is a mips16 instruction and if we want the extended
149      form of INSN_MO.  */
150   bfd_boolean use_extend;
151
152   /* The 16-bit extension instruction to use when USE_EXTEND is true.  */
153   unsigned short extend;
154
155   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
156      a copy of INSN_MO->match with the operands filled in.  */
157   unsigned long insn_opcode;
158
159   /* The frag that contains the instruction.  */
160   struct frag *frag;
161
162   /* The offset into FRAG of the first instruction byte.  */
163   long where;
164
165   /* The relocs associated with the instruction, if any.  */
166   fixS *fixp[3];
167
168   /* True if this entry cannot be moved from its current position.  */
169   unsigned int fixed_p : 1;
170
171   /* True if this instruction occurred in a .set noreorder block.  */
172   unsigned int noreorder_p : 1;
173
174   /* True for mips16 instructions that jump to an absolute address.  */
175   unsigned int mips16_absolute_jump_p : 1;
176
177   /* True if this instruction is complete.  */
178   unsigned int complete_p : 1;
179 };
180
181 /* The ABI to use.  */
182 enum mips_abi_level
183 {
184   NO_ABI = 0,
185   O32_ABI,
186   O64_ABI,
187   N32_ABI,
188   N64_ABI,
189   EABI_ABI
190 };
191
192 /* MIPS ABI we are using for this output file.  */
193 static enum mips_abi_level mips_abi = NO_ABI;
194
195 /* Whether or not we have code that can call pic code.  */
196 int mips_abicalls = FALSE;
197
198 /* Whether or not we have code which can be put into a shared
199    library.  */
200 static bfd_boolean mips_in_shared = TRUE;
201
202 /* This is the set of options which may be modified by the .set
203    pseudo-op.  We use a struct so that .set push and .set pop are more
204    reliable.  */
205
206 struct mips_set_options
207 {
208   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
209      if it has not been initialized.  Changed by `.set mipsN', and the
210      -mipsN command line option, and the default CPU.  */
211   int isa;
212   /* Enabled Application Specific Extensions (ASEs).  These are set to -1
213      if they have not been initialized.  Changed by `.set <asename>', by
214      command line options, and based on the default architecture.  */
215   int ase_mips3d;
216   int ase_mdmx;
217   int ase_smartmips;
218   int ase_dsp;
219   int ase_dspr2;
220   int ase_mt;
221   int ase_mcu;
222   /* Whether we are assembling for the mips16 processor.  0 if we are
223      not, 1 if we are, and -1 if the value has not been initialized.
224      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
225      -nomips16 command line options, and the default CPU.  */
226   int mips16;
227   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
228      1 if we are, and -1 if the value has not been initialized.  Changed
229      by `.set micromips' and `.set nomicromips', and the -mmicromips
230      and -mno-micromips command line options, and the default CPU.  */
231   int micromips;
232   /* Non-zero if we should not reorder instructions.  Changed by `.set
233      reorder' and `.set noreorder'.  */
234   int noreorder;
235   /* Non-zero if we should not permit the register designated "assembler
236      temporary" to be used in instructions.  The value is the register
237      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
238      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
239   unsigned int at;
240   /* Non-zero if we should warn when a macro instruction expands into
241      more than one machine instruction.  Changed by `.set nomacro' and
242      `.set macro'.  */
243   int warn_about_macros;
244   /* Non-zero if we should not move instructions.  Changed by `.set
245      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
246   int nomove;
247   /* Non-zero if we should not optimize branches by moving the target
248      of the branch into the delay slot.  Actually, we don't perform
249      this optimization anyhow.  Changed by `.set bopt' and `.set
250      nobopt'.  */
251   int nobopt;
252   /* Non-zero if we should not autoextend mips16 instructions.
253      Changed by `.set autoextend' and `.set noautoextend'.  */
254   int noautoextend;
255   /* Restrict general purpose registers and floating point registers
256      to 32 bit.  This is initially determined when -mgp32 or -mfp32
257      is passed but can changed if the assembler code uses .set mipsN.  */
258   int gp32;
259   int fp32;
260   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
261      command line option, and the default CPU.  */
262   int arch;
263   /* True if ".set sym32" is in effect.  */
264   bfd_boolean sym32;
265   /* True if floating-point operations are not allowed.  Changed by .set
266      softfloat or .set hardfloat, by command line options -msoft-float or
267      -mhard-float.  The default is false.  */
268   bfd_boolean soft_float;
269
270   /* True if only single-precision floating-point operations are allowed.
271      Changed by .set singlefloat or .set doublefloat, command-line options
272      -msingle-float or -mdouble-float.  The default is false.  */
273   bfd_boolean single_float;
274 };
275
276 /* This is the struct we use to hold the current set of options.  Note
277    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
278    -1 to indicate that they have not been initialized.  */
279
280 /* True if -mgp32 was passed.  */
281 static int file_mips_gp32 = -1;
282
283 /* True if -mfp32 was passed.  */
284 static int file_mips_fp32 = -1;
285
286 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
287 static int file_mips_soft_float = 0;
288
289 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
290 static int file_mips_single_float = 0;
291
292 static struct mips_set_options mips_opts =
293 {
294   /* isa */ ISA_UNKNOWN, /* ase_mips3d */ -1, /* ase_mdmx */ -1,
295   /* ase_smartmips */ 0, /* ase_dsp */ -1, /* ase_dspr2 */ -1, /* ase_mt */ -1,
296   /* ase_mcu */ -1, /* mips16 */ -1, /* micromips */ -1, /* noreorder */ 0,
297   /* at */ ATREG, /* warn_about_macros */ 0, /* nomove */ 0, /* nobopt */ 0,
298   /* noautoextend */ 0, /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN,
299   /* sym32 */ FALSE, /* soft_float */ FALSE, /* single_float */ FALSE
300 };
301
302 /* These variables are filled in with the masks of registers used.
303    The object format code reads them and puts them in the appropriate
304    place.  */
305 unsigned long mips_gprmask;
306 unsigned long mips_cprmask[4];
307
308 /* MIPS ISA we are using for this output file.  */
309 static int file_mips_isa = ISA_UNKNOWN;
310
311 /* True if any MIPS16 code was produced.  */
312 static int file_ase_mips16;
313
314 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
315                               || mips_opts.isa == ISA_MIPS32R2          \
316                               || mips_opts.isa == ISA_MIPS64            \
317                               || mips_opts.isa == ISA_MIPS64R2)
318
319 /* True if any microMIPS code was produced.  */
320 static int file_ase_micromips;
321
322 /* True if we want to create R_MIPS_JALR for jalr $25.  */
323 #ifdef TE_IRIX
324 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
325 #else
326 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
327    because there's no place for any addend, the only acceptable
328    expression is a bare symbol.  */
329 #define MIPS_JALR_HINT_P(EXPR) \
330   (!HAVE_IN_PLACE_ADDENDS \
331    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
332 #endif
333
334 /* True if -mips3d was passed or implied by arguments passed on the
335    command line (e.g., by -march).  */
336 static int file_ase_mips3d;
337
338 /* True if -mdmx was passed or implied by arguments passed on the
339    command line (e.g., by -march).  */
340 static int file_ase_mdmx;
341
342 /* True if -msmartmips was passed or implied by arguments passed on the
343    command line (e.g., by -march).  */
344 static int file_ase_smartmips;
345
346 #define ISA_SUPPORTS_SMARTMIPS (mips_opts.isa == ISA_MIPS32             \
347                                 || mips_opts.isa == ISA_MIPS32R2)
348
349 /* True if -mdsp was passed or implied by arguments passed on the
350    command line (e.g., by -march).  */
351 static int file_ase_dsp;
352
353 #define ISA_SUPPORTS_DSP_ASE (mips_opts.isa == ISA_MIPS32R2             \
354                               || mips_opts.isa == ISA_MIPS64R2)
355
356 #define ISA_SUPPORTS_DSP64_ASE (mips_opts.isa == ISA_MIPS64R2)
357
358 /* True if -mdspr2 was passed or implied by arguments passed on the
359    command line (e.g., by -march).  */
360 static int file_ase_dspr2;
361
362 #define ISA_SUPPORTS_DSPR2_ASE (mips_opts.isa == ISA_MIPS32R2           \
363                                 || mips_opts.isa == ISA_MIPS64R2)
364
365 /* True if -mmt was passed or implied by arguments passed on the
366    command line (e.g., by -march).  */
367 static int file_ase_mt;
368
369 #define ISA_SUPPORTS_MT_ASE (mips_opts.isa == ISA_MIPS32R2              \
370                              || mips_opts.isa == ISA_MIPS64R2)
371
372 #define ISA_SUPPORTS_MCU_ASE (mips_opts.isa == ISA_MIPS32R2             \
373                               || mips_opts.isa == ISA_MIPS64R2          \
374                               || mips_opts.micromips)
375
376 /* The argument of the -march= flag.  The architecture we are assembling.  */
377 static int file_mips_arch = CPU_UNKNOWN;
378 static const char *mips_arch_string;
379
380 /* The argument of the -mtune= flag.  The architecture for which we
381    are optimizing.  */
382 static int mips_tune = CPU_UNKNOWN;
383 static const char *mips_tune_string;
384
385 /* True when generating 32-bit code for a 64-bit processor.  */
386 static int mips_32bitmode = 0;
387
388 /* True if the given ABI requires 32-bit registers.  */
389 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
390
391 /* Likewise 64-bit registers.  */
392 #define ABI_NEEDS_64BIT_REGS(ABI)       \
393   ((ABI) == N32_ABI                     \
394    || (ABI) == N64_ABI                  \
395    || (ABI) == O64_ABI)
396
397 /*  Return true if ISA supports 64 bit wide gp registers.  */
398 #define ISA_HAS_64BIT_REGS(ISA)         \
399   ((ISA) == ISA_MIPS3                   \
400    || (ISA) == ISA_MIPS4                \
401    || (ISA) == ISA_MIPS5                \
402    || (ISA) == ISA_MIPS64               \
403    || (ISA) == ISA_MIPS64R2)
404
405 /*  Return true if ISA supports 64 bit wide float registers.  */
406 #define ISA_HAS_64BIT_FPRS(ISA)         \
407   ((ISA) == ISA_MIPS3                   \
408    || (ISA) == ISA_MIPS4                \
409    || (ISA) == ISA_MIPS5                \
410    || (ISA) == ISA_MIPS32R2             \
411    || (ISA) == ISA_MIPS64               \
412    || (ISA) == ISA_MIPS64R2)
413
414 /* Return true if ISA supports 64-bit right rotate (dror et al.)
415    instructions.  */
416 #define ISA_HAS_DROR(ISA)               \
417   ((ISA) == ISA_MIPS64R2                \
418    || (mips_opts.micromips              \
419        && ISA_HAS_64BIT_REGS (ISA))     \
420    )
421
422 /* Return true if ISA supports 32-bit right rotate (ror et al.)
423    instructions.  */
424 #define ISA_HAS_ROR(ISA)                \
425   ((ISA) == ISA_MIPS32R2                \
426    || (ISA) == ISA_MIPS64R2             \
427    || mips_opts.ase_smartmips           \
428    || mips_opts.micromips               \
429    )
430
431 /* Return true if ISA supports single-precision floats in odd registers.  */
432 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
433   ((ISA) == ISA_MIPS32                  \
434    || (ISA) == ISA_MIPS32R2             \
435    || (ISA) == ISA_MIPS64               \
436    || (ISA) == ISA_MIPS64R2)
437
438 /* Return true if ISA supports move to/from high part of a 64-bit
439    floating-point register. */
440 #define ISA_HAS_MXHC1(ISA)              \
441   ((ISA) == ISA_MIPS32R2                \
442    || (ISA) == ISA_MIPS64R2)
443
444 #define HAVE_32BIT_GPRS                            \
445     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
446
447 #define HAVE_32BIT_FPRS                            \
448     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
449
450 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
451 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
452
453 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
454
455 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
456
457 /* True if relocations are stored in-place.  */
458 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
459
460 /* The ABI-derived address size.  */
461 #define HAVE_64BIT_ADDRESSES \
462   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
463 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
464
465 /* The size of symbolic constants (i.e., expressions of the form
466    "SYMBOL" or "SYMBOL + OFFSET").  */
467 #define HAVE_32BIT_SYMBOLS \
468   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
469 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
470
471 /* Addresses are loaded in different ways, depending on the address size
472    in use.  The n32 ABI Documentation also mandates the use of additions
473    with overflow checking, but existing implementations don't follow it.  */
474 #define ADDRESS_ADD_INSN                                                \
475    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
476
477 #define ADDRESS_ADDI_INSN                                               \
478    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
479
480 #define ADDRESS_LOAD_INSN                                               \
481    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
482
483 #define ADDRESS_STORE_INSN                                              \
484    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
485
486 /* Return true if the given CPU supports the MIPS16 ASE.  */
487 #define CPU_HAS_MIPS16(cpu)                                             \
488    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
489     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
490
491 /* Return true if the given CPU supports the microMIPS ASE.  */
492 #define CPU_HAS_MICROMIPS(cpu)  0
493
494 /* True if CPU has a dror instruction.  */
495 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
496
497 /* True if CPU has a ror instruction.  */
498 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
499
500 /* True if CPU is in the Octeon family */
501 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
502
503 /* True if CPU has seq/sne and seqi/snei instructions.  */
504 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
505
506 /* True if CPU does not implement the all the coprocessor insns.  For these
507    CPUs only those COP insns are accepted that are explicitly marked to be
508    available on the CPU.  ISA membership for COP insns is ignored.  */
509 #define NO_ISA_COP(CPU)         (CPU_IS_OCTEON (CPU))
510
511 /* True if mflo and mfhi can be immediately followed by instructions
512    which write to the HI and LO registers.
513
514    According to MIPS specifications, MIPS ISAs I, II, and III need
515    (at least) two instructions between the reads of HI/LO and
516    instructions which write them, and later ISAs do not.  Contradicting
517    the MIPS specifications, some MIPS IV processor user manuals (e.g.
518    the UM for the NEC Vr5000) document needing the instructions between
519    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
520    MIPS64 and later ISAs to have the interlocks, plus any specific
521    earlier-ISA CPUs for which CPU documentation declares that the
522    instructions are really interlocked.  */
523 #define hilo_interlocks \
524   (mips_opts.isa == ISA_MIPS32                        \
525    || mips_opts.isa == ISA_MIPS32R2                   \
526    || mips_opts.isa == ISA_MIPS64                     \
527    || mips_opts.isa == ISA_MIPS64R2                   \
528    || mips_opts.arch == CPU_R4010                     \
529    || mips_opts.arch == CPU_R10000                    \
530    || mips_opts.arch == CPU_R12000                    \
531    || mips_opts.arch == CPU_R14000                    \
532    || mips_opts.arch == CPU_R16000                    \
533    || mips_opts.arch == CPU_RM7000                    \
534    || mips_opts.arch == CPU_VR5500                    \
535    || mips_opts.micromips                             \
536    )
537
538 /* Whether the processor uses hardware interlocks to protect reads
539    from the GPRs after they are loaded from memory, and thus does not
540    require nops to be inserted.  This applies to instructions marked
541    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
542    level I and microMIPS mode instructions are always interlocked.  */
543 #define gpr_interlocks                                \
544   (mips_opts.isa != ISA_MIPS1                         \
545    || mips_opts.arch == CPU_R3900                     \
546    || mips_opts.micromips                             \
547    )
548
549 /* Whether the processor uses hardware interlocks to avoid delays
550    required by coprocessor instructions, and thus does not require
551    nops to be inserted.  This applies to instructions marked
552    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
553    between instructions marked INSN_WRITE_COND_CODE and ones marked
554    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
555    levels I, II, and III and microMIPS mode instructions are always
556    interlocked.  */
557 /* Itbl support may require additional care here.  */
558 #define cop_interlocks                                \
559   ((mips_opts.isa != ISA_MIPS1                        \
560     && mips_opts.isa != ISA_MIPS2                     \
561     && mips_opts.isa != ISA_MIPS3)                    \
562    || mips_opts.arch == CPU_R4300                     \
563    || mips_opts.micromips                             \
564    )
565
566 /* Whether the processor uses hardware interlocks to protect reads
567    from coprocessor registers after they are loaded from memory, and
568    thus does not require nops to be inserted.  This applies to
569    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
570    requires at MIPS ISA level I and microMIPS mode instructions are
571    always interlocked.  */
572 #define cop_mem_interlocks                            \
573   (mips_opts.isa != ISA_MIPS1                         \
574    || mips_opts.micromips                             \
575    )
576
577 /* Is this a mfhi or mflo instruction?  */
578 #define MF_HILO_INSN(PINFO) \
579   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
580
581 /* Returns true for a (non floating-point) coprocessor instruction.  Reading
582    or writing the condition code is only possible on the coprocessors and
583    these insns are not marked with INSN_COP.  Thus for these insns use the
584    condition-code flags.  */
585 #define COP_INSN(PINFO)                                                 \
586   (PINFO != INSN_MACRO                                                  \
587    && ((PINFO) & (FP_S | FP_D)) == 0                                    \
588    && ((PINFO) & (INSN_COP | INSN_READ_COND_CODE | INSN_WRITE_COND_CODE)))
589
590 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
591    has been selected.  This implies, in particular, that addresses of text
592    labels have their LSB set.  */
593 #define HAVE_CODE_COMPRESSION                                           \
594   ((mips_opts.mips16 | mips_opts.micromips) != 0)
595
596 /* MIPS PIC level.  */
597
598 enum mips_pic_level mips_pic;
599
600 /* 1 if we should generate 32 bit offsets from the $gp register in
601    SVR4_PIC mode.  Currently has no meaning in other modes.  */
602 static int mips_big_got = 0;
603
604 /* 1 if trap instructions should used for overflow rather than break
605    instructions.  */
606 static int mips_trap = 0;
607
608 /* 1 if double width floating point constants should not be constructed
609    by assembling two single width halves into two single width floating
610    point registers which just happen to alias the double width destination
611    register.  On some architectures this aliasing can be disabled by a bit
612    in the status register, and the setting of this bit cannot be determined
613    automatically at assemble time.  */
614 static int mips_disable_float_construction;
615
616 /* Non-zero if any .set noreorder directives were used.  */
617
618 static int mips_any_noreorder;
619
620 /* Non-zero if nops should be inserted when the register referenced in
621    an mfhi/mflo instruction is read in the next two instructions.  */
622 static int mips_7000_hilo_fix;
623
624 /* The size of objects in the small data section.  */
625 static unsigned int g_switch_value = 8;
626 /* Whether the -G option was used.  */
627 static int g_switch_seen = 0;
628
629 #define N_RMASK 0xc4
630 #define N_VFP   0xd4
631
632 /* If we can determine in advance that GP optimization won't be
633    possible, we can skip the relaxation stuff that tries to produce
634    GP-relative references.  This makes delay slot optimization work
635    better.
636
637    This function can only provide a guess, but it seems to work for
638    gcc output.  It needs to guess right for gcc, otherwise gcc
639    will put what it thinks is a GP-relative instruction in a branch
640    delay slot.
641
642    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
643    fixed it for the non-PIC mode.  KR 95/04/07  */
644 static int nopic_need_relax (symbolS *, int);
645
646 /* handle of the OPCODE hash table */
647 static struct hash_control *op_hash = NULL;
648
649 /* The opcode hash table we use for the mips16.  */
650 static struct hash_control *mips16_op_hash = NULL;
651
652 /* The opcode hash table we use for the microMIPS ASE.  */
653 static struct hash_control *micromips_op_hash = NULL;
654
655 /* This array holds the chars that always start a comment.  If the
656     pre-processor is disabled, these aren't very useful */
657 const char comment_chars[] = "#";
658
659 /* This array holds the chars that only start a comment at the beginning of
660    a line.  If the line seems to have the form '# 123 filename'
661    .line and .file directives will appear in the pre-processed output */
662 /* Note that input_file.c hand checks for '#' at the beginning of the
663    first line of the input file.  This is because the compiler outputs
664    #NO_APP at the beginning of its output.  */
665 /* Also note that C style comments are always supported.  */
666 const char line_comment_chars[] = "#";
667
668 /* This array holds machine specific line separator characters.  */
669 const char line_separator_chars[] = ";";
670
671 /* Chars that can be used to separate mant from exp in floating point nums */
672 const char EXP_CHARS[] = "eE";
673
674 /* Chars that mean this number is a floating point constant */
675 /* As in 0f12.456 */
676 /* or    0d1.2345e12 */
677 const char FLT_CHARS[] = "rRsSfFdDxXpP";
678
679 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
680    changed in read.c .  Ideally it shouldn't have to know about it at all,
681    but nothing is ideal around here.
682  */
683
684 static char *insn_error;
685
686 static int auto_align = 1;
687
688 /* When outputting SVR4 PIC code, the assembler needs to know the
689    offset in the stack frame from which to restore the $gp register.
690    This is set by the .cprestore pseudo-op, and saved in this
691    variable.  */
692 static offsetT mips_cprestore_offset = -1;
693
694 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
695    more optimizations, it can use a register value instead of a memory-saved
696    offset and even an other register than $gp as global pointer.  */
697 static offsetT mips_cpreturn_offset = -1;
698 static int mips_cpreturn_register = -1;
699 static int mips_gp_register = GP;
700 static int mips_gprel_offset = 0;
701
702 /* Whether mips_cprestore_offset has been set in the current function
703    (or whether it has already been warned about, if not).  */
704 static int mips_cprestore_valid = 0;
705
706 /* This is the register which holds the stack frame, as set by the
707    .frame pseudo-op.  This is needed to implement .cprestore.  */
708 static int mips_frame_reg = SP;
709
710 /* Whether mips_frame_reg has been set in the current function
711    (or whether it has already been warned about, if not).  */
712 static int mips_frame_reg_valid = 0;
713
714 /* To output NOP instructions correctly, we need to keep information
715    about the previous two instructions.  */
716
717 /* Whether we are optimizing.  The default value of 2 means to remove
718    unneeded NOPs and swap branch instructions when possible.  A value
719    of 1 means to not swap branches.  A value of 0 means to always
720    insert NOPs.  */
721 static int mips_optimize = 2;
722
723 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
724    equivalent to seeing no -g option at all.  */
725 static int mips_debug = 0;
726
727 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
728 #define MAX_VR4130_NOPS 4
729
730 /* The maximum number of NOPs needed to fill delay slots.  */
731 #define MAX_DELAY_NOPS 2
732
733 /* The maximum number of NOPs needed for any purpose.  */
734 #define MAX_NOPS 4
735
736 /* A list of previous instructions, with index 0 being the most recent.
737    We need to look back MAX_NOPS instructions when filling delay slots
738    or working around processor errata.  We need to look back one
739    instruction further if we're thinking about using history[0] to
740    fill a branch delay slot.  */
741 static struct mips_cl_insn history[1 + MAX_NOPS];
742
743 /* Nop instructions used by emit_nop.  */
744 static struct mips_cl_insn nop_insn;
745 static struct mips_cl_insn mips16_nop_insn;
746 static struct mips_cl_insn micromips_nop16_insn;
747 static struct mips_cl_insn micromips_nop32_insn;
748
749 /* The appropriate nop for the current mode.  */
750 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn \
751                   : (mips_opts.micromips ? &micromips_nop16_insn : &nop_insn))
752
753 /* The size of NOP_INSN in bytes.  */
754 #define NOP_INSN_SIZE (HAVE_CODE_COMPRESSION ? 2 : 4)
755
756 /* If this is set, it points to a frag holding nop instructions which
757    were inserted before the start of a noreorder section.  If those
758    nops turn out to be unnecessary, the size of the frag can be
759    decreased.  */
760 static fragS *prev_nop_frag;
761
762 /* The number of nop instructions we created in prev_nop_frag.  */
763 static int prev_nop_frag_holds;
764
765 /* The number of nop instructions that we know we need in
766    prev_nop_frag.  */
767 static int prev_nop_frag_required;
768
769 /* The number of instructions we've seen since prev_nop_frag.  */
770 static int prev_nop_frag_since;
771
772 /* For ECOFF and ELF, relocations against symbols are done in two
773    parts, with a HI relocation and a LO relocation.  Each relocation
774    has only 16 bits of space to store an addend.  This means that in
775    order for the linker to handle carries correctly, it must be able
776    to locate both the HI and the LO relocation.  This means that the
777    relocations must appear in order in the relocation table.
778
779    In order to implement this, we keep track of each unmatched HI
780    relocation.  We then sort them so that they immediately precede the
781    corresponding LO relocation.  */
782
783 struct mips_hi_fixup
784 {
785   /* Next HI fixup.  */
786   struct mips_hi_fixup *next;
787   /* This fixup.  */
788   fixS *fixp;
789   /* The section this fixup is in.  */
790   segT seg;
791 };
792
793 /* The list of unmatched HI relocs.  */
794
795 static struct mips_hi_fixup *mips_hi_fixup_list;
796
797 /* The frag containing the last explicit relocation operator.
798    Null if explicit relocations have not been used.  */
799
800 static fragS *prev_reloc_op_frag;
801
802 /* Map normal MIPS register numbers to mips16 register numbers.  */
803
804 #define X ILLEGAL_REG
805 static const int mips32_to_16_reg_map[] =
806 {
807   X, X, 2, 3, 4, 5, 6, 7,
808   X, X, X, X, X, X, X, X,
809   0, 1, X, X, X, X, X, X,
810   X, X, X, X, X, X, X, X
811 };
812 #undef X
813
814 /* Map mips16 register numbers to normal MIPS register numbers.  */
815
816 static const unsigned int mips16_to_32_reg_map[] =
817 {
818   16, 17, 2, 3, 4, 5, 6, 7
819 };
820
821 /* Map normal MIPS register numbers to microMIPS register numbers.  */
822
823 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
824 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
825 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
826 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
827 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
828 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
829 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
830
831 #define X ILLEGAL_REG
832 /* reg type h: 4, 5, 6.  */
833 static const int mips32_to_micromips_reg_h_map[] =
834 {
835   X, X, X, X, 4, 5, 6, X,
836   X, X, X, X, X, X, X, X,
837   X, X, X, X, X, X, X, X,
838   X, X, X, X, X, X, X, X
839 };
840
841 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
842 static const int mips32_to_micromips_reg_m_map[] =
843 {
844   0, X, 2, 3, X, X, X, X,
845   X, X, X, X, X, X, X, X,
846   4, 1, 5, 6, 7, X, X, X,
847   X, X, X, X, X, X, X, X
848 };
849
850 /* reg type q: 0, 2-7. 17.  */
851 static const int mips32_to_micromips_reg_q_map[] =
852 {
853   0, X, 2, 3, 4, 5, 6, 7,
854   X, X, X, X, X, X, X, X,
855   X, 1, X, X, X, X, X, X,
856   X, X, X, X, X, X, X, X
857 };
858
859 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
860 #undef X
861
862 /* Map microMIPS register numbers to normal MIPS register numbers.  */
863
864 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
865 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
866 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
867 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
868 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
869 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
870
871 /* The microMIPS registers with type h.  */
872 static const unsigned int micromips_to_32_reg_h_map[] =
873 {
874   5, 5, 6, 4, 4, 4, 4, 4
875 };
876
877 /* The microMIPS registers with type i.  */
878 static const unsigned int micromips_to_32_reg_i_map[] =
879 {
880   6, 7, 7, 21, 22, 5, 6, 7
881 };
882
883 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
884
885 /* The microMIPS registers with type m.  */
886 static const unsigned int micromips_to_32_reg_m_map[] =
887 {
888   0, 17, 2, 3, 16, 18, 19, 20
889 };
890
891 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
892
893 /* The microMIPS registers with type q.  */
894 static const unsigned int micromips_to_32_reg_q_map[] =
895 {
896   0, 17, 2, 3, 4, 5, 6, 7
897 };
898
899 /* microMIPS imm type B.  */
900 static const int micromips_imm_b_map[] =
901 {
902   1, 4, 8, 12, 16, 20, 24, -1
903 };
904
905 /* microMIPS imm type C.  */
906 static const int micromips_imm_c_map[] =
907 {
908   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
909 };
910
911 /* Classifies the kind of instructions we're interested in when
912    implementing -mfix-vr4120.  */
913 enum fix_vr4120_class
914 {
915   FIX_VR4120_MACC,
916   FIX_VR4120_DMACC,
917   FIX_VR4120_MULT,
918   FIX_VR4120_DMULT,
919   FIX_VR4120_DIV,
920   FIX_VR4120_MTHILO,
921   NUM_FIX_VR4120_CLASSES
922 };
923
924 /* ...likewise -mfix-loongson2f-jump.  */
925 static bfd_boolean mips_fix_loongson2f_jump;
926
927 /* ...likewise -mfix-loongson2f-nop.  */
928 static bfd_boolean mips_fix_loongson2f_nop;
929
930 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
931 static bfd_boolean mips_fix_loongson2f;
932
933 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
934    there must be at least one other instruction between an instruction
935    of type X and an instruction of type Y.  */
936 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
937
938 /* True if -mfix-vr4120 is in force.  */
939 static int mips_fix_vr4120;
940
941 /* ...likewise -mfix-vr4130.  */
942 static int mips_fix_vr4130;
943
944 /* ...likewise -mfix-24k.  */
945 static int mips_fix_24k;
946
947 /* ...likewise -mfix-cn63xxp1 */
948 static bfd_boolean mips_fix_cn63xxp1;
949
950 /* We don't relax branches by default, since this causes us to expand
951    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
952    fail to compute the offset before expanding the macro to the most
953    efficient expansion.  */
954
955 static int mips_relax_branch;
956 \f
957 /* The expansion of many macros depends on the type of symbol that
958    they refer to.  For example, when generating position-dependent code,
959    a macro that refers to a symbol may have two different expansions,
960    one which uses GP-relative addresses and one which uses absolute
961    addresses.  When generating SVR4-style PIC, a macro may have
962    different expansions for local and global symbols.
963
964    We handle these situations by generating both sequences and putting
965    them in variant frags.  In position-dependent code, the first sequence
966    will be the GP-relative one and the second sequence will be the
967    absolute one.  In SVR4 PIC, the first sequence will be for global
968    symbols and the second will be for local symbols.
969
970    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
971    SECOND are the lengths of the two sequences in bytes.  These fields
972    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
973    the subtype has the following flags:
974
975    RELAX_USE_SECOND
976         Set if it has been decided that we should use the second
977         sequence instead of the first.
978
979    RELAX_SECOND_LONGER
980         Set in the first variant frag if the macro's second implementation
981         is longer than its first.  This refers to the macro as a whole,
982         not an individual relaxation.
983
984    RELAX_NOMACRO
985         Set in the first variant frag if the macro appeared in a .set nomacro
986         block and if one alternative requires a warning but the other does not.
987
988    RELAX_DELAY_SLOT
989         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
990         delay slot.
991
992    RELAX_DELAY_SLOT_16BIT
993         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
994         16-bit instruction.
995
996    RELAX_DELAY_SLOT_SIZE_FIRST
997         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
998         the macro is of the wrong size for the branch delay slot.
999
1000    RELAX_DELAY_SLOT_SIZE_SECOND
1001         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1002         the macro is of the wrong size for the branch delay slot.
1003
1004    The frag's "opcode" points to the first fixup for relaxable code.
1005
1006    Relaxable macros are generated using a sequence such as:
1007
1008       relax_start (SYMBOL);
1009       ... generate first expansion ...
1010       relax_switch ();
1011       ... generate second expansion ...
1012       relax_end ();
1013
1014    The code and fixups for the unwanted alternative are discarded
1015    by md_convert_frag.  */
1016 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
1017
1018 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1019 #define RELAX_SECOND(X) ((X) & 0xff)
1020 #define RELAX_USE_SECOND 0x10000
1021 #define RELAX_SECOND_LONGER 0x20000
1022 #define RELAX_NOMACRO 0x40000
1023 #define RELAX_DELAY_SLOT 0x80000
1024 #define RELAX_DELAY_SLOT_16BIT 0x100000
1025 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
1026 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
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, uncond, likely, link, toofar)   \
1096   ((relax_substateT)                                            \
1097    (0xc0000000                                                  \
1098     | ((at) & 0x1f)                                             \
1099     | ((toofar) ? 0x20 : 0)                                     \
1100     | ((link) ? 0x40 : 0)                                       \
1101     | ((likely) ? 0x80 : 0)                                     \
1102     | ((uncond) ? 0x100 : 0)))
1103 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1104 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1105 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1106 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1107 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1108 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1109
1110 /* For mips16 code, we use an entirely different form of relaxation.
1111    mips16 supports two versions of most instructions which take
1112    immediate values: a small one which takes some small value, and a
1113    larger one which takes a 16 bit value.  Since branches also follow
1114    this pattern, relaxing these values is required.
1115
1116    We can assemble both mips16 and normal MIPS code in a single
1117    object.  Therefore, we need to support this type of relaxation at
1118    the same time that we support the relaxation described above.  We
1119    use the high bit of the subtype field to distinguish these cases.
1120
1121    The information we store for this type of relaxation is the
1122    argument code found in the opcode file for this relocation, whether
1123    the user explicitly requested a small or extended form, and whether
1124    the relocation is in a jump or jal delay slot.  That tells us the
1125    size of the value, and how it should be stored.  We also store
1126    whether the fragment is considered to be extended or not.  We also
1127    store whether this is known to be a branch to a different section,
1128    whether we have tried to relax this frag yet, and whether we have
1129    ever extended a PC relative fragment because of a shift count.  */
1130 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1131   (0x80000000                                                   \
1132    | ((type) & 0xff)                                            \
1133    | ((small) ? 0x100 : 0)                                      \
1134    | ((ext) ? 0x200 : 0)                                        \
1135    | ((dslot) ? 0x400 : 0)                                      \
1136    | ((jal_dslot) ? 0x800 : 0))
1137 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1138 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1139 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1140 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1141 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1142 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1143 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1144 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1145 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1146 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1147 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1148 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1149
1150 /* For microMIPS code, we use relaxation similar to one we use for
1151    MIPS16 code.  Some instructions that take immediate values support
1152    two encodings: a small one which takes some small value, and a
1153    larger one which takes a 16 bit value.  As some branches also follow
1154    this pattern, relaxing these values is required.
1155
1156    We can assemble both microMIPS and normal MIPS code in a single
1157    object.  Therefore, we need to support this type of relaxation at
1158    the same time that we support the relaxation described above.  We
1159    use one of the high bits of the subtype field to distinguish these
1160    cases.
1161
1162    The information we store for this type of relaxation is the argument
1163    code found in the opcode file for this relocation, the register
1164    selected as the assembler temporary, whether the branch is
1165    unconditional, whether it is compact, whether it stores the link
1166    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1167    branches to a sequence of instructions is enabled, and whether the
1168    displacement of a branch is too large to fit as an immediate argument
1169    of a 16-bit and a 32-bit branch, respectively.  */
1170 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1171                                relax32, toofar16, toofar32)     \
1172   (0x40000000                                                   \
1173    | ((type) & 0xff)                                            \
1174    | (((at) & 0x1f) << 8)                                       \
1175    | ((uncond) ? 0x2000 : 0)                                    \
1176    | ((compact) ? 0x4000 : 0)                                   \
1177    | ((link) ? 0x8000 : 0)                                      \
1178    | ((relax32) ? 0x10000 : 0)                                  \
1179    | ((toofar16) ? 0x20000 : 0)                                 \
1180    | ((toofar32) ? 0x40000 : 0))
1181 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1182 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1183 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1184 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1185 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1186 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1187 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1188
1189 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1190 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1191 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1192 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1193 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1194 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1195
1196 /* Is the given value a sign-extended 32-bit value?  */
1197 #define IS_SEXT_32BIT_NUM(x)                                            \
1198   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1199    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1200
1201 /* Is the given value a sign-extended 16-bit value?  */
1202 #define IS_SEXT_16BIT_NUM(x)                                            \
1203   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1204    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1205
1206 /* Is the given value a sign-extended 12-bit value?  */
1207 #define IS_SEXT_12BIT_NUM(x)                                            \
1208   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1209
1210 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1211 #define IS_ZEXT_32BIT_NUM(x)                                            \
1212   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1213    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1214
1215 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1216    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1217 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1218   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1219               | (((VALUE) & (MASK)) << (SHIFT)))
1220
1221 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1222    SHIFT places.  */
1223 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1224   (((STRUCT) >> (SHIFT)) & (MASK))
1225
1226 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1227    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1228
1229    include/opcode/mips.h specifies operand fields using the macros
1230    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1231    with "MIPS16OP" instead of "OP".  */
1232 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1233   do \
1234     if (!(MICROMIPS)) \
1235       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1236                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1237     else \
1238       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1239                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1240   while (0)
1241 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1242   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1243                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1244
1245 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1246 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1247   (!(MICROMIPS) \
1248    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1249    : EXTRACT_BITS ((INSN).insn_opcode, \
1250                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1251 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1252   EXTRACT_BITS ((INSN).insn_opcode, \
1253                 MIPS16OP_MASK_##FIELD, \
1254                 MIPS16OP_SH_##FIELD)
1255 \f
1256 /* Whether or not we are emitting a branch-likely macro.  */
1257 static bfd_boolean emit_branch_likely_macro = FALSE;
1258
1259 /* Global variables used when generating relaxable macros.  See the
1260    comment above RELAX_ENCODE for more details about how relaxation
1261    is used.  */
1262 static struct {
1263   /* 0 if we're not emitting a relaxable macro.
1264      1 if we're emitting the first of the two relaxation alternatives.
1265      2 if we're emitting the second alternative.  */
1266   int sequence;
1267
1268   /* The first relaxable fixup in the current frag.  (In other words,
1269      the first fixup that refers to relaxable code.)  */
1270   fixS *first_fixup;
1271
1272   /* sizes[0] says how many bytes of the first alternative are stored in
1273      the current frag.  Likewise sizes[1] for the second alternative.  */
1274   unsigned int sizes[2];
1275
1276   /* The symbol on which the choice of sequence depends.  */
1277   symbolS *symbol;
1278 } mips_relax;
1279 \f
1280 /* Global variables used to decide whether a macro needs a warning.  */
1281 static struct {
1282   /* True if the macro is in a branch delay slot.  */
1283   bfd_boolean delay_slot_p;
1284
1285   /* Set to the length in bytes required if the macro is in a delay slot
1286      that requires a specific length of instruction, otherwise zero.  */
1287   unsigned int delay_slot_length;
1288
1289   /* For relaxable macros, sizes[0] is the length of the first alternative
1290      in bytes and sizes[1] is the length of the second alternative.
1291      For non-relaxable macros, both elements give the length of the
1292      macro in bytes.  */
1293   unsigned int sizes[2];
1294
1295   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1296      instruction of the first alternative in bytes and first_insn_sizes[1]
1297      is the length of the first instruction of the second alternative.
1298      For non-relaxable macros, both elements give the length of the first
1299      instruction in bytes.
1300
1301      Set to zero if we haven't yet seen the first instruction.  */
1302   unsigned int first_insn_sizes[2];
1303
1304   /* For relaxable macros, insns[0] is the number of instructions for the
1305      first alternative and insns[1] is the number of instructions for the
1306      second alternative.
1307
1308      For non-relaxable macros, both elements give the number of
1309      instructions for the macro.  */
1310   unsigned int insns[2];
1311
1312   /* The first variant frag for this macro.  */
1313   fragS *first_frag;
1314 } mips_macro_warning;
1315 \f
1316 /* Prototypes for static functions.  */
1317
1318 #define internalError()                                                 \
1319     as_fatal (_("internal Error, line %d, %s"), __LINE__, __FILE__)
1320
1321 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1322
1323 static void append_insn
1324   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1325    bfd_boolean expansionp);
1326 static void mips_no_prev_insn (void);
1327 static void macro_build (expressionS *, const char *, const char *, ...);
1328 static void mips16_macro_build
1329   (expressionS *, const char *, const char *, va_list *);
1330 static void load_register (int, expressionS *, int);
1331 static void macro_start (void);
1332 static void macro_end (void);
1333 static void macro (struct mips_cl_insn * ip);
1334 static void mips16_macro (struct mips_cl_insn * ip);
1335 static void mips_ip (char *str, struct mips_cl_insn * ip);
1336 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1337 static void mips16_immed
1338   (char *, unsigned int, int, offsetT, bfd_boolean, bfd_boolean, bfd_boolean,
1339    unsigned long *, bfd_boolean *, unsigned short *);
1340 static size_t my_getSmallExpression
1341   (expressionS *, bfd_reloc_code_real_type *, char *);
1342 static void my_getExpression (expressionS *, char *);
1343 static void s_align (int);
1344 static void s_change_sec (int);
1345 static void s_change_section (int);
1346 static void s_cons (int);
1347 static void s_float_cons (int);
1348 static void s_mips_globl (int);
1349 static void s_option (int);
1350 static void s_mipsset (int);
1351 static void s_abicalls (int);
1352 static void s_cpload (int);
1353 static void s_cpsetup (int);
1354 static void s_cplocal (int);
1355 static void s_cprestore (int);
1356 static void s_cpreturn (int);
1357 static void s_dtprelword (int);
1358 static void s_dtpreldword (int);
1359 static void s_tprelword (int);
1360 static void s_tpreldword (int);
1361 static void s_gpvalue (int);
1362 static void s_gpword (int);
1363 static void s_gpdword (int);
1364 static void s_cpadd (int);
1365 static void s_insn (int);
1366 static void md_obj_begin (void);
1367 static void md_obj_end (void);
1368 static void s_mips_ent (int);
1369 static void s_mips_end (int);
1370 static void s_mips_frame (int);
1371 static void s_mips_mask (int reg_type);
1372 static void s_mips_stab (int);
1373 static void s_mips_weakext (int);
1374 static void s_mips_file (int);
1375 static void s_mips_loc (int);
1376 static bfd_boolean pic_need_relax (symbolS *, asection *);
1377 static int relaxed_branch_length (fragS *, asection *, int);
1378 static int validate_mips_insn (const struct mips_opcode *);
1379 static int validate_micromips_insn (const struct mips_opcode *);
1380 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1381 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1382
1383 /* Table and functions used to map between CPU/ISA names, and
1384    ISA levels, and CPU numbers.  */
1385
1386 struct mips_cpu_info
1387 {
1388   const char *name;           /* CPU or ISA name.  */
1389   int flags;                  /* ASEs available, or ISA flag.  */
1390   int isa;                    /* ISA level.  */
1391   int cpu;                    /* CPU number (default CPU if ISA).  */
1392 };
1393
1394 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1395 #define MIPS_CPU_ASE_SMARTMIPS  0x0002  /* CPU implements SmartMIPS ASE */
1396 #define MIPS_CPU_ASE_DSP        0x0004  /* CPU implements DSP ASE */
1397 #define MIPS_CPU_ASE_MT         0x0008  /* CPU implements MT ASE */
1398 #define MIPS_CPU_ASE_MIPS3D     0x0010  /* CPU implements MIPS-3D ASE */
1399 #define MIPS_CPU_ASE_MDMX       0x0020  /* CPU implements MDMX ASE */
1400 #define MIPS_CPU_ASE_DSPR2      0x0040  /* CPU implements DSP R2 ASE */
1401 #define MIPS_CPU_ASE_MCU        0x0080  /* CPU implements MCU ASE */
1402
1403 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1404 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1405 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1406 \f
1407 /* Pseudo-op table.
1408
1409    The following pseudo-ops from the Kane and Heinrich MIPS book
1410    should be defined here, but are currently unsupported: .alias,
1411    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1412
1413    The following pseudo-ops from the Kane and Heinrich MIPS book are
1414    specific to the type of debugging information being generated, and
1415    should be defined by the object format: .aent, .begin, .bend,
1416    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1417    .vreg.
1418
1419    The following pseudo-ops from the Kane and Heinrich MIPS book are
1420    not MIPS CPU specific, but are also not specific to the object file
1421    format.  This file is probably the best place to define them, but
1422    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1423
1424 static const pseudo_typeS mips_pseudo_table[] =
1425 {
1426   /* MIPS specific pseudo-ops.  */
1427   {"option", s_option, 0},
1428   {"set", s_mipsset, 0},
1429   {"rdata", s_change_sec, 'r'},
1430   {"sdata", s_change_sec, 's'},
1431   {"livereg", s_ignore, 0},
1432   {"abicalls", s_abicalls, 0},
1433   {"cpload", s_cpload, 0},
1434   {"cpsetup", s_cpsetup, 0},
1435   {"cplocal", s_cplocal, 0},
1436   {"cprestore", s_cprestore, 0},
1437   {"cpreturn", s_cpreturn, 0},
1438   {"dtprelword", s_dtprelword, 0},
1439   {"dtpreldword", s_dtpreldword, 0},
1440   {"tprelword", s_tprelword, 0},
1441   {"tpreldword", s_tpreldword, 0},
1442   {"gpvalue", s_gpvalue, 0},
1443   {"gpword", s_gpword, 0},
1444   {"gpdword", s_gpdword, 0},
1445   {"cpadd", s_cpadd, 0},
1446   {"insn", s_insn, 0},
1447
1448   /* Relatively generic pseudo-ops that happen to be used on MIPS
1449      chips.  */
1450   {"asciiz", stringer, 8 + 1},
1451   {"bss", s_change_sec, 'b'},
1452   {"err", s_err, 0},
1453   {"half", s_cons, 1},
1454   {"dword", s_cons, 3},
1455   {"weakext", s_mips_weakext, 0},
1456   {"origin", s_org, 0},
1457   {"repeat", s_rept, 0},
1458
1459   /* For MIPS this is non-standard, but we define it for consistency.  */
1460   {"sbss", s_change_sec, 'B'},
1461
1462   /* These pseudo-ops are defined in read.c, but must be overridden
1463      here for one reason or another.  */
1464   {"align", s_align, 0},
1465   {"byte", s_cons, 0},
1466   {"data", s_change_sec, 'd'},
1467   {"double", s_float_cons, 'd'},
1468   {"float", s_float_cons, 'f'},
1469   {"globl", s_mips_globl, 0},
1470   {"global", s_mips_globl, 0},
1471   {"hword", s_cons, 1},
1472   {"int", s_cons, 2},
1473   {"long", s_cons, 2},
1474   {"octa", s_cons, 4},
1475   {"quad", s_cons, 3},
1476   {"section", s_change_section, 0},
1477   {"short", s_cons, 1},
1478   {"single", s_float_cons, 'f'},
1479   {"stabn", s_mips_stab, 'n'},
1480   {"text", s_change_sec, 't'},
1481   {"word", s_cons, 2},
1482
1483   { "extern", ecoff_directive_extern, 0},
1484
1485   { NULL, NULL, 0 },
1486 };
1487
1488 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1489 {
1490   /* These pseudo-ops should be defined by the object file format.
1491      However, a.out doesn't support them, so we have versions here.  */
1492   {"aent", s_mips_ent, 1},
1493   {"bgnb", s_ignore, 0},
1494   {"end", s_mips_end, 0},
1495   {"endb", s_ignore, 0},
1496   {"ent", s_mips_ent, 0},
1497   {"file", s_mips_file, 0},
1498   {"fmask", s_mips_mask, 'F'},
1499   {"frame", s_mips_frame, 0},
1500   {"loc", s_mips_loc, 0},
1501   {"mask", s_mips_mask, 'R'},
1502   {"verstamp", s_ignore, 0},
1503   { NULL, NULL, 0 },
1504 };
1505
1506 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1507    purpose of the `.dc.a' internal pseudo-op.  */
1508
1509 int
1510 mips_address_bytes (void)
1511 {
1512   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1513 }
1514
1515 extern void pop_insert (const pseudo_typeS *);
1516
1517 void
1518 mips_pop_insert (void)
1519 {
1520   pop_insert (mips_pseudo_table);
1521   if (! ECOFF_DEBUGGING)
1522     pop_insert (mips_nonecoff_pseudo_table);
1523 }
1524 \f
1525 /* Symbols labelling the current insn.  */
1526
1527 struct insn_label_list
1528 {
1529   struct insn_label_list *next;
1530   symbolS *label;
1531 };
1532
1533 static struct insn_label_list *free_insn_labels;
1534 #define label_list tc_segment_info_data.labels
1535
1536 static void mips_clear_insn_labels (void);
1537 static void mips_mark_labels (void);
1538 static void mips_compressed_mark_labels (void);
1539
1540 static inline void
1541 mips_clear_insn_labels (void)
1542 {
1543   register struct insn_label_list **pl;
1544   segment_info_type *si;
1545
1546   if (now_seg)
1547     {
1548       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1549         ;
1550       
1551       si = seg_info (now_seg);
1552       *pl = si->label_list;
1553       si->label_list = NULL;
1554     }
1555 }
1556
1557 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1558
1559 static inline void
1560 mips_mark_labels (void)
1561 {
1562   if (HAVE_CODE_COMPRESSION)
1563     mips_compressed_mark_labels ();
1564 }
1565 \f
1566 static char *expr_end;
1567
1568 /* Expressions which appear in instructions.  These are set by
1569    mips_ip.  */
1570
1571 static expressionS imm_expr;
1572 static expressionS imm2_expr;
1573 static expressionS offset_expr;
1574
1575 /* Relocs associated with imm_expr and offset_expr.  */
1576
1577 static bfd_reloc_code_real_type imm_reloc[3]
1578   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1579 static bfd_reloc_code_real_type offset_reloc[3]
1580   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1581
1582 /* This is set to the resulting size of the instruction to be produced
1583    by mips16_ip if an explicit extension is used or by mips_ip if an
1584    explicit size is supplied.  */
1585
1586 static unsigned int forced_insn_length;
1587
1588 #ifdef OBJ_ELF
1589 /* The pdr segment for per procedure frame/regmask info.  Not used for
1590    ECOFF debugging.  */
1591
1592 static segT pdr_seg;
1593 #endif
1594
1595 /* The default target format to use.  */
1596
1597 #if defined (TE_FreeBSD)
1598 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1599 #elif defined (TE_TMIPS)
1600 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1601 #else
1602 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1603 #endif
1604
1605 const char *
1606 mips_target_format (void)
1607 {
1608   switch (OUTPUT_FLAVOR)
1609     {
1610     case bfd_target_ecoff_flavour:
1611       return target_big_endian ? "ecoff-bigmips" : ECOFF_LITTLE_FORMAT;
1612     case bfd_target_coff_flavour:
1613       return "pe-mips";
1614     case bfd_target_elf_flavour:
1615 #ifdef TE_VXWORKS
1616       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1617         return (target_big_endian
1618                 ? "elf32-bigmips-vxworks"
1619                 : "elf32-littlemips-vxworks");
1620 #endif
1621       return (target_big_endian
1622               ? (HAVE_64BIT_OBJECTS
1623                  ? ELF_TARGET ("elf64-", "big")
1624                  : (HAVE_NEWABI
1625                     ? ELF_TARGET ("elf32-n", "big")
1626                     : ELF_TARGET ("elf32-", "big")))
1627               : (HAVE_64BIT_OBJECTS
1628                  ? ELF_TARGET ("elf64-", "little")
1629                  : (HAVE_NEWABI
1630                     ? ELF_TARGET ("elf32-n", "little")
1631                     : ELF_TARGET ("elf32-", "little"))));
1632     default:
1633       abort ();
1634       return NULL;
1635     }
1636 }
1637
1638 /* Return the length of a microMIPS instruction in bytes.  If bits of
1639    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1640    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1641    major opcode) will require further modifications to the opcode
1642    table.  */
1643
1644 static inline unsigned int
1645 micromips_insn_length (const struct mips_opcode *mo)
1646 {
1647   return (mo->mask >> 16) == 0 ? 2 : 4;
1648 }
1649
1650 /* Return the length of instruction INSN.  */
1651
1652 static inline unsigned int
1653 insn_length (const struct mips_cl_insn *insn)
1654 {
1655   if (mips_opts.micromips)
1656     return micromips_insn_length (insn->insn_mo);
1657   else if (mips_opts.mips16)
1658     return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1659   else
1660     return 4;
1661 }
1662
1663 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1664
1665 static void
1666 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1667 {
1668   size_t i;
1669
1670   insn->insn_mo = mo;
1671   insn->use_extend = FALSE;
1672   insn->extend = 0;
1673   insn->insn_opcode = mo->match;
1674   insn->frag = NULL;
1675   insn->where = 0;
1676   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1677     insn->fixp[i] = NULL;
1678   insn->fixed_p = (mips_opts.noreorder > 0);
1679   insn->noreorder_p = (mips_opts.noreorder > 0);
1680   insn->mips16_absolute_jump_p = 0;
1681   insn->complete_p = 0;
1682 }
1683
1684 /* Record the current MIPS16/microMIPS mode in now_seg.  */
1685
1686 static void
1687 mips_record_compressed_mode (void)
1688 {
1689   segment_info_type *si;
1690
1691   si = seg_info (now_seg);
1692   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
1693     si->tc_segment_info_data.mips16 = mips_opts.mips16;
1694   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
1695     si->tc_segment_info_data.micromips = mips_opts.micromips;
1696 }
1697
1698 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1699
1700 static void
1701 install_insn (const struct mips_cl_insn *insn)
1702 {
1703   char *f = insn->frag->fr_literal + insn->where;
1704   if (!HAVE_CODE_COMPRESSION)
1705     md_number_to_chars (f, insn->insn_opcode, 4);
1706   else if (mips_opts.micromips)
1707     {
1708       unsigned int length = insn_length (insn);
1709       if (length == 2)
1710         md_number_to_chars (f, insn->insn_opcode, 2);
1711       else if (length == 4)
1712         {
1713           md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1714           f += 2;
1715           md_number_to_chars (f, insn->insn_opcode & 0xffff, 2);
1716         }
1717       else
1718         as_bad (_("48-bit microMIPS instructions are not supported"));
1719     }
1720   else if (insn->mips16_absolute_jump_p)
1721     {
1722       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1723       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1724     }
1725   else
1726     {
1727       if (insn->use_extend)
1728         {
1729           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1730           f += 2;
1731         }
1732       md_number_to_chars (f, insn->insn_opcode, 2);
1733     }
1734   mips_record_compressed_mode ();
1735 }
1736
1737 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1738    and install the opcode in the new location.  */
1739
1740 static void
1741 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1742 {
1743   size_t i;
1744
1745   insn->frag = frag;
1746   insn->where = where;
1747   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1748     if (insn->fixp[i] != NULL)
1749       {
1750         insn->fixp[i]->fx_frag = frag;
1751         insn->fixp[i]->fx_where = where;
1752       }
1753   install_insn (insn);
1754 }
1755
1756 /* Add INSN to the end of the output.  */
1757
1758 static void
1759 add_fixed_insn (struct mips_cl_insn *insn)
1760 {
1761   char *f = frag_more (insn_length (insn));
1762   move_insn (insn, frag_now, f - frag_now->fr_literal);
1763 }
1764
1765 /* Start a variant frag and move INSN to the start of the variant part,
1766    marking it as fixed.  The other arguments are as for frag_var.  */
1767
1768 static void
1769 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1770                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1771 {
1772   frag_grow (max_chars);
1773   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1774   insn->fixed_p = 1;
1775   frag_var (rs_machine_dependent, max_chars, var,
1776             subtype, symbol, offset, NULL);
1777 }
1778
1779 /* Insert N copies of INSN into the history buffer, starting at
1780    position FIRST.  Neither FIRST nor N need to be clipped.  */
1781
1782 static void
1783 insert_into_history (unsigned int first, unsigned int n,
1784                      const struct mips_cl_insn *insn)
1785 {
1786   if (mips_relax.sequence != 2)
1787     {
1788       unsigned int i;
1789
1790       for (i = ARRAY_SIZE (history); i-- > first;)
1791         if (i >= first + n)
1792           history[i] = history[i - n];
1793         else
1794           history[i] = *insn;
1795     }
1796 }
1797
1798 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1799    the idea is to make it obvious at a glance that each errata is
1800    included.  */
1801
1802 static void
1803 init_vr4120_conflicts (void)
1804 {
1805 #define CONFLICT(FIRST, SECOND) \
1806     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1807
1808   /* Errata 21 - [D]DIV[U] after [D]MACC */
1809   CONFLICT (MACC, DIV);
1810   CONFLICT (DMACC, DIV);
1811
1812   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1813   CONFLICT (DMULT, DMULT);
1814   CONFLICT (DMULT, DMACC);
1815   CONFLICT (DMACC, DMULT);
1816   CONFLICT (DMACC, DMACC);
1817
1818   /* Errata 24 - MT{LO,HI} after [D]MACC */
1819   CONFLICT (MACC, MTHILO);
1820   CONFLICT (DMACC, MTHILO);
1821
1822   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1823      instruction is executed immediately after a MACC or DMACC
1824      instruction, the result of [either instruction] is incorrect."  */
1825   CONFLICT (MACC, MULT);
1826   CONFLICT (MACC, DMULT);
1827   CONFLICT (DMACC, MULT);
1828   CONFLICT (DMACC, DMULT);
1829
1830   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1831      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1832      DDIV or DDIVU instruction, the result of the MACC or
1833      DMACC instruction is incorrect.".  */
1834   CONFLICT (DMULT, MACC);
1835   CONFLICT (DMULT, DMACC);
1836   CONFLICT (DIV, MACC);
1837   CONFLICT (DIV, DMACC);
1838
1839 #undef CONFLICT
1840 }
1841
1842 struct regname {
1843   const char *name;
1844   unsigned int num;
1845 };
1846
1847 #define RTYPE_MASK      0x1ff00
1848 #define RTYPE_NUM       0x00100
1849 #define RTYPE_FPU       0x00200
1850 #define RTYPE_FCC       0x00400
1851 #define RTYPE_VEC       0x00800
1852 #define RTYPE_GP        0x01000
1853 #define RTYPE_CP0       0x02000
1854 #define RTYPE_PC        0x04000
1855 #define RTYPE_ACC       0x08000
1856 #define RTYPE_CCC       0x10000
1857 #define RNUM_MASK       0x000ff
1858 #define RWARN           0x80000
1859
1860 #define GENERIC_REGISTER_NUMBERS \
1861     {"$0",      RTYPE_NUM | 0},  \
1862     {"$1",      RTYPE_NUM | 1},  \
1863     {"$2",      RTYPE_NUM | 2},  \
1864     {"$3",      RTYPE_NUM | 3},  \
1865     {"$4",      RTYPE_NUM | 4},  \
1866     {"$5",      RTYPE_NUM | 5},  \
1867     {"$6",      RTYPE_NUM | 6},  \
1868     {"$7",      RTYPE_NUM | 7},  \
1869     {"$8",      RTYPE_NUM | 8},  \
1870     {"$9",      RTYPE_NUM | 9},  \
1871     {"$10",     RTYPE_NUM | 10}, \
1872     {"$11",     RTYPE_NUM | 11}, \
1873     {"$12",     RTYPE_NUM | 12}, \
1874     {"$13",     RTYPE_NUM | 13}, \
1875     {"$14",     RTYPE_NUM | 14}, \
1876     {"$15",     RTYPE_NUM | 15}, \
1877     {"$16",     RTYPE_NUM | 16}, \
1878     {"$17",     RTYPE_NUM | 17}, \
1879     {"$18",     RTYPE_NUM | 18}, \
1880     {"$19",     RTYPE_NUM | 19}, \
1881     {"$20",     RTYPE_NUM | 20}, \
1882     {"$21",     RTYPE_NUM | 21}, \
1883     {"$22",     RTYPE_NUM | 22}, \
1884     {"$23",     RTYPE_NUM | 23}, \
1885     {"$24",     RTYPE_NUM | 24}, \
1886     {"$25",     RTYPE_NUM | 25}, \
1887     {"$26",     RTYPE_NUM | 26}, \
1888     {"$27",     RTYPE_NUM | 27}, \
1889     {"$28",     RTYPE_NUM | 28}, \
1890     {"$29",     RTYPE_NUM | 29}, \
1891     {"$30",     RTYPE_NUM | 30}, \
1892     {"$31",     RTYPE_NUM | 31} 
1893
1894 #define FPU_REGISTER_NAMES       \
1895     {"$f0",     RTYPE_FPU | 0},  \
1896     {"$f1",     RTYPE_FPU | 1},  \
1897     {"$f2",     RTYPE_FPU | 2},  \
1898     {"$f3",     RTYPE_FPU | 3},  \
1899     {"$f4",     RTYPE_FPU | 4},  \
1900     {"$f5",     RTYPE_FPU | 5},  \
1901     {"$f6",     RTYPE_FPU | 6},  \
1902     {"$f7",     RTYPE_FPU | 7},  \
1903     {"$f8",     RTYPE_FPU | 8},  \
1904     {"$f9",     RTYPE_FPU | 9},  \
1905     {"$f10",    RTYPE_FPU | 10}, \
1906     {"$f11",    RTYPE_FPU | 11}, \
1907     {"$f12",    RTYPE_FPU | 12}, \
1908     {"$f13",    RTYPE_FPU | 13}, \
1909     {"$f14",    RTYPE_FPU | 14}, \
1910     {"$f15",    RTYPE_FPU | 15}, \
1911     {"$f16",    RTYPE_FPU | 16}, \
1912     {"$f17",    RTYPE_FPU | 17}, \
1913     {"$f18",    RTYPE_FPU | 18}, \
1914     {"$f19",    RTYPE_FPU | 19}, \
1915     {"$f20",    RTYPE_FPU | 20}, \
1916     {"$f21",    RTYPE_FPU | 21}, \
1917     {"$f22",    RTYPE_FPU | 22}, \
1918     {"$f23",    RTYPE_FPU | 23}, \
1919     {"$f24",    RTYPE_FPU | 24}, \
1920     {"$f25",    RTYPE_FPU | 25}, \
1921     {"$f26",    RTYPE_FPU | 26}, \
1922     {"$f27",    RTYPE_FPU | 27}, \
1923     {"$f28",    RTYPE_FPU | 28}, \
1924     {"$f29",    RTYPE_FPU | 29}, \
1925     {"$f30",    RTYPE_FPU | 30}, \
1926     {"$f31",    RTYPE_FPU | 31}
1927
1928 #define FPU_CONDITION_CODE_NAMES \
1929     {"$fcc0",   RTYPE_FCC | 0},  \
1930     {"$fcc1",   RTYPE_FCC | 1},  \
1931     {"$fcc2",   RTYPE_FCC | 2},  \
1932     {"$fcc3",   RTYPE_FCC | 3},  \
1933     {"$fcc4",   RTYPE_FCC | 4},  \
1934     {"$fcc5",   RTYPE_FCC | 5},  \
1935     {"$fcc6",   RTYPE_FCC | 6},  \
1936     {"$fcc7",   RTYPE_FCC | 7}
1937
1938 #define COPROC_CONDITION_CODE_NAMES         \
1939     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
1940     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
1941     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
1942     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
1943     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
1944     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
1945     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
1946     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
1947
1948 #define N32N64_SYMBOLIC_REGISTER_NAMES \
1949     {"$a4",     RTYPE_GP | 8},  \
1950     {"$a5",     RTYPE_GP | 9},  \
1951     {"$a6",     RTYPE_GP | 10}, \
1952     {"$a7",     RTYPE_GP | 11}, \
1953     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
1954     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
1955     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
1956     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
1957     {"$t0",     RTYPE_GP | 12}, \
1958     {"$t1",     RTYPE_GP | 13}, \
1959     {"$t2",     RTYPE_GP | 14}, \
1960     {"$t3",     RTYPE_GP | 15}
1961
1962 #define O32_SYMBOLIC_REGISTER_NAMES \
1963     {"$t0",     RTYPE_GP | 8},  \
1964     {"$t1",     RTYPE_GP | 9},  \
1965     {"$t2",     RTYPE_GP | 10}, \
1966     {"$t3",     RTYPE_GP | 11}, \
1967     {"$t4",     RTYPE_GP | 12}, \
1968     {"$t5",     RTYPE_GP | 13}, \
1969     {"$t6",     RTYPE_GP | 14}, \
1970     {"$t7",     RTYPE_GP | 15}, \
1971     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
1972     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
1973     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
1974     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
1975
1976 /* Remaining symbolic register names */
1977 #define SYMBOLIC_REGISTER_NAMES \
1978     {"$zero",   RTYPE_GP | 0},  \
1979     {"$at",     RTYPE_GP | 1},  \
1980     {"$AT",     RTYPE_GP | 1},  \
1981     {"$v0",     RTYPE_GP | 2},  \
1982     {"$v1",     RTYPE_GP | 3},  \
1983     {"$a0",     RTYPE_GP | 4},  \
1984     {"$a1",     RTYPE_GP | 5},  \
1985     {"$a2",     RTYPE_GP | 6},  \
1986     {"$a3",     RTYPE_GP | 7},  \
1987     {"$s0",     RTYPE_GP | 16}, \
1988     {"$s1",     RTYPE_GP | 17}, \
1989     {"$s2",     RTYPE_GP | 18}, \
1990     {"$s3",     RTYPE_GP | 19}, \
1991     {"$s4",     RTYPE_GP | 20}, \
1992     {"$s5",     RTYPE_GP | 21}, \
1993     {"$s6",     RTYPE_GP | 22}, \
1994     {"$s7",     RTYPE_GP | 23}, \
1995     {"$t8",     RTYPE_GP | 24}, \
1996     {"$t9",     RTYPE_GP | 25}, \
1997     {"$k0",     RTYPE_GP | 26}, \
1998     {"$kt0",    RTYPE_GP | 26}, \
1999     {"$k1",     RTYPE_GP | 27}, \
2000     {"$kt1",    RTYPE_GP | 27}, \
2001     {"$gp",     RTYPE_GP | 28}, \
2002     {"$sp",     RTYPE_GP | 29}, \
2003     {"$s8",     RTYPE_GP | 30}, \
2004     {"$fp",     RTYPE_GP | 30}, \
2005     {"$ra",     RTYPE_GP | 31}
2006
2007 #define MIPS16_SPECIAL_REGISTER_NAMES \
2008     {"$pc",     RTYPE_PC | 0}
2009
2010 #define MDMX_VECTOR_REGISTER_NAMES \
2011     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2012     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2013     {"$v2",     RTYPE_VEC | 2},  \
2014     {"$v3",     RTYPE_VEC | 3},  \
2015     {"$v4",     RTYPE_VEC | 4},  \
2016     {"$v5",     RTYPE_VEC | 5},  \
2017     {"$v6",     RTYPE_VEC | 6},  \
2018     {"$v7",     RTYPE_VEC | 7},  \
2019     {"$v8",     RTYPE_VEC | 8},  \
2020     {"$v9",     RTYPE_VEC | 9},  \
2021     {"$v10",    RTYPE_VEC | 10}, \
2022     {"$v11",    RTYPE_VEC | 11}, \
2023     {"$v12",    RTYPE_VEC | 12}, \
2024     {"$v13",    RTYPE_VEC | 13}, \
2025     {"$v14",    RTYPE_VEC | 14}, \
2026     {"$v15",    RTYPE_VEC | 15}, \
2027     {"$v16",    RTYPE_VEC | 16}, \
2028     {"$v17",    RTYPE_VEC | 17}, \
2029     {"$v18",    RTYPE_VEC | 18}, \
2030     {"$v19",    RTYPE_VEC | 19}, \
2031     {"$v20",    RTYPE_VEC | 20}, \
2032     {"$v21",    RTYPE_VEC | 21}, \
2033     {"$v22",    RTYPE_VEC | 22}, \
2034     {"$v23",    RTYPE_VEC | 23}, \
2035     {"$v24",    RTYPE_VEC | 24}, \
2036     {"$v25",    RTYPE_VEC | 25}, \
2037     {"$v26",    RTYPE_VEC | 26}, \
2038     {"$v27",    RTYPE_VEC | 27}, \
2039     {"$v28",    RTYPE_VEC | 28}, \
2040     {"$v29",    RTYPE_VEC | 29}, \
2041     {"$v30",    RTYPE_VEC | 30}, \
2042     {"$v31",    RTYPE_VEC | 31}
2043
2044 #define MIPS_DSP_ACCUMULATOR_NAMES \
2045     {"$ac0",    RTYPE_ACC | 0}, \
2046     {"$ac1",    RTYPE_ACC | 1}, \
2047     {"$ac2",    RTYPE_ACC | 2}, \
2048     {"$ac3",    RTYPE_ACC | 3}
2049
2050 static const struct regname reg_names[] = {
2051   GENERIC_REGISTER_NUMBERS,
2052   FPU_REGISTER_NAMES,
2053   FPU_CONDITION_CODE_NAMES,
2054   COPROC_CONDITION_CODE_NAMES,
2055
2056   /* The $txx registers depends on the abi,
2057      these will be added later into the symbol table from
2058      one of the tables below once mips_abi is set after 
2059      parsing of arguments from the command line. */
2060   SYMBOLIC_REGISTER_NAMES,
2061
2062   MIPS16_SPECIAL_REGISTER_NAMES,
2063   MDMX_VECTOR_REGISTER_NAMES,
2064   MIPS_DSP_ACCUMULATOR_NAMES,
2065   {0, 0}
2066 };
2067
2068 static const struct regname reg_names_o32[] = {
2069   O32_SYMBOLIC_REGISTER_NAMES,
2070   {0, 0}
2071 };
2072
2073 static const struct regname reg_names_n32n64[] = {
2074   N32N64_SYMBOLIC_REGISTER_NAMES,
2075   {0, 0}
2076 };
2077
2078 /* Check if S points at a valid register specifier according to TYPES.
2079    If so, then return 1, advance S to consume the specifier and store
2080    the register's number in REGNOP, otherwise return 0.  */
2081
2082 static int
2083 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2084 {
2085   symbolS *symbolP;
2086   char *e;
2087   char save_c;
2088   int reg = -1;
2089
2090   /* Find end of name.  */
2091   e = *s;
2092   if (is_name_beginner (*e))
2093     ++e;
2094   while (is_part_of_name (*e))
2095     ++e;
2096
2097   /* Terminate name.  */
2098   save_c = *e;
2099   *e = '\0';
2100
2101   /* Look for a register symbol.  */
2102   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2103     {
2104       int r = S_GET_VALUE (symbolP);
2105       if (r & types)
2106         reg = r & RNUM_MASK;
2107       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2108         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2109         reg = (r & RNUM_MASK) - 2;
2110     }
2111   /* Else see if this is a register defined in an itbl entry.  */
2112   else if ((types & RTYPE_GP) && itbl_have_entries)
2113     {
2114       char *n = *s;
2115       unsigned long r;
2116
2117       if (*n == '$')
2118         ++n;
2119       if (itbl_get_reg_val (n, &r))
2120         reg = r & RNUM_MASK;
2121     }
2122
2123   /* Advance to next token if a register was recognised.  */
2124   if (reg >= 0)
2125     *s = e;
2126   else if (types & RWARN)
2127     as_warn (_("Unrecognized register name `%s'"), *s);
2128
2129   *e = save_c;
2130   if (regnop)
2131     *regnop = reg;
2132   return reg >= 0;
2133 }
2134
2135 /* Check if S points at a valid register list according to TYPES.
2136    If so, then return 1, advance S to consume the list and store
2137    the registers present on the list as a bitmask of ones in REGLISTP,
2138    otherwise return 0.  A valid list comprises a comma-separated
2139    enumeration of valid single registers and/or dash-separated
2140    contiguous register ranges as determined by their numbers.
2141
2142    As a special exception if one of s0-s7 registers is specified as
2143    the range's lower delimiter and s8 (fp) is its upper one, then no
2144    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2145    are selected; they have to be listed separately if needed.  */
2146
2147 static int
2148 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2149 {
2150   unsigned int reglist = 0;
2151   unsigned int lastregno;
2152   bfd_boolean ok = TRUE;
2153   unsigned int regmask;
2154   char *s_endlist = *s;
2155   char *s_reset = *s;
2156   unsigned int regno;
2157
2158   while (reg_lookup (s, types, &regno))
2159     {
2160       lastregno = regno;
2161       if (**s == '-')
2162         {
2163           (*s)++;
2164           ok = reg_lookup (s, types, &lastregno);
2165           if (ok && lastregno < regno)
2166             ok = FALSE;
2167           if (!ok)
2168             break;
2169         }
2170
2171       if (lastregno == FP && regno >= S0 && regno <= S7)
2172         {
2173           lastregno = S7;
2174           reglist |= 1 << FP;
2175         }
2176       regmask = 1 << lastregno;
2177       regmask = (regmask << 1) - 1;
2178       regmask ^= (1 << regno) - 1;
2179       reglist |= regmask;
2180
2181       s_endlist = *s;
2182       if (**s != ',')
2183         break;
2184       (*s)++;
2185     }
2186
2187   if (ok)
2188     *s = s_endlist;
2189   else
2190     *s = s_reset;
2191   if (reglistp)
2192     *reglistp = reglist;
2193   return ok && reglist != 0;
2194 }
2195
2196 /* Return TRUE if opcode MO is valid on the currently selected ISA and
2197    architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2198
2199 static bfd_boolean
2200 is_opcode_valid (const struct mips_opcode *mo)
2201 {
2202   int isa = mips_opts.isa;
2203   int fp_s, fp_d;
2204
2205   if (mips_opts.ase_mdmx)
2206     isa |= INSN_MDMX;
2207   if (mips_opts.ase_dsp)
2208     isa |= INSN_DSP;
2209   if (mips_opts.ase_dsp && ISA_SUPPORTS_DSP64_ASE)
2210     isa |= INSN_DSP64;
2211   if (mips_opts.ase_dspr2)
2212     isa |= INSN_DSPR2;
2213   if (mips_opts.ase_mt)
2214     isa |= INSN_MT;
2215   if (mips_opts.ase_mips3d)
2216     isa |= INSN_MIPS3D;
2217   if (mips_opts.ase_smartmips)
2218     isa |= INSN_SMARTMIPS;
2219   if (mips_opts.ase_mcu)
2220     isa |= INSN_MCU;
2221
2222   /* Don't accept instructions based on the ISA if the CPU does not implement
2223      all the coprocessor insns. */
2224   if (NO_ISA_COP (mips_opts.arch)
2225       && COP_INSN (mo->pinfo))
2226     isa = 0;
2227
2228   if (!OPCODE_IS_MEMBER (mo, isa, mips_opts.arch))
2229     return FALSE;
2230
2231   /* Check whether the instruction or macro requires single-precision or
2232      double-precision floating-point support.  Note that this information is
2233      stored differently in the opcode table for insns and macros.  */
2234   if (mo->pinfo == INSN_MACRO)
2235     {
2236       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2237       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2238     }
2239   else
2240     {
2241       fp_s = mo->pinfo & FP_S;
2242       fp_d = mo->pinfo & FP_D;
2243     }
2244
2245   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2246     return FALSE;
2247
2248   if (fp_s && mips_opts.soft_float)
2249     return FALSE;
2250
2251   return TRUE;
2252 }
2253
2254 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2255    selected ISA and architecture.  */
2256
2257 static bfd_boolean
2258 is_opcode_valid_16 (const struct mips_opcode *mo)
2259 {
2260   return OPCODE_IS_MEMBER (mo, mips_opts.isa, mips_opts.arch) ? TRUE : FALSE;
2261 }
2262
2263 /* Return TRUE if the size of the microMIPS opcode MO matches one
2264    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2265
2266 static bfd_boolean
2267 is_size_valid (const struct mips_opcode *mo)
2268 {
2269   if (!mips_opts.micromips)
2270     return TRUE;
2271
2272   if (!forced_insn_length)
2273     return TRUE;
2274   if (mo->pinfo == INSN_MACRO)
2275     return FALSE;
2276   return forced_insn_length == micromips_insn_length (mo);
2277 }
2278
2279 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2280    of the preceding instruction.  Always TRUE in the standard MIPS mode.  */
2281
2282 static bfd_boolean
2283 is_delay_slot_valid (const struct mips_opcode *mo)
2284 {
2285   if (!mips_opts.micromips)
2286     return TRUE;
2287
2288   if (mo->pinfo == INSN_MACRO)
2289     return TRUE;
2290   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2291       && micromips_insn_length (mo) != 4)
2292     return FALSE;
2293   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2294       && micromips_insn_length (mo) != 2)
2295     return FALSE;
2296
2297   return TRUE;
2298 }
2299
2300 /* This function is called once, at assembler startup time.  It should set up
2301    all the tables, etc. that the MD part of the assembler will need.  */
2302
2303 void
2304 md_begin (void)
2305 {
2306   const char *retval = NULL;
2307   int i = 0;
2308   int broken = 0;
2309
2310   if (mips_pic != NO_PIC)
2311     {
2312       if (g_switch_seen && g_switch_value != 0)
2313         as_bad (_("-G may not be used in position-independent code"));
2314       g_switch_value = 0;
2315     }
2316
2317   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2318     as_warn (_("Could not set architecture and machine"));
2319
2320   op_hash = hash_new ();
2321
2322   for (i = 0; i < NUMOPCODES;)
2323     {
2324       const char *name = mips_opcodes[i].name;
2325
2326       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2327       if (retval != NULL)
2328         {
2329           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2330                    mips_opcodes[i].name, retval);
2331           /* Probably a memory allocation problem?  Give up now.  */
2332           as_fatal (_("Broken assembler.  No assembly attempted."));
2333         }
2334       do
2335         {
2336           if (mips_opcodes[i].pinfo != INSN_MACRO)
2337             {
2338               if (!validate_mips_insn (&mips_opcodes[i]))
2339                 broken = 1;
2340               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2341                 {
2342                   create_insn (&nop_insn, mips_opcodes + i);
2343                   if (mips_fix_loongson2f_nop)
2344                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2345                   nop_insn.fixed_p = 1;
2346                 }
2347             }
2348           ++i;
2349         }
2350       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2351     }
2352
2353   mips16_op_hash = hash_new ();
2354
2355   i = 0;
2356   while (i < bfd_mips16_num_opcodes)
2357     {
2358       const char *name = mips16_opcodes[i].name;
2359
2360       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2361       if (retval != NULL)
2362         as_fatal (_("internal: can't hash `%s': %s"),
2363                   mips16_opcodes[i].name, retval);
2364       do
2365         {
2366           if (mips16_opcodes[i].pinfo != INSN_MACRO
2367               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2368                   != mips16_opcodes[i].match))
2369             {
2370               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2371                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2372               broken = 1;
2373             }
2374           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2375             {
2376               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2377               mips16_nop_insn.fixed_p = 1;
2378             }
2379           ++i;
2380         }
2381       while (i < bfd_mips16_num_opcodes
2382              && strcmp (mips16_opcodes[i].name, name) == 0);
2383     }
2384
2385   micromips_op_hash = hash_new ();
2386
2387   i = 0;
2388   while (i < bfd_micromips_num_opcodes)
2389     {
2390       const char *name = micromips_opcodes[i].name;
2391
2392       retval = hash_insert (micromips_op_hash, name,
2393                             (void *) &micromips_opcodes[i]);
2394       if (retval != NULL)
2395         as_fatal (_("internal: can't hash `%s': %s"),
2396                   micromips_opcodes[i].name, retval);
2397       do
2398         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2399           {
2400             struct mips_cl_insn *micromips_nop_insn;
2401
2402             if (!validate_micromips_insn (&micromips_opcodes[i]))
2403               broken = 1;
2404
2405             if (micromips_insn_length (micromips_opcodes + i) == 2)
2406               micromips_nop_insn = &micromips_nop16_insn;
2407             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2408               micromips_nop_insn = &micromips_nop32_insn;
2409             else
2410               continue;
2411
2412             if (micromips_nop_insn->insn_mo == NULL
2413                 && strcmp (name, "nop") == 0)
2414               {
2415                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2416                 micromips_nop_insn->fixed_p = 1;
2417               }
2418           }
2419       while (++i < bfd_micromips_num_opcodes
2420              && strcmp (micromips_opcodes[i].name, name) == 0);
2421     }
2422
2423   if (broken)
2424     as_fatal (_("Broken assembler.  No assembly attempted."));
2425
2426   /* We add all the general register names to the symbol table.  This
2427      helps us detect invalid uses of them.  */
2428   for (i = 0; reg_names[i].name; i++) 
2429     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2430                                      reg_names[i].num, /* & RNUM_MASK, */
2431                                      &zero_address_frag));
2432   if (HAVE_NEWABI)
2433     for (i = 0; reg_names_n32n64[i].name; i++) 
2434       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2435                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2436                                        &zero_address_frag));
2437   else
2438     for (i = 0; reg_names_o32[i].name; i++) 
2439       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2440                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2441                                        &zero_address_frag));
2442
2443   mips_no_prev_insn ();
2444
2445   mips_gprmask = 0;
2446   mips_cprmask[0] = 0;
2447   mips_cprmask[1] = 0;
2448   mips_cprmask[2] = 0;
2449   mips_cprmask[3] = 0;
2450
2451   /* set the default alignment for the text section (2**2) */
2452   record_alignment (text_section, 2);
2453
2454   bfd_set_gp_size (stdoutput, g_switch_value);
2455
2456 #ifdef OBJ_ELF
2457   if (IS_ELF)
2458     {
2459       /* On a native system other than VxWorks, sections must be aligned
2460          to 16 byte boundaries.  When configured for an embedded ELF
2461          target, we don't bother.  */
2462       if (strncmp (TARGET_OS, "elf", 3) != 0
2463           && strncmp (TARGET_OS, "vxworks", 7) != 0)
2464         {
2465           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2466           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2467           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2468         }
2469
2470       /* Create a .reginfo section for register masks and a .mdebug
2471          section for debugging information.  */
2472       {
2473         segT seg;
2474         subsegT subseg;
2475         flagword flags;
2476         segT sec;
2477
2478         seg = now_seg;
2479         subseg = now_subseg;
2480
2481         /* The ABI says this section should be loaded so that the
2482            running program can access it.  However, we don't load it
2483            if we are configured for an embedded target */
2484         flags = SEC_READONLY | SEC_DATA;
2485         if (strncmp (TARGET_OS, "elf", 3) != 0)
2486           flags |= SEC_ALLOC | SEC_LOAD;
2487
2488         if (mips_abi != N64_ABI)
2489           {
2490             sec = subseg_new (".reginfo", (subsegT) 0);
2491
2492             bfd_set_section_flags (stdoutput, sec, flags);
2493             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2494
2495             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2496           }
2497         else
2498           {
2499             /* The 64-bit ABI uses a .MIPS.options section rather than
2500                .reginfo section.  */
2501             sec = subseg_new (".MIPS.options", (subsegT) 0);
2502             bfd_set_section_flags (stdoutput, sec, flags);
2503             bfd_set_section_alignment (stdoutput, sec, 3);
2504
2505             /* Set up the option header.  */
2506             {
2507               Elf_Internal_Options opthdr;
2508               char *f;
2509
2510               opthdr.kind = ODK_REGINFO;
2511               opthdr.size = (sizeof (Elf_External_Options)
2512                              + sizeof (Elf64_External_RegInfo));
2513               opthdr.section = 0;
2514               opthdr.info = 0;
2515               f = frag_more (sizeof (Elf_External_Options));
2516               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2517                                              (Elf_External_Options *) f);
2518
2519               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2520             }
2521           }
2522
2523         if (ECOFF_DEBUGGING)
2524           {
2525             sec = subseg_new (".mdebug", (subsegT) 0);
2526             (void) bfd_set_section_flags (stdoutput, sec,
2527                                           SEC_HAS_CONTENTS | SEC_READONLY);
2528             (void) bfd_set_section_alignment (stdoutput, sec, 2);
2529           }
2530         else if (mips_flag_pdr)
2531           {
2532             pdr_seg = subseg_new (".pdr", (subsegT) 0);
2533             (void) bfd_set_section_flags (stdoutput, pdr_seg,
2534                                           SEC_READONLY | SEC_RELOC
2535                                           | SEC_DEBUGGING);
2536             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2537           }
2538
2539         subseg_set (seg, subseg);
2540       }
2541     }
2542 #endif /* OBJ_ELF */
2543
2544   if (! ECOFF_DEBUGGING)
2545     md_obj_begin ();
2546
2547   if (mips_fix_vr4120)
2548     init_vr4120_conflicts ();
2549 }
2550
2551 void
2552 md_mips_end (void)
2553 {
2554   mips_emit_delays ();
2555   if (! ECOFF_DEBUGGING)
2556     md_obj_end ();
2557 }
2558
2559 void
2560 md_assemble (char *str)
2561 {
2562   struct mips_cl_insn insn;
2563   bfd_reloc_code_real_type unused_reloc[3]
2564     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2565
2566   imm_expr.X_op = O_absent;
2567   imm2_expr.X_op = O_absent;
2568   offset_expr.X_op = O_absent;
2569   imm_reloc[0] = BFD_RELOC_UNUSED;
2570   imm_reloc[1] = BFD_RELOC_UNUSED;
2571   imm_reloc[2] = BFD_RELOC_UNUSED;
2572   offset_reloc[0] = BFD_RELOC_UNUSED;
2573   offset_reloc[1] = BFD_RELOC_UNUSED;
2574   offset_reloc[2] = BFD_RELOC_UNUSED;
2575
2576   if (mips_opts.mips16)
2577     mips16_ip (str, &insn);
2578   else
2579     {
2580       mips_ip (str, &insn);
2581       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
2582             str, insn.insn_opcode));
2583     }
2584
2585   if (insn_error)
2586     {
2587       as_bad ("%s `%s'", insn_error, str);
2588       return;
2589     }
2590
2591   if (insn.insn_mo->pinfo == INSN_MACRO)
2592     {
2593       macro_start ();
2594       if (mips_opts.mips16)
2595         mips16_macro (&insn);
2596       else
2597         macro (&insn);
2598       macro_end ();
2599     }
2600   else
2601     {
2602       if (imm_expr.X_op != O_absent)
2603         append_insn (&insn, &imm_expr, imm_reloc, FALSE);
2604       else if (offset_expr.X_op != O_absent)
2605         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
2606       else
2607         append_insn (&insn, NULL, unused_reloc, FALSE);
2608     }
2609 }
2610
2611 /* Convenience functions for abstracting away the differences between
2612    MIPS16 and non-MIPS16 relocations.  */
2613
2614 static inline bfd_boolean
2615 mips16_reloc_p (bfd_reloc_code_real_type reloc)
2616 {
2617   switch (reloc)
2618     {
2619     case BFD_RELOC_MIPS16_JMP:
2620     case BFD_RELOC_MIPS16_GPREL:
2621     case BFD_RELOC_MIPS16_GOT16:
2622     case BFD_RELOC_MIPS16_CALL16:
2623     case BFD_RELOC_MIPS16_HI16_S:
2624     case BFD_RELOC_MIPS16_HI16:
2625     case BFD_RELOC_MIPS16_LO16:
2626       return TRUE;
2627
2628     default:
2629       return FALSE;
2630     }
2631 }
2632
2633 static inline bfd_boolean
2634 micromips_reloc_p (bfd_reloc_code_real_type reloc)
2635 {
2636   switch (reloc)
2637     {
2638     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
2639     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
2640     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
2641     case BFD_RELOC_MICROMIPS_GPREL16:
2642     case BFD_RELOC_MICROMIPS_JMP:
2643     case BFD_RELOC_MICROMIPS_HI16:
2644     case BFD_RELOC_MICROMIPS_HI16_S:
2645     case BFD_RELOC_MICROMIPS_LO16:
2646     case BFD_RELOC_MICROMIPS_LITERAL:
2647     case BFD_RELOC_MICROMIPS_GOT16:
2648     case BFD_RELOC_MICROMIPS_CALL16:
2649     case BFD_RELOC_MICROMIPS_GOT_HI16:
2650     case BFD_RELOC_MICROMIPS_GOT_LO16:
2651     case BFD_RELOC_MICROMIPS_CALL_HI16:
2652     case BFD_RELOC_MICROMIPS_CALL_LO16:
2653     case BFD_RELOC_MICROMIPS_SUB:
2654     case BFD_RELOC_MICROMIPS_GOT_PAGE:
2655     case BFD_RELOC_MICROMIPS_GOT_OFST:
2656     case BFD_RELOC_MICROMIPS_GOT_DISP:
2657     case BFD_RELOC_MICROMIPS_HIGHEST:
2658     case BFD_RELOC_MICROMIPS_HIGHER:
2659     case BFD_RELOC_MICROMIPS_SCN_DISP:
2660     case BFD_RELOC_MICROMIPS_JALR:
2661       return TRUE;
2662
2663     default:
2664       return FALSE;
2665     }
2666 }
2667
2668 static inline bfd_boolean
2669 jmp_reloc_p (bfd_reloc_code_real_type reloc)
2670 {
2671   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
2672 }
2673
2674 static inline bfd_boolean
2675 got16_reloc_p (bfd_reloc_code_real_type reloc)
2676 {
2677   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
2678           || reloc == BFD_RELOC_MICROMIPS_GOT16);
2679 }
2680
2681 static inline bfd_boolean
2682 hi16_reloc_p (bfd_reloc_code_real_type reloc)
2683 {
2684   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
2685           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
2686 }
2687
2688 static inline bfd_boolean
2689 lo16_reloc_p (bfd_reloc_code_real_type reloc)
2690 {
2691   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
2692           || reloc == BFD_RELOC_MICROMIPS_LO16);
2693 }
2694
2695 static inline bfd_boolean
2696 jalr_reloc_p (bfd_reloc_code_real_type reloc)
2697 {
2698   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
2699 }
2700
2701 /* Return true if the given relocation might need a matching %lo().
2702    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
2703    need a matching %lo() when applied to local symbols.  */
2704
2705 static inline bfd_boolean
2706 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
2707 {
2708   return (HAVE_IN_PLACE_ADDENDS
2709           && (hi16_reloc_p (reloc)
2710               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
2711                  all GOT16 relocations evaluate to "G".  */
2712               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
2713 }
2714
2715 /* Return the type of %lo() reloc needed by RELOC, given that
2716    reloc_needs_lo_p.  */
2717
2718 static inline bfd_reloc_code_real_type
2719 matching_lo_reloc (bfd_reloc_code_real_type reloc)
2720 {
2721   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
2722           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
2723              : BFD_RELOC_LO16));
2724 }
2725
2726 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
2727    relocation.  */
2728
2729 static inline bfd_boolean
2730 fixup_has_matching_lo_p (fixS *fixp)
2731 {
2732   return (fixp->fx_next != NULL
2733           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
2734           && fixp->fx_addsy == fixp->fx_next->fx_addsy
2735           && fixp->fx_offset == fixp->fx_next->fx_offset);
2736 }
2737
2738 /* This function returns true if modifying a register requires a
2739    delay.  */
2740
2741 static int
2742 reg_needs_delay (unsigned int reg)
2743 {
2744   unsigned long prev_pinfo;
2745
2746   prev_pinfo = history[0].insn_mo->pinfo;
2747   if (! mips_opts.noreorder
2748       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
2749            && ! gpr_interlocks)
2750           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
2751               && ! cop_interlocks)))
2752     {
2753       /* A load from a coprocessor or from memory.  All load delays
2754          delay the use of general register rt for one instruction.  */
2755       /* Itbl support may require additional care here.  */
2756       know (prev_pinfo & INSN_WRITE_GPR_T);
2757       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
2758         return 1;
2759     }
2760
2761   return 0;
2762 }
2763
2764 /* Move all labels in LABELS to the current insertion point.  TEXT_P
2765    says whether the labels refer to text or data.  */
2766
2767 static void
2768 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
2769 {
2770   struct insn_label_list *l;
2771   valueT val;
2772
2773   for (l = labels; l != NULL; l = l->next)
2774     {
2775       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
2776       symbol_set_frag (l->label, frag_now);
2777       val = (valueT) frag_now_fix ();
2778       /* MIPS16/microMIPS text labels are stored as odd.  */
2779       if (text_p && HAVE_CODE_COMPRESSION)
2780         ++val;
2781       S_SET_VALUE (l->label, val);
2782     }
2783 }
2784
2785 /* Move all labels in insn_labels to the current insertion point
2786    and treat them as text labels.  */
2787
2788 static void
2789 mips_move_text_labels (void)
2790 {
2791   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
2792 }
2793
2794 static bfd_boolean
2795 s_is_linkonce (symbolS *sym, segT from_seg)
2796 {
2797   bfd_boolean linkonce = FALSE;
2798   segT symseg = S_GET_SEGMENT (sym);
2799
2800   if (symseg != from_seg && !S_IS_LOCAL (sym))
2801     {
2802       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
2803         linkonce = TRUE;
2804 #ifdef OBJ_ELF
2805       /* The GNU toolchain uses an extension for ELF: a section
2806          beginning with the magic string .gnu.linkonce is a
2807          linkonce section.  */
2808       if (strncmp (segment_name (symseg), ".gnu.linkonce",
2809                    sizeof ".gnu.linkonce" - 1) == 0)
2810         linkonce = TRUE;
2811 #endif
2812     }
2813   return linkonce;
2814 }
2815
2816 /* Mark instruction labels in MIPS16/microMIPS mode.  This permits the
2817    linker to handle them specially, such as generating jalx instructions
2818    when needed.  We also make them odd for the duration of the assembly,
2819    in order to generate the right sort of code.  We will make them even
2820    in the adjust_symtab routine, while leaving them marked.  This is
2821    convenient for the debugger and the disassembler.  The linker knows
2822    to make them odd again.  */
2823
2824 static void
2825 mips_compressed_mark_labels (void)
2826 {
2827   segment_info_type *si = seg_info (now_seg);
2828   struct insn_label_list *l;
2829
2830   gas_assert (HAVE_CODE_COMPRESSION);
2831
2832   for (l = si->label_list; l != NULL; l = l->next)
2833    {
2834       symbolS *label = l->label;
2835
2836 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
2837       if (IS_ELF)
2838         {
2839           if (mips_opts.mips16)
2840             S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
2841           else
2842             S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
2843         }
2844 #endif
2845       if ((S_GET_VALUE (label) & 1) == 0
2846         /* Don't adjust the address if the label is global or weak, or
2847            in a link-once section, since we'll be emitting symbol reloc
2848            references to it which will be patched up by the linker, and
2849            the final value of the symbol may or may not be MIPS16/microMIPS.  */
2850           && ! S_IS_WEAK (label)
2851           && ! S_IS_EXTERNAL (label)
2852           && ! s_is_linkonce (label, now_seg))
2853         S_SET_VALUE (label, S_GET_VALUE (label) | 1);
2854     }
2855 }
2856
2857 /* End the current frag.  Make it a variant frag and record the
2858    relaxation info.  */
2859
2860 static void
2861 relax_close_frag (void)
2862 {
2863   mips_macro_warning.first_frag = frag_now;
2864   frag_var (rs_machine_dependent, 0, 0,
2865             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
2866             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
2867
2868   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
2869   mips_relax.first_fixup = 0;
2870 }
2871
2872 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
2873    See the comment above RELAX_ENCODE for more details.  */
2874
2875 static void
2876 relax_start (symbolS *symbol)
2877 {
2878   gas_assert (mips_relax.sequence == 0);
2879   mips_relax.sequence = 1;
2880   mips_relax.symbol = symbol;
2881 }
2882
2883 /* Start generating the second version of a relaxable sequence.
2884    See the comment above RELAX_ENCODE for more details.  */
2885
2886 static void
2887 relax_switch (void)
2888 {
2889   gas_assert (mips_relax.sequence == 1);
2890   mips_relax.sequence = 2;
2891 }
2892
2893 /* End the current relaxable sequence.  */
2894
2895 static void
2896 relax_end (void)
2897 {
2898   gas_assert (mips_relax.sequence == 2);
2899   relax_close_frag ();
2900   mips_relax.sequence = 0;
2901 }
2902
2903 /* Return true if IP is a delayed branch or jump.  */
2904
2905 static inline bfd_boolean
2906 delayed_branch_p (const struct mips_cl_insn *ip)
2907 {
2908   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
2909                                 | INSN_COND_BRANCH_DELAY
2910                                 | INSN_COND_BRANCH_LIKELY)) != 0;
2911 }
2912
2913 /* Return true if IP is a compact branch or jump.  */
2914
2915 static inline bfd_boolean
2916 compact_branch_p (const struct mips_cl_insn *ip)
2917 {
2918   if (mips_opts.mips16)
2919     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
2920                                   | MIPS16_INSN_COND_BRANCH)) != 0;
2921   else
2922     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
2923                                    | INSN2_COND_BRANCH)) != 0;
2924 }
2925
2926 /* Return true if IP is an unconditional branch or jump.  */
2927
2928 static inline bfd_boolean
2929 uncond_branch_p (const struct mips_cl_insn *ip)
2930 {
2931   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
2932           || (mips_opts.mips16
2933               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
2934               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
2935 }
2936
2937 /* Return true if IP is a branch-likely instruction.  */
2938
2939 static inline bfd_boolean
2940 branch_likely_p (const struct mips_cl_insn *ip)
2941 {
2942   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
2943 }
2944
2945 /* Return the type of nop that should be used to fill the delay slot
2946    of delayed branch IP.  */
2947
2948 static struct mips_cl_insn *
2949 get_delay_slot_nop (const struct mips_cl_insn *ip)
2950 {
2951   if (mips_opts.micromips
2952       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
2953     return &micromips_nop32_insn;
2954   return NOP_INSN;
2955 }
2956
2957 /* Return the mask of core registers that IP reads or writes.  */
2958
2959 static unsigned int
2960 gpr_mod_mask (const struct mips_cl_insn *ip)
2961 {
2962   unsigned long pinfo2;
2963   unsigned int mask;
2964
2965   mask = 0;
2966   pinfo2 = ip->insn_mo->pinfo2;
2967   if (mips_opts.micromips)
2968     {
2969       if (pinfo2 & INSN2_MOD_GPR_MD)
2970         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
2971       if (pinfo2 & INSN2_MOD_GPR_MF)
2972         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
2973       if (pinfo2 & INSN2_MOD_SP)
2974         mask |= 1 << SP;
2975     }
2976   return mask;
2977 }
2978
2979 /* Return the mask of core registers that IP reads.  */
2980
2981 static unsigned int
2982 gpr_read_mask (const struct mips_cl_insn *ip)
2983 {
2984   unsigned long pinfo, pinfo2;
2985   unsigned int mask;
2986
2987   mask = gpr_mod_mask (ip);
2988   pinfo = ip->insn_mo->pinfo;
2989   pinfo2 = ip->insn_mo->pinfo2;
2990   if (mips_opts.mips16)
2991     {
2992       if (pinfo & MIPS16_INSN_READ_X)
2993         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
2994       if (pinfo & MIPS16_INSN_READ_Y)
2995         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
2996       if (pinfo & MIPS16_INSN_READ_T)
2997         mask |= 1 << TREG;
2998       if (pinfo & MIPS16_INSN_READ_SP)
2999         mask |= 1 << SP;
3000       if (pinfo & MIPS16_INSN_READ_31)
3001         mask |= 1 << RA;
3002       if (pinfo & MIPS16_INSN_READ_Z)
3003         mask |= 1 << (mips16_to_32_reg_map
3004                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3005       if (pinfo & MIPS16_INSN_READ_GPR_X)
3006         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3007     }
3008   else
3009     {
3010       if (pinfo2 & INSN2_READ_GPR_D)
3011         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3012       if (pinfo & INSN_READ_GPR_T)
3013         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3014       if (pinfo & INSN_READ_GPR_S)
3015         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3016       if (pinfo2 & INSN2_READ_GP)
3017         mask |= 1 << GP;
3018       if (pinfo2 & INSN2_READ_GPR_31)
3019         mask |= 1 << RA;
3020       if (pinfo2 & INSN2_READ_GPR_Z)
3021         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3022     }
3023   if (mips_opts.micromips)
3024     {
3025       if (pinfo2 & INSN2_READ_GPR_MC)
3026         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3027       if (pinfo2 & INSN2_READ_GPR_ME)
3028         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3029       if (pinfo2 & INSN2_READ_GPR_MG)
3030         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3031       if (pinfo2 & INSN2_READ_GPR_MJ)
3032         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3033       if (pinfo2 & INSN2_READ_GPR_MMN)
3034         {
3035           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3036           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3037         }
3038       if (pinfo2 & INSN2_READ_GPR_MP)
3039         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3040       if (pinfo2 & INSN2_READ_GPR_MQ)
3041         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3042     }
3043   /* Don't include register 0.  */
3044   return mask & ~1;
3045 }
3046
3047 /* Return the mask of core registers that IP writes.  */
3048
3049 static unsigned int
3050 gpr_write_mask (const struct mips_cl_insn *ip)
3051 {
3052   unsigned long pinfo, pinfo2;
3053   unsigned int mask;
3054
3055   mask = gpr_mod_mask (ip);
3056   pinfo = ip->insn_mo->pinfo;
3057   pinfo2 = ip->insn_mo->pinfo2;
3058   if (mips_opts.mips16)
3059     {
3060       if (pinfo & MIPS16_INSN_WRITE_X)
3061         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3062       if (pinfo & MIPS16_INSN_WRITE_Y)
3063         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3064       if (pinfo & MIPS16_INSN_WRITE_Z)
3065         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3066       if (pinfo & MIPS16_INSN_WRITE_T)
3067         mask |= 1 << TREG;
3068       if (pinfo & MIPS16_INSN_WRITE_SP)
3069         mask |= 1 << SP;
3070       if (pinfo & MIPS16_INSN_WRITE_31)
3071         mask |= 1 << RA;
3072       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3073         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3074     }
3075   else
3076     {
3077       if (pinfo & INSN_WRITE_GPR_D)
3078         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3079       if (pinfo & INSN_WRITE_GPR_T)
3080         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3081       if (pinfo & INSN_WRITE_GPR_S)
3082         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3083       if (pinfo & INSN_WRITE_GPR_31)
3084         mask |= 1 << RA;
3085       if (pinfo2 & INSN2_WRITE_GPR_Z)
3086         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3087     }
3088   if (mips_opts.micromips)
3089     {
3090       if (pinfo2 & INSN2_WRITE_GPR_MB)
3091         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3092       if (pinfo2 & INSN2_WRITE_GPR_MHI)
3093         {
3094           mask |= 1 << micromips_to_32_reg_h_map[EXTRACT_OPERAND (1, MH, *ip)];
3095           mask |= 1 << micromips_to_32_reg_i_map[EXTRACT_OPERAND (1, MI, *ip)];
3096         }
3097       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3098         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3099       if (pinfo2 & INSN2_WRITE_GPR_MP)
3100         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3101     }
3102   /* Don't include register 0.  */
3103   return mask & ~1;
3104 }
3105
3106 /* Return the mask of floating-point registers that IP reads.  */
3107
3108 static unsigned int
3109 fpr_read_mask (const struct mips_cl_insn *ip)
3110 {
3111   unsigned long pinfo, pinfo2;
3112   unsigned int mask;
3113
3114   mask = 0;
3115   pinfo = ip->insn_mo->pinfo;
3116   pinfo2 = ip->insn_mo->pinfo2;
3117   if (!mips_opts.mips16)
3118     {
3119       if (pinfo2 & INSN2_READ_FPR_D)
3120         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3121       if (pinfo & INSN_READ_FPR_S)
3122         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3123       if (pinfo & INSN_READ_FPR_T)
3124         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3125       if (pinfo & INSN_READ_FPR_R)
3126         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3127       if (pinfo2 & INSN2_READ_FPR_Z)
3128         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3129     }
3130   /* Conservatively treat all operands to an FP_D instruction are doubles.
3131      (This is overly pessimistic for things like cvt.d.s.)  */
3132   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3133     mask |= mask << 1;
3134   return mask;
3135 }
3136
3137 /* Return the mask of floating-point registers that IP writes.  */
3138
3139 static unsigned int
3140 fpr_write_mask (const struct mips_cl_insn *ip)
3141 {
3142   unsigned long pinfo, pinfo2;
3143   unsigned int mask;
3144
3145   mask = 0;
3146   pinfo = ip->insn_mo->pinfo;
3147   pinfo2 = ip->insn_mo->pinfo2;
3148   if (!mips_opts.mips16)
3149     {
3150       if (pinfo & INSN_WRITE_FPR_D)
3151         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3152       if (pinfo & INSN_WRITE_FPR_S)
3153         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3154       if (pinfo & INSN_WRITE_FPR_T)
3155         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3156       if (pinfo2 & INSN2_WRITE_FPR_Z)
3157         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3158     }
3159   /* Conservatively treat all operands to an FP_D instruction are doubles.
3160      (This is overly pessimistic for things like cvt.s.d.)  */
3161   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3162     mask |= mask << 1;
3163   return mask;
3164 }
3165
3166 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3167    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3168    by VR4120 errata.  */
3169
3170 static unsigned int
3171 classify_vr4120_insn (const char *name)
3172 {
3173   if (strncmp (name, "macc", 4) == 0)
3174     return FIX_VR4120_MACC;
3175   if (strncmp (name, "dmacc", 5) == 0)
3176     return FIX_VR4120_DMACC;
3177   if (strncmp (name, "mult", 4) == 0)
3178     return FIX_VR4120_MULT;
3179   if (strncmp (name, "dmult", 5) == 0)
3180     return FIX_VR4120_DMULT;
3181   if (strstr (name, "div"))
3182     return FIX_VR4120_DIV;
3183   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3184     return FIX_VR4120_MTHILO;
3185   return NUM_FIX_VR4120_CLASSES;
3186 }
3187
3188 #define INSN_ERET  0x42000018
3189 #define INSN_DERET 0x4200001f
3190
3191 /* Return the number of instructions that must separate INSN1 and INSN2,
3192    where INSN1 is the earlier instruction.  Return the worst-case value
3193    for any INSN2 if INSN2 is null.  */
3194
3195 static unsigned int
3196 insns_between (const struct mips_cl_insn *insn1,
3197                const struct mips_cl_insn *insn2)
3198 {
3199   unsigned long pinfo1, pinfo2;
3200   unsigned int mask;
3201
3202   /* This function needs to know which pinfo flags are set for INSN2
3203      and which registers INSN2 uses.  The former is stored in PINFO2 and
3204      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3205      will have every flag set and INSN2_USES_GPR will always return true.  */
3206   pinfo1 = insn1->insn_mo->pinfo;
3207   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3208
3209 #define INSN2_USES_GPR(REG) \
3210   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3211
3212   /* For most targets, write-after-read dependencies on the HI and LO
3213      registers must be separated by at least two instructions.  */
3214   if (!hilo_interlocks)
3215     {
3216       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3217         return 2;
3218       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3219         return 2;
3220     }
3221
3222   /* If we're working around r7000 errata, there must be two instructions
3223      between an mfhi or mflo and any instruction that uses the result.  */
3224   if (mips_7000_hilo_fix
3225       && !mips_opts.micromips
3226       && MF_HILO_INSN (pinfo1)
3227       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3228     return 2;
3229
3230   /* If we're working around 24K errata, one instruction is required
3231      if an ERET or DERET is followed by a branch instruction.  */
3232   if (mips_fix_24k && !mips_opts.micromips)
3233     {
3234       if (insn1->insn_opcode == INSN_ERET
3235           || insn1->insn_opcode == INSN_DERET)
3236         {
3237           if (insn2 == NULL
3238               || insn2->insn_opcode == INSN_ERET
3239               || insn2->insn_opcode == INSN_DERET
3240               || delayed_branch_p (insn2))
3241             return 1;
3242         }
3243     }
3244
3245   /* If working around VR4120 errata, check for combinations that need
3246      a single intervening instruction.  */
3247   if (mips_fix_vr4120 && !mips_opts.micromips)
3248     {
3249       unsigned int class1, class2;
3250
3251       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3252       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3253         {
3254           if (insn2 == NULL)
3255             return 1;
3256           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3257           if (vr4120_conflicts[class1] & (1 << class2))
3258             return 1;
3259         }
3260     }
3261
3262   if (!HAVE_CODE_COMPRESSION)
3263     {
3264       /* Check for GPR or coprocessor load delays.  All such delays
3265          are on the RT register.  */
3266       /* Itbl support may require additional care here.  */
3267       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3268           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3269         {
3270           know (pinfo1 & INSN_WRITE_GPR_T);
3271           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3272             return 1;
3273         }
3274
3275       /* Check for generic coprocessor hazards.
3276
3277          This case is not handled very well.  There is no special
3278          knowledge of CP0 handling, and the coprocessors other than
3279          the floating point unit are not distinguished at all.  */
3280       /* Itbl support may require additional care here. FIXME!
3281          Need to modify this to include knowledge about
3282          user specified delays!  */
3283       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3284                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3285         {
3286           /* Handle cases where INSN1 writes to a known general coprocessor
3287              register.  There must be a one instruction delay before INSN2
3288              if INSN2 reads that register, otherwise no delay is needed.  */
3289           mask = fpr_write_mask (insn1);
3290           if (mask != 0)
3291             {
3292               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3293                 return 1;
3294             }
3295           else
3296             {
3297               /* Read-after-write dependencies on the control registers
3298                  require a two-instruction gap.  */
3299               if ((pinfo1 & INSN_WRITE_COND_CODE)
3300                   && (pinfo2 & INSN_READ_COND_CODE))
3301                 return 2;
3302
3303               /* We don't know exactly what INSN1 does.  If INSN2 is
3304                  also a coprocessor instruction, assume there must be
3305                  a one instruction gap.  */
3306               if (pinfo2 & INSN_COP)
3307                 return 1;
3308             }
3309         }
3310
3311       /* Check for read-after-write dependencies on the coprocessor
3312          control registers in cases where INSN1 does not need a general
3313          coprocessor delay.  This means that INSN1 is a floating point
3314          comparison instruction.  */
3315       /* Itbl support may require additional care here.  */
3316       else if (!cop_interlocks
3317                && (pinfo1 & INSN_WRITE_COND_CODE)
3318                && (pinfo2 & INSN_READ_COND_CODE))
3319         return 1;
3320     }
3321
3322 #undef INSN2_USES_GPR
3323
3324   return 0;
3325 }
3326
3327 /* Return the number of nops that would be needed to work around the
3328    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3329    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3330    that are contained within the first IGNORE instructions of HIST.  */
3331
3332 static int
3333 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3334                  const struct mips_cl_insn *insn)
3335 {
3336   int i, j;
3337   unsigned int mask;
3338
3339   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3340      are not affected by the errata.  */
3341   if (insn != 0
3342       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3343           || strcmp (insn->insn_mo->name, "mtlo") == 0
3344           || strcmp (insn->insn_mo->name, "mthi") == 0))
3345     return 0;
3346
3347   /* Search for the first MFLO or MFHI.  */
3348   for (i = 0; i < MAX_VR4130_NOPS; i++)
3349     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3350       {
3351         /* Extract the destination register.  */
3352         mask = gpr_write_mask (&hist[i]);
3353
3354         /* No nops are needed if INSN reads that register.  */
3355         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3356           return 0;
3357
3358         /* ...or if any of the intervening instructions do.  */
3359         for (j = 0; j < i; j++)
3360           if (gpr_read_mask (&hist[j]) & mask)
3361             return 0;
3362
3363         if (i >= ignore)
3364           return MAX_VR4130_NOPS - i;
3365       }
3366   return 0;
3367 }
3368
3369 #define BASE_REG_EQ(INSN1, INSN2)       \
3370   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3371       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3372
3373 /* Return the minimum alignment for this store instruction.  */
3374
3375 static int
3376 fix_24k_align_to (const struct mips_opcode *mo)
3377 {
3378   if (strcmp (mo->name, "sh") == 0)
3379     return 2;
3380
3381   if (strcmp (mo->name, "swc1") == 0
3382       || strcmp (mo->name, "swc2") == 0
3383       || strcmp (mo->name, "sw") == 0
3384       || strcmp (mo->name, "sc") == 0
3385       || strcmp (mo->name, "s.s") == 0)
3386     return 4;
3387
3388   if (strcmp (mo->name, "sdc1") == 0
3389       || strcmp (mo->name, "sdc2") == 0
3390       || strcmp (mo->name, "s.d") == 0)
3391     return 8;
3392
3393   /* sb, swl, swr */
3394   return 1;
3395 }
3396
3397 struct fix_24k_store_info
3398   {
3399     /* Immediate offset, if any, for this store instruction.  */
3400     short off;
3401     /* Alignment required by this store instruction.  */
3402     int align_to;
3403     /* True for register offsets.  */
3404     int register_offset;
3405   };
3406
3407 /* Comparison function used by qsort.  */
3408
3409 static int
3410 fix_24k_sort (const void *a, const void *b)
3411 {
3412   const struct fix_24k_store_info *pos1 = a;
3413   const struct fix_24k_store_info *pos2 = b;
3414
3415   return (pos1->off - pos2->off);
3416 }
3417
3418 /* INSN is a store instruction.  Try to record the store information
3419    in STINFO.  Return false if the information isn't known.  */
3420
3421 static bfd_boolean
3422 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3423                            const struct mips_cl_insn *insn)
3424 {
3425   /* The instruction must have a known offset.  */
3426   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3427     return FALSE;
3428
3429   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3430   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3431   return TRUE;
3432 }
3433
3434 /* Return the number of nops that would be needed to work around the 24k
3435    "lost data on stores during refill" errata if instruction INSN
3436    immediately followed the 2 instructions described by HIST.
3437    Ignore hazards that are contained within the first IGNORE
3438    instructions of HIST.
3439
3440    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3441    for the data cache refills and store data. The following describes
3442    the scenario where the store data could be lost.
3443
3444    * A data cache miss, due to either a load or a store, causing fill
3445      data to be supplied by the memory subsystem
3446    * The first three doublewords of fill data are returned and written
3447      into the cache
3448    * A sequence of four stores occurs in consecutive cycles around the
3449      final doubleword of the fill:
3450    * Store A
3451    * Store B
3452    * Store C
3453    * Zero, One or more instructions
3454    * Store D
3455
3456    The four stores A-D must be to different doublewords of the line that
3457    is being filled. The fourth instruction in the sequence above permits
3458    the fill of the final doubleword to be transferred from the FSB into
3459    the cache. In the sequence above, the stores may be either integer
3460    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
3461    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
3462    different doublewords on the line. If the floating point unit is
3463    running in 1:2 mode, it is not possible to create the sequence above
3464    using only floating point store instructions.
3465
3466    In this case, the cache line being filled is incorrectly marked
3467    invalid, thereby losing the data from any store to the line that
3468    occurs between the original miss and the completion of the five
3469    cycle sequence shown above.
3470
3471    The workarounds are:
3472
3473    * Run the data cache in write-through mode.
3474    * Insert a non-store instruction between
3475      Store A and Store B or Store B and Store C.  */
3476   
3477 static int
3478 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
3479               const struct mips_cl_insn *insn)
3480 {
3481   struct fix_24k_store_info pos[3];
3482   int align, i, base_offset;
3483
3484   if (ignore >= 2)
3485     return 0;
3486
3487   /* If the previous instruction wasn't a store, there's nothing to
3488      worry about.  */
3489   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3490     return 0;
3491
3492   /* If the instructions after the previous one are unknown, we have
3493      to assume the worst.  */
3494   if (!insn)
3495     return 1;
3496
3497   /* Check whether we are dealing with three consecutive stores.  */
3498   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
3499       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3500     return 0;
3501
3502   /* If we don't know the relationship between the store addresses,
3503      assume the worst.  */
3504   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
3505       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
3506     return 1;
3507
3508   if (!fix_24k_record_store_info (&pos[0], insn)
3509       || !fix_24k_record_store_info (&pos[1], &hist[0])
3510       || !fix_24k_record_store_info (&pos[2], &hist[1]))
3511     return 1;
3512
3513   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
3514
3515   /* Pick a value of ALIGN and X such that all offsets are adjusted by
3516      X bytes and such that the base register + X is known to be aligned
3517      to align bytes.  */
3518
3519   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
3520     align = 8;
3521   else
3522     {
3523       align = pos[0].align_to;
3524       base_offset = pos[0].off;
3525       for (i = 1; i < 3; i++)
3526         if (align < pos[i].align_to)
3527           {
3528             align = pos[i].align_to;
3529             base_offset = pos[i].off;
3530           }
3531       for (i = 0; i < 3; i++)
3532         pos[i].off -= base_offset;
3533     }
3534
3535   pos[0].off &= ~align + 1;
3536   pos[1].off &= ~align + 1;
3537   pos[2].off &= ~align + 1;
3538
3539   /* If any two stores write to the same chunk, they also write to the
3540      same doubleword.  The offsets are still sorted at this point.  */
3541   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
3542     return 0;
3543
3544   /* A range of at least 9 bytes is needed for the stores to be in
3545      non-overlapping doublewords.  */
3546   if (pos[2].off - pos[0].off <= 8)
3547     return 0;
3548
3549   if (pos[2].off - pos[1].off >= 24
3550       || pos[1].off - pos[0].off >= 24
3551       || pos[2].off - pos[0].off >= 32)
3552     return 0;
3553
3554   return 1;
3555 }
3556
3557 /* Return the number of nops that would be needed if instruction INSN
3558    immediately followed the MAX_NOPS instructions given by HIST,
3559    where HIST[0] is the most recent instruction.  Ignore hazards
3560    between INSN and the first IGNORE instructions in HIST.
3561
3562    If INSN is null, return the worse-case number of nops for any
3563    instruction.  */
3564
3565 static int
3566 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
3567                const struct mips_cl_insn *insn)
3568 {
3569   int i, nops, tmp_nops;
3570
3571   nops = 0;
3572   for (i = ignore; i < MAX_DELAY_NOPS; i++)
3573     {
3574       tmp_nops = insns_between (hist + i, insn) - i;
3575       if (tmp_nops > nops)
3576         nops = tmp_nops;
3577     }
3578
3579   if (mips_fix_vr4130 && !mips_opts.micromips)
3580     {
3581       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
3582       if (tmp_nops > nops)
3583         nops = tmp_nops;
3584     }
3585
3586   if (mips_fix_24k && !mips_opts.micromips)
3587     {
3588       tmp_nops = nops_for_24k (ignore, hist, insn);
3589       if (tmp_nops > nops)
3590         nops = tmp_nops;
3591     }
3592
3593   return nops;
3594 }
3595
3596 /* The variable arguments provide NUM_INSNS extra instructions that
3597    might be added to HIST.  Return the largest number of nops that
3598    would be needed after the extended sequence, ignoring hazards
3599    in the first IGNORE instructions.  */
3600
3601 static int
3602 nops_for_sequence (int num_insns, int ignore,
3603                    const struct mips_cl_insn *hist, ...)
3604 {
3605   va_list args;
3606   struct mips_cl_insn buffer[MAX_NOPS];
3607   struct mips_cl_insn *cursor;
3608   int nops;
3609
3610   va_start (args, hist);
3611   cursor = buffer + num_insns;
3612   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
3613   while (cursor > buffer)
3614     *--cursor = *va_arg (args, const struct mips_cl_insn *);
3615
3616   nops = nops_for_insn (ignore, buffer, NULL);
3617   va_end (args);
3618   return nops;
3619 }
3620
3621 /* Like nops_for_insn, but if INSN is a branch, take into account the
3622    worst-case delay for the branch target.  */
3623
3624 static int
3625 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
3626                          const struct mips_cl_insn *insn)
3627 {
3628   int nops, tmp_nops;
3629
3630   nops = nops_for_insn (ignore, hist, insn);
3631   if (delayed_branch_p (insn))
3632     {
3633       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
3634                                     hist, insn, get_delay_slot_nop (insn));
3635       if (tmp_nops > nops)
3636         nops = tmp_nops;
3637     }
3638   else if (compact_branch_p (insn))
3639     {
3640       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
3641       if (tmp_nops > nops)
3642         nops = tmp_nops;
3643     }
3644   return nops;
3645 }
3646
3647 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
3648
3649 static void
3650 fix_loongson2f_nop (struct mips_cl_insn * ip)
3651 {
3652   gas_assert (!HAVE_CODE_COMPRESSION);
3653   if (strcmp (ip->insn_mo->name, "nop") == 0)
3654     ip->insn_opcode = LOONGSON2F_NOP_INSN;
3655 }
3656
3657 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
3658                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
3659
3660 static void
3661 fix_loongson2f_jump (struct mips_cl_insn * ip)
3662 {
3663   gas_assert (!HAVE_CODE_COMPRESSION);
3664   if (strcmp (ip->insn_mo->name, "j") == 0
3665       || strcmp (ip->insn_mo->name, "jr") == 0
3666       || strcmp (ip->insn_mo->name, "jalr") == 0)
3667     {
3668       int sreg;
3669       expressionS ep;
3670
3671       if (! mips_opts.at)
3672         return;
3673
3674       sreg = EXTRACT_OPERAND (0, RS, *ip);
3675       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
3676         return;
3677
3678       ep.X_op = O_constant;
3679       ep.X_add_number = 0xcfff0000;
3680       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
3681       ep.X_add_number = 0xffff;
3682       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
3683       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
3684     }
3685 }
3686
3687 static void
3688 fix_loongson2f (struct mips_cl_insn * ip)
3689 {
3690   if (mips_fix_loongson2f_nop)
3691     fix_loongson2f_nop (ip);
3692
3693   if (mips_fix_loongson2f_jump)
3694     fix_loongson2f_jump (ip);
3695 }
3696
3697 /* IP is a branch that has a delay slot, and we need to fill it
3698    automatically.   Return true if we can do that by swapping IP
3699    with the previous instruction.  */
3700
3701 static bfd_boolean
3702 can_swap_branch_p (struct mips_cl_insn *ip)
3703 {
3704   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
3705   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
3706
3707   /* -O2 and above is required for this optimization.  */
3708   if (mips_optimize < 2)
3709     return FALSE;
3710
3711   /* If we have seen .set volatile or .set nomove, don't optimize.  */
3712   if (mips_opts.nomove)
3713     return FALSE;
3714
3715   /* We can't swap if the previous instruction's position is fixed.  */
3716   if (history[0].fixed_p)
3717     return FALSE;
3718
3719   /* If the previous previous insn was in a .set noreorder, we can't
3720      swap.  Actually, the MIPS assembler will swap in this situation.
3721      However, gcc configured -with-gnu-as will generate code like
3722
3723         .set    noreorder
3724         lw      $4,XXX
3725         .set    reorder
3726         INSN
3727         bne     $4,$0,foo
3728
3729      in which we can not swap the bne and INSN.  If gcc is not configured
3730      -with-gnu-as, it does not output the .set pseudo-ops.  */
3731   if (history[1].noreorder_p)
3732     return FALSE;
3733
3734   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
3735      This means that the previous instruction was a 4-byte one anyhow.  */
3736   if (mips_opts.mips16 && history[0].fixp[0])
3737     return FALSE;
3738
3739   /* If the branch is itself the target of a branch, we can not swap.
3740      We cheat on this; all we check for is whether there is a label on
3741      this instruction.  If there are any branches to anything other than
3742      a label, users must use .set noreorder.  */
3743   if (seg_info (now_seg)->label_list)
3744     return FALSE;
3745
3746   /* If the previous instruction is in a variant frag other than this
3747      branch's one, we cannot do the swap.  This does not apply to
3748      MIPS16 code, which uses variant frags for different purposes.  */
3749   if (!mips_opts.mips16
3750       && history[0].frag
3751       && history[0].frag->fr_type == rs_machine_dependent)
3752     return FALSE;
3753
3754   /* We do not swap with instructions that cannot architecturally
3755      be placed in a branch delay slot, such as SYNC or ERET.  We
3756      also refrain from swapping with a trap instruction, since it
3757      complicates trap handlers to have the trap instruction be in
3758      a delay slot.  */
3759   prev_pinfo = history[0].insn_mo->pinfo;
3760   if (prev_pinfo & INSN_NO_DELAY_SLOT)
3761     return FALSE;
3762
3763   /* Check for conflicts between the branch and the instructions
3764      before the candidate delay slot.  */
3765   if (nops_for_insn (0, history + 1, ip) > 0)
3766     return FALSE;
3767
3768   /* Check for conflicts between the swapped sequence and the
3769      target of the branch.  */
3770   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
3771     return FALSE;
3772
3773   /* If the branch reads a register that the previous
3774      instruction sets, we can not swap.  */
3775   gpr_read = gpr_read_mask (ip);
3776   prev_gpr_write = gpr_write_mask (&history[0]);
3777   if (gpr_read & prev_gpr_write)
3778     return FALSE;
3779
3780   /* If the branch writes a register that the previous
3781      instruction sets, we can not swap.  */
3782   gpr_write = gpr_write_mask (ip);
3783   if (gpr_write & prev_gpr_write)
3784     return FALSE;
3785
3786   /* If the branch writes a register that the previous
3787      instruction reads, we can not swap.  */
3788   prev_gpr_read = gpr_read_mask (&history[0]);
3789   if (gpr_write & prev_gpr_read)
3790     return FALSE;
3791
3792   /* If one instruction sets a condition code and the
3793      other one uses a condition code, we can not swap.  */
3794   pinfo = ip->insn_mo->pinfo;
3795   if ((pinfo & INSN_READ_COND_CODE)
3796       && (prev_pinfo & INSN_WRITE_COND_CODE))
3797     return FALSE;
3798   if ((pinfo & INSN_WRITE_COND_CODE)
3799       && (prev_pinfo & INSN_READ_COND_CODE))
3800     return FALSE;
3801
3802   /* If the previous instruction uses the PC, we can not swap.  */
3803   prev_pinfo2 = history[0].insn_mo->pinfo2;
3804   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
3805     return FALSE;
3806   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
3807     return FALSE;
3808
3809   /* If the previous instruction has an incorrect size for a fixed
3810      branch delay slot in microMIPS mode, we cannot swap.  */
3811   pinfo2 = ip->insn_mo->pinfo2;
3812   if (mips_opts.micromips
3813       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
3814       && insn_length (history) != 2)
3815     return FALSE;
3816   if (mips_opts.micromips
3817       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
3818       && insn_length (history) != 4)
3819     return FALSE;
3820
3821   return TRUE;
3822 }
3823
3824 /* Decide how we should add IP to the instruction stream.  */
3825
3826 static enum append_method
3827 get_append_method (struct mips_cl_insn *ip)
3828 {
3829   unsigned long pinfo;
3830
3831   /* The relaxed version of a macro sequence must be inherently
3832      hazard-free.  */
3833   if (mips_relax.sequence == 2)
3834     return APPEND_ADD;
3835
3836   /* We must not dabble with instructions in a ".set norerorder" block.  */
3837   if (mips_opts.noreorder)
3838     return APPEND_ADD;
3839
3840   /* Otherwise, it's our responsibility to fill branch delay slots.  */
3841   if (delayed_branch_p (ip))
3842     {
3843       if (!branch_likely_p (ip) && can_swap_branch_p (ip))
3844         return APPEND_SWAP;
3845
3846       pinfo = ip->insn_mo->pinfo;
3847       if (mips_opts.mips16
3848           && ISA_SUPPORTS_MIPS16E
3849           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
3850         return APPEND_ADD_COMPACT;
3851
3852       return APPEND_ADD_WITH_NOP;
3853     }
3854
3855   return APPEND_ADD;
3856 }
3857
3858 /* IP is a MIPS16 instruction whose opcode we have just changed.
3859    Point IP->insn_mo to the new opcode's definition.  */
3860
3861 static void
3862 find_altered_mips16_opcode (struct mips_cl_insn *ip)
3863 {
3864   const struct mips_opcode *mo, *end;
3865
3866   end = &mips16_opcodes[bfd_mips16_num_opcodes];
3867   for (mo = ip->insn_mo; mo < end; mo++)
3868     if ((ip->insn_opcode & mo->mask) == mo->match)
3869       {
3870         ip->insn_mo = mo;
3871         return;
3872       }
3873   abort ();
3874 }
3875
3876 /* For microMIPS macros, we need to generate a local number label
3877    as the target of branches.  */
3878 #define MICROMIPS_LABEL_CHAR            '\037'
3879 static unsigned long micromips_target_label;
3880 static char micromips_target_name[32];
3881
3882 static char *
3883 micromips_label_name (void)
3884 {
3885   char *p = micromips_target_name;
3886   char symbol_name_temporary[24];
3887   unsigned long l;
3888   int i;
3889
3890   if (*p)
3891     return p;
3892
3893   i = 0;
3894   l = micromips_target_label;
3895 #ifdef LOCAL_LABEL_PREFIX
3896   *p++ = LOCAL_LABEL_PREFIX;
3897 #endif
3898   *p++ = 'L';
3899   *p++ = MICROMIPS_LABEL_CHAR;
3900   do
3901     {
3902       symbol_name_temporary[i++] = l % 10 + '0';
3903       l /= 10;
3904     }
3905   while (l != 0);
3906   while (i > 0)
3907     *p++ = symbol_name_temporary[--i];
3908   *p = '\0';
3909
3910   return micromips_target_name;
3911 }
3912
3913 static void
3914 micromips_label_expr (expressionS *label_expr)
3915 {
3916   label_expr->X_op = O_symbol;
3917   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
3918   label_expr->X_add_number = 0;
3919 }
3920
3921 static void
3922 micromips_label_inc (void)
3923 {
3924   micromips_target_label++;
3925   *micromips_target_name = '\0';
3926 }
3927
3928 static void
3929 micromips_add_label (void)
3930 {
3931   symbolS *s;
3932
3933   s = colon (micromips_label_name ());
3934   micromips_label_inc ();
3935 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
3936   if (IS_ELF)
3937     S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
3938 #else
3939   (void) s;
3940 #endif
3941 }
3942
3943 /* If assembling microMIPS code, then return the microMIPS reloc
3944    corresponding to the requested one if any.  Otherwise return
3945    the reloc unchanged.  */
3946
3947 static bfd_reloc_code_real_type
3948 micromips_map_reloc (bfd_reloc_code_real_type reloc)
3949 {
3950   static const bfd_reloc_code_real_type relocs[][2] =
3951     {
3952       /* Keep sorted incrementally by the left-hand key.  */
3953       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
3954       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
3955       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
3956       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
3957       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
3958       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
3959       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
3960       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
3961       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
3962       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
3963       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
3964       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
3965       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
3966       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
3967       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
3968       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
3969       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
3970       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
3971       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
3972       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
3973       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
3974       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
3975       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
3976       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
3977       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
3978       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
3979       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
3980     };
3981   bfd_reloc_code_real_type r;
3982   size_t i;
3983
3984   if (!mips_opts.micromips)
3985     return reloc;
3986   for (i = 0; i < ARRAY_SIZE (relocs); i++)
3987     {
3988       r = relocs[i][0];
3989       if (r > reloc)
3990         return reloc;
3991       if (r == reloc)
3992         return relocs[i][1];
3993     }
3994   return reloc;
3995 }
3996
3997 /* Output an instruction.  IP is the instruction information.
3998    ADDRESS_EXPR is an operand of the instruction to be used with
3999    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
4000    a macro expansion.  */
4001
4002 static void
4003 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
4004              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
4005 {
4006   unsigned long prev_pinfo2, pinfo;
4007   bfd_boolean relaxed_branch = FALSE;
4008   enum append_method method;
4009   bfd_boolean relax32;
4010   int branch_disp;
4011
4012   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
4013     fix_loongson2f (ip);
4014
4015   mips_mark_labels ();
4016
4017   file_ase_mips16 |= mips_opts.mips16;
4018   file_ase_micromips |= mips_opts.micromips;
4019
4020   prev_pinfo2 = history[0].insn_mo->pinfo2;
4021   pinfo = ip->insn_mo->pinfo;
4022
4023   if (mips_opts.micromips
4024       && !expansionp
4025       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
4026            && micromips_insn_length (ip->insn_mo) != 2)
4027           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
4028               && micromips_insn_length (ip->insn_mo) != 4)))
4029     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
4030              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
4031
4032   if (address_expr == NULL)
4033     ip->complete_p = 1;
4034   else if (*reloc_type <= BFD_RELOC_UNUSED
4035            && address_expr->X_op == O_constant)
4036     {
4037       unsigned int tmp;
4038
4039       ip->complete_p = 1;
4040       switch (*reloc_type)
4041         {
4042         case BFD_RELOC_32:
4043           ip->insn_opcode |= address_expr->X_add_number;
4044           break;
4045
4046         case BFD_RELOC_MIPS_HIGHEST:
4047           tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
4048           ip->insn_opcode |= tmp & 0xffff;
4049           break;
4050
4051         case BFD_RELOC_MIPS_HIGHER:
4052           tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
4053           ip->insn_opcode |= tmp & 0xffff;
4054           break;
4055
4056         case BFD_RELOC_HI16_S:
4057           tmp = (address_expr->X_add_number + 0x8000) >> 16;
4058           ip->insn_opcode |= tmp & 0xffff;
4059           break;
4060
4061         case BFD_RELOC_HI16:
4062           ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
4063           break;
4064
4065         case BFD_RELOC_UNUSED:
4066         case BFD_RELOC_LO16:
4067         case BFD_RELOC_MIPS_GOT_DISP:
4068           ip->insn_opcode |= address_expr->X_add_number & 0xffff;
4069           break;
4070
4071         case BFD_RELOC_MIPS_JMP:
4072           {
4073             int shift;
4074
4075             shift = mips_opts.micromips ? 1 : 2;
4076             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4077               as_bad (_("jump to misaligned address (0x%lx)"),
4078                       (unsigned long) address_expr->X_add_number);
4079             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4080                                 & 0x3ffffff);
4081             ip->complete_p = 0;
4082           }
4083           break;
4084
4085         case BFD_RELOC_MIPS16_JMP:
4086           if ((address_expr->X_add_number & 3) != 0)
4087             as_bad (_("jump to misaligned address (0x%lx)"),
4088                     (unsigned long) address_expr->X_add_number);
4089           ip->insn_opcode |=
4090             (((address_expr->X_add_number & 0x7c0000) << 3)
4091                | ((address_expr->X_add_number & 0xf800000) >> 7)
4092                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4093           ip->complete_p = 0;
4094           break;
4095
4096         case BFD_RELOC_16_PCREL_S2:
4097           {
4098             int shift;
4099
4100             shift = mips_opts.micromips ? 1 : 2;
4101             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4102               as_bad (_("branch to misaligned address (0x%lx)"),
4103                       (unsigned long) address_expr->X_add_number);
4104             if (!mips_relax_branch)
4105               {
4106                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4107                     & ~((1 << (shift + 16)) - 1))
4108                   as_bad (_("branch address range overflow (0x%lx)"),
4109                           (unsigned long) address_expr->X_add_number);
4110                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4111                                     & 0xffff);
4112               }
4113             ip->complete_p = 0;
4114           }
4115           break;
4116
4117         default:
4118           internalError ();
4119         }       
4120     }
4121
4122   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4123     {
4124       /* There are a lot of optimizations we could do that we don't.
4125          In particular, we do not, in general, reorder instructions.
4126          If you use gcc with optimization, it will reorder
4127          instructions and generally do much more optimization then we
4128          do here; repeating all that work in the assembler would only
4129          benefit hand written assembly code, and does not seem worth
4130          it.  */
4131       int nops = (mips_optimize == 0
4132                   ? nops_for_insn (0, history, NULL)
4133                   : nops_for_insn_or_target (0, history, ip));
4134       if (nops > 0)
4135         {
4136           fragS *old_frag;
4137           unsigned long old_frag_offset;
4138           int i;
4139
4140           old_frag = frag_now;
4141           old_frag_offset = frag_now_fix ();
4142
4143           for (i = 0; i < nops; i++)
4144             add_fixed_insn (NOP_INSN);
4145           insert_into_history (0, nops, NOP_INSN);
4146
4147           if (listing)
4148             {
4149               listing_prev_line ();
4150               /* We may be at the start of a variant frag.  In case we
4151                  are, make sure there is enough space for the frag
4152                  after the frags created by listing_prev_line.  The
4153                  argument to frag_grow here must be at least as large
4154                  as the argument to all other calls to frag_grow in
4155                  this file.  We don't have to worry about being in the
4156                  middle of a variant frag, because the variants insert
4157                  all needed nop instructions themselves.  */
4158               frag_grow (40);
4159             }
4160
4161           mips_move_text_labels ();
4162
4163 #ifndef NO_ECOFF_DEBUGGING
4164           if (ECOFF_DEBUGGING)
4165             ecoff_fix_loc (old_frag, old_frag_offset);
4166 #endif
4167         }
4168     }
4169   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4170     {
4171       int nops;
4172
4173       /* Work out how many nops in prev_nop_frag are needed by IP,
4174          ignoring hazards generated by the first prev_nop_frag_since
4175          instructions.  */
4176       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4177       gas_assert (nops <= prev_nop_frag_holds);
4178
4179       /* Enforce NOPS as a minimum.  */
4180       if (nops > prev_nop_frag_required)
4181         prev_nop_frag_required = nops;
4182
4183       if (prev_nop_frag_holds == prev_nop_frag_required)
4184         {
4185           /* Settle for the current number of nops.  Update the history
4186              accordingly (for the benefit of any future .set reorder code).  */
4187           prev_nop_frag = NULL;
4188           insert_into_history (prev_nop_frag_since,
4189                                prev_nop_frag_holds, NOP_INSN);
4190         }
4191       else
4192         {
4193           /* Allow this instruction to replace one of the nops that was
4194              tentatively added to prev_nop_frag.  */
4195           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4196           prev_nop_frag_holds--;
4197           prev_nop_frag_since++;
4198         }
4199     }
4200
4201   method = get_append_method (ip);
4202   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
4203
4204 #ifdef OBJ_ELF
4205   /* The value passed to dwarf2_emit_insn is the distance between
4206      the beginning of the current instruction and the address that
4207      should be recorded in the debug tables.  This is normally the
4208      current address.
4209
4210      For MIPS16/microMIPS debug info we want to use ISA-encoded
4211      addresses, so we use -1 for an address higher by one than the
4212      current one.
4213
4214      If the instruction produced is a branch that we will swap with
4215      the preceding instruction, then we add the displacement by which
4216      the branch will be moved backwards.  This is more appropriate
4217      and for MIPS16/microMIPS code also prevents a debugger from
4218      placing a breakpoint in the middle of the branch (and corrupting
4219      code if software breakpoints are used).  */
4220   dwarf2_emit_insn ((HAVE_CODE_COMPRESSION ? -1 : 0) + branch_disp);
4221 #endif
4222
4223   relax32 = (mips_relax_branch
4224              /* Don't try branch relaxation within .set nomacro, or within
4225                 .set noat if we use $at for PIC computations.  If it turns
4226                 out that the branch was out-of-range, we'll get an error.  */
4227              && !mips_opts.warn_about_macros
4228              && (mips_opts.at || mips_pic == NO_PIC)
4229              /* Don't relax BPOSGE32/64 as they have no complementing
4230                 branches.  */
4231              && !(ip->insn_mo->membership & (INSN_DSP64 | INSN_DSP)));
4232
4233   if (!HAVE_CODE_COMPRESSION
4234       && address_expr
4235       && relax32
4236       && *reloc_type == BFD_RELOC_16_PCREL_S2
4237       && delayed_branch_p (ip))
4238     {
4239       relaxed_branch = TRUE;
4240       add_relaxed_insn (ip, (relaxed_branch_length
4241                              (NULL, NULL,
4242                               uncond_branch_p (ip) ? -1
4243                               : branch_likely_p (ip) ? 1
4244                               : 0)), 4,
4245                         RELAX_BRANCH_ENCODE
4246                         (AT,
4247                          uncond_branch_p (ip),
4248                          branch_likely_p (ip),
4249                          pinfo & INSN_WRITE_GPR_31,
4250                          0),
4251                         address_expr->X_add_symbol,
4252                         address_expr->X_add_number);
4253       *reloc_type = BFD_RELOC_UNUSED;
4254     }
4255   else if (mips_opts.micromips
4256            && address_expr
4257            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4258                || *reloc_type > BFD_RELOC_UNUSED)
4259            && (delayed_branch_p (ip) || compact_branch_p (ip))
4260            /* Don't try branch relaxation when users specify
4261               16-bit/32-bit instructions.  */
4262            && !forced_insn_length)
4263     {
4264       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4265       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4266       int uncond = uncond_branch_p (ip) ? -1 : 0;
4267       int compact = compact_branch_p (ip);
4268       int al = pinfo & INSN_WRITE_GPR_31;
4269       int length32;
4270
4271       gas_assert (address_expr != NULL);
4272       gas_assert (!mips_relax.sequence);
4273
4274       relaxed_branch = TRUE;
4275       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4276       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4277                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
4278                                                 relax32, 0, 0),
4279                         address_expr->X_add_symbol,
4280                         address_expr->X_add_number);
4281       *reloc_type = BFD_RELOC_UNUSED;
4282     }
4283   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4284     {
4285       /* We need to set up a variant frag.  */
4286       gas_assert (address_expr != NULL);
4287       add_relaxed_insn (ip, 4, 0,
4288                         RELAX_MIPS16_ENCODE
4289                         (*reloc_type - BFD_RELOC_UNUSED,
4290                          forced_insn_length == 2, forced_insn_length == 4,
4291                          delayed_branch_p (&history[0]),
4292                          history[0].mips16_absolute_jump_p),
4293                         make_expr_symbol (address_expr), 0);
4294     }
4295   else if (mips_opts.mips16
4296            && ! ip->use_extend
4297            && *reloc_type != BFD_RELOC_MIPS16_JMP)
4298     {
4299       if (!delayed_branch_p (ip))
4300         /* Make sure there is enough room to swap this instruction with
4301            a following jump instruction.  */
4302         frag_grow (6);
4303       add_fixed_insn (ip);
4304     }
4305   else
4306     {
4307       if (mips_opts.mips16
4308           && mips_opts.noreorder
4309           && delayed_branch_p (&history[0]))
4310         as_warn (_("extended instruction in delay slot"));
4311
4312       if (mips_relax.sequence)
4313         {
4314           /* If we've reached the end of this frag, turn it into a variant
4315              frag and record the information for the instructions we've
4316              written so far.  */
4317           if (frag_room () < 4)
4318             relax_close_frag ();
4319           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4320         }
4321
4322       if (mips_relax.sequence != 2)
4323         {
4324           if (mips_macro_warning.first_insn_sizes[0] == 0)
4325             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4326           mips_macro_warning.sizes[0] += insn_length (ip);
4327           mips_macro_warning.insns[0]++;
4328         }
4329       if (mips_relax.sequence != 1)
4330         {
4331           if (mips_macro_warning.first_insn_sizes[1] == 0)
4332             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4333           mips_macro_warning.sizes[1] += insn_length (ip);
4334           mips_macro_warning.insns[1]++;
4335         }
4336
4337       if (mips_opts.mips16)
4338         {
4339           ip->fixed_p = 1;
4340           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4341         }
4342       add_fixed_insn (ip);
4343     }
4344
4345   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4346     {
4347       bfd_reloc_code_real_type final_type[3];
4348       reloc_howto_type *howto0;
4349       reloc_howto_type *howto;
4350       int i;
4351
4352       /* Perform any necessary conversion to microMIPS relocations
4353          and find out how many relocations there actually are.  */
4354       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4355         final_type[i] = micromips_map_reloc (reloc_type[i]);
4356
4357       /* In a compound relocation, it is the final (outermost)
4358          operator that determines the relocated field.  */
4359       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4360
4361       if (howto == NULL)
4362         {
4363           /* To reproduce this failure try assembling gas/testsuites/
4364              gas/mips/mips16-intermix.s with a mips-ecoff targeted
4365              assembler.  */
4366           as_bad (_("Unsupported MIPS relocation number %d"),
4367                   final_type[i - 1]);
4368           howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16);
4369         }
4370
4371       if (i > 1)
4372         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4373       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4374                                  bfd_get_reloc_size (howto),
4375                                  address_expr,
4376                                  howto0 && howto0->pc_relative,
4377                                  final_type[0]);
4378
4379       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4380       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
4381         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4382
4383       /* These relocations can have an addend that won't fit in
4384          4 octets for 64bit assembly.  */
4385       if (HAVE_64BIT_GPRS
4386           && ! howto->partial_inplace
4387           && (reloc_type[0] == BFD_RELOC_16
4388               || reloc_type[0] == BFD_RELOC_32
4389               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4390               || reloc_type[0] == BFD_RELOC_GPREL16
4391               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4392               || reloc_type[0] == BFD_RELOC_GPREL32
4393               || reloc_type[0] == BFD_RELOC_64
4394               || reloc_type[0] == BFD_RELOC_CTOR
4395               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4396               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4397               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4398               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4399               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4400               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4401               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4402               || hi16_reloc_p (reloc_type[0])
4403               || lo16_reloc_p (reloc_type[0])))
4404         ip->fixp[0]->fx_no_overflow = 1;
4405
4406       if (mips_relax.sequence)
4407         {
4408           if (mips_relax.first_fixup == 0)
4409             mips_relax.first_fixup = ip->fixp[0];
4410         }
4411       else if (reloc_needs_lo_p (*reloc_type))
4412         {
4413           struct mips_hi_fixup *hi_fixup;
4414
4415           /* Reuse the last entry if it already has a matching %lo.  */
4416           hi_fixup = mips_hi_fixup_list;
4417           if (hi_fixup == 0
4418               || !fixup_has_matching_lo_p (hi_fixup->fixp))
4419             {
4420               hi_fixup = ((struct mips_hi_fixup *)
4421                           xmalloc (sizeof (struct mips_hi_fixup)));
4422               hi_fixup->next = mips_hi_fixup_list;
4423               mips_hi_fixup_list = hi_fixup;
4424             }
4425           hi_fixup->fixp = ip->fixp[0];
4426           hi_fixup->seg = now_seg;
4427         }
4428
4429       /* Add fixups for the second and third relocations, if given.
4430          Note that the ABI allows the second relocation to be
4431          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
4432          moment we only use RSS_UNDEF, but we could add support
4433          for the others if it ever becomes necessary.  */
4434       for (i = 1; i < 3; i++)
4435         if (reloc_type[i] != BFD_RELOC_UNUSED)
4436           {
4437             ip->fixp[i] = fix_new (ip->frag, ip->where,
4438                                    ip->fixp[0]->fx_size, NULL, 0,
4439                                    FALSE, final_type[i]);
4440
4441             /* Use fx_tcbit to mark compound relocs.  */
4442             ip->fixp[0]->fx_tcbit = 1;
4443             ip->fixp[i]->fx_tcbit = 1;
4444           }
4445     }
4446   install_insn (ip);
4447
4448   /* Update the register mask information.  */
4449   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
4450   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
4451
4452   switch (method)
4453     {
4454     case APPEND_ADD:
4455       insert_into_history (0, 1, ip);
4456       break;
4457
4458     case APPEND_ADD_WITH_NOP:
4459       {
4460         struct mips_cl_insn *nop;
4461
4462         insert_into_history (0, 1, ip);
4463         nop = get_delay_slot_nop (ip);
4464         add_fixed_insn (nop);
4465         insert_into_history (0, 1, nop);
4466         if (mips_relax.sequence)
4467           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
4468       }
4469       break;
4470
4471     case APPEND_ADD_COMPACT:
4472       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
4473       gas_assert (mips_opts.mips16);
4474       ip->insn_opcode |= 0x0080;
4475       find_altered_mips16_opcode (ip);
4476       install_insn (ip);
4477       insert_into_history (0, 1, ip);
4478       break;
4479
4480     case APPEND_SWAP:
4481       {
4482         struct mips_cl_insn delay = history[0];
4483         if (mips_opts.mips16)
4484           {
4485             know (delay.frag == ip->frag);
4486             move_insn (ip, delay.frag, delay.where);
4487             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
4488           }
4489         else if (relaxed_branch)
4490           {
4491             /* Add the delay slot instruction to the end of the
4492                current frag and shrink the fixed part of the
4493                original frag.  If the branch occupies the tail of
4494                the latter, move it backwards to cover the gap.  */
4495             delay.frag->fr_fix -= branch_disp;
4496             if (delay.frag == ip->frag)
4497               move_insn (ip, ip->frag, ip->where - branch_disp);
4498             add_fixed_insn (&delay);
4499           }
4500         else
4501           {
4502             move_insn (&delay, ip->frag,
4503                        ip->where - branch_disp + insn_length (ip));
4504             move_insn (ip, history[0].frag, history[0].where);
4505           }
4506         history[0] = *ip;
4507         delay.fixed_p = 1;
4508         insert_into_history (0, 1, &delay);
4509       }
4510       break;
4511     }
4512
4513   /* If we have just completed an unconditional branch, clear the history.  */
4514   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
4515       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
4516     mips_no_prev_insn ();
4517
4518   /* We need to emit a label at the end of branch-likely macros.  */
4519   if (emit_branch_likely_macro)
4520     {
4521       emit_branch_likely_macro = FALSE;
4522       micromips_add_label ();
4523     }
4524
4525   /* We just output an insn, so the next one doesn't have a label.  */
4526   mips_clear_insn_labels ();
4527 }
4528
4529 /* Forget that there was any previous instruction or label.  */
4530
4531 static void
4532 mips_no_prev_insn (void)
4533 {
4534   prev_nop_frag = NULL;
4535   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
4536   mips_clear_insn_labels ();
4537 }
4538
4539 /* This function must be called before we emit something other than
4540    instructions.  It is like mips_no_prev_insn except that it inserts
4541    any NOPS that might be needed by previous instructions.  */
4542
4543 void
4544 mips_emit_delays (void)
4545 {
4546   if (! mips_opts.noreorder)
4547     {
4548       int nops = nops_for_insn (0, history, NULL);
4549       if (nops > 0)
4550         {
4551           while (nops-- > 0)
4552             add_fixed_insn (NOP_INSN);
4553           mips_move_text_labels ();
4554         }
4555     }
4556   mips_no_prev_insn ();
4557 }
4558
4559 /* Start a (possibly nested) noreorder block.  */
4560
4561 static void
4562 start_noreorder (void)
4563 {
4564   if (mips_opts.noreorder == 0)
4565     {
4566       unsigned int i;
4567       int nops;
4568
4569       /* None of the instructions before the .set noreorder can be moved.  */
4570       for (i = 0; i < ARRAY_SIZE (history); i++)
4571         history[i].fixed_p = 1;
4572
4573       /* Insert any nops that might be needed between the .set noreorder
4574          block and the previous instructions.  We will later remove any
4575          nops that turn out not to be needed.  */
4576       nops = nops_for_insn (0, history, NULL);
4577       if (nops > 0)
4578         {
4579           if (mips_optimize != 0)
4580             {
4581               /* Record the frag which holds the nop instructions, so
4582                  that we can remove them if we don't need them.  */
4583               frag_grow (nops * NOP_INSN_SIZE);
4584               prev_nop_frag = frag_now;
4585               prev_nop_frag_holds = nops;
4586               prev_nop_frag_required = 0;
4587               prev_nop_frag_since = 0;
4588             }
4589
4590           for (; nops > 0; --nops)
4591             add_fixed_insn (NOP_INSN);
4592
4593           /* Move on to a new frag, so that it is safe to simply
4594              decrease the size of prev_nop_frag.  */
4595           frag_wane (frag_now);
4596           frag_new (0);
4597           mips_move_text_labels ();
4598         }
4599       mips_mark_labels ();
4600       mips_clear_insn_labels ();
4601     }
4602   mips_opts.noreorder++;
4603   mips_any_noreorder = 1;
4604 }
4605
4606 /* End a nested noreorder block.  */
4607
4608 static void
4609 end_noreorder (void)
4610 {
4611   mips_opts.noreorder--;
4612   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
4613     {
4614       /* Commit to inserting prev_nop_frag_required nops and go back to
4615          handling nop insertion the .set reorder way.  */
4616       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
4617                                 * NOP_INSN_SIZE);
4618       insert_into_history (prev_nop_frag_since,
4619                            prev_nop_frag_required, NOP_INSN);
4620       prev_nop_frag = NULL;
4621     }
4622 }
4623
4624 /* Set up global variables for the start of a new macro.  */
4625
4626 static void
4627 macro_start (void)
4628 {
4629   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
4630   memset (&mips_macro_warning.first_insn_sizes, 0,
4631           sizeof (mips_macro_warning.first_insn_sizes));
4632   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
4633   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
4634                                      && delayed_branch_p (&history[0]));
4635   switch (history[0].insn_mo->pinfo2
4636           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
4637     {
4638     case INSN2_BRANCH_DELAY_32BIT:
4639       mips_macro_warning.delay_slot_length = 4;
4640       break;
4641     case INSN2_BRANCH_DELAY_16BIT:
4642       mips_macro_warning.delay_slot_length = 2;
4643       break;
4644     default:
4645       mips_macro_warning.delay_slot_length = 0;
4646       break;
4647     }
4648   mips_macro_warning.first_frag = NULL;
4649 }
4650
4651 /* Given that a macro is longer than one instruction or of the wrong size,
4652    return the appropriate warning for it.  Return null if no warning is
4653    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
4654    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
4655    and RELAX_NOMACRO.  */
4656
4657 static const char *
4658 macro_warning (relax_substateT subtype)
4659 {
4660   if (subtype & RELAX_DELAY_SLOT)
4661     return _("Macro instruction expanded into multiple instructions"
4662              " in a branch delay slot");
4663   else if (subtype & RELAX_NOMACRO)
4664     return _("Macro instruction expanded into multiple instructions");
4665   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
4666                       | RELAX_DELAY_SLOT_SIZE_SECOND))
4667     return ((subtype & RELAX_DELAY_SLOT_16BIT)
4668             ? _("Macro instruction expanded into a wrong size instruction"
4669                 " in a 16-bit branch delay slot")
4670             : _("Macro instruction expanded into a wrong size instruction"
4671                 " in a 32-bit branch delay slot"));
4672   else
4673     return 0;
4674 }
4675
4676 /* Finish up a macro.  Emit warnings as appropriate.  */
4677
4678 static void
4679 macro_end (void)
4680 {
4681   /* Relaxation warning flags.  */
4682   relax_substateT subtype = 0;
4683
4684   /* Check delay slot size requirements.  */
4685   if (mips_macro_warning.delay_slot_length == 2)
4686     subtype |= RELAX_DELAY_SLOT_16BIT;
4687   if (mips_macro_warning.delay_slot_length != 0)
4688     {
4689       if (mips_macro_warning.delay_slot_length
4690           != mips_macro_warning.first_insn_sizes[0])
4691         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
4692       if (mips_macro_warning.delay_slot_length
4693           != mips_macro_warning.first_insn_sizes[1])
4694         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
4695     }
4696
4697   /* Check instruction count requirements.  */
4698   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
4699     {
4700       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
4701         subtype |= RELAX_SECOND_LONGER;
4702       if (mips_opts.warn_about_macros)
4703         subtype |= RELAX_NOMACRO;
4704       if (mips_macro_warning.delay_slot_p)
4705         subtype |= RELAX_DELAY_SLOT;
4706     }
4707
4708   /* If both alternatives fail to fill a delay slot correctly,
4709      emit the warning now.  */
4710   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
4711       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
4712     {
4713       relax_substateT s;
4714       const char *msg;
4715
4716       s = subtype & (RELAX_DELAY_SLOT_16BIT
4717                      | RELAX_DELAY_SLOT_SIZE_FIRST
4718                      | RELAX_DELAY_SLOT_SIZE_SECOND);
4719       msg = macro_warning (s);
4720       if (msg != NULL)
4721         as_warn ("%s", msg);
4722       subtype &= ~s;
4723     }
4724
4725   /* If both implementations are longer than 1 instruction, then emit the
4726      warning now.  */
4727   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
4728     {
4729       relax_substateT s;
4730       const char *msg;
4731
4732       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
4733       msg = macro_warning (s);
4734       if (msg != NULL)
4735         as_warn ("%s", msg);
4736       subtype &= ~s;
4737     }
4738
4739   /* If any flags still set, then one implementation might need a warning
4740      and the other either will need one of a different kind or none at all.
4741      Pass any remaining flags over to relaxation.  */
4742   if (mips_macro_warning.first_frag != NULL)
4743     mips_macro_warning.first_frag->fr_subtype |= subtype;
4744 }
4745
4746 /* Instruction operand formats used in macros that vary between
4747    standard MIPS and microMIPS code.  */
4748
4749 static const char * const brk_fmt[2] = { "c", "mF" };
4750 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
4751 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
4752 static const char * const lui_fmt[2] = { "t,u", "s,u" };
4753 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
4754 static const char * const mfhl_fmt[2] = { "d", "mj" };
4755 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
4756 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
4757
4758 #define BRK_FMT (brk_fmt[mips_opts.micromips])
4759 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
4760 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
4761 #define LUI_FMT (lui_fmt[mips_opts.micromips])
4762 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
4763 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips])
4764 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
4765 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
4766
4767 /* Read a macro's relocation codes from *ARGS and store them in *R.
4768    The first argument in *ARGS will be either the code for a single
4769    relocation or -1 followed by the three codes that make up a
4770    composite relocation.  */
4771
4772 static void
4773 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
4774 {
4775   int i, next;
4776
4777   next = va_arg (*args, int);
4778   if (next >= 0)
4779     r[0] = (bfd_reloc_code_real_type) next;
4780   else
4781     for (i = 0; i < 3; i++)
4782       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
4783 }
4784
4785 /* Build an instruction created by a macro expansion.  This is passed
4786    a pointer to the count of instructions created so far, an
4787    expression, the name of the instruction to build, an operand format
4788    string, and corresponding arguments.  */
4789
4790 static void
4791 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
4792 {
4793   const struct mips_opcode *mo = NULL;
4794   bfd_reloc_code_real_type r[3];
4795   const struct mips_opcode *amo;
4796   struct hash_control *hash;
4797   struct mips_cl_insn insn;
4798   va_list args;
4799
4800   va_start (args, fmt);
4801
4802   if (mips_opts.mips16)
4803     {
4804       mips16_macro_build (ep, name, fmt, &args);
4805       va_end (args);
4806       return;
4807     }
4808
4809   r[0] = BFD_RELOC_UNUSED;
4810   r[1] = BFD_RELOC_UNUSED;
4811   r[2] = BFD_RELOC_UNUSED;
4812   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
4813   amo = (struct mips_opcode *) hash_find (hash, name);
4814   gas_assert (amo);
4815   gas_assert (strcmp (name, amo->name) == 0);
4816
4817   do
4818     {
4819       /* Search until we get a match for NAME.  It is assumed here that
4820          macros will never generate MDMX, MIPS-3D, or MT instructions.
4821          We try to match an instruction that fulfils the branch delay
4822          slot instruction length requirement (if any) of the previous
4823          instruction.  While doing this we record the first instruction
4824          seen that matches all the other conditions and use it anyway
4825          if the requirement cannot be met; we will issue an appropriate
4826          warning later on.  */
4827       if (strcmp (fmt, amo->args) == 0
4828           && amo->pinfo != INSN_MACRO
4829           && is_opcode_valid (amo)
4830           && is_size_valid (amo))
4831         {
4832           if (is_delay_slot_valid (amo))
4833             {
4834               mo = amo;
4835               break;
4836             }
4837           else if (!mo)
4838             mo = amo;
4839         }
4840
4841       ++amo;
4842       gas_assert (amo->name);
4843     }
4844   while (strcmp (name, amo->name) == 0);
4845
4846   gas_assert (mo);
4847   create_insn (&insn, mo);
4848   for (;;)
4849     {
4850       switch (*fmt++)
4851         {
4852         case '\0':
4853           break;
4854
4855         case ',':
4856         case '(':
4857         case ')':
4858           continue;
4859
4860         case '+':
4861           switch (*fmt++)
4862             {
4863             case 'A':
4864             case 'E':
4865               INSERT_OPERAND (mips_opts.micromips,
4866                               EXTLSB, insn, va_arg (args, int));
4867               continue;
4868
4869             case 'B':
4870             case 'F':
4871               /* Note that in the macro case, these arguments are already
4872                  in MSB form.  (When handling the instruction in the
4873                  non-macro case, these arguments are sizes from which
4874                  MSB values must be calculated.)  */
4875               INSERT_OPERAND (mips_opts.micromips,
4876                               INSMSB, insn, va_arg (args, int));
4877               continue;
4878
4879             case 'C':
4880             case 'G':
4881             case 'H':
4882               /* Note that in the macro case, these arguments are already
4883                  in MSBD form.  (When handling the instruction in the
4884                  non-macro case, these arguments are sizes from which
4885                  MSBD values must be calculated.)  */
4886               INSERT_OPERAND (mips_opts.micromips,
4887                               EXTMSBD, insn, va_arg (args, int));
4888               continue;
4889
4890             case 'Q':
4891               gas_assert (!mips_opts.micromips);
4892               INSERT_OPERAND (0, SEQI, insn, va_arg (args, int));
4893               continue;
4894
4895             default:
4896               internalError ();
4897             }
4898           continue;
4899
4900         case '2':
4901           gas_assert (!mips_opts.micromips);
4902           INSERT_OPERAND (0, BP, insn, va_arg (args, int));
4903           continue;
4904
4905         case 'n':
4906           gas_assert (mips_opts.micromips);
4907         case 't':
4908         case 'w':
4909         case 'E':
4910           INSERT_OPERAND (mips_opts.micromips, RT, insn, va_arg (args, int));
4911           continue;
4912
4913         case 'c':
4914           gas_assert (!mips_opts.micromips);
4915           INSERT_OPERAND (0, CODE, insn, va_arg (args, int));
4916           continue;
4917
4918         case 'W':
4919           gas_assert (!mips_opts.micromips);
4920         case 'T':
4921           INSERT_OPERAND (mips_opts.micromips, FT, insn, va_arg (args, int));
4922           continue;
4923
4924         case 'G':
4925           if (mips_opts.micromips)
4926             INSERT_OPERAND (1, RS, insn, va_arg (args, int));
4927           else
4928             INSERT_OPERAND (0, RD, insn, va_arg (args, int));
4929           continue;
4930
4931         case 'K':
4932           gas_assert (!mips_opts.micromips);
4933         case 'd':
4934           INSERT_OPERAND (mips_opts.micromips, RD, insn, va_arg (args, int));
4935           continue;
4936
4937         case 'U':
4938           gas_assert (!mips_opts.micromips);
4939           {
4940             int tmp = va_arg (args, int);
4941
4942             INSERT_OPERAND (0, RT, insn, tmp);
4943             INSERT_OPERAND (0, RD, insn, tmp);
4944           }
4945           continue;
4946
4947         case 'V':
4948         case 'S':
4949           gas_assert (!mips_opts.micromips);
4950           INSERT_OPERAND (0, FS, insn, va_arg (args, int));
4951           continue;
4952
4953         case 'z':
4954           continue;
4955
4956         case '<':
4957           INSERT_OPERAND (mips_opts.micromips,
4958                           SHAMT, insn, va_arg (args, int));
4959           continue;
4960
4961         case 'D':
4962           gas_assert (!mips_opts.micromips);
4963           INSERT_OPERAND (0, FD, insn, va_arg (args, int));
4964           continue;
4965
4966         case 'B':
4967           gas_assert (!mips_opts.micromips);
4968           INSERT_OPERAND (0, CODE20, insn, va_arg (args, int));
4969           continue;
4970
4971         case 'J':
4972           gas_assert (!mips_opts.micromips);
4973           INSERT_OPERAND (0, CODE19, insn, va_arg (args, int));
4974           continue;
4975
4976         case 'q':
4977           gas_assert (!mips_opts.micromips);
4978           INSERT_OPERAND (0, CODE2, insn, va_arg (args, int));
4979           continue;
4980
4981         case 'b':
4982         case 's':
4983         case 'r':
4984         case 'v':
4985           INSERT_OPERAND (mips_opts.micromips, RS, insn, va_arg (args, int));
4986           continue;
4987
4988         case 'i':
4989         case 'j':
4990           macro_read_relocs (&args, r);
4991           gas_assert (*r == BFD_RELOC_GPREL16
4992                       || *r == BFD_RELOC_MIPS_HIGHER
4993                       || *r == BFD_RELOC_HI16_S
4994                       || *r == BFD_RELOC_LO16
4995                       || *r == BFD_RELOC_MIPS_GOT_OFST);
4996           continue;
4997
4998         case 'o':
4999           macro_read_relocs (&args, r);
5000           continue;
5001
5002         case 'u':
5003           macro_read_relocs (&args, r);
5004           gas_assert (ep != NULL
5005                       && (ep->X_op == O_constant
5006                           || (ep->X_op == O_symbol
5007                               && (*r == BFD_RELOC_MIPS_HIGHEST
5008                                   || *r == BFD_RELOC_HI16_S
5009                                   || *r == BFD_RELOC_HI16
5010                                   || *r == BFD_RELOC_GPREL16
5011                                   || *r == BFD_RELOC_MIPS_GOT_HI16
5012                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
5013           continue;
5014
5015         case 'p':
5016           gas_assert (ep != NULL);
5017
5018           /*
5019            * This allows macro() to pass an immediate expression for
5020            * creating short branches without creating a symbol.
5021            *
5022            * We don't allow branch relaxation for these branches, as
5023            * they should only appear in ".set nomacro" anyway.
5024            */
5025           if (ep->X_op == O_constant)
5026             {
5027               /* For microMIPS we always use relocations for branches.
5028                  So we should not resolve immediate values.  */
5029               gas_assert (!mips_opts.micromips);
5030
5031               if ((ep->X_add_number & 3) != 0)
5032                 as_bad (_("branch to misaligned address (0x%lx)"),
5033                         (unsigned long) ep->X_add_number);
5034               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5035                 as_bad (_("branch address range overflow (0x%lx)"),
5036                         (unsigned long) ep->X_add_number);
5037               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5038               ep = NULL;
5039             }
5040           else
5041             *r = BFD_RELOC_16_PCREL_S2;
5042           continue;
5043
5044         case 'a':
5045           gas_assert (ep != NULL);
5046           *r = BFD_RELOC_MIPS_JMP;
5047           continue;
5048
5049         case 'C':
5050           gas_assert (!mips_opts.micromips);
5051           INSERT_OPERAND (0, COPZ, insn, va_arg (args, unsigned long));
5052           continue;
5053
5054         case 'k':
5055           INSERT_OPERAND (mips_opts.micromips,
5056                           CACHE, insn, va_arg (args, unsigned long));
5057           continue;
5058
5059         case '|':
5060           gas_assert (mips_opts.micromips);
5061           INSERT_OPERAND (1, TRAP, insn, va_arg (args, int));
5062           continue;
5063
5064         case '.':
5065           gas_assert (mips_opts.micromips);
5066           INSERT_OPERAND (1, OFFSET10, insn, va_arg (args, int));
5067           continue;
5068
5069         case '\\':
5070           INSERT_OPERAND (mips_opts.micromips,
5071                           3BITPOS, insn, va_arg (args, unsigned int));
5072           continue;
5073
5074         case '~':
5075           INSERT_OPERAND (mips_opts.micromips,
5076                           OFFSET12, insn, va_arg (args, unsigned long));
5077           continue;
5078
5079         case 'N':
5080           gas_assert (mips_opts.micromips);
5081           INSERT_OPERAND (1, BCC, insn, va_arg (args, int));
5082           continue;
5083
5084         case 'm':       /* Opcode extension character.  */
5085           gas_assert (mips_opts.micromips);
5086           switch (*fmt++)
5087             {
5088             case 'j':
5089               INSERT_OPERAND (1, MJ, insn, va_arg (args, int));
5090               break;
5091
5092             case 'p':
5093               INSERT_OPERAND (1, MP, insn, va_arg (args, int));
5094               break;
5095
5096             case 'F':
5097               INSERT_OPERAND (1, IMMF, insn, va_arg (args, int));
5098               break;
5099
5100             default:
5101               internalError ();
5102             }
5103           continue;
5104
5105         default:
5106           internalError ();
5107         }
5108       break;
5109     }
5110   va_end (args);
5111   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5112
5113   append_insn (&insn, ep, r, TRUE);
5114 }
5115
5116 static void
5117 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5118                     va_list *args)
5119 {
5120   struct mips_opcode *mo;
5121   struct mips_cl_insn insn;
5122   bfd_reloc_code_real_type r[3]
5123     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5124
5125   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5126   gas_assert (mo);
5127   gas_assert (strcmp (name, mo->name) == 0);
5128
5129   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5130     {
5131       ++mo;
5132       gas_assert (mo->name);
5133       gas_assert (strcmp (name, mo->name) == 0);
5134     }
5135
5136   create_insn (&insn, mo);
5137   for (;;)
5138     {
5139       int c;
5140
5141       c = *fmt++;
5142       switch (c)
5143         {
5144         case '\0':
5145           break;
5146
5147         case ',':
5148         case '(':
5149         case ')':
5150           continue;
5151
5152         case 'y':
5153         case 'w':
5154           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
5155           continue;
5156
5157         case 'x':
5158         case 'v':
5159           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
5160           continue;
5161
5162         case 'z':
5163           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
5164           continue;
5165
5166         case 'Z':
5167           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
5168           continue;
5169
5170         case '0':
5171         case 'S':
5172         case 'P':
5173         case 'R':
5174           continue;
5175
5176         case 'X':
5177           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
5178           continue;
5179
5180         case 'Y':
5181           {
5182             int regno;
5183
5184             regno = va_arg (*args, int);
5185             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
5186             MIPS16_INSERT_OPERAND (REG32R, insn, regno);
5187           }
5188           continue;
5189
5190         case '<':
5191         case '>':
5192         case '4':
5193         case '5':
5194         case 'H':
5195         case 'W':
5196         case 'D':
5197         case 'j':
5198         case '8':
5199         case 'V':
5200         case 'C':
5201         case 'U':
5202         case 'k':
5203         case 'K':
5204         case 'p':
5205         case 'q':
5206           {
5207             gas_assert (ep != NULL);
5208
5209             if (ep->X_op != O_constant)
5210               *r = (int) BFD_RELOC_UNUSED + c;
5211             else
5212               {
5213                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
5214                               FALSE, &insn.insn_opcode, &insn.use_extend,
5215                               &insn.extend);
5216                 ep = NULL;
5217                 *r = BFD_RELOC_UNUSED;
5218               }
5219           }
5220           continue;
5221
5222         case '6':
5223           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
5224           continue;
5225         }
5226
5227       break;
5228     }
5229
5230   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5231
5232   append_insn (&insn, ep, r, TRUE);
5233 }
5234
5235 /*
5236  * Sign-extend 32-bit mode constants that have bit 31 set and all
5237  * higher bits unset.
5238  */
5239 static void
5240 normalize_constant_expr (expressionS *ex)
5241 {
5242   if (ex->X_op == O_constant
5243       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5244     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5245                         - 0x80000000);
5246 }
5247
5248 /*
5249  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5250  * all higher bits unset.
5251  */
5252 static void
5253 normalize_address_expr (expressionS *ex)
5254 {
5255   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5256         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5257       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5258     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5259                         - 0x80000000);
5260 }
5261
5262 /*
5263  * Generate a "jalr" instruction with a relocation hint to the called
5264  * function.  This occurs in NewABI PIC code.
5265  */
5266 static void
5267 macro_build_jalr (expressionS *ep, int cprestore)
5268 {
5269   static const bfd_reloc_code_real_type jalr_relocs[2]
5270     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5271   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5272   const char *jalr;
5273   char *f = NULL;
5274
5275   if (MIPS_JALR_HINT_P (ep))
5276     {
5277       frag_grow (8);
5278       f = frag_more (0);
5279     }
5280   if (mips_opts.micromips)
5281     {
5282       jalr = mips_opts.noreorder && !cprestore ? "jalr" : "jalrs";
5283       if (MIPS_JALR_HINT_P (ep))
5284         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5285       else
5286         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5287     }
5288   else
5289     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5290   if (MIPS_JALR_HINT_P (ep))
5291     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5292 }
5293
5294 /*
5295  * Generate a "lui" instruction.
5296  */
5297 static void
5298 macro_build_lui (expressionS *ep, int regnum)
5299 {
5300   gas_assert (! mips_opts.mips16);
5301
5302   if (ep->X_op != O_constant)
5303     {
5304       gas_assert (ep->X_op == O_symbol);
5305       /* _gp_disp is a special case, used from s_cpload.
5306          __gnu_local_gp is used if mips_no_shared.  */
5307       gas_assert (mips_pic == NO_PIC
5308               || (! HAVE_NEWABI
5309                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5310               || (! mips_in_shared
5311                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5312                              "__gnu_local_gp") == 0));
5313     }
5314
5315   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5316 }
5317
5318 /* Generate a sequence of instructions to do a load or store from a constant
5319    offset off of a base register (breg) into/from a target register (treg),
5320    using AT if necessary.  */
5321 static void
5322 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5323                               int treg, int breg, int dbl)
5324 {
5325   gas_assert (ep->X_op == O_constant);
5326
5327   /* Sign-extending 32-bit constants makes their handling easier.  */
5328   if (!dbl)
5329     normalize_constant_expr (ep);
5330
5331   /* Right now, this routine can only handle signed 32-bit constants.  */
5332   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5333     as_warn (_("operand overflow"));
5334
5335   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5336     {
5337       /* Signed 16-bit offset will fit in the op.  Easy!  */
5338       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5339     }
5340   else
5341     {
5342       /* 32-bit offset, need multiple instructions and AT, like:
5343            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5344            addu     $tempreg,$tempreg,$breg
5345            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5346          to handle the complete offset.  */
5347       macro_build_lui (ep, AT);
5348       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5349       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5350
5351       if (!mips_opts.at)
5352         as_bad (_("Macro used $at after \".set noat\""));
5353     }
5354 }
5355
5356 /*                      set_at()
5357  * Generates code to set the $at register to true (one)
5358  * if reg is less than the immediate expression.
5359  */
5360 static void
5361 set_at (int reg, int unsignedp)
5362 {
5363   if (imm_expr.X_op == O_constant
5364       && imm_expr.X_add_number >= -0x8000
5365       && imm_expr.X_add_number < 0x8000)
5366     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5367                  AT, reg, BFD_RELOC_LO16);
5368   else
5369     {
5370       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5371       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5372     }
5373 }
5374
5375 /* Warn if an expression is not a constant.  */
5376
5377 static void
5378 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5379 {
5380   if (ex->X_op == O_big)
5381     as_bad (_("unsupported large constant"));
5382   else if (ex->X_op != O_constant)
5383     as_bad (_("Instruction %s requires absolute expression"),
5384             ip->insn_mo->name);
5385
5386   if (HAVE_32BIT_GPRS)
5387     normalize_constant_expr (ex);
5388 }
5389
5390 /* Count the leading zeroes by performing a binary chop. This is a
5391    bulky bit of source, but performance is a LOT better for the
5392    majority of values than a simple loop to count the bits:
5393        for (lcnt = 0; (lcnt < 32); lcnt++)
5394          if ((v) & (1 << (31 - lcnt)))
5395            break;
5396   However it is not code size friendly, and the gain will drop a bit
5397   on certain cached systems.
5398 */
5399 #define COUNT_TOP_ZEROES(v)             \
5400   (((v) & ~0xffff) == 0                 \
5401    ? ((v) & ~0xff) == 0                 \
5402      ? ((v) & ~0xf) == 0                \
5403        ? ((v) & ~0x3) == 0              \
5404          ? ((v) & ~0x1) == 0            \
5405            ? !(v)                       \
5406              ? 32                       \
5407              : 31                       \
5408            : 30                         \
5409          : ((v) & ~0x7) == 0            \
5410            ? 29                         \
5411            : 28                         \
5412        : ((v) & ~0x3f) == 0             \
5413          ? ((v) & ~0x1f) == 0           \
5414            ? 27                         \
5415            : 26                         \
5416          : ((v) & ~0x7f) == 0           \
5417            ? 25                         \
5418            : 24                         \
5419      : ((v) & ~0xfff) == 0              \
5420        ? ((v) & ~0x3ff) == 0            \
5421          ? ((v) & ~0x1ff) == 0          \
5422            ? 23                         \
5423            : 22                         \
5424          : ((v) & ~0x7ff) == 0          \
5425            ? 21                         \
5426            : 20                         \
5427        : ((v) & ~0x3fff) == 0           \
5428          ? ((v) & ~0x1fff) == 0         \
5429            ? 19                         \
5430            : 18                         \
5431          : ((v) & ~0x7fff) == 0         \
5432            ? 17                         \
5433            : 16                         \
5434    : ((v) & ~0xffffff) == 0             \
5435      ? ((v) & ~0xfffff) == 0            \
5436        ? ((v) & ~0x3ffff) == 0          \
5437          ? ((v) & ~0x1ffff) == 0        \
5438            ? 15                         \
5439            : 14                         \
5440          : ((v) & ~0x7ffff) == 0        \
5441            ? 13                         \
5442            : 12                         \
5443        : ((v) & ~0x3fffff) == 0         \
5444          ? ((v) & ~0x1fffff) == 0       \
5445            ? 11                         \
5446            : 10                         \
5447          : ((v) & ~0x7fffff) == 0       \
5448            ? 9                          \
5449            : 8                          \
5450      : ((v) & ~0xfffffff) == 0          \
5451        ? ((v) & ~0x3ffffff) == 0        \
5452          ? ((v) & ~0x1ffffff) == 0      \
5453            ? 7                          \
5454            : 6                          \
5455          : ((v) & ~0x7ffffff) == 0      \
5456            ? 5                          \
5457            : 4                          \
5458        : ((v) & ~0x3fffffff) == 0       \
5459          ? ((v) & ~0x1fffffff) == 0     \
5460            ? 3                          \
5461            : 2                          \
5462          : ((v) & ~0x7fffffff) == 0     \
5463            ? 1                          \
5464            : 0)
5465
5466 /*                      load_register()
5467  *  This routine generates the least number of instructions necessary to load
5468  *  an absolute expression value into a register.
5469  */
5470 static void
5471 load_register (int reg, expressionS *ep, int dbl)
5472 {
5473   int freg;
5474   expressionS hi32, lo32;
5475
5476   if (ep->X_op != O_big)
5477     {
5478       gas_assert (ep->X_op == O_constant);
5479
5480       /* Sign-extending 32-bit constants makes their handling easier.  */
5481       if (!dbl)
5482         normalize_constant_expr (ep);
5483
5484       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
5485         {
5486           /* We can handle 16 bit signed values with an addiu to
5487              $zero.  No need to ever use daddiu here, since $zero and
5488              the result are always correct in 32 bit mode.  */
5489           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5490           return;
5491         }
5492       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
5493         {
5494           /* We can handle 16 bit unsigned values with an ori to
5495              $zero.  */
5496           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5497           return;
5498         }
5499       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
5500         {
5501           /* 32 bit values require an lui.  */
5502           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5503           if ((ep->X_add_number & 0xffff) != 0)
5504             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5505           return;
5506         }
5507     }
5508
5509   /* The value is larger than 32 bits.  */
5510
5511   if (!dbl || HAVE_32BIT_GPRS)
5512     {
5513       char value[32];
5514
5515       sprintf_vma (value, ep->X_add_number);
5516       as_bad (_("Number (0x%s) larger than 32 bits"), value);
5517       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5518       return;
5519     }
5520
5521   if (ep->X_op != O_big)
5522     {
5523       hi32 = *ep;
5524       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5525       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5526       hi32.X_add_number &= 0xffffffff;
5527       lo32 = *ep;
5528       lo32.X_add_number &= 0xffffffff;
5529     }
5530   else
5531     {
5532       gas_assert (ep->X_add_number > 2);
5533       if (ep->X_add_number == 3)
5534         generic_bignum[3] = 0;
5535       else if (ep->X_add_number > 4)
5536         as_bad (_("Number larger than 64 bits"));
5537       lo32.X_op = O_constant;
5538       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
5539       hi32.X_op = O_constant;
5540       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
5541     }
5542
5543   if (hi32.X_add_number == 0)
5544     freg = 0;
5545   else
5546     {
5547       int shift, bit;
5548       unsigned long hi, lo;
5549
5550       if (hi32.X_add_number == (offsetT) 0xffffffff)
5551         {
5552           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
5553             {
5554               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5555               return;
5556             }
5557           if (lo32.X_add_number & 0x80000000)
5558             {
5559               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5560               if (lo32.X_add_number & 0xffff)
5561                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5562               return;
5563             }
5564         }
5565
5566       /* Check for 16bit shifted constant.  We know that hi32 is
5567          non-zero, so start the mask on the first bit of the hi32
5568          value.  */
5569       shift = 17;
5570       do
5571         {
5572           unsigned long himask, lomask;
5573
5574           if (shift < 32)
5575             {
5576               himask = 0xffff >> (32 - shift);
5577               lomask = (0xffff << shift) & 0xffffffff;
5578             }
5579           else
5580             {
5581               himask = 0xffff << (shift - 32);
5582               lomask = 0;
5583             }
5584           if ((hi32.X_add_number & ~(offsetT) himask) == 0
5585               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
5586             {
5587               expressionS tmp;
5588
5589               tmp.X_op = O_constant;
5590               if (shift < 32)
5591                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
5592                                     | (lo32.X_add_number >> shift));
5593               else
5594                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
5595               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5596               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5597                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5598               return;
5599             }
5600           ++shift;
5601         }
5602       while (shift <= (64 - 16));
5603
5604       /* Find the bit number of the lowest one bit, and store the
5605          shifted value in hi/lo.  */
5606       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
5607       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
5608       if (lo != 0)
5609         {
5610           bit = 0;
5611           while ((lo & 1) == 0)
5612             {
5613               lo >>= 1;
5614               ++bit;
5615             }
5616           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
5617           hi >>= bit;
5618         }
5619       else
5620         {
5621           bit = 32;
5622           while ((hi & 1) == 0)
5623             {
5624               hi >>= 1;
5625               ++bit;
5626             }
5627           lo = hi;
5628           hi = 0;
5629         }
5630
5631       /* Optimize if the shifted value is a (power of 2) - 1.  */
5632       if ((hi == 0 && ((lo + 1) & lo) == 0)
5633           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
5634         {
5635           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
5636           if (shift != 0)
5637             {
5638               expressionS tmp;
5639
5640               /* This instruction will set the register to be all
5641                  ones.  */
5642               tmp.X_op = O_constant;
5643               tmp.X_add_number = (offsetT) -1;
5644               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5645               if (bit != 0)
5646                 {
5647                   bit += shift;
5648                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5649                                reg, reg, (bit >= 32) ? bit - 32 : bit);
5650                 }
5651               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
5652                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5653               return;
5654             }
5655         }
5656
5657       /* Sign extend hi32 before calling load_register, because we can
5658          generally get better code when we load a sign extended value.  */
5659       if ((hi32.X_add_number & 0x80000000) != 0)
5660         hi32.X_add_number |= ~(offsetT) 0xffffffff;
5661       load_register (reg, &hi32, 0);
5662       freg = reg;
5663     }
5664   if ((lo32.X_add_number & 0xffff0000) == 0)
5665     {
5666       if (freg != 0)
5667         {
5668           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
5669           freg = reg;
5670         }
5671     }
5672   else
5673     {
5674       expressionS mid16;
5675
5676       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
5677         {
5678           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5679           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
5680           return;
5681         }
5682
5683       if (freg != 0)
5684         {
5685           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
5686           freg = reg;
5687         }
5688       mid16 = lo32;
5689       mid16.X_add_number >>= 16;
5690       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5691       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5692       freg = reg;
5693     }
5694   if ((lo32.X_add_number & 0xffff) != 0)
5695     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5696 }
5697
5698 static inline void
5699 load_delay_nop (void)
5700 {
5701   if (!gpr_interlocks)
5702     macro_build (NULL, "nop", "");
5703 }
5704
5705 /* Load an address into a register.  */
5706
5707 static void
5708 load_address (int reg, expressionS *ep, int *used_at)
5709 {
5710   if (ep->X_op != O_constant
5711       && ep->X_op != O_symbol)
5712     {
5713       as_bad (_("expression too complex"));
5714       ep->X_op = O_constant;
5715     }
5716
5717   if (ep->X_op == O_constant)
5718     {
5719       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
5720       return;
5721     }
5722
5723   if (mips_pic == NO_PIC)
5724     {
5725       /* If this is a reference to a GP relative symbol, we want
5726            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
5727          Otherwise we want
5728            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
5729            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5730          If we have an addend, we always use the latter form.
5731
5732          With 64bit address space and a usable $at we want
5733            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5734            lui          $at,<sym>               (BFD_RELOC_HI16_S)
5735            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5736            daddiu       $at,<sym>               (BFD_RELOC_LO16)
5737            dsll32       $reg,0
5738            daddu        $reg,$reg,$at
5739
5740          If $at is already in use, we use a path which is suboptimal
5741          on superscalar processors.
5742            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5743            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5744            dsll         $reg,16
5745            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
5746            dsll         $reg,16
5747            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
5748
5749          For GP relative symbols in 64bit address space we can use
5750          the same sequence as in 32bit address space.  */
5751       if (HAVE_64BIT_SYMBOLS)
5752         {
5753           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5754               && !nopic_need_relax (ep->X_add_symbol, 1))
5755             {
5756               relax_start (ep->X_add_symbol);
5757               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5758                            mips_gp_register, BFD_RELOC_GPREL16);
5759               relax_switch ();
5760             }
5761
5762           if (*used_at == 0 && mips_opts.at)
5763             {
5764               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5765               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
5766               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5767                            BFD_RELOC_MIPS_HIGHER);
5768               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
5769               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
5770               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
5771               *used_at = 1;
5772             }
5773           else
5774             {
5775               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5776               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5777                            BFD_RELOC_MIPS_HIGHER);
5778               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5779               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
5780               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5781               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
5782             }
5783
5784           if (mips_relax.sequence)
5785             relax_end ();
5786         }
5787       else
5788         {
5789           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5790               && !nopic_need_relax (ep->X_add_symbol, 1))
5791             {
5792               relax_start (ep->X_add_symbol);
5793               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5794                            mips_gp_register, BFD_RELOC_GPREL16);
5795               relax_switch ();
5796             }
5797           macro_build_lui (ep, reg);
5798           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
5799                        reg, reg, BFD_RELOC_LO16);
5800           if (mips_relax.sequence)
5801             relax_end ();
5802         }
5803     }
5804   else if (!mips_big_got)
5805     {
5806       expressionS ex;
5807
5808       /* If this is a reference to an external symbol, we want
5809            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5810          Otherwise we want
5811            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5812            nop
5813            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5814          If there is a constant, it must be added in after.
5815
5816          If we have NewABI, we want
5817            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5818          unless we're referencing a global symbol with a non-zero
5819          offset, in which case cst must be added separately.  */
5820       if (HAVE_NEWABI)
5821         {
5822           if (ep->X_add_number)
5823             {
5824               ex.X_add_number = ep->X_add_number;
5825               ep->X_add_number = 0;
5826               relax_start (ep->X_add_symbol);
5827               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5828                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5829               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5830                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5831               ex.X_op = O_constant;
5832               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5833                            reg, reg, BFD_RELOC_LO16);
5834               ep->X_add_number = ex.X_add_number;
5835               relax_switch ();
5836             }
5837           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5838                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5839           if (mips_relax.sequence)
5840             relax_end ();
5841         }
5842       else
5843         {
5844           ex.X_add_number = ep->X_add_number;
5845           ep->X_add_number = 0;
5846           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5847                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5848           load_delay_nop ();
5849           relax_start (ep->X_add_symbol);
5850           relax_switch ();
5851           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5852                        BFD_RELOC_LO16);
5853           relax_end ();
5854
5855           if (ex.X_add_number != 0)
5856             {
5857               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5858                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5859               ex.X_op = O_constant;
5860               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5861                            reg, reg, BFD_RELOC_LO16);
5862             }
5863         }
5864     }
5865   else if (mips_big_got)
5866     {
5867       expressionS ex;
5868
5869       /* This is the large GOT case.  If this is a reference to an
5870          external symbol, we want
5871            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
5872            addu         $reg,$reg,$gp
5873            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
5874
5875          Otherwise, for a reference to a local symbol in old ABI, we want
5876            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5877            nop
5878            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5879          If there is a constant, it must be added in after.
5880
5881          In the NewABI, for local symbols, with or without offsets, we want:
5882            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
5883            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
5884       */
5885       if (HAVE_NEWABI)
5886         {
5887           ex.X_add_number = ep->X_add_number;
5888           ep->X_add_number = 0;
5889           relax_start (ep->X_add_symbol);
5890           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5891           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5892                        reg, reg, mips_gp_register);
5893           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5894                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5895           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5896             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5897           else if (ex.X_add_number)
5898             {
5899               ex.X_op = O_constant;
5900               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5901                            BFD_RELOC_LO16);
5902             }
5903
5904           ep->X_add_number = ex.X_add_number;
5905           relax_switch ();
5906           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5907                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
5908           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5909                        BFD_RELOC_MIPS_GOT_OFST);
5910           relax_end ();
5911         }
5912       else
5913         {
5914           ex.X_add_number = ep->X_add_number;
5915           ep->X_add_number = 0;
5916           relax_start (ep->X_add_symbol);
5917           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5918           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5919                        reg, reg, mips_gp_register);
5920           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5921                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5922           relax_switch ();
5923           if (reg_needs_delay (mips_gp_register))
5924             {
5925               /* We need a nop before loading from $gp.  This special
5926                  check is required because the lui which starts the main
5927                  instruction stream does not refer to $gp, and so will not
5928                  insert the nop which may be required.  */
5929               macro_build (NULL, "nop", "");
5930             }
5931           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5932                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5933           load_delay_nop ();
5934           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5935                        BFD_RELOC_LO16);
5936           relax_end ();
5937
5938           if (ex.X_add_number != 0)
5939             {
5940               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5941                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5942               ex.X_op = O_constant;
5943               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5944                            BFD_RELOC_LO16);
5945             }
5946         }
5947     }
5948   else
5949     abort ();
5950
5951   if (!mips_opts.at && *used_at == 1)
5952     as_bad (_("Macro used $at after \".set noat\""));
5953 }
5954
5955 /* Move the contents of register SOURCE into register DEST.  */
5956
5957 static void
5958 move_register (int dest, int source)
5959 {
5960   /* Prefer to use a 16-bit microMIPS instruction unless the previous
5961      instruction specifically requires a 32-bit one.  */
5962   if (mips_opts.micromips
5963       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5964     macro_build (NULL, "move", "mp,mj", dest, source);
5965   else
5966     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
5967                  dest, source, 0);
5968 }
5969
5970 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
5971    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
5972    The two alternatives are:
5973
5974    Global symbol                Local sybmol
5975    -------------                ------------
5976    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
5977    ...                          ...
5978    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
5979
5980    load_got_offset emits the first instruction and add_got_offset
5981    emits the second for a 16-bit offset or add_got_offset_hilo emits
5982    a sequence to add a 32-bit offset using a scratch register.  */
5983
5984 static void
5985 load_got_offset (int dest, expressionS *local)
5986 {
5987   expressionS global;
5988
5989   global = *local;
5990   global.X_add_number = 0;
5991
5992   relax_start (local->X_add_symbol);
5993   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5994                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5995   relax_switch ();
5996   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5997                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5998   relax_end ();
5999 }
6000
6001 static void
6002 add_got_offset (int dest, expressionS *local)
6003 {
6004   expressionS global;
6005
6006   global.X_op = O_constant;
6007   global.X_op_symbol = NULL;
6008   global.X_add_symbol = NULL;
6009   global.X_add_number = local->X_add_number;
6010
6011   relax_start (local->X_add_symbol);
6012   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
6013                dest, dest, BFD_RELOC_LO16);
6014   relax_switch ();
6015   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
6016   relax_end ();
6017 }
6018
6019 static void
6020 add_got_offset_hilo (int dest, expressionS *local, int tmp)
6021 {
6022   expressionS global;
6023   int hold_mips_optimize;
6024
6025   global.X_op = O_constant;
6026   global.X_op_symbol = NULL;
6027   global.X_add_symbol = NULL;
6028   global.X_add_number = local->X_add_number;
6029
6030   relax_start (local->X_add_symbol);
6031   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6032   relax_switch ();
6033   /* Set mips_optimize around the lui instruction to avoid
6034      inserting an unnecessary nop after the lw.  */
6035   hold_mips_optimize = mips_optimize;
6036   mips_optimize = 2;
6037   macro_build_lui (&global, tmp);
6038   mips_optimize = hold_mips_optimize;
6039   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6040   relax_end ();
6041
6042   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6043 }
6044
6045 /* Emit a sequence of instructions to emulate a branch likely operation.
6046    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6047    is its complementing branch with the original condition negated.
6048    CALL is set if the original branch specified the link operation.
6049    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6050
6051    Code like this is produced in the noreorder mode:
6052
6053         BRNEG   <args>, 1f
6054          nop
6055         b       <sym>
6056          delay slot (executed only if branch taken)
6057     1:
6058
6059    or, if CALL is set:
6060
6061         BRNEG   <args>, 1f
6062          nop
6063         bal     <sym>
6064          delay slot (executed only if branch taken)
6065     1:
6066
6067    In the reorder mode the delay slot would be filled with a nop anyway,
6068    so code produced is simply:
6069
6070         BR      <args>, <sym>
6071          nop
6072
6073    This function is used when producing code for the microMIPS ASE that
6074    does not implement branch likely instructions in hardware.  */
6075
6076 static void
6077 macro_build_branch_likely (const char *br, const char *brneg,
6078                            int call, expressionS *ep, const char *fmt,
6079                            unsigned int sreg, unsigned int treg)
6080 {
6081   int noreorder = mips_opts.noreorder;
6082   expressionS expr1;
6083
6084   gas_assert (mips_opts.micromips);
6085   start_noreorder ();
6086   if (noreorder)
6087     {
6088       micromips_label_expr (&expr1);
6089       macro_build (&expr1, brneg, fmt, sreg, treg);
6090       macro_build (NULL, "nop", "");
6091       macro_build (ep, call ? "bal" : "b", "p");
6092
6093       /* Set to true so that append_insn adds a label.  */
6094       emit_branch_likely_macro = TRUE;
6095     }
6096   else
6097     {
6098       macro_build (ep, br, fmt, sreg, treg);
6099       macro_build (NULL, "nop", "");
6100     }
6101   end_noreorder ();
6102 }
6103
6104 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6105    the condition code tested.  EP specifies the branch target.  */
6106
6107 static void
6108 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6109 {
6110   const int call = 0;
6111   const char *brneg;
6112   const char *br;
6113
6114   switch (type)
6115     {
6116     case M_BC1FL:
6117       br = "bc1f";
6118       brneg = "bc1t";
6119       break;
6120     case M_BC1TL:
6121       br = "bc1t";
6122       brneg = "bc1f";
6123       break;
6124     case M_BC2FL:
6125       br = "bc2f";
6126       brneg = "bc2t";
6127       break;
6128     case M_BC2TL:
6129       br = "bc2t";
6130       brneg = "bc2f";
6131       break;
6132     default:
6133       abort ();
6134     }
6135   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6136 }
6137
6138 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6139    the register tested.  EP specifies the branch target.  */
6140
6141 static void
6142 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6143 {
6144   const char *brneg = NULL;
6145   const char *br;
6146   int call = 0;
6147
6148   switch (type)
6149     {
6150     case M_BGEZ:
6151       br = "bgez";
6152       break;
6153     case M_BGEZL:
6154       br = mips_opts.micromips ? "bgez" : "bgezl";
6155       brneg = "bltz";
6156       break;
6157     case M_BGEZALL:
6158       gas_assert (mips_opts.micromips);
6159       br = "bgezals";
6160       brneg = "bltz";
6161       call = 1;
6162       break;
6163     case M_BGTZ:
6164       br = "bgtz";
6165       break;
6166     case M_BGTZL:
6167       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6168       brneg = "blez";
6169       break;
6170     case M_BLEZ:
6171       br = "blez";
6172       break;
6173     case M_BLEZL:
6174       br = mips_opts.micromips ? "blez" : "blezl";
6175       brneg = "bgtz";
6176       break;
6177     case M_BLTZ:
6178       br = "bltz";
6179       break;
6180     case M_BLTZL:
6181       br = mips_opts.micromips ? "bltz" : "bltzl";
6182       brneg = "bgez";
6183       break;
6184     case M_BLTZALL:
6185       gas_assert (mips_opts.micromips);
6186       br = "bltzals";
6187       brneg = "bgez";
6188       call = 1;
6189       break;
6190     default:
6191       abort ();
6192     }
6193   if (mips_opts.micromips && brneg)
6194     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6195   else
6196     macro_build (ep, br, "s,p", sreg);
6197 }
6198
6199 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6200    TREG as the registers tested.  EP specifies the branch target.  */
6201
6202 static void
6203 macro_build_branch_rsrt (int type, expressionS *ep,
6204                          unsigned int sreg, unsigned int treg)
6205 {
6206   const char *brneg = NULL;
6207   const int call = 0;
6208   const char *br;
6209
6210   switch (type)
6211     {
6212     case M_BEQ:
6213     case M_BEQ_I:
6214       br = "beq";
6215       break;
6216     case M_BEQL:
6217     case M_BEQL_I:
6218       br = mips_opts.micromips ? "beq" : "beql";
6219       brneg = "bne";
6220       break;
6221     case M_BNE:
6222     case M_BNE_I:
6223       br = "bne";
6224       break;
6225     case M_BNEL:
6226     case M_BNEL_I:
6227       br = mips_opts.micromips ? "bne" : "bnel";
6228       brneg = "beq";
6229       break;
6230     default:
6231       abort ();
6232     }
6233   if (mips_opts.micromips && brneg)
6234     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6235   else
6236     macro_build (ep, br, "s,t,p", sreg, treg);
6237 }
6238
6239 /*
6240  *                      Build macros
6241  *   This routine implements the seemingly endless macro or synthesized
6242  * instructions and addressing modes in the mips assembly language. Many
6243  * of these macros are simple and are similar to each other. These could
6244  * probably be handled by some kind of table or grammar approach instead of
6245  * this verbose method. Others are not simple macros but are more like
6246  * optimizing code generation.
6247  *   One interesting optimization is when several store macros appear
6248  * consecutively that would load AT with the upper half of the same address.
6249  * The ensuing load upper instructions are ommited. This implies some kind
6250  * of global optimization. We currently only optimize within a single macro.
6251  *   For many of the load and store macros if the address is specified as a
6252  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6253  * first load register 'at' with zero and use it as the base register. The
6254  * mips assembler simply uses register $zero. Just one tiny optimization
6255  * we're missing.
6256  */
6257 static void
6258 macro (struct mips_cl_insn *ip)
6259 {
6260   unsigned int treg, sreg, dreg, breg;
6261   unsigned int tempreg;
6262   int mask;
6263   int used_at = 0;
6264   expressionS label_expr;
6265   expressionS expr1;
6266   expressionS *ep;
6267   const char *s;
6268   const char *s2;
6269   const char *fmt;
6270   int likely = 0;
6271   int coproc = 0;
6272   int off12 = 0;
6273   int call = 0;
6274   int jals = 0;
6275   int dbl = 0;
6276   int imm = 0;
6277   int ust = 0;
6278   int lp = 0;
6279   int ab = 0;
6280   int off0 = 0;
6281   int off;
6282   offsetT maxnum;
6283   bfd_reloc_code_real_type r;
6284   int hold_mips_optimize;
6285
6286   gas_assert (! mips_opts.mips16);
6287
6288   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6289   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6290   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6291   mask = ip->insn_mo->mask;
6292
6293   label_expr.X_op = O_constant;
6294   label_expr.X_op_symbol = NULL;
6295   label_expr.X_add_symbol = NULL;
6296   label_expr.X_add_number = 0;
6297
6298   expr1.X_op = O_constant;
6299   expr1.X_op_symbol = NULL;
6300   expr1.X_add_symbol = NULL;
6301   expr1.X_add_number = 1;
6302
6303   switch (mask)
6304     {
6305     case M_DABS:
6306       dbl = 1;
6307     case M_ABS:
6308       /*    bgez    $a0,1f
6309             move    v0,$a0
6310             sub     v0,$zero,$a0
6311          1:
6312        */
6313
6314       start_noreorder ();
6315
6316       if (mips_opts.micromips)
6317         micromips_label_expr (&label_expr);
6318       else
6319         label_expr.X_add_number = 8;
6320       macro_build (&label_expr, "bgez", "s,p", sreg);
6321       if (dreg == sreg)
6322         macro_build (NULL, "nop", "");
6323       else
6324         move_register (dreg, sreg);
6325       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6326       if (mips_opts.micromips)
6327         micromips_add_label ();
6328
6329       end_noreorder ();
6330       break;
6331
6332     case M_ADD_I:
6333       s = "addi";
6334       s2 = "add";
6335       goto do_addi;
6336     case M_ADDU_I:
6337       s = "addiu";
6338       s2 = "addu";
6339       goto do_addi;
6340     case M_DADD_I:
6341       dbl = 1;
6342       s = "daddi";
6343       s2 = "dadd";
6344       if (!mips_opts.micromips)
6345         goto do_addi;
6346       if (imm_expr.X_op == O_constant
6347           && imm_expr.X_add_number >= -0x200
6348           && imm_expr.X_add_number < 0x200)
6349         {
6350           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
6351           break;
6352         }
6353       goto do_addi_i;
6354     case M_DADDU_I:
6355       dbl = 1;
6356       s = "daddiu";
6357       s2 = "daddu";
6358     do_addi:
6359       if (imm_expr.X_op == O_constant
6360           && imm_expr.X_add_number >= -0x8000
6361           && imm_expr.X_add_number < 0x8000)
6362         {
6363           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
6364           break;
6365         }
6366     do_addi_i:
6367       used_at = 1;
6368       load_register (AT, &imm_expr, dbl);
6369       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6370       break;
6371
6372     case M_AND_I:
6373       s = "andi";
6374       s2 = "and";
6375       goto do_bit;
6376     case M_OR_I:
6377       s = "ori";
6378       s2 = "or";
6379       goto do_bit;
6380     case M_NOR_I:
6381       s = "";
6382       s2 = "nor";
6383       goto do_bit;
6384     case M_XOR_I:
6385       s = "xori";
6386       s2 = "xor";
6387     do_bit:
6388       if (imm_expr.X_op == O_constant
6389           && imm_expr.X_add_number >= 0
6390           && imm_expr.X_add_number < 0x10000)
6391         {
6392           if (mask != M_NOR_I)
6393             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
6394           else
6395             {
6396               macro_build (&imm_expr, "ori", "t,r,i",
6397                            treg, sreg, BFD_RELOC_LO16);
6398               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
6399             }
6400           break;
6401         }
6402
6403       used_at = 1;
6404       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6405       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6406       break;
6407
6408     case M_BALIGN:
6409       switch (imm_expr.X_add_number)
6410         {
6411         case 0:
6412           macro_build (NULL, "nop", "");
6413           break;
6414         case 2:
6415           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
6416           break;
6417         default:
6418           macro_build (NULL, "balign", "t,s,2", treg, sreg,
6419                        (int) imm_expr.X_add_number);
6420           break;
6421         }
6422       break;
6423
6424     case M_BC1FL:
6425     case M_BC1TL:
6426     case M_BC2FL:
6427     case M_BC2TL:
6428       gas_assert (mips_opts.micromips);
6429       macro_build_branch_ccl (mask, &offset_expr,
6430                               EXTRACT_OPERAND (1, BCC, *ip));
6431       break;
6432
6433     case M_BEQ_I:
6434     case M_BEQL_I:
6435     case M_BNE_I:
6436     case M_BNEL_I:
6437       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6438         treg = 0;
6439       else
6440         {
6441           treg = AT;
6442           used_at = 1;
6443           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
6444         }
6445       /* Fall through.  */
6446     case M_BEQL:
6447     case M_BNEL:
6448       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
6449       break;
6450
6451     case M_BGEL:
6452       likely = 1;
6453     case M_BGE:
6454       if (treg == 0)
6455         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
6456       else if (sreg == 0)
6457         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
6458       else
6459         {
6460           used_at = 1;
6461           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6462           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6463                                    &offset_expr, AT, ZERO);
6464         }
6465       break;
6466
6467     case M_BGEZL:
6468     case M_BGEZALL:
6469     case M_BGTZL:
6470     case M_BLEZL:
6471     case M_BLTZL:
6472     case M_BLTZALL:
6473       macro_build_branch_rs (mask, &offset_expr, sreg);
6474       break;
6475
6476     case M_BGTL_I:
6477       likely = 1;
6478     case M_BGT_I:
6479       /* Check for > max integer.  */
6480       maxnum = 0x7fffffff;
6481       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6482         {
6483           maxnum <<= 16;
6484           maxnum |= 0xffff;
6485           maxnum <<= 16;
6486           maxnum |= 0xffff;
6487         }
6488       if (imm_expr.X_op == O_constant
6489           && imm_expr.X_add_number >= maxnum
6490           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6491         {
6492         do_false:
6493           /* Result is always false.  */
6494           if (! likely)
6495             macro_build (NULL, "nop", "");
6496           else
6497             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
6498           break;
6499         }
6500       if (imm_expr.X_op != O_constant)
6501         as_bad (_("Unsupported large constant"));
6502       ++imm_expr.X_add_number;
6503       /* FALLTHROUGH */
6504     case M_BGE_I:
6505     case M_BGEL_I:
6506       if (mask == M_BGEL_I)
6507         likely = 1;
6508       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6509         {
6510           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
6511                                  &offset_expr, sreg);
6512           break;
6513         }
6514       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6515         {
6516           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
6517                                  &offset_expr, sreg);
6518           break;
6519         }
6520       maxnum = 0x7fffffff;
6521       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6522         {
6523           maxnum <<= 16;
6524           maxnum |= 0xffff;
6525           maxnum <<= 16;
6526           maxnum |= 0xffff;
6527         }
6528       maxnum = - maxnum - 1;
6529       if (imm_expr.X_op == O_constant
6530           && imm_expr.X_add_number <= maxnum
6531           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6532         {
6533         do_true:
6534           /* result is always true */
6535           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
6536           macro_build (&offset_expr, "b", "p");
6537           break;
6538         }
6539       used_at = 1;
6540       set_at (sreg, 0);
6541       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6542                                &offset_expr, AT, ZERO);
6543       break;
6544
6545     case M_BGEUL:
6546       likely = 1;
6547     case M_BGEU:
6548       if (treg == 0)
6549         goto do_true;
6550       else if (sreg == 0)
6551         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6552                                  &offset_expr, ZERO, treg);
6553       else
6554         {
6555           used_at = 1;
6556           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6557           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6558                                    &offset_expr, AT, ZERO);
6559         }
6560       break;
6561
6562     case M_BGTUL_I:
6563       likely = 1;
6564     case M_BGTU_I:
6565       if (sreg == 0
6566           || (HAVE_32BIT_GPRS
6567               && imm_expr.X_op == O_constant
6568               && imm_expr.X_add_number == -1))
6569         goto do_false;
6570       if (imm_expr.X_op != O_constant)
6571         as_bad (_("Unsupported large constant"));
6572       ++imm_expr.X_add_number;
6573       /* FALLTHROUGH */
6574     case M_BGEU_I:
6575     case M_BGEUL_I:
6576       if (mask == M_BGEUL_I)
6577         likely = 1;
6578       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6579         goto do_true;
6580       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6581         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6582                                  &offset_expr, sreg, ZERO);
6583       else
6584         {
6585           used_at = 1;
6586           set_at (sreg, 1);
6587           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6588                                    &offset_expr, AT, ZERO);
6589         }
6590       break;
6591
6592     case M_BGTL:
6593       likely = 1;
6594     case M_BGT:
6595       if (treg == 0)
6596         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
6597       else if (sreg == 0)
6598         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
6599       else
6600         {
6601           used_at = 1;
6602           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6603           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6604                                    &offset_expr, AT, ZERO);
6605         }
6606       break;
6607
6608     case M_BGTUL:
6609       likely = 1;
6610     case M_BGTU:
6611       if (treg == 0)
6612         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6613                                  &offset_expr, sreg, ZERO);
6614       else if (sreg == 0)
6615         goto do_false;
6616       else
6617         {
6618           used_at = 1;
6619           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6620           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6621                                    &offset_expr, AT, ZERO);
6622         }
6623       break;
6624
6625     case M_BLEL:
6626       likely = 1;
6627     case M_BLE:
6628       if (treg == 0)
6629         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6630       else if (sreg == 0)
6631         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
6632       else
6633         {
6634           used_at = 1;
6635           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6636           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6637                                    &offset_expr, AT, ZERO);
6638         }
6639       break;
6640
6641     case M_BLEL_I:
6642       likely = 1;
6643     case M_BLE_I:
6644       maxnum = 0x7fffffff;
6645       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6646         {
6647           maxnum <<= 16;
6648           maxnum |= 0xffff;
6649           maxnum <<= 16;
6650           maxnum |= 0xffff;
6651         }
6652       if (imm_expr.X_op == O_constant
6653           && imm_expr.X_add_number >= maxnum
6654           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6655         goto do_true;
6656       if (imm_expr.X_op != O_constant)
6657         as_bad (_("Unsupported large constant"));
6658       ++imm_expr.X_add_number;
6659       /* FALLTHROUGH */
6660     case M_BLT_I:
6661     case M_BLTL_I:
6662       if (mask == M_BLTL_I)
6663         likely = 1;
6664       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6665         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6666       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6667         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6668       else
6669         {
6670           used_at = 1;
6671           set_at (sreg, 0);
6672           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6673                                    &offset_expr, AT, ZERO);
6674         }
6675       break;
6676
6677     case M_BLEUL:
6678       likely = 1;
6679     case M_BLEU:
6680       if (treg == 0)
6681         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6682                                  &offset_expr, sreg, ZERO);
6683       else if (sreg == 0)
6684         goto do_true;
6685       else
6686         {
6687           used_at = 1;
6688           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6689           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6690                                    &offset_expr, AT, ZERO);
6691         }
6692       break;
6693
6694     case M_BLEUL_I:
6695       likely = 1;
6696     case M_BLEU_I:
6697       if (sreg == 0
6698           || (HAVE_32BIT_GPRS
6699               && imm_expr.X_op == O_constant
6700               && imm_expr.X_add_number == -1))
6701         goto do_true;
6702       if (imm_expr.X_op != O_constant)
6703         as_bad (_("Unsupported large constant"));
6704       ++imm_expr.X_add_number;
6705       /* FALLTHROUGH */
6706     case M_BLTU_I:
6707     case M_BLTUL_I:
6708       if (mask == M_BLTUL_I)
6709         likely = 1;
6710       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6711         goto do_false;
6712       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6713         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6714                                  &offset_expr, sreg, ZERO);
6715       else
6716         {
6717           used_at = 1;
6718           set_at (sreg, 1);
6719           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6720                                    &offset_expr, AT, ZERO);
6721         }
6722       break;
6723
6724     case M_BLTL:
6725       likely = 1;
6726     case M_BLT:
6727       if (treg == 0)
6728         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6729       else if (sreg == 0)
6730         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
6731       else
6732         {
6733           used_at = 1;
6734           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6735           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6736                                    &offset_expr, AT, ZERO);
6737         }
6738       break;
6739
6740     case M_BLTUL:
6741       likely = 1;
6742     case M_BLTU:
6743       if (treg == 0)
6744         goto do_false;
6745       else if (sreg == 0)
6746         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6747                                  &offset_expr, ZERO, treg);
6748       else
6749         {
6750           used_at = 1;
6751           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6752           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6753                                    &offset_expr, AT, ZERO);
6754         }
6755       break;
6756
6757     case M_DEXT:
6758       {
6759         /* Use unsigned arithmetic.  */
6760         addressT pos;
6761         addressT size;
6762
6763         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6764           {
6765             as_bad (_("Unsupported large constant"));
6766             pos = size = 1;
6767           }
6768         else
6769           {
6770             pos = imm_expr.X_add_number;
6771             size = imm2_expr.X_add_number;
6772           }
6773
6774         if (pos > 63)
6775           {
6776             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6777             pos = 1;
6778           }
6779         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6780           {
6781             as_bad (_("Improper extract size (%lu, position %lu)"),
6782                     (unsigned long) size, (unsigned long) pos);
6783             size = 1;
6784           }
6785
6786         if (size <= 32 && pos < 32)
6787           {
6788             s = "dext";
6789             fmt = "t,r,+A,+C";
6790           }
6791         else if (size <= 32)
6792           {
6793             s = "dextu";
6794             fmt = "t,r,+E,+H";
6795           }
6796         else
6797           {
6798             s = "dextm";
6799             fmt = "t,r,+A,+G";
6800           }
6801         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6802                      (int) (size - 1));
6803       }
6804       break;
6805
6806     case M_DINS:
6807       {
6808         /* Use unsigned arithmetic.  */
6809         addressT pos;
6810         addressT size;
6811
6812         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6813           {
6814             as_bad (_("Unsupported large constant"));
6815             pos = size = 1;
6816           }
6817         else
6818           {
6819             pos = imm_expr.X_add_number;
6820             size = imm2_expr.X_add_number;
6821           }
6822
6823         if (pos > 63)
6824           {
6825             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6826             pos = 1;
6827           }
6828         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6829           {
6830             as_bad (_("Improper insert size (%lu, position %lu)"),
6831                     (unsigned long) size, (unsigned long) pos);
6832             size = 1;
6833           }
6834
6835         if (pos < 32 && (pos + size - 1) < 32)
6836           {
6837             s = "dins";
6838             fmt = "t,r,+A,+B";
6839           }
6840         else if (pos >= 32)
6841           {
6842             s = "dinsu";
6843             fmt = "t,r,+E,+F";
6844           }
6845         else
6846           {
6847             s = "dinsm";
6848             fmt = "t,r,+A,+F";
6849           }
6850         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6851                      (int) (pos + size - 1));
6852       }
6853       break;
6854
6855     case M_DDIV_3:
6856       dbl = 1;
6857     case M_DIV_3:
6858       s = "mflo";
6859       goto do_div3;
6860     case M_DREM_3:
6861       dbl = 1;
6862     case M_REM_3:
6863       s = "mfhi";
6864     do_div3:
6865       if (treg == 0)
6866         {
6867           as_warn (_("Divide by zero."));
6868           if (mips_trap)
6869             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6870           else
6871             macro_build (NULL, "break", BRK_FMT, 7);
6872           break;
6873         }
6874
6875       start_noreorder ();
6876       if (mips_trap)
6877         {
6878           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
6879           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6880         }
6881       else
6882         {
6883           if (mips_opts.micromips)
6884             micromips_label_expr (&label_expr);
6885           else
6886             label_expr.X_add_number = 8;
6887           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
6888           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6889           macro_build (NULL, "break", BRK_FMT, 7);
6890           if (mips_opts.micromips)
6891             micromips_add_label ();
6892         }
6893       expr1.X_add_number = -1;
6894       used_at = 1;
6895       load_register (AT, &expr1, dbl);
6896       if (mips_opts.micromips)
6897         micromips_label_expr (&label_expr);
6898       else
6899         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
6900       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
6901       if (dbl)
6902         {
6903           expr1.X_add_number = 1;
6904           load_register (AT, &expr1, dbl);
6905           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
6906         }
6907       else
6908         {
6909           expr1.X_add_number = 0x80000000;
6910           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
6911         }
6912       if (mips_trap)
6913         {
6914           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
6915           /* We want to close the noreorder block as soon as possible, so
6916              that later insns are available for delay slot filling.  */
6917           end_noreorder ();
6918         }
6919       else
6920         {
6921           if (mips_opts.micromips)
6922             micromips_label_expr (&label_expr);
6923           else
6924             label_expr.X_add_number = 8;
6925           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
6926           macro_build (NULL, "nop", "");
6927
6928           /* We want to close the noreorder block as soon as possible, so
6929              that later insns are available for delay slot filling.  */
6930           end_noreorder ();
6931
6932           macro_build (NULL, "break", BRK_FMT, 6);
6933         }
6934       if (mips_opts.micromips)
6935         micromips_add_label ();
6936       macro_build (NULL, s, MFHL_FMT, dreg);
6937       break;
6938
6939     case M_DIV_3I:
6940       s = "div";
6941       s2 = "mflo";
6942       goto do_divi;
6943     case M_DIVU_3I:
6944       s = "divu";
6945       s2 = "mflo";
6946       goto do_divi;
6947     case M_REM_3I:
6948       s = "div";
6949       s2 = "mfhi";
6950       goto do_divi;
6951     case M_REMU_3I:
6952       s = "divu";
6953       s2 = "mfhi";
6954       goto do_divi;
6955     case M_DDIV_3I:
6956       dbl = 1;
6957       s = "ddiv";
6958       s2 = "mflo";
6959       goto do_divi;
6960     case M_DDIVU_3I:
6961       dbl = 1;
6962       s = "ddivu";
6963       s2 = "mflo";
6964       goto do_divi;
6965     case M_DREM_3I:
6966       dbl = 1;
6967       s = "ddiv";
6968       s2 = "mfhi";
6969       goto do_divi;
6970     case M_DREMU_3I:
6971       dbl = 1;
6972       s = "ddivu";
6973       s2 = "mfhi";
6974     do_divi:
6975       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6976         {
6977           as_warn (_("Divide by zero."));
6978           if (mips_trap)
6979             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6980           else
6981             macro_build (NULL, "break", BRK_FMT, 7);
6982           break;
6983         }
6984       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6985         {
6986           if (strcmp (s2, "mflo") == 0)
6987             move_register (dreg, sreg);
6988           else
6989             move_register (dreg, ZERO);
6990           break;
6991         }
6992       if (imm_expr.X_op == O_constant
6993           && imm_expr.X_add_number == -1
6994           && s[strlen (s) - 1] != 'u')
6995         {
6996           if (strcmp (s2, "mflo") == 0)
6997             {
6998               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
6999             }
7000           else
7001             move_register (dreg, ZERO);
7002           break;
7003         }
7004
7005       used_at = 1;
7006       load_register (AT, &imm_expr, dbl);
7007       macro_build (NULL, s, "z,s,t", sreg, AT);
7008       macro_build (NULL, s2, MFHL_FMT, dreg);
7009       break;
7010
7011     case M_DIVU_3:
7012       s = "divu";
7013       s2 = "mflo";
7014       goto do_divu3;
7015     case M_REMU_3:
7016       s = "divu";
7017       s2 = "mfhi";
7018       goto do_divu3;
7019     case M_DDIVU_3:
7020       s = "ddivu";
7021       s2 = "mflo";
7022       goto do_divu3;
7023     case M_DREMU_3:
7024       s = "ddivu";
7025       s2 = "mfhi";
7026     do_divu3:
7027       start_noreorder ();
7028       if (mips_trap)
7029         {
7030           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7031           macro_build (NULL, s, "z,s,t", sreg, treg);
7032           /* We want to close the noreorder block as soon as possible, so
7033              that later insns are available for delay slot filling.  */
7034           end_noreorder ();
7035         }
7036       else
7037         {
7038           if (mips_opts.micromips)
7039             micromips_label_expr (&label_expr);
7040           else
7041             label_expr.X_add_number = 8;
7042           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7043           macro_build (NULL, s, "z,s,t", sreg, treg);
7044
7045           /* We want to close the noreorder block as soon as possible, so
7046              that later insns are available for delay slot filling.  */
7047           end_noreorder ();
7048           macro_build (NULL, "break", BRK_FMT, 7);
7049           if (mips_opts.micromips)
7050             micromips_add_label ();
7051         }
7052       macro_build (NULL, s2, MFHL_FMT, dreg);
7053       break;
7054
7055     case M_DLCA_AB:
7056       dbl = 1;
7057     case M_LCA_AB:
7058       call = 1;
7059       goto do_la;
7060     case M_DLA_AB:
7061       dbl = 1;
7062     case M_LA_AB:
7063     do_la:
7064       /* Load the address of a symbol into a register.  If breg is not
7065          zero, we then add a base register to it.  */
7066
7067       if (dbl && HAVE_32BIT_GPRS)
7068         as_warn (_("dla used to load 32-bit register"));
7069
7070       if (!dbl && HAVE_64BIT_OBJECTS)
7071         as_warn (_("la used to load 64-bit address"));
7072
7073       if (offset_expr.X_op == O_constant
7074           && offset_expr.X_add_number >= -0x8000
7075           && offset_expr.X_add_number < 0x8000)
7076         {
7077           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
7078                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
7079           break;
7080         }
7081
7082       if (mips_opts.at && (treg == breg))
7083         {
7084           tempreg = AT;
7085           used_at = 1;
7086         }
7087       else
7088         {
7089           tempreg = treg;
7090         }
7091
7092       if (offset_expr.X_op != O_symbol
7093           && offset_expr.X_op != O_constant)
7094         {
7095           as_bad (_("Expression too complex"));
7096           offset_expr.X_op = O_constant;
7097         }
7098
7099       if (offset_expr.X_op == O_constant)
7100         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7101       else if (mips_pic == NO_PIC)
7102         {
7103           /* If this is a reference to a GP relative symbol, we want
7104                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7105              Otherwise we want
7106                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7107                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7108              If we have a constant, we need two instructions anyhow,
7109              so we may as well always use the latter form.
7110
7111              With 64bit address space and a usable $at we want
7112                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7113                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7114                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7115                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7116                dsll32   $tempreg,0
7117                daddu    $tempreg,$tempreg,$at
7118
7119              If $at is already in use, we use a path which is suboptimal
7120              on superscalar processors.
7121                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7122                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7123                dsll     $tempreg,16
7124                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7125                dsll     $tempreg,16
7126                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7127
7128              For GP relative symbols in 64bit address space we can use
7129              the same sequence as in 32bit address space.  */
7130           if (HAVE_64BIT_SYMBOLS)
7131             {
7132               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7133                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7134                 {
7135                   relax_start (offset_expr.X_add_symbol);
7136                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7137                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7138                   relax_switch ();
7139                 }
7140
7141               if (used_at == 0 && mips_opts.at)
7142                 {
7143                   macro_build (&offset_expr, "lui", LUI_FMT,
7144                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7145                   macro_build (&offset_expr, "lui", LUI_FMT,
7146                                AT, BFD_RELOC_HI16_S);
7147                   macro_build (&offset_expr, "daddiu", "t,r,j",
7148                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7149                   macro_build (&offset_expr, "daddiu", "t,r,j",
7150                                AT, AT, BFD_RELOC_LO16);
7151                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7152                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7153                   used_at = 1;
7154                 }
7155               else
7156                 {
7157                   macro_build (&offset_expr, "lui", LUI_FMT,
7158                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7159                   macro_build (&offset_expr, "daddiu", "t,r,j",
7160                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7161                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7162                   macro_build (&offset_expr, "daddiu", "t,r,j",
7163                                tempreg, tempreg, BFD_RELOC_HI16_S);
7164                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7165                   macro_build (&offset_expr, "daddiu", "t,r,j",
7166                                tempreg, tempreg, BFD_RELOC_LO16);
7167                 }
7168
7169               if (mips_relax.sequence)
7170                 relax_end ();
7171             }
7172           else
7173             {
7174               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7175                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7176                 {
7177                   relax_start (offset_expr.X_add_symbol);
7178                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7179                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7180                   relax_switch ();
7181                 }
7182               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7183                 as_bad (_("Offset too large"));
7184               macro_build_lui (&offset_expr, tempreg);
7185               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7186                            tempreg, tempreg, BFD_RELOC_LO16);
7187               if (mips_relax.sequence)
7188                 relax_end ();
7189             }
7190         }
7191       else if (!mips_big_got && !HAVE_NEWABI)
7192         {
7193           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7194
7195           /* If this is a reference to an external symbol, and there
7196              is no constant, we want
7197                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7198              or for lca or if tempreg is PIC_CALL_REG
7199                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7200              For a local symbol, we want
7201                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7202                nop
7203                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7204
7205              If we have a small constant, and this is a reference to
7206              an external symbol, we want
7207                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7208                nop
7209                addiu    $tempreg,$tempreg,<constant>
7210              For a local symbol, we want the same instruction
7211              sequence, but we output a BFD_RELOC_LO16 reloc on the
7212              addiu instruction.
7213
7214              If we have a large constant, and this is a reference to
7215              an external symbol, we want
7216                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7217                lui      $at,<hiconstant>
7218                addiu    $at,$at,<loconstant>
7219                addu     $tempreg,$tempreg,$at
7220              For a local symbol, we want the same instruction
7221              sequence, but we output a BFD_RELOC_LO16 reloc on the
7222              addiu instruction.
7223            */
7224
7225           if (offset_expr.X_add_number == 0)
7226             {
7227               if (mips_pic == SVR4_PIC
7228                   && breg == 0
7229                   && (call || tempreg == PIC_CALL_REG))
7230                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7231
7232               relax_start (offset_expr.X_add_symbol);
7233               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7234                            lw_reloc_type, mips_gp_register);
7235               if (breg != 0)
7236                 {
7237                   /* We're going to put in an addu instruction using
7238                      tempreg, so we may as well insert the nop right
7239                      now.  */
7240                   load_delay_nop ();
7241                 }
7242               relax_switch ();
7243               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7244                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7245               load_delay_nop ();
7246               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7247                            tempreg, tempreg, BFD_RELOC_LO16);
7248               relax_end ();
7249               /* FIXME: If breg == 0, and the next instruction uses
7250                  $tempreg, then if this variant case is used an extra
7251                  nop will be generated.  */
7252             }
7253           else if (offset_expr.X_add_number >= -0x8000
7254                    && offset_expr.X_add_number < 0x8000)
7255             {
7256               load_got_offset (tempreg, &offset_expr);
7257               load_delay_nop ();
7258               add_got_offset (tempreg, &offset_expr);
7259             }
7260           else
7261             {
7262               expr1.X_add_number = offset_expr.X_add_number;
7263               offset_expr.X_add_number =
7264                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
7265               load_got_offset (tempreg, &offset_expr);
7266               offset_expr.X_add_number = expr1.X_add_number;
7267               /* If we are going to add in a base register, and the
7268                  target register and the base register are the same,
7269                  then we are using AT as a temporary register.  Since
7270                  we want to load the constant into AT, we add our
7271                  current AT (from the global offset table) and the
7272                  register into the register now, and pretend we were
7273                  not using a base register.  */
7274               if (breg == treg)
7275                 {
7276                   load_delay_nop ();
7277                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7278                                treg, AT, breg);
7279                   breg = 0;
7280                   tempreg = treg;
7281                 }
7282               add_got_offset_hilo (tempreg, &offset_expr, AT);
7283               used_at = 1;
7284             }
7285         }
7286       else if (!mips_big_got && HAVE_NEWABI)
7287         {
7288           int add_breg_early = 0;
7289
7290           /* If this is a reference to an external, and there is no
7291              constant, or local symbol (*), with or without a
7292              constant, we want
7293                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7294              or for lca or if tempreg is PIC_CALL_REG
7295                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7296
7297              If we have a small constant, and this is a reference to
7298              an external symbol, we want
7299                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7300                addiu    $tempreg,$tempreg,<constant>
7301
7302              If we have a large constant, and this is a reference to
7303              an external symbol, we want
7304                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7305                lui      $at,<hiconstant>
7306                addiu    $at,$at,<loconstant>
7307                addu     $tempreg,$tempreg,$at
7308
7309              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7310              local symbols, even though it introduces an additional
7311              instruction.  */
7312
7313           if (offset_expr.X_add_number)
7314             {
7315               expr1.X_add_number = offset_expr.X_add_number;
7316               offset_expr.X_add_number = 0;
7317
7318               relax_start (offset_expr.X_add_symbol);
7319               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7320                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7321
7322               if (expr1.X_add_number >= -0x8000
7323                   && expr1.X_add_number < 0x8000)
7324                 {
7325                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7326                                tempreg, tempreg, BFD_RELOC_LO16);
7327                 }
7328               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7329                 {
7330                   /* If we are going to add in a base register, and the
7331                      target register and the base register are the same,
7332                      then we are using AT as a temporary register.  Since
7333                      we want to load the constant into AT, we add our
7334                      current AT (from the global offset table) and the
7335                      register into the register now, and pretend we were
7336                      not using a base register.  */
7337                   if (breg != treg)
7338                     dreg = tempreg;
7339                   else
7340                     {
7341                       gas_assert (tempreg == AT);
7342                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7343                                    treg, AT, breg);
7344                       dreg = treg;
7345                       add_breg_early = 1;
7346                     }
7347
7348                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7349                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7350                                dreg, dreg, AT);
7351
7352                   used_at = 1;
7353                 }
7354               else
7355                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7356
7357               relax_switch ();
7358               offset_expr.X_add_number = expr1.X_add_number;
7359
7360               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7361                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7362               if (add_breg_early)
7363                 {
7364                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7365                                treg, tempreg, breg);
7366                   breg = 0;
7367                   tempreg = treg;
7368                 }
7369               relax_end ();
7370             }
7371           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7372             {
7373               relax_start (offset_expr.X_add_symbol);
7374               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7375                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7376               relax_switch ();
7377               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7378                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7379               relax_end ();
7380             }
7381           else
7382             {
7383               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7384                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7385             }
7386         }
7387       else if (mips_big_got && !HAVE_NEWABI)
7388         {
7389           int gpdelay;
7390           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7391           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7392           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7393
7394           /* This is the large GOT case.  If this is a reference to an
7395              external symbol, and there is no constant, we want
7396                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7397                addu     $tempreg,$tempreg,$gp
7398                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7399              or for lca or if tempreg is PIC_CALL_REG
7400                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7401                addu     $tempreg,$tempreg,$gp
7402                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7403              For a local symbol, we want
7404                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7405                nop
7406                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7407
7408              If we have a small constant, and this is a reference to
7409              an external symbol, we want
7410                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7411                addu     $tempreg,$tempreg,$gp
7412                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7413                nop
7414                addiu    $tempreg,$tempreg,<constant>
7415              For a local symbol, we want
7416                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7417                nop
7418                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
7419
7420              If we have a large constant, and this is a reference to
7421              an external symbol, we want
7422                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7423                addu     $tempreg,$tempreg,$gp
7424                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7425                lui      $at,<hiconstant>
7426                addiu    $at,$at,<loconstant>
7427                addu     $tempreg,$tempreg,$at
7428              For a local symbol, we want
7429                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7430                lui      $at,<hiconstant>
7431                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
7432                addu     $tempreg,$tempreg,$at
7433           */
7434
7435           expr1.X_add_number = offset_expr.X_add_number;
7436           offset_expr.X_add_number = 0;
7437           relax_start (offset_expr.X_add_symbol);
7438           gpdelay = reg_needs_delay (mips_gp_register);
7439           if (expr1.X_add_number == 0 && breg == 0
7440               && (call || tempreg == PIC_CALL_REG))
7441             {
7442               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7443               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7444             }
7445           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7446           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7447                        tempreg, tempreg, mips_gp_register);
7448           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7449                        tempreg, lw_reloc_type, tempreg);
7450           if (expr1.X_add_number == 0)
7451             {
7452               if (breg != 0)
7453                 {
7454                   /* We're going to put in an addu instruction using
7455                      tempreg, so we may as well insert the nop right
7456                      now.  */
7457                   load_delay_nop ();
7458                 }
7459             }
7460           else if (expr1.X_add_number >= -0x8000
7461                    && expr1.X_add_number < 0x8000)
7462             {
7463               load_delay_nop ();
7464               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7465                            tempreg, tempreg, BFD_RELOC_LO16);
7466             }
7467           else
7468             {
7469               /* If we are going to add in a base register, and the
7470                  target register and the base register are the same,
7471                  then we are using AT as a temporary register.  Since
7472                  we want to load the constant into AT, we add our
7473                  current AT (from the global offset table) and the
7474                  register into the register now, and pretend we were
7475                  not using a base register.  */
7476               if (breg != treg)
7477                 dreg = tempreg;
7478               else
7479                 {
7480                   gas_assert (tempreg == AT);
7481                   load_delay_nop ();
7482                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7483                                treg, AT, breg);
7484                   dreg = treg;
7485                 }
7486
7487               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7488               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7489
7490               used_at = 1;
7491             }
7492           offset_expr.X_add_number =
7493             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
7494           relax_switch ();
7495
7496           if (gpdelay)
7497             {
7498               /* This is needed because this instruction uses $gp, but
7499                  the first instruction on the main stream does not.  */
7500               macro_build (NULL, "nop", "");
7501             }
7502
7503           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7504                        local_reloc_type, mips_gp_register);
7505           if (expr1.X_add_number >= -0x8000
7506               && expr1.X_add_number < 0x8000)
7507             {
7508               load_delay_nop ();
7509               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7510                            tempreg, tempreg, BFD_RELOC_LO16);
7511               /* FIXME: If add_number is 0, and there was no base
7512                  register, the external symbol case ended with a load,
7513                  so if the symbol turns out to not be external, and
7514                  the next instruction uses tempreg, an unnecessary nop
7515                  will be inserted.  */
7516             }
7517           else
7518             {
7519               if (breg == treg)
7520                 {
7521                   /* We must add in the base register now, as in the
7522                      external symbol case.  */
7523                   gas_assert (tempreg == AT);
7524                   load_delay_nop ();
7525                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7526                                treg, AT, breg);
7527                   tempreg = treg;
7528                   /* We set breg to 0 because we have arranged to add
7529                      it in in both cases.  */
7530                   breg = 0;
7531                 }
7532
7533               macro_build_lui (&expr1, AT);
7534               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7535                            AT, AT, BFD_RELOC_LO16);
7536               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7537                            tempreg, tempreg, AT);
7538               used_at = 1;
7539             }
7540           relax_end ();
7541         }
7542       else if (mips_big_got && HAVE_NEWABI)
7543         {
7544           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7545           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7546           int add_breg_early = 0;
7547
7548           /* This is the large GOT case.  If this is a reference to an
7549              external symbol, and there is no constant, we want
7550                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7551                add      $tempreg,$tempreg,$gp
7552                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7553              or for lca or if tempreg is PIC_CALL_REG
7554                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7555                add      $tempreg,$tempreg,$gp
7556                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7557
7558              If we have a small constant, and this is a reference to
7559              an external symbol, we want
7560                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7561                add      $tempreg,$tempreg,$gp
7562                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7563                addi     $tempreg,$tempreg,<constant>
7564
7565              If we have a large constant, and this is a reference to
7566              an external symbol, we want
7567                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7568                addu     $tempreg,$tempreg,$gp
7569                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7570                lui      $at,<hiconstant>
7571                addi     $at,$at,<loconstant>
7572                add      $tempreg,$tempreg,$at
7573
7574              If we have NewABI, and we know it's a local symbol, we want
7575                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7576                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7577              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
7578
7579           relax_start (offset_expr.X_add_symbol);
7580
7581           expr1.X_add_number = offset_expr.X_add_number;
7582           offset_expr.X_add_number = 0;
7583
7584           if (expr1.X_add_number == 0 && breg == 0
7585               && (call || tempreg == PIC_CALL_REG))
7586             {
7587               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7588               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7589             }
7590           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7591           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7592                        tempreg, tempreg, mips_gp_register);
7593           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7594                        tempreg, lw_reloc_type, tempreg);
7595
7596           if (expr1.X_add_number == 0)
7597             ;
7598           else if (expr1.X_add_number >= -0x8000
7599                    && expr1.X_add_number < 0x8000)
7600             {
7601               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7602                            tempreg, tempreg, BFD_RELOC_LO16);
7603             }
7604           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7605             {
7606               /* If we are going to add in a base register, and the
7607                  target register and the base register are the same,
7608                  then we are using AT as a temporary register.  Since
7609                  we want to load the constant into AT, we add our
7610                  current AT (from the global offset table) and the
7611                  register into the register now, and pretend we were
7612                  not using a base register.  */
7613               if (breg != treg)
7614                 dreg = tempreg;
7615               else
7616                 {
7617                   gas_assert (tempreg == AT);
7618                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7619                                treg, AT, breg);
7620                   dreg = treg;
7621                   add_breg_early = 1;
7622                 }
7623
7624               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7625               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7626
7627               used_at = 1;
7628             }
7629           else
7630             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7631
7632           relax_switch ();
7633           offset_expr.X_add_number = expr1.X_add_number;
7634           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7635                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7636           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
7637                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
7638           if (add_breg_early)
7639             {
7640               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7641                            treg, tempreg, breg);
7642               breg = 0;
7643               tempreg = treg;
7644             }
7645           relax_end ();
7646         }
7647       else
7648         abort ();
7649
7650       if (breg != 0)
7651         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
7652       break;
7653
7654     case M_MSGSND:
7655       gas_assert (!mips_opts.micromips);
7656       {
7657         unsigned long temp = (treg << 16) | (0x01);
7658         macro_build (NULL, "c2", "C", temp);
7659       }
7660       break;
7661
7662     case M_MSGLD:
7663       gas_assert (!mips_opts.micromips);
7664       {
7665         unsigned long temp = (0x02);
7666         macro_build (NULL, "c2", "C", temp);
7667       }
7668       break;
7669
7670     case M_MSGLD_T:
7671       gas_assert (!mips_opts.micromips);
7672       {
7673         unsigned long temp = (treg << 16) | (0x02);
7674         macro_build (NULL, "c2", "C", temp);
7675       }
7676       break;
7677
7678     case M_MSGWAIT:
7679       gas_assert (!mips_opts.micromips);
7680       macro_build (NULL, "c2", "C", 3);
7681       break;
7682
7683     case M_MSGWAIT_T:
7684       gas_assert (!mips_opts.micromips);
7685       {
7686         unsigned long temp = (treg << 16) | 0x03;
7687         macro_build (NULL, "c2", "C", temp);
7688       }
7689       break;
7690
7691     case M_J_A:
7692       /* The j instruction may not be used in PIC code, since it
7693          requires an absolute address.  We convert it to a b
7694          instruction.  */
7695       if (mips_pic == NO_PIC)
7696         macro_build (&offset_expr, "j", "a");
7697       else
7698         macro_build (&offset_expr, "b", "p");
7699       break;
7700
7701       /* The jal instructions must be handled as macros because when
7702          generating PIC code they expand to multi-instruction
7703          sequences.  Normally they are simple instructions.  */
7704     case M_JALS_1:
7705       dreg = RA;
7706       /* Fall through.  */
7707     case M_JALS_2:
7708       gas_assert (mips_opts.micromips);
7709       jals = 1;
7710       goto jal;
7711     case M_JAL_1:
7712       dreg = RA;
7713       /* Fall through.  */
7714     case M_JAL_2:
7715     jal:
7716       if (mips_pic == NO_PIC)
7717         {
7718           s = jals ? "jalrs" : "jalr";
7719           if (mips_opts.micromips && dreg == RA)
7720             macro_build (NULL, s, "mj", sreg);
7721           else
7722             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7723         }
7724       else
7725         {
7726           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
7727                            && mips_cprestore_offset >= 0);
7728
7729           if (sreg != PIC_CALL_REG)
7730             as_warn (_("MIPS PIC call to register other than $25"));
7731
7732           s = (mips_opts.micromips && (!mips_opts.noreorder || cprestore)
7733                ? "jalrs" : "jalr");
7734           if (mips_opts.micromips && dreg == RA)
7735             macro_build (NULL, s, "mj", sreg);
7736           else
7737             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7738           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
7739             {
7740               if (mips_cprestore_offset < 0)
7741                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7742               else
7743                 {
7744                   if (!mips_frame_reg_valid)
7745                     {
7746                       as_warn (_("No .frame pseudo-op used in PIC code"));
7747                       /* Quiet this warning.  */
7748                       mips_frame_reg_valid = 1;
7749                     }
7750                   if (!mips_cprestore_valid)
7751                     {
7752                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7753                       /* Quiet this warning.  */
7754                       mips_cprestore_valid = 1;
7755                     }
7756                   if (mips_opts.noreorder)
7757                     macro_build (NULL, "nop", "");
7758                   expr1.X_add_number = mips_cprestore_offset;
7759                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7760                                                 mips_gp_register,
7761                                                 mips_frame_reg,
7762                                                 HAVE_64BIT_ADDRESSES);
7763                 }
7764             }
7765         }
7766
7767       break;
7768
7769     case M_JALS_A:
7770       gas_assert (mips_opts.micromips);
7771       jals = 1;
7772       /* Fall through.  */
7773     case M_JAL_A:
7774       if (mips_pic == NO_PIC)
7775         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
7776       else if (mips_pic == SVR4_PIC)
7777         {
7778           /* If this is a reference to an external symbol, and we are
7779              using a small GOT, we want
7780                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
7781                nop
7782                jalr     $ra,$25
7783                nop
7784                lw       $gp,cprestore($sp)
7785              The cprestore value is set using the .cprestore
7786              pseudo-op.  If we are using a big GOT, we want
7787                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
7788                addu     $25,$25,$gp
7789                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
7790                nop
7791                jalr     $ra,$25
7792                nop
7793                lw       $gp,cprestore($sp)
7794              If the symbol is not external, we want
7795                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7796                nop
7797                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
7798                jalr     $ra,$25
7799                nop
7800                lw $gp,cprestore($sp)
7801
7802              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
7803              sequences above, minus nops, unless the symbol is local,
7804              which enables us to use GOT_PAGE/GOT_OFST (big got) or
7805              GOT_DISP.  */
7806           if (HAVE_NEWABI)
7807             {
7808               if (!mips_big_got)
7809                 {
7810                   relax_start (offset_expr.X_add_symbol);
7811                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7812                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7813                                mips_gp_register);
7814                   relax_switch ();
7815                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7816                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
7817                                mips_gp_register);
7818                   relax_end ();
7819                 }
7820               else
7821                 {
7822                   relax_start (offset_expr.X_add_symbol);
7823                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7824                                BFD_RELOC_MIPS_CALL_HI16);
7825                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7826                                PIC_CALL_REG, mips_gp_register);
7827                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7828                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7829                                PIC_CALL_REG);
7830                   relax_switch ();
7831                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7832                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
7833                                mips_gp_register);
7834                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7835                                PIC_CALL_REG, PIC_CALL_REG,
7836                                BFD_RELOC_MIPS_GOT_OFST);
7837                   relax_end ();
7838                 }
7839
7840               macro_build_jalr (&offset_expr, 0);
7841             }
7842           else
7843             {
7844               relax_start (offset_expr.X_add_symbol);
7845               if (!mips_big_got)
7846                 {
7847                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7848                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7849                                mips_gp_register);
7850                   load_delay_nop ();
7851                   relax_switch ();
7852                 }
7853               else
7854                 {
7855                   int gpdelay;
7856
7857                   gpdelay = reg_needs_delay (mips_gp_register);
7858                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7859                                BFD_RELOC_MIPS_CALL_HI16);
7860                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7861                                PIC_CALL_REG, mips_gp_register);
7862                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7863                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7864                                PIC_CALL_REG);
7865                   load_delay_nop ();
7866                   relax_switch ();
7867                   if (gpdelay)
7868                     macro_build (NULL, "nop", "");
7869                 }
7870               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7871                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
7872                            mips_gp_register);
7873               load_delay_nop ();
7874               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7875                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
7876               relax_end ();
7877               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
7878
7879               if (mips_cprestore_offset < 0)
7880                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7881               else
7882                 {
7883                   if (!mips_frame_reg_valid)
7884                     {
7885                       as_warn (_("No .frame pseudo-op used in PIC code"));
7886                       /* Quiet this warning.  */
7887                       mips_frame_reg_valid = 1;
7888                     }
7889                   if (!mips_cprestore_valid)
7890                     {
7891                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7892                       /* Quiet this warning.  */
7893                       mips_cprestore_valid = 1;
7894                     }
7895                   if (mips_opts.noreorder)
7896                     macro_build (NULL, "nop", "");
7897                   expr1.X_add_number = mips_cprestore_offset;
7898                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7899                                                 mips_gp_register,
7900                                                 mips_frame_reg,
7901                                                 HAVE_64BIT_ADDRESSES);
7902                 }
7903             }
7904         }
7905       else if (mips_pic == VXWORKS_PIC)
7906         as_bad (_("Non-PIC jump used in PIC library"));
7907       else
7908         abort ();
7909
7910       break;
7911
7912     case M_ACLR_AB:
7913       ab = 1;
7914     case M_ACLR_OB:
7915       s = "aclr";
7916       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
7917       fmt = "\\,~(b)";
7918       off12 = 1;
7919       goto ld_st;
7920     case M_ASET_AB:
7921       ab = 1;
7922     case M_ASET_OB:
7923       s = "aset";
7924       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
7925       fmt = "\\,~(b)";
7926       off12 = 1;
7927       goto ld_st;
7928     case M_LB_AB:
7929       ab = 1;
7930       s = "lb";
7931       fmt = "t,o(b)";
7932       goto ld;
7933     case M_LBU_AB:
7934       ab = 1;
7935       s = "lbu";
7936       fmt = "t,o(b)";
7937       goto ld;
7938     case M_LH_AB:
7939       ab = 1;
7940       s = "lh";
7941       fmt = "t,o(b)";
7942       goto ld;
7943     case M_LHU_AB:
7944       ab = 1;
7945       s = "lhu";
7946       fmt = "t,o(b)";
7947       goto ld;
7948     case M_LW_AB:
7949       ab = 1;
7950       s = "lw";
7951       fmt = "t,o(b)";
7952       goto ld;
7953     case M_LWC0_AB:
7954       ab = 1;
7955       gas_assert (!mips_opts.micromips);
7956       s = "lwc0";
7957       fmt = "E,o(b)";
7958       /* Itbl support may require additional care here.  */
7959       coproc = 1;
7960       goto ld_st;
7961     case M_LWC1_AB:
7962       ab = 1;
7963       s = "lwc1";
7964       fmt = "T,o(b)";
7965       /* Itbl support may require additional care here.  */
7966       coproc = 1;
7967       goto ld_st;
7968     case M_LWC2_AB:
7969       ab = 1;
7970     case M_LWC2_OB:
7971       s = "lwc2";
7972       fmt = COP12_FMT;
7973       off12 = mips_opts.micromips;
7974       /* Itbl support may require additional care here.  */
7975       coproc = 1;
7976       goto ld_st;
7977     case M_LWC3_AB:
7978       ab = 1;
7979       gas_assert (!mips_opts.micromips);
7980       s = "lwc3";
7981       fmt = "E,o(b)";
7982       /* Itbl support may require additional care here.  */
7983       coproc = 1;
7984       goto ld_st;
7985     case M_LWL_AB:
7986       ab = 1;
7987     case M_LWL_OB:
7988       s = "lwl";
7989       fmt = MEM12_FMT;
7990       off12 = mips_opts.micromips;
7991       goto ld_st;
7992     case M_LWR_AB:
7993       ab = 1;
7994     case M_LWR_OB:
7995       s = "lwr";
7996       fmt = MEM12_FMT;
7997       off12 = mips_opts.micromips;
7998       goto ld_st;
7999     case M_LDC1_AB:
8000       ab = 1;
8001       s = "ldc1";
8002       fmt = "T,o(b)";
8003       /* Itbl support may require additional care here.  */
8004       coproc = 1;
8005       goto ld_st;
8006     case M_LDC2_AB:
8007       ab = 1;
8008     case M_LDC2_OB:
8009       s = "ldc2";
8010       fmt = COP12_FMT;
8011       off12 = mips_opts.micromips;
8012       /* Itbl support may require additional care here.  */
8013       coproc = 1;
8014       goto ld_st;
8015     case M_LDC3_AB:
8016       ab = 1;
8017       s = "ldc3";
8018       fmt = "E,o(b)";
8019       /* Itbl support may require additional care here.  */
8020       coproc = 1;
8021       goto ld_st;
8022     case M_LDL_AB:
8023       ab = 1;
8024     case M_LDL_OB:
8025       s = "ldl";
8026       fmt = MEM12_FMT;
8027       off12 = mips_opts.micromips;
8028       goto ld_st;
8029     case M_LDR_AB:
8030       ab = 1;
8031     case M_LDR_OB:
8032       s = "ldr";
8033       fmt = MEM12_FMT;
8034       off12 = mips_opts.micromips;
8035       goto ld_st;
8036     case M_LL_AB:
8037       ab = 1;
8038     case M_LL_OB:
8039       s = "ll";
8040       fmt = MEM12_FMT;
8041       off12 = mips_opts.micromips;
8042       goto ld;
8043     case M_LLD_AB:
8044       ab = 1;
8045     case M_LLD_OB:
8046       s = "lld";
8047       fmt = MEM12_FMT;
8048       off12 = mips_opts.micromips;
8049       goto ld;
8050     case M_LWU_AB:
8051       ab = 1;
8052     case M_LWU_OB:
8053       s = "lwu";
8054       fmt = MEM12_FMT;
8055       off12 = mips_opts.micromips;
8056       goto ld;
8057     case M_LWP_AB:
8058       ab = 1;
8059     case M_LWP_OB:
8060       gas_assert (mips_opts.micromips);
8061       s = "lwp";
8062       fmt = "t,~(b)";
8063       off12 = 1;
8064       lp = 1;
8065       goto ld;
8066     case M_LDP_AB:
8067       ab = 1;
8068     case M_LDP_OB:
8069       gas_assert (mips_opts.micromips);
8070       s = "ldp";
8071       fmt = "t,~(b)";
8072       off12 = 1;
8073       lp = 1;
8074       goto ld;
8075     case M_LWM_AB:
8076       ab = 1;
8077     case M_LWM_OB:
8078       gas_assert (mips_opts.micromips);
8079       s = "lwm";
8080       fmt = "n,~(b)";
8081       off12 = 1;
8082       goto ld_st;
8083     case M_LDM_AB:
8084       ab = 1;
8085     case M_LDM_OB:
8086       gas_assert (mips_opts.micromips);
8087       s = "ldm";
8088       fmt = "n,~(b)";
8089       off12 = 1;
8090       goto ld_st;
8091
8092     ld:
8093       if (breg == treg + lp)
8094         goto ld_st;
8095       else
8096         tempreg = treg + lp;
8097       goto ld_noat;
8098
8099     case M_SB_AB:
8100       ab = 1;
8101       s = "sb";
8102       fmt = "t,o(b)";
8103       goto ld_st;
8104     case M_SH_AB:
8105       ab = 1;
8106       s = "sh";
8107       fmt = "t,o(b)";
8108       goto ld_st;
8109     case M_SW_AB:
8110       ab = 1;
8111       s = "sw";
8112       fmt = "t,o(b)";
8113       goto ld_st;
8114     case M_SWC0_AB:
8115       ab = 1;
8116       gas_assert (!mips_opts.micromips);
8117       s = "swc0";
8118       fmt = "E,o(b)";
8119       /* Itbl support may require additional care here.  */
8120       coproc = 1;
8121       goto ld_st;
8122     case M_SWC1_AB:
8123       ab = 1;
8124       s = "swc1";
8125       fmt = "T,o(b)";
8126       /* Itbl support may require additional care here.  */
8127       coproc = 1;
8128       goto ld_st;
8129     case M_SWC2_AB:
8130       ab = 1;
8131     case M_SWC2_OB:
8132       s = "swc2";
8133       fmt = COP12_FMT;
8134       off12 = mips_opts.micromips;
8135       /* Itbl support may require additional care here.  */
8136       coproc = 1;
8137       goto ld_st;
8138     case M_SWC3_AB:
8139       ab = 1;
8140       gas_assert (!mips_opts.micromips);
8141       s = "swc3";
8142       fmt = "E,o(b)";
8143       /* Itbl support may require additional care here.  */
8144       coproc = 1;
8145       goto ld_st;
8146     case M_SWL_AB:
8147       ab = 1;
8148     case M_SWL_OB:
8149       s = "swl";
8150       fmt = MEM12_FMT;
8151       off12 = mips_opts.micromips;
8152       goto ld_st;
8153     case M_SWR_AB:
8154       ab = 1;
8155     case M_SWR_OB:
8156       s = "swr";
8157       fmt = MEM12_FMT;
8158       off12 = mips_opts.micromips;
8159       goto ld_st;
8160     case M_SC_AB:
8161       ab = 1;
8162     case M_SC_OB:
8163       s = "sc";
8164       fmt = MEM12_FMT;
8165       off12 = mips_opts.micromips;
8166       goto ld_st;
8167     case M_SCD_AB:
8168       ab = 1;
8169     case M_SCD_OB:
8170       s = "scd";
8171       fmt = MEM12_FMT;
8172       off12 = mips_opts.micromips;
8173       goto ld_st;
8174     case M_CACHE_AB:
8175       ab = 1;
8176     case M_CACHE_OB:
8177       s = "cache";
8178       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8179       off12 = mips_opts.micromips;
8180       goto ld_st;
8181     case M_PREF_AB:
8182       ab = 1;
8183     case M_PREF_OB:
8184       s = "pref";
8185       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8186       off12 = mips_opts.micromips;
8187       goto ld_st;
8188     case M_SDC1_AB:
8189       ab = 1;
8190       s = "sdc1";
8191       fmt = "T,o(b)";
8192       coproc = 1;
8193       /* Itbl support may require additional care here.  */
8194       goto ld_st;
8195     case M_SDC2_AB:
8196       ab = 1;
8197     case M_SDC2_OB:
8198       s = "sdc2";
8199       fmt = COP12_FMT;
8200       off12 = mips_opts.micromips;
8201       /* Itbl support may require additional care here.  */
8202       coproc = 1;
8203       goto ld_st;
8204     case M_SDC3_AB:
8205       ab = 1;
8206       gas_assert (!mips_opts.micromips);
8207       s = "sdc3";
8208       fmt = "E,o(b)";
8209       /* Itbl support may require additional care here.  */
8210       coproc = 1;
8211       goto ld_st;
8212     case M_SDL_AB:
8213       ab = 1;
8214     case M_SDL_OB:
8215       s = "sdl";
8216       fmt = MEM12_FMT;
8217       off12 = mips_opts.micromips;
8218       goto ld_st;
8219     case M_SDR_AB:
8220       ab = 1;
8221     case M_SDR_OB:
8222       s = "sdr";
8223       fmt = MEM12_FMT;
8224       off12 = mips_opts.micromips;
8225       goto ld_st;
8226     case M_SWP_AB:
8227       ab = 1;
8228     case M_SWP_OB:
8229       gas_assert (mips_opts.micromips);
8230       s = "swp";
8231       fmt = "t,~(b)";
8232       off12 = 1;
8233       goto ld_st;
8234     case M_SDP_AB:
8235       ab = 1;
8236     case M_SDP_OB:
8237       gas_assert (mips_opts.micromips);
8238       s = "sdp";
8239       fmt = "t,~(b)";
8240       off12 = 1;
8241       goto ld_st;
8242     case M_SWM_AB:
8243       ab = 1;
8244     case M_SWM_OB:
8245       gas_assert (mips_opts.micromips);
8246       s = "swm";
8247       fmt = "n,~(b)";
8248       off12 = 1;
8249       goto ld_st;
8250     case M_SDM_AB:
8251       ab = 1;
8252     case M_SDM_OB:
8253       gas_assert (mips_opts.micromips);
8254       s = "sdm";
8255       fmt = "n,~(b)";
8256       off12 = 1;
8257
8258     ld_st:
8259       tempreg = AT;
8260       used_at = 1;
8261     ld_noat:
8262       if (coproc
8263           && NO_ISA_COP (mips_opts.arch)
8264           && (ip->insn_mo->pinfo2 & (INSN2_M_FP_S | INSN2_M_FP_D)) == 0)
8265         {
8266           as_bad (_("Opcode not supported on this processor: %s"),
8267                   mips_cpu_info_from_arch (mips_opts.arch)->name);
8268           break;
8269         }
8270
8271       if (offset_expr.X_op != O_constant
8272           && offset_expr.X_op != O_symbol)
8273         {
8274           as_bad (_("Expression too complex"));
8275           offset_expr.X_op = O_constant;
8276         }
8277
8278       if (HAVE_32BIT_ADDRESSES
8279           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8280         {
8281           char value [32];
8282
8283           sprintf_vma (value, offset_expr.X_add_number);
8284           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8285         }
8286
8287       /* A constant expression in PIC code can be handled just as it
8288          is in non PIC code.  */
8289       if (offset_expr.X_op == O_constant)
8290         {
8291           int hipart = 0;
8292
8293           expr1.X_add_number = offset_expr.X_add_number;
8294           normalize_address_expr (&expr1);
8295           if (!off12 && !IS_SEXT_16BIT_NUM (expr1.X_add_number))
8296             {
8297               expr1.X_add_number = ((expr1.X_add_number + 0x8000)
8298                                     & ~(bfd_vma) 0xffff);
8299               hipart = 1;
8300             }
8301           else if (off12 && !IS_SEXT_12BIT_NUM (expr1.X_add_number))
8302             {
8303               expr1.X_add_number = ((expr1.X_add_number + 0x800)
8304                                     & ~(bfd_vma) 0xfff);
8305               hipart = 1;
8306             }
8307           if (hipart)
8308             {
8309               load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8310               if (breg != 0)
8311                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8312                              tempreg, tempreg, breg);
8313               breg = tempreg;
8314             }
8315           if (off0)
8316             {
8317               if (offset_expr.X_add_number == 0)
8318                 tempreg = breg;
8319               else
8320                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
8321                              "t,r,j", tempreg, breg, BFD_RELOC_LO16);
8322               macro_build (NULL, s, fmt, treg, tempreg);
8323             }
8324           else if (!off12)
8325             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, breg);
8326           else
8327             macro_build (NULL, s, fmt,
8328                          treg, (unsigned long) offset_expr.X_add_number, breg);
8329         }
8330       else if (off12 || off0)
8331         {
8332           /* A 12-bit or 0-bit offset field is too narrow to be used
8333              for a low-part relocation, so load the whole address into
8334              the auxillary register.  In the case of "A(b)" addresses,
8335              we first load absolute address "A" into the register and
8336              then add base register "b".  In the case of "o(b)" addresses,
8337              we simply need to add 16-bit offset "o" to base register "b", and
8338              offset_reloc already contains the relocations associated
8339              with "o".  */
8340           if (ab)
8341             {
8342               load_address (tempreg, &offset_expr, &used_at);
8343               if (breg != 0)
8344                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8345                              tempreg, tempreg, breg);
8346             }
8347           else
8348             macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8349                          tempreg, breg, -1,
8350                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8351           expr1.X_add_number = 0;
8352           if (off0)
8353             macro_build (NULL, s, fmt, treg, tempreg);
8354           else
8355             macro_build (NULL, s, fmt,
8356                          treg, (unsigned long) expr1.X_add_number, tempreg);
8357         }
8358       else if (mips_pic == NO_PIC)
8359         {
8360           /* If this is a reference to a GP relative symbol, and there
8361              is no base register, we want
8362                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8363              Otherwise, if there is no base register, we want
8364                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8365                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8366              If we have a constant, we need two instructions anyhow,
8367              so we always use the latter form.
8368
8369              If we have a base register, and this is a reference to a
8370              GP relative symbol, we want
8371                addu     $tempreg,$breg,$gp
8372                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
8373              Otherwise we want
8374                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8375                addu     $tempreg,$tempreg,$breg
8376                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8377              With a constant we always use the latter case.
8378
8379              With 64bit address space and no base register and $at usable,
8380              we want
8381                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8382                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8383                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8384                dsll32   $tempreg,0
8385                daddu    $tempreg,$at
8386                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8387              If we have a base register, we want
8388                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8389                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8390                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8391                daddu    $at,$breg
8392                dsll32   $tempreg,0
8393                daddu    $tempreg,$at
8394                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8395
8396              Without $at we can't generate the optimal path for superscalar
8397              processors here since this would require two temporary registers.
8398                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8399                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8400                dsll     $tempreg,16
8401                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8402                dsll     $tempreg,16
8403                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8404              If we have a base register, we want
8405                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8406                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8407                dsll     $tempreg,16
8408                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8409                dsll     $tempreg,16
8410                daddu    $tempreg,$tempreg,$breg
8411                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8412
8413              For GP relative symbols in 64bit address space we can use
8414              the same sequence as in 32bit address space.  */
8415           if (HAVE_64BIT_SYMBOLS)
8416             {
8417               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8418                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8419                 {
8420                   relax_start (offset_expr.X_add_symbol);
8421                   if (breg == 0)
8422                     {
8423                       macro_build (&offset_expr, s, fmt, treg,
8424                                    BFD_RELOC_GPREL16, mips_gp_register);
8425                     }
8426                   else
8427                     {
8428                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8429                                    tempreg, breg, mips_gp_register);
8430                       macro_build (&offset_expr, s, fmt, treg,
8431                                    BFD_RELOC_GPREL16, tempreg);
8432                     }
8433                   relax_switch ();
8434                 }
8435
8436               if (used_at == 0 && mips_opts.at)
8437                 {
8438                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8439                                BFD_RELOC_MIPS_HIGHEST);
8440                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
8441                                BFD_RELOC_HI16_S);
8442                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8443                                tempreg, BFD_RELOC_MIPS_HIGHER);
8444                   if (breg != 0)
8445                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
8446                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8447                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8448                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
8449                                tempreg);
8450                   used_at = 1;
8451                 }
8452               else
8453                 {
8454                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8455                                BFD_RELOC_MIPS_HIGHEST);
8456                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8457                                tempreg, BFD_RELOC_MIPS_HIGHER);
8458                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8459                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8460                                tempreg, BFD_RELOC_HI16_S);
8461                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8462                   if (breg != 0)
8463                     macro_build (NULL, "daddu", "d,v,t",
8464                                  tempreg, tempreg, breg);
8465                   macro_build (&offset_expr, s, fmt, treg,
8466                                BFD_RELOC_LO16, tempreg);
8467                 }
8468
8469               if (mips_relax.sequence)
8470                 relax_end ();
8471               break;
8472             }
8473
8474           if (breg == 0)
8475             {
8476               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8477                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8478                 {
8479                   relax_start (offset_expr.X_add_symbol);
8480                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
8481                                mips_gp_register);
8482                   relax_switch ();
8483                 }
8484               macro_build_lui (&offset_expr, tempreg);
8485               macro_build (&offset_expr, s, fmt, treg,
8486                            BFD_RELOC_LO16, tempreg);
8487               if (mips_relax.sequence)
8488                 relax_end ();
8489             }
8490           else
8491             {
8492               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8493                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8494                 {
8495                   relax_start (offset_expr.X_add_symbol);
8496                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8497                                tempreg, breg, mips_gp_register);
8498                   macro_build (&offset_expr, s, fmt, treg,
8499                                BFD_RELOC_GPREL16, tempreg);
8500                   relax_switch ();
8501                 }
8502               macro_build_lui (&offset_expr, tempreg);
8503               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8504                            tempreg, tempreg, breg);
8505               macro_build (&offset_expr, s, fmt, treg,
8506                            BFD_RELOC_LO16, tempreg);
8507               if (mips_relax.sequence)
8508                 relax_end ();
8509             }
8510         }
8511       else if (!mips_big_got)
8512         {
8513           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8514
8515           /* If this is a reference to an external symbol, we want
8516                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8517                nop
8518                <op>     $treg,0($tempreg)
8519              Otherwise we want
8520                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8521                nop
8522                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8523                <op>     $treg,0($tempreg)
8524
8525              For NewABI, we want
8526                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8527                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
8528
8529              If there is a base register, we add it to $tempreg before
8530              the <op>.  If there is a constant, we stick it in the
8531              <op> instruction.  We don't handle constants larger than
8532              16 bits, because we have no way to load the upper 16 bits
8533              (actually, we could handle them for the subset of cases
8534              in which we are not using $at).  */
8535           gas_assert (offset_expr.X_op == O_symbol);
8536           if (HAVE_NEWABI)
8537             {
8538               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8539                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8540               if (breg != 0)
8541                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8542                              tempreg, tempreg, breg);
8543               macro_build (&offset_expr, s, fmt, treg,
8544                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
8545               break;
8546             }
8547           expr1.X_add_number = offset_expr.X_add_number;
8548           offset_expr.X_add_number = 0;
8549           if (expr1.X_add_number < -0x8000
8550               || expr1.X_add_number >= 0x8000)
8551             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8552           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8553                        lw_reloc_type, mips_gp_register);
8554           load_delay_nop ();
8555           relax_start (offset_expr.X_add_symbol);
8556           relax_switch ();
8557           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8558                        tempreg, BFD_RELOC_LO16);
8559           relax_end ();
8560           if (breg != 0)
8561             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8562                          tempreg, tempreg, breg);
8563           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8564         }
8565       else if (mips_big_got && !HAVE_NEWABI)
8566         {
8567           int gpdelay;
8568
8569           /* If this is a reference to an external symbol, we want
8570                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8571                addu     $tempreg,$tempreg,$gp
8572                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8573                <op>     $treg,0($tempreg)
8574              Otherwise we want
8575                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8576                nop
8577                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8578                <op>     $treg,0($tempreg)
8579              If there is a base register, we add it to $tempreg before
8580              the <op>.  If there is a constant, we stick it in the
8581              <op> instruction.  We don't handle constants larger than
8582              16 bits, because we have no way to load the upper 16 bits
8583              (actually, we could handle them for the subset of cases
8584              in which we are not using $at).  */
8585           gas_assert (offset_expr.X_op == O_symbol);
8586           expr1.X_add_number = offset_expr.X_add_number;
8587           offset_expr.X_add_number = 0;
8588           if (expr1.X_add_number < -0x8000
8589               || expr1.X_add_number >= 0x8000)
8590             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8591           gpdelay = reg_needs_delay (mips_gp_register);
8592           relax_start (offset_expr.X_add_symbol);
8593           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8594                        BFD_RELOC_MIPS_GOT_HI16);
8595           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
8596                        mips_gp_register);
8597           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8598                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
8599           relax_switch ();
8600           if (gpdelay)
8601             macro_build (NULL, "nop", "");
8602           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8603                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8604           load_delay_nop ();
8605           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8606                        tempreg, BFD_RELOC_LO16);
8607           relax_end ();
8608
8609           if (breg != 0)
8610             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8611                          tempreg, tempreg, breg);
8612           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8613         }
8614       else if (mips_big_got && HAVE_NEWABI)
8615         {
8616           /* If this is a reference to an external symbol, we want
8617                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8618                add      $tempreg,$tempreg,$gp
8619                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8620                <op>     $treg,<ofst>($tempreg)
8621              Otherwise, for local symbols, we want:
8622                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8623                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
8624           gas_assert (offset_expr.X_op == O_symbol);
8625           expr1.X_add_number = offset_expr.X_add_number;
8626           offset_expr.X_add_number = 0;
8627           if (expr1.X_add_number < -0x8000
8628               || expr1.X_add_number >= 0x8000)
8629             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8630           relax_start (offset_expr.X_add_symbol);
8631           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8632                        BFD_RELOC_MIPS_GOT_HI16);
8633           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
8634                        mips_gp_register);
8635           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8636                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
8637           if (breg != 0)
8638             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8639                          tempreg, tempreg, breg);
8640           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8641
8642           relax_switch ();
8643           offset_expr.X_add_number = expr1.X_add_number;
8644           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8645                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8646           if (breg != 0)
8647             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8648                          tempreg, tempreg, breg);
8649           macro_build (&offset_expr, s, fmt, treg,
8650                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
8651           relax_end ();
8652         }
8653       else
8654         abort ();
8655
8656       break;
8657
8658     case M_LI:
8659     case M_LI_S:
8660       load_register (treg, &imm_expr, 0);
8661       break;
8662
8663     case M_DLI:
8664       load_register (treg, &imm_expr, 1);
8665       break;
8666
8667     case M_LI_SS:
8668       if (imm_expr.X_op == O_constant)
8669         {
8670           used_at = 1;
8671           load_register (AT, &imm_expr, 0);
8672           macro_build (NULL, "mtc1", "t,G", AT, treg);
8673           break;
8674         }
8675       else
8676         {
8677           gas_assert (offset_expr.X_op == O_symbol
8678                       && strcmp (segment_name (S_GET_SEGMENT
8679                                                (offset_expr.X_add_symbol)),
8680                                  ".lit4") == 0
8681                       && offset_expr.X_add_number == 0);
8682           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
8683                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8684           break;
8685         }
8686
8687     case M_LI_D:
8688       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
8689          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
8690          order 32 bits of the value and the low order 32 bits are either
8691          zero or in OFFSET_EXPR.  */
8692       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8693         {
8694           if (HAVE_64BIT_GPRS)
8695             load_register (treg, &imm_expr, 1);
8696           else
8697             {
8698               int hreg, lreg;
8699
8700               if (target_big_endian)
8701                 {
8702                   hreg = treg;
8703                   lreg = treg + 1;
8704                 }
8705               else
8706                 {
8707                   hreg = treg + 1;
8708                   lreg = treg;
8709                 }
8710
8711               if (hreg <= 31)
8712                 load_register (hreg, &imm_expr, 0);
8713               if (lreg <= 31)
8714                 {
8715                   if (offset_expr.X_op == O_absent)
8716                     move_register (lreg, 0);
8717                   else
8718                     {
8719                       gas_assert (offset_expr.X_op == O_constant);
8720                       load_register (lreg, &offset_expr, 0);
8721                     }
8722                 }
8723             }
8724           break;
8725         }
8726
8727       /* We know that sym is in the .rdata section.  First we get the
8728          upper 16 bits of the address.  */
8729       if (mips_pic == NO_PIC)
8730         {
8731           macro_build_lui (&offset_expr, AT);
8732           used_at = 1;
8733         }
8734       else
8735         {
8736           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8737                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8738           used_at = 1;
8739         }
8740
8741       /* Now we load the register(s).  */
8742       if (HAVE_64BIT_GPRS)
8743         {
8744           used_at = 1;
8745           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8746         }
8747       else
8748         {
8749           used_at = 1;
8750           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8751           if (treg != RA)
8752             {
8753               /* FIXME: How in the world do we deal with the possible
8754                  overflow here?  */
8755               offset_expr.X_add_number += 4;
8756               macro_build (&offset_expr, "lw", "t,o(b)",
8757                            treg + 1, BFD_RELOC_LO16, AT);
8758             }
8759         }
8760       break;
8761
8762     case M_LI_DD:
8763       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
8764          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
8765          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
8766          the value and the low order 32 bits are either zero or in
8767          OFFSET_EXPR.  */
8768       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8769         {
8770           used_at = 1;
8771           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
8772           if (HAVE_64BIT_FPRS)
8773             {
8774               gas_assert (HAVE_64BIT_GPRS);
8775               macro_build (NULL, "dmtc1", "t,S", AT, treg);
8776             }
8777           else
8778             {
8779               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
8780               if (offset_expr.X_op == O_absent)
8781                 macro_build (NULL, "mtc1", "t,G", 0, treg);
8782               else
8783                 {
8784                   gas_assert (offset_expr.X_op == O_constant);
8785                   load_register (AT, &offset_expr, 0);
8786                   macro_build (NULL, "mtc1", "t,G", AT, treg);
8787                 }
8788             }
8789           break;
8790         }
8791
8792       gas_assert (offset_expr.X_op == O_symbol
8793                   && offset_expr.X_add_number == 0);
8794       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
8795       if (strcmp (s, ".lit8") == 0)
8796         {
8797           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8798             {
8799               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
8800                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8801               break;
8802             }
8803           breg = mips_gp_register;
8804           r = BFD_RELOC_MIPS_LITERAL;
8805           goto dob;
8806         }
8807       else
8808         {
8809           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
8810           used_at = 1;
8811           if (mips_pic != NO_PIC)
8812             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8813                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
8814           else
8815             {
8816               /* FIXME: This won't work for a 64 bit address.  */
8817               macro_build_lui (&offset_expr, AT);
8818             }
8819
8820           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8821             {
8822               macro_build (&offset_expr, "ldc1", "T,o(b)",
8823                            treg, BFD_RELOC_LO16, AT);
8824               break;
8825             }
8826           breg = AT;
8827           r = BFD_RELOC_LO16;
8828           goto dob;
8829         }
8830
8831     case M_L_DOB:
8832       /* Even on a big endian machine $fn comes before $fn+1.  We have
8833          to adjust when loading from memory.  */
8834       r = BFD_RELOC_LO16;
8835     dob:
8836       gas_assert (!mips_opts.micromips);
8837       gas_assert (mips_opts.isa == ISA_MIPS1);
8838       macro_build (&offset_expr, "lwc1", "T,o(b)",
8839                    target_big_endian ? treg + 1 : treg, r, breg);
8840       /* FIXME: A possible overflow which I don't know how to deal
8841          with.  */
8842       offset_expr.X_add_number += 4;
8843       macro_build (&offset_expr, "lwc1", "T,o(b)",
8844                    target_big_endian ? treg : treg + 1, r, breg);
8845       break;
8846
8847     case M_S_DOB:
8848       gas_assert (!mips_opts.micromips);
8849       gas_assert (mips_opts.isa == ISA_MIPS1);
8850       /* Even on a big endian machine $fn comes before $fn+1.  We have
8851          to adjust when storing to memory.  */
8852       macro_build (&offset_expr, "swc1", "T,o(b)",
8853                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
8854       offset_expr.X_add_number += 4;
8855       macro_build (&offset_expr, "swc1", "T,o(b)",
8856                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
8857       break;
8858
8859     case M_L_DAB:
8860       gas_assert (!mips_opts.micromips);
8861       /*
8862        * The MIPS assembler seems to check for X_add_number not
8863        * being double aligned and generating:
8864        *        lui     at,%hi(foo+1)
8865        *        addu    at,at,v1
8866        *        addiu   at,at,%lo(foo+1)
8867        *        lwc1    f2,0(at)
8868        *        lwc1    f3,4(at)
8869        * But, the resulting address is the same after relocation so why
8870        * generate the extra instruction?
8871        */
8872       /* Itbl support may require additional care here.  */
8873       coproc = 1;
8874       fmt = "T,o(b)";
8875       if (mips_opts.isa != ISA_MIPS1)
8876         {
8877           s = "ldc1";
8878           goto ld_st;
8879         }
8880       s = "lwc1";
8881       goto ldd_std;
8882
8883     case M_S_DAB:
8884       gas_assert (!mips_opts.micromips);
8885       /* Itbl support may require additional care here.  */
8886       coproc = 1;
8887       fmt = "T,o(b)";
8888       if (mips_opts.isa != ISA_MIPS1)
8889         {
8890           s = "sdc1";
8891           goto ld_st;
8892         }
8893       s = "swc1";
8894       goto ldd_std;
8895
8896     case M_LD_AB:
8897       fmt = "t,o(b)";
8898       if (HAVE_64BIT_GPRS)
8899         {
8900           s = "ld";
8901           goto ld;
8902         }
8903       s = "lw";
8904       goto ldd_std;
8905
8906     case M_SD_AB:
8907       fmt = "t,o(b)";
8908       if (HAVE_64BIT_GPRS)
8909         {
8910           s = "sd";
8911           goto ld_st;
8912         }
8913       s = "sw";
8914
8915     ldd_std:
8916       if (offset_expr.X_op != O_symbol
8917           && offset_expr.X_op != O_constant)
8918         {
8919           as_bad (_("Expression too complex"));
8920           offset_expr.X_op = O_constant;
8921         }
8922
8923       if (HAVE_32BIT_ADDRESSES
8924           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8925         {
8926           char value [32];
8927
8928           sprintf_vma (value, offset_expr.X_add_number);
8929           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8930         }
8931
8932       /* Even on a big endian machine $fn comes before $fn+1.  We have
8933          to adjust when loading from memory.  We set coproc if we must
8934          load $fn+1 first.  */
8935       /* Itbl support may require additional care here.  */
8936       if (!target_big_endian)
8937         coproc = 0;
8938
8939       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
8940         {
8941           /* If this is a reference to a GP relative symbol, we want
8942                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8943                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
8944              If we have a base register, we use this
8945                addu     $at,$breg,$gp
8946                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
8947                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
8948              If this is not a GP relative symbol, we want
8949                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8950                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
8951                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
8952              If there is a base register, we add it to $at after the
8953              lui instruction.  If there is a constant, we always use
8954              the last case.  */
8955           if (offset_expr.X_op == O_symbol
8956               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8957               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8958             {
8959               relax_start (offset_expr.X_add_symbol);
8960               if (breg == 0)
8961                 {
8962                   tempreg = mips_gp_register;
8963                 }
8964               else
8965                 {
8966                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8967                                AT, breg, mips_gp_register);
8968                   tempreg = AT;
8969                   used_at = 1;
8970                 }
8971
8972               /* Itbl support may require additional care here.  */
8973               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8974                            BFD_RELOC_GPREL16, tempreg);
8975               offset_expr.X_add_number += 4;
8976
8977               /* Set mips_optimize to 2 to avoid inserting an
8978                  undesired nop.  */
8979               hold_mips_optimize = mips_optimize;
8980               mips_optimize = 2;
8981               /* Itbl support may require additional care here.  */
8982               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8983                            BFD_RELOC_GPREL16, tempreg);
8984               mips_optimize = hold_mips_optimize;
8985
8986               relax_switch ();
8987
8988               offset_expr.X_add_number -= 4;
8989             }
8990           used_at = 1;
8991           macro_build_lui (&offset_expr, AT);
8992           if (breg != 0)
8993             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
8994           /* Itbl support may require additional care here.  */
8995           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8996                        BFD_RELOC_LO16, AT);
8997           /* FIXME: How do we handle overflow here?  */
8998           offset_expr.X_add_number += 4;
8999           /* Itbl support may require additional care here.  */
9000           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9001                        BFD_RELOC_LO16, AT);
9002           if (mips_relax.sequence)
9003             relax_end ();
9004         }
9005       else if (!mips_big_got)
9006         {
9007           /* If this is a reference to an external symbol, we want
9008                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9009                nop
9010                <op>     $treg,0($at)
9011                <op>     $treg+1,4($at)
9012              Otherwise we want
9013                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9014                nop
9015                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9016                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9017              If there is a base register we add it to $at before the
9018              lwc1 instructions.  If there is a constant we include it
9019              in the lwc1 instructions.  */
9020           used_at = 1;
9021           expr1.X_add_number = offset_expr.X_add_number;
9022           if (expr1.X_add_number < -0x8000
9023               || expr1.X_add_number >= 0x8000 - 4)
9024             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9025           load_got_offset (AT, &offset_expr);
9026           load_delay_nop ();
9027           if (breg != 0)
9028             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9029
9030           /* Set mips_optimize to 2 to avoid inserting an undesired
9031              nop.  */
9032           hold_mips_optimize = mips_optimize;
9033           mips_optimize = 2;
9034
9035           /* Itbl support may require additional care here.  */
9036           relax_start (offset_expr.X_add_symbol);
9037           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9038                        BFD_RELOC_LO16, AT);
9039           expr1.X_add_number += 4;
9040           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9041                        BFD_RELOC_LO16, AT);
9042           relax_switch ();
9043           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9044                        BFD_RELOC_LO16, AT);
9045           offset_expr.X_add_number += 4;
9046           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9047                        BFD_RELOC_LO16, AT);
9048           relax_end ();
9049
9050           mips_optimize = hold_mips_optimize;
9051         }
9052       else if (mips_big_got)
9053         {
9054           int gpdelay;
9055
9056           /* If this is a reference to an external symbol, we want
9057                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9058                addu     $at,$at,$gp
9059                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9060                nop
9061                <op>     $treg,0($at)
9062                <op>     $treg+1,4($at)
9063              Otherwise we want
9064                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9065                nop
9066                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9067                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9068              If there is a base register we add it to $at before the
9069              lwc1 instructions.  If there is a constant we include it
9070              in the lwc1 instructions.  */
9071           used_at = 1;
9072           expr1.X_add_number = offset_expr.X_add_number;
9073           offset_expr.X_add_number = 0;
9074           if (expr1.X_add_number < -0x8000
9075               || expr1.X_add_number >= 0x8000 - 4)
9076             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9077           gpdelay = reg_needs_delay (mips_gp_register);
9078           relax_start (offset_expr.X_add_symbol);
9079           macro_build (&offset_expr, "lui", LUI_FMT,
9080                        AT, BFD_RELOC_MIPS_GOT_HI16);
9081           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9082                        AT, AT, mips_gp_register);
9083           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9084                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9085           load_delay_nop ();
9086           if (breg != 0)
9087             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9088           /* Itbl support may require additional care here.  */
9089           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9090                        BFD_RELOC_LO16, AT);
9091           expr1.X_add_number += 4;
9092
9093           /* Set mips_optimize to 2 to avoid inserting an undesired
9094              nop.  */
9095           hold_mips_optimize = mips_optimize;
9096           mips_optimize = 2;
9097           /* Itbl support may require additional care here.  */
9098           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9099                        BFD_RELOC_LO16, AT);
9100           mips_optimize = hold_mips_optimize;
9101           expr1.X_add_number -= 4;
9102
9103           relax_switch ();
9104           offset_expr.X_add_number = expr1.X_add_number;
9105           if (gpdelay)
9106             macro_build (NULL, "nop", "");
9107           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9108                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9109           load_delay_nop ();
9110           if (breg != 0)
9111             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9112           /* Itbl support may require additional care here.  */
9113           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9114                        BFD_RELOC_LO16, AT);
9115           offset_expr.X_add_number += 4;
9116
9117           /* Set mips_optimize to 2 to avoid inserting an undesired
9118              nop.  */
9119           hold_mips_optimize = mips_optimize;
9120           mips_optimize = 2;
9121           /* Itbl support may require additional care here.  */
9122           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9123                        BFD_RELOC_LO16, AT);
9124           mips_optimize = hold_mips_optimize;
9125           relax_end ();
9126         }
9127       else
9128         abort ();
9129
9130       break;
9131
9132     case M_LD_OB:
9133       s = HAVE_64BIT_GPRS ? "ld" : "lw";
9134       goto sd_ob;
9135     case M_SD_OB:
9136       s = HAVE_64BIT_GPRS ? "sd" : "sw";
9137     sd_ob:
9138       macro_build (&offset_expr, s, "t,o(b)", treg,
9139                    -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9140                    breg);
9141       if (!HAVE_64BIT_GPRS)
9142         {
9143           offset_expr.X_add_number += 4;
9144           macro_build (&offset_expr, s, "t,o(b)", treg + 1,
9145                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9146                        breg);
9147         }
9148       break;
9149
9150         
9151     case M_SAA_AB:
9152       ab = 1;
9153     case M_SAA_OB:
9154       s = "saa";
9155       off0 = 1;
9156       fmt = "t,(b)";
9157       goto ld_st;
9158     case M_SAAD_AB:
9159       ab = 1;
9160     case M_SAAD_OB:
9161       s = "saad";
9162       off0 = 1;
9163       fmt = "t,(b)";
9164       goto ld_st;
9165
9166    /* New code added to support COPZ instructions.
9167       This code builds table entries out of the macros in mip_opcodes.
9168       R4000 uses interlocks to handle coproc delays.
9169       Other chips (like the R3000) require nops to be inserted for delays.
9170
9171       FIXME: Currently, we require that the user handle delays.
9172       In order to fill delay slots for non-interlocked chips,
9173       we must have a way to specify delays based on the coprocessor.
9174       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9175       What are the side-effects of the cop instruction?
9176       What cache support might we have and what are its effects?
9177       Both coprocessor & memory require delays. how long???
9178       What registers are read/set/modified?
9179
9180       If an itbl is provided to interpret cop instructions,
9181       this knowledge can be encoded in the itbl spec.  */
9182
9183     case M_COP0:
9184       s = "c0";
9185       goto copz;
9186     case M_COP1:
9187       s = "c1";
9188       goto copz;
9189     case M_COP2:
9190       s = "c2";
9191       goto copz;
9192     case M_COP3:
9193       s = "c3";
9194     copz:
9195       gas_assert (!mips_opts.micromips);
9196       if (NO_ISA_COP (mips_opts.arch)
9197           && (ip->insn_mo->pinfo2 & INSN2_M_FP_S) == 0)
9198         {
9199           as_bad (_("Opcode not supported on this processor: %s"),
9200                   mips_cpu_info_from_arch (mips_opts.arch)->name);
9201           break;
9202         }
9203
9204       /* For now we just do C (same as Cz).  The parameter will be
9205          stored in insn_opcode by mips_ip.  */
9206       macro_build (NULL, s, "C", ip->insn_opcode);
9207       break;
9208
9209     case M_MOVE:
9210       move_register (dreg, sreg);
9211       break;
9212
9213     case M_DMUL:
9214       dbl = 1;
9215     case M_MUL:
9216       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9217       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9218       break;
9219
9220     case M_DMUL_I:
9221       dbl = 1;
9222     case M_MUL_I:
9223       /* The MIPS assembler some times generates shifts and adds.  I'm
9224          not trying to be that fancy. GCC should do this for us
9225          anyway.  */
9226       used_at = 1;
9227       load_register (AT, &imm_expr, dbl);
9228       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9229       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9230       break;
9231
9232     case M_DMULO_I:
9233       dbl = 1;
9234     case M_MULO_I:
9235       imm = 1;
9236       goto do_mulo;
9237
9238     case M_DMULO:
9239       dbl = 1;
9240     case M_MULO:
9241     do_mulo:
9242       start_noreorder ();
9243       used_at = 1;
9244       if (imm)
9245         load_register (AT, &imm_expr, dbl);
9246       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9247       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9248       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9249       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9250       if (mips_trap)
9251         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9252       else
9253         {
9254           if (mips_opts.micromips)
9255             micromips_label_expr (&label_expr);
9256           else
9257             label_expr.X_add_number = 8;
9258           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9259           macro_build (NULL, "nop", "");
9260           macro_build (NULL, "break", BRK_FMT, 6);
9261           if (mips_opts.micromips)
9262             micromips_add_label ();
9263         }
9264       end_noreorder ();
9265       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9266       break;
9267
9268     case M_DMULOU_I:
9269       dbl = 1;
9270     case M_MULOU_I:
9271       imm = 1;
9272       goto do_mulou;
9273
9274     case M_DMULOU:
9275       dbl = 1;
9276     case M_MULOU:
9277     do_mulou:
9278       start_noreorder ();
9279       used_at = 1;
9280       if (imm)
9281         load_register (AT, &imm_expr, dbl);
9282       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9283                    sreg, imm ? AT : treg);
9284       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9285       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9286       if (mips_trap)
9287         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9288       else
9289         {
9290           if (mips_opts.micromips)
9291             micromips_label_expr (&label_expr);
9292           else
9293             label_expr.X_add_number = 8;
9294           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9295           macro_build (NULL, "nop", "");
9296           macro_build (NULL, "break", BRK_FMT, 6);
9297           if (mips_opts.micromips)
9298             micromips_add_label ();
9299         }
9300       end_noreorder ();
9301       break;
9302
9303     case M_DROL:
9304       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9305         {
9306           if (dreg == sreg)
9307             {
9308               tempreg = AT;
9309               used_at = 1;
9310             }
9311           else
9312             {
9313               tempreg = dreg;
9314             }
9315           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9316           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9317           break;
9318         }
9319       used_at = 1;
9320       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9321       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9322       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9323       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9324       break;
9325
9326     case M_ROL:
9327       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9328         {
9329           if (dreg == sreg)
9330             {
9331               tempreg = AT;
9332               used_at = 1;
9333             }
9334           else
9335             {
9336               tempreg = dreg;
9337             }
9338           macro_build (NULL, "negu", "d,w", tempreg, treg);
9339           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
9340           break;
9341         }
9342       used_at = 1;
9343       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9344       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
9345       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
9346       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9347       break;
9348
9349     case M_DROL_I:
9350       {
9351         unsigned int rot;
9352         char *l;
9353         char *rr;
9354
9355         if (imm_expr.X_op != O_constant)
9356           as_bad (_("Improper rotate count"));
9357         rot = imm_expr.X_add_number & 0x3f;
9358         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9359           {
9360             rot = (64 - rot) & 0x3f;
9361             if (rot >= 32)
9362               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9363             else
9364               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9365             break;
9366           }
9367         if (rot == 0)
9368           {
9369             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9370             break;
9371           }
9372         l = (rot < 0x20) ? "dsll" : "dsll32";
9373         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
9374         rot &= 0x1f;
9375         used_at = 1;
9376         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
9377         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9378         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9379       }
9380       break;
9381
9382     case M_ROL_I:
9383       {
9384         unsigned int rot;
9385
9386         if (imm_expr.X_op != O_constant)
9387           as_bad (_("Improper rotate count"));
9388         rot = imm_expr.X_add_number & 0x1f;
9389         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9390           {
9391             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
9392             break;
9393           }
9394         if (rot == 0)
9395           {
9396             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9397             break;
9398           }
9399         used_at = 1;
9400         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
9401         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9402         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9403       }
9404       break;
9405
9406     case M_DROR:
9407       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9408         {
9409           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
9410           break;
9411         }
9412       used_at = 1;
9413       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9414       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
9415       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
9416       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9417       break;
9418
9419     case M_ROR:
9420       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9421         {
9422           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
9423           break;
9424         }
9425       used_at = 1;
9426       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9427       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
9428       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
9429       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9430       break;
9431
9432     case M_DROR_I:
9433       {
9434         unsigned int rot;
9435         char *l;
9436         char *rr;
9437
9438         if (imm_expr.X_op != O_constant)
9439           as_bad (_("Improper rotate count"));
9440         rot = imm_expr.X_add_number & 0x3f;
9441         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9442           {
9443             if (rot >= 32)
9444               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9445             else
9446               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9447             break;
9448           }
9449         if (rot == 0)
9450           {
9451             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9452             break;
9453           }
9454         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
9455         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
9456         rot &= 0x1f;
9457         used_at = 1;
9458         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
9459         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9460         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9461       }
9462       break;
9463
9464     case M_ROR_I:
9465       {
9466         unsigned int rot;
9467
9468         if (imm_expr.X_op != O_constant)
9469           as_bad (_("Improper rotate count"));
9470         rot = imm_expr.X_add_number & 0x1f;
9471         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9472           {
9473             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
9474             break;
9475           }
9476         if (rot == 0)
9477           {
9478             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9479             break;
9480           }
9481         used_at = 1;
9482         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
9483         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9484         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9485       }
9486       break;
9487
9488     case M_SEQ:
9489       if (sreg == 0)
9490         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
9491       else if (treg == 0)
9492         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9493       else
9494         {
9495           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9496           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9497         }
9498       break;
9499
9500     case M_SEQ_I:
9501       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9502         {
9503           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9504           break;
9505         }
9506       if (sreg == 0)
9507         {
9508           as_warn (_("Instruction %s: result is always false"),
9509                    ip->insn_mo->name);
9510           move_register (dreg, 0);
9511           break;
9512         }
9513       if (CPU_HAS_SEQ (mips_opts.arch)
9514           && -512 <= imm_expr.X_add_number
9515           && imm_expr.X_add_number < 512)
9516         {
9517           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
9518                        (int) imm_expr.X_add_number);
9519           break;
9520         }
9521       if (imm_expr.X_op == O_constant
9522           && imm_expr.X_add_number >= 0
9523           && imm_expr.X_add_number < 0x10000)
9524         {
9525           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9526         }
9527       else if (imm_expr.X_op == O_constant
9528                && imm_expr.X_add_number > -0x8000
9529                && imm_expr.X_add_number < 0)
9530         {
9531           imm_expr.X_add_number = -imm_expr.X_add_number;
9532           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9533                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9534         }
9535       else if (CPU_HAS_SEQ (mips_opts.arch))
9536         {
9537           used_at = 1;
9538           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9539           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
9540           break;
9541         }
9542       else
9543         {
9544           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9545           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9546           used_at = 1;
9547         }
9548       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9549       break;
9550
9551     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
9552       s = "slt";
9553       goto sge;
9554     case M_SGEU:
9555       s = "sltu";
9556     sge:
9557       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
9558       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9559       break;
9560
9561     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
9562     case M_SGEU_I:
9563       if (imm_expr.X_op == O_constant
9564           && imm_expr.X_add_number >= -0x8000
9565           && imm_expr.X_add_number < 0x8000)
9566         {
9567           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
9568                        dreg, sreg, BFD_RELOC_LO16);
9569         }
9570       else
9571         {
9572           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9573           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
9574                        dreg, sreg, AT);
9575           used_at = 1;
9576         }
9577       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9578       break;
9579
9580     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
9581       s = "slt";
9582       goto sgt;
9583     case M_SGTU:
9584       s = "sltu";
9585     sgt:
9586       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9587       break;
9588
9589     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
9590       s = "slt";
9591       goto sgti;
9592     case M_SGTU_I:
9593       s = "sltu";
9594     sgti:
9595       used_at = 1;
9596       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9597       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9598       break;
9599
9600     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
9601       s = "slt";
9602       goto sle;
9603     case M_SLEU:
9604       s = "sltu";
9605     sle:
9606       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9607       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9608       break;
9609
9610     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
9611       s = "slt";
9612       goto slei;
9613     case M_SLEU_I:
9614       s = "sltu";
9615     slei:
9616       used_at = 1;
9617       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9618       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9619       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9620       break;
9621
9622     case M_SLT_I:
9623       if (imm_expr.X_op == O_constant
9624           && imm_expr.X_add_number >= -0x8000
9625           && imm_expr.X_add_number < 0x8000)
9626         {
9627           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9628           break;
9629         }
9630       used_at = 1;
9631       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9632       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
9633       break;
9634
9635     case M_SLTU_I:
9636       if (imm_expr.X_op == O_constant
9637           && imm_expr.X_add_number >= -0x8000
9638           && imm_expr.X_add_number < 0x8000)
9639         {
9640           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
9641                        BFD_RELOC_LO16);
9642           break;
9643         }
9644       used_at = 1;
9645       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9646       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
9647       break;
9648
9649     case M_SNE:
9650       if (sreg == 0)
9651         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
9652       else if (treg == 0)
9653         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9654       else
9655         {
9656           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9657           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9658         }
9659       break;
9660
9661     case M_SNE_I:
9662       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9663         {
9664           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9665           break;
9666         }
9667       if (sreg == 0)
9668         {
9669           as_warn (_("Instruction %s: result is always true"),
9670                    ip->insn_mo->name);
9671           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
9672                        dreg, 0, BFD_RELOC_LO16);
9673           break;
9674         }
9675       if (CPU_HAS_SEQ (mips_opts.arch)
9676           && -512 <= imm_expr.X_add_number
9677           && imm_expr.X_add_number < 512)
9678         {
9679           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
9680                        (int) imm_expr.X_add_number);
9681           break;
9682         }
9683       if (imm_expr.X_op == O_constant
9684           && imm_expr.X_add_number >= 0
9685           && imm_expr.X_add_number < 0x10000)
9686         {
9687           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9688         }
9689       else if (imm_expr.X_op == O_constant
9690                && imm_expr.X_add_number > -0x8000
9691                && imm_expr.X_add_number < 0)
9692         {
9693           imm_expr.X_add_number = -imm_expr.X_add_number;
9694           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9695                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9696         }
9697       else if (CPU_HAS_SEQ (mips_opts.arch))
9698         {
9699           used_at = 1;
9700           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9701           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
9702           break;
9703         }
9704       else
9705         {
9706           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9707           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9708           used_at = 1;
9709         }
9710       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9711       break;
9712
9713     case M_SUB_I:
9714       s = "addi";
9715       s2 = "sub";
9716       goto do_subi;
9717     case M_SUBU_I:
9718       s = "addiu";
9719       s2 = "subu";
9720       goto do_subi;
9721     case M_DSUB_I:
9722       dbl = 1;
9723       s = "daddi";
9724       s2 = "dsub";
9725       if (!mips_opts.micromips)
9726         goto do_subi;
9727       if (imm_expr.X_op == O_constant
9728           && imm_expr.X_add_number > -0x200
9729           && imm_expr.X_add_number <= 0x200)
9730         {
9731           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
9732           break;
9733         }
9734       goto do_subi_i;
9735     case M_DSUBU_I:
9736       dbl = 1;
9737       s = "daddiu";
9738       s2 = "dsubu";
9739     do_subi:
9740       if (imm_expr.X_op == O_constant
9741           && imm_expr.X_add_number > -0x8000
9742           && imm_expr.X_add_number <= 0x8000)
9743         {
9744           imm_expr.X_add_number = -imm_expr.X_add_number;
9745           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9746           break;
9747         }
9748     do_subi_i:
9749       used_at = 1;
9750       load_register (AT, &imm_expr, dbl);
9751       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
9752       break;
9753
9754     case M_TEQ_I:
9755       s = "teq";
9756       goto trap;
9757     case M_TGE_I:
9758       s = "tge";
9759       goto trap;
9760     case M_TGEU_I:
9761       s = "tgeu";
9762       goto trap;
9763     case M_TLT_I:
9764       s = "tlt";
9765       goto trap;
9766     case M_TLTU_I:
9767       s = "tltu";
9768       goto trap;
9769     case M_TNE_I:
9770       s = "tne";
9771     trap:
9772       used_at = 1;
9773       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9774       macro_build (NULL, s, "s,t", sreg, AT);
9775       break;
9776
9777     case M_TRUNCWS:
9778     case M_TRUNCWD:
9779       gas_assert (!mips_opts.micromips);
9780       gas_assert (mips_opts.isa == ISA_MIPS1);
9781       used_at = 1;
9782       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
9783       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
9784
9785       /*
9786        * Is the double cfc1 instruction a bug in the mips assembler;
9787        * or is there a reason for it?
9788        */
9789       start_noreorder ();
9790       macro_build (NULL, "cfc1", "t,G", treg, RA);
9791       macro_build (NULL, "cfc1", "t,G", treg, RA);
9792       macro_build (NULL, "nop", "");
9793       expr1.X_add_number = 3;
9794       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
9795       expr1.X_add_number = 2;
9796       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
9797       macro_build (NULL, "ctc1", "t,G", AT, RA);
9798       macro_build (NULL, "nop", "");
9799       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
9800                    dreg, sreg);
9801       macro_build (NULL, "ctc1", "t,G", treg, RA);
9802       macro_build (NULL, "nop", "");
9803       end_noreorder ();
9804       break;
9805
9806     case M_ULH_A:
9807       ab = 1;
9808     case M_ULH:
9809       s = "lb";
9810       s2 = "lbu";
9811       off = 1;
9812       goto uld_st;
9813     case M_ULHU_A:
9814       ab = 1;
9815     case M_ULHU:
9816       s = "lbu";
9817       s2 = "lbu";
9818       off = 1;
9819       goto uld_st;
9820     case M_ULW_A:
9821       ab = 1;
9822     case M_ULW:
9823       s = "lwl";
9824       s2 = "lwr";
9825       off12 = mips_opts.micromips;
9826       off = 3;
9827       goto uld_st;
9828     case M_ULD_A:
9829       ab = 1;
9830     case M_ULD:
9831       s = "ldl";
9832       s2 = "ldr";
9833       off12 = mips_opts.micromips;
9834       off = 7;
9835       goto uld_st;
9836     case M_USH_A:
9837       ab = 1;
9838     case M_USH:
9839       s = "sb";
9840       s2 = "sb";
9841       off = 1;
9842       ust = 1;
9843       goto uld_st;
9844     case M_USW_A:
9845       ab = 1;
9846     case M_USW:
9847       s = "swl";
9848       s2 = "swr";
9849       off12 = mips_opts.micromips;
9850       off = 3;
9851       ust = 1;
9852       goto uld_st;
9853     case M_USD_A:
9854       ab = 1;
9855     case M_USD:
9856       s = "sdl";
9857       s2 = "sdr";
9858       off12 = mips_opts.micromips;
9859       off = 7;
9860       ust = 1;
9861
9862     uld_st:
9863       if (!ab && offset_expr.X_add_number >= 0x8000 - off)
9864         as_bad (_("Operand overflow"));
9865
9866       ep = &offset_expr;
9867       expr1.X_add_number = 0;
9868       if (ab)
9869         {
9870           used_at = 1;
9871           tempreg = AT;
9872           load_address (tempreg, ep, &used_at);
9873           if (breg != 0)
9874             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9875                          tempreg, tempreg, breg);
9876           breg = tempreg;
9877           tempreg = treg;
9878           ep = &expr1;
9879         }
9880       else if (off12
9881                && (offset_expr.X_op != O_constant
9882                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number)
9883                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number + off)))
9884         {
9885           used_at = 1;
9886           tempreg = AT;
9887           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg,
9888                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9889           breg = tempreg;
9890           tempreg = treg;
9891           ep = &expr1;
9892         }
9893       else if (!ust && treg == breg)
9894         {
9895           used_at = 1;
9896           tempreg = AT;
9897         }
9898       else
9899         tempreg = treg;
9900
9901       if (off == 1)
9902         goto ulh_sh;
9903
9904       if (!target_big_endian)
9905         ep->X_add_number += off;
9906       if (!off12)
9907         macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9908       else
9909         macro_build (NULL, s, "t,~(b)",
9910                      tempreg, (unsigned long) ep->X_add_number, breg);
9911
9912       if (!target_big_endian)
9913         ep->X_add_number -= off;
9914       else
9915         ep->X_add_number += off;
9916       if (!off12)
9917         macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9918       else
9919         macro_build (NULL, s2, "t,~(b)",
9920                      tempreg, (unsigned long) ep->X_add_number, breg);
9921
9922       /* If necessary, move the result in tempreg to the final destination.  */
9923       if (!ust && treg != tempreg)
9924         {
9925           /* Protect second load's delay slot.  */
9926           load_delay_nop ();
9927           move_register (treg, tempreg);
9928         }
9929       break;
9930
9931     ulh_sh:
9932       used_at = 1;
9933       if (target_big_endian == ust)
9934         ep->X_add_number += off;
9935       tempreg = ust || ab ? treg : AT;
9936       macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9937
9938       /* For halfword transfers we need a temporary register to shuffle
9939          bytes.  Unfortunately for M_USH_A we have none available before
9940          the next store as AT holds the base address.  We deal with this
9941          case by clobbering TREG and then restoring it as with ULH.  */
9942       tempreg = ust == ab ? treg : AT;
9943       if (ust)
9944         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
9945
9946       if (target_big_endian == ust)
9947         ep->X_add_number -= off;
9948       else
9949         ep->X_add_number += off;
9950       macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9951
9952       /* For M_USH_A re-retrieve the LSB.  */
9953       if (ust && ab)
9954         {
9955           if (target_big_endian)
9956             ep->X_add_number += off;
9957           else
9958             ep->X_add_number -= off;
9959           macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
9960         }
9961       /* For ULH and M_USH_A OR the LSB in.  */
9962       if (!ust || ab)
9963         {
9964           tempreg = !ab ? AT : treg;
9965           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
9966           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
9967         }
9968       break;
9969
9970     default:
9971       /* FIXME: Check if this is one of the itbl macros, since they
9972          are added dynamically.  */
9973       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
9974       break;
9975     }
9976   if (!mips_opts.at && used_at)
9977     as_bad (_("Macro used $at after \".set noat\""));
9978 }
9979
9980 /* Implement macros in mips16 mode.  */
9981
9982 static void
9983 mips16_macro (struct mips_cl_insn *ip)
9984 {
9985   int mask;
9986   int xreg, yreg, zreg, tmp;
9987   expressionS expr1;
9988   int dbl;
9989   const char *s, *s2, *s3;
9990
9991   mask = ip->insn_mo->mask;
9992
9993   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
9994   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
9995   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
9996
9997   expr1.X_op = O_constant;
9998   expr1.X_op_symbol = NULL;
9999   expr1.X_add_symbol = NULL;
10000   expr1.X_add_number = 1;
10001
10002   dbl = 0;
10003
10004   switch (mask)
10005     {
10006     default:
10007       internalError ();
10008
10009     case M_DDIV_3:
10010       dbl = 1;
10011     case M_DIV_3:
10012       s = "mflo";
10013       goto do_div3;
10014     case M_DREM_3:
10015       dbl = 1;
10016     case M_REM_3:
10017       s = "mfhi";
10018     do_div3:
10019       start_noreorder ();
10020       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
10021       expr1.X_add_number = 2;
10022       macro_build (&expr1, "bnez", "x,p", yreg);
10023       macro_build (NULL, "break", "6", 7);
10024
10025       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
10026          since that causes an overflow.  We should do that as well,
10027          but I don't see how to do the comparisons without a temporary
10028          register.  */
10029       end_noreorder ();
10030       macro_build (NULL, s, "x", zreg);
10031       break;
10032
10033     case M_DIVU_3:
10034       s = "divu";
10035       s2 = "mflo";
10036       goto do_divu3;
10037     case M_REMU_3:
10038       s = "divu";
10039       s2 = "mfhi";
10040       goto do_divu3;
10041     case M_DDIVU_3:
10042       s = "ddivu";
10043       s2 = "mflo";
10044       goto do_divu3;
10045     case M_DREMU_3:
10046       s = "ddivu";
10047       s2 = "mfhi";
10048     do_divu3:
10049       start_noreorder ();
10050       macro_build (NULL, s, "0,x,y", xreg, yreg);
10051       expr1.X_add_number = 2;
10052       macro_build (&expr1, "bnez", "x,p", yreg);
10053       macro_build (NULL, "break", "6", 7);
10054       end_noreorder ();
10055       macro_build (NULL, s2, "x", zreg);
10056       break;
10057
10058     case M_DMUL:
10059       dbl = 1;
10060     case M_MUL:
10061       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
10062       macro_build (NULL, "mflo", "x", zreg);
10063       break;
10064
10065     case M_DSUBU_I:
10066       dbl = 1;
10067       goto do_subu;
10068     case M_SUBU_I:
10069     do_subu:
10070       if (imm_expr.X_op != O_constant)
10071         as_bad (_("Unsupported large constant"));
10072       imm_expr.X_add_number = -imm_expr.X_add_number;
10073       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10074       break;
10075
10076     case M_SUBU_I_2:
10077       if (imm_expr.X_op != O_constant)
10078         as_bad (_("Unsupported large constant"));
10079       imm_expr.X_add_number = -imm_expr.X_add_number;
10080       macro_build (&imm_expr, "addiu", "x,k", xreg);
10081       break;
10082
10083     case M_DSUBU_I_2:
10084       if (imm_expr.X_op != O_constant)
10085         as_bad (_("Unsupported large constant"));
10086       imm_expr.X_add_number = -imm_expr.X_add_number;
10087       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10088       break;
10089
10090     case M_BEQ:
10091       s = "cmp";
10092       s2 = "bteqz";
10093       goto do_branch;
10094     case M_BNE:
10095       s = "cmp";
10096       s2 = "btnez";
10097       goto do_branch;
10098     case M_BLT:
10099       s = "slt";
10100       s2 = "btnez";
10101       goto do_branch;
10102     case M_BLTU:
10103       s = "sltu";
10104       s2 = "btnez";
10105       goto do_branch;
10106     case M_BLE:
10107       s = "slt";
10108       s2 = "bteqz";
10109       goto do_reverse_branch;
10110     case M_BLEU:
10111       s = "sltu";
10112       s2 = "bteqz";
10113       goto do_reverse_branch;
10114     case M_BGE:
10115       s = "slt";
10116       s2 = "bteqz";
10117       goto do_branch;
10118     case M_BGEU:
10119       s = "sltu";
10120       s2 = "bteqz";
10121       goto do_branch;
10122     case M_BGT:
10123       s = "slt";
10124       s2 = "btnez";
10125       goto do_reverse_branch;
10126     case M_BGTU:
10127       s = "sltu";
10128       s2 = "btnez";
10129
10130     do_reverse_branch:
10131       tmp = xreg;
10132       xreg = yreg;
10133       yreg = tmp;
10134
10135     do_branch:
10136       macro_build (NULL, s, "x,y", xreg, yreg);
10137       macro_build (&offset_expr, s2, "p");
10138       break;
10139
10140     case M_BEQ_I:
10141       s = "cmpi";
10142       s2 = "bteqz";
10143       s3 = "x,U";
10144       goto do_branch_i;
10145     case M_BNE_I:
10146       s = "cmpi";
10147       s2 = "btnez";
10148       s3 = "x,U";
10149       goto do_branch_i;
10150     case M_BLT_I:
10151       s = "slti";
10152       s2 = "btnez";
10153       s3 = "x,8";
10154       goto do_branch_i;
10155     case M_BLTU_I:
10156       s = "sltiu";
10157       s2 = "btnez";
10158       s3 = "x,8";
10159       goto do_branch_i;
10160     case M_BLE_I:
10161       s = "slti";
10162       s2 = "btnez";
10163       s3 = "x,8";
10164       goto do_addone_branch_i;
10165     case M_BLEU_I:
10166       s = "sltiu";
10167       s2 = "btnez";
10168       s3 = "x,8";
10169       goto do_addone_branch_i;
10170     case M_BGE_I:
10171       s = "slti";
10172       s2 = "bteqz";
10173       s3 = "x,8";
10174       goto do_branch_i;
10175     case M_BGEU_I:
10176       s = "sltiu";
10177       s2 = "bteqz";
10178       s3 = "x,8";
10179       goto do_branch_i;
10180     case M_BGT_I:
10181       s = "slti";
10182       s2 = "bteqz";
10183       s3 = "x,8";
10184       goto do_addone_branch_i;
10185     case M_BGTU_I:
10186       s = "sltiu";
10187       s2 = "bteqz";
10188       s3 = "x,8";
10189
10190     do_addone_branch_i:
10191       if (imm_expr.X_op != O_constant)
10192         as_bad (_("Unsupported large constant"));
10193       ++imm_expr.X_add_number;
10194
10195     do_branch_i:
10196       macro_build (&imm_expr, s, s3, xreg);
10197       macro_build (&offset_expr, s2, "p");
10198       break;
10199
10200     case M_ABS:
10201       expr1.X_add_number = 0;
10202       macro_build (&expr1, "slti", "x,8", yreg);
10203       if (xreg != yreg)
10204         move_register (xreg, yreg);
10205       expr1.X_add_number = 2;
10206       macro_build (&expr1, "bteqz", "p");
10207       macro_build (NULL, "neg", "x,w", xreg, xreg);
10208     }
10209 }
10210
10211 /* For consistency checking, verify that all bits are specified either
10212    by the match/mask part of the instruction definition, or by the
10213    operand list.  */
10214 static int
10215 validate_mips_insn (const struct mips_opcode *opc)
10216 {
10217   const char *p = opc->args;
10218   char c;
10219   unsigned long used_bits = opc->mask;
10220
10221   if ((used_bits & opc->match) != opc->match)
10222     {
10223       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
10224               opc->name, opc->args);
10225       return 0;
10226     }
10227 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
10228   while (*p)
10229     switch (c = *p++)
10230       {
10231       case ',': break;
10232       case '(': break;
10233       case ')': break;
10234       case '+':
10235         switch (c = *p++)
10236           {
10237           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
10238           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
10239           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
10240           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
10241           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10242           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10243           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10244           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
10245                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10246           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10247           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10248           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10249           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10250           case 'I': break;
10251           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
10252           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
10253                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10254           case 'x': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10255           case 'X': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10256           case 'p': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10257           case 'P': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10258           case 'Q': USE_BITS (OP_MASK_SEQI,     OP_SH_SEQI);    break;
10259           case 's': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10260           case 'S': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10261           case 'z': USE_BITS (OP_MASK_RZ,       OP_SH_RZ);      break;
10262           case 'Z': USE_BITS (OP_MASK_FZ,       OP_SH_FZ);      break;
10263           case 'a': USE_BITS (OP_MASK_OFFSET_A, OP_SH_OFFSET_A); break;
10264           case 'b': USE_BITS (OP_MASK_OFFSET_B, OP_SH_OFFSET_B); break;
10265           case 'c': USE_BITS (OP_MASK_OFFSET_C, OP_SH_OFFSET_C); break;
10266
10267           default:
10268             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
10269                     c, opc->name, opc->args);
10270             return 0;
10271           }
10272         break;
10273       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10274       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10275       case 'A': break;
10276       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
10277       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
10278       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10279       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10280       case 'F': break;
10281       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10282       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
10283       case 'I': break;
10284       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
10285       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10286       case 'L': break;
10287       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
10288       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
10289       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
10290       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
10291                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10292       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
10293       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10294       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10295       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10296       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10297       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10298       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10299       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10300       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
10301       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10302       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
10303       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10304       case 'f': break;
10305       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
10306       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10307       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10308       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
10309       case 'l': break;
10310       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10311       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10312       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
10313       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10314       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10315       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10316       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10317       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10318       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10319       case 'x': break;
10320       case 'z': break;
10321       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
10322       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
10323                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10324       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
10325       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
10326       case '[': break;
10327       case ']': break;
10328       case '1': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10329       case '2': USE_BITS (OP_MASK_BP,           OP_SH_BP);      break;
10330       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
10331       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
10332       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
10333       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10334       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
10335       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
10336       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
10337       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
10338       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
10339       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
10340       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
10341       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
10342       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
10343       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
10344       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
10345       case '\\': USE_BITS (OP_MASK_3BITPOS,     OP_SH_3BITPOS); break;
10346       case '~': USE_BITS (OP_MASK_OFFSET12,     OP_SH_OFFSET12); break;
10347       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10348       default:
10349         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
10350                 c, opc->name, opc->args);
10351         return 0;
10352       }
10353 #undef USE_BITS
10354   if (used_bits != 0xffffffff)
10355     {
10356       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
10357               ~used_bits & 0xffffffff, opc->name, opc->args);
10358       return 0;
10359     }
10360   return 1;
10361 }
10362
10363 /* For consistency checking, verify that the length implied matches the
10364    major opcode and that all bits are specified either by the match/mask
10365    part of the instruction definition, or by the operand list.  */
10366
10367 static int
10368 validate_micromips_insn (const struct mips_opcode *opc)
10369 {
10370   unsigned long match = opc->match;
10371   unsigned long mask = opc->mask;
10372   const char *p = opc->args;
10373   unsigned long insn_bits;
10374   unsigned long used_bits;
10375   unsigned long major;
10376   unsigned int length;
10377   char e;
10378   char c;
10379
10380   if ((mask & match) != match)
10381     {
10382       as_bad (_("Internal error: bad microMIPS opcode (mask error): %s %s"),
10383               opc->name, opc->args);
10384       return 0;
10385     }
10386   length = micromips_insn_length (opc);
10387   if (length != 2 && length != 4)
10388     {
10389       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
10390                 "%s %s"), length, opc->name, opc->args);
10391       return 0;
10392     }
10393   major = match >> (10 + 8 * (length - 2));
10394   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
10395       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
10396     {
10397       as_bad (_("Internal error: bad microMIPS opcode "
10398                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
10399       return 0;
10400     }
10401
10402   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
10403   insn_bits = 1 << 4 * length;
10404   insn_bits <<= 4 * length;
10405   insn_bits -= 1;
10406   used_bits = mask;
10407 #define USE_BITS(field) \
10408   (used_bits |= MICROMIPSOP_MASK_##field << MICROMIPSOP_SH_##field)
10409   while (*p)
10410     switch (c = *p++)
10411       {
10412       case ',': break;
10413       case '(': break;
10414       case ')': break;
10415       case '+':
10416         e = c;
10417         switch (c = *p++)
10418           {
10419           case 'A': USE_BITS (EXTLSB);  break;
10420           case 'B': USE_BITS (INSMSB);  break;
10421           case 'C': USE_BITS (EXTMSBD); break;
10422           case 'D': USE_BITS (RS);      USE_BITS (SEL); break;
10423           case 'E': USE_BITS (EXTLSB);  break;
10424           case 'F': USE_BITS (INSMSB);  break;
10425           case 'G': USE_BITS (EXTMSBD); break;
10426           case 'H': USE_BITS (EXTMSBD); break;
10427           default:
10428             as_bad (_("Internal error: bad mips opcode "
10429                       "(unknown extension operand type `%c%c'): %s %s"),
10430                     e, c, opc->name, opc->args);
10431             return 0;
10432           }
10433         break;
10434       case 'm':
10435         e = c;
10436         switch (c = *p++)
10437           {
10438           case 'A': USE_BITS (IMMA);    break;
10439           case 'B': USE_BITS (IMMB);    break;
10440           case 'C': USE_BITS (IMMC);    break;
10441           case 'D': USE_BITS (IMMD);    break;
10442           case 'E': USE_BITS (IMME);    break;
10443           case 'F': USE_BITS (IMMF);    break;
10444           case 'G': USE_BITS (IMMG);    break;
10445           case 'H': USE_BITS (IMMH);    break;
10446           case 'I': USE_BITS (IMMI);    break;
10447           case 'J': USE_BITS (IMMJ);    break;
10448           case 'L': USE_BITS (IMML);    break;
10449           case 'M': USE_BITS (IMMM);    break;
10450           case 'N': USE_BITS (IMMN);    break;
10451           case 'O': USE_BITS (IMMO);    break;
10452           case 'P': USE_BITS (IMMP);    break;
10453           case 'Q': USE_BITS (IMMQ);    break;
10454           case 'U': USE_BITS (IMMU);    break;
10455           case 'W': USE_BITS (IMMW);    break;
10456           case 'X': USE_BITS (IMMX);    break;
10457           case 'Y': USE_BITS (IMMY);    break;
10458           case 'Z': break;
10459           case 'a': break;
10460           case 'b': USE_BITS (MB);      break;
10461           case 'c': USE_BITS (MC);      break;
10462           case 'd': USE_BITS (MD);      break;
10463           case 'e': USE_BITS (ME);      break;
10464           case 'f': USE_BITS (MF);      break;
10465           case 'g': USE_BITS (MG);      break;
10466           case 'h': USE_BITS (MH);      break;
10467           case 'i': USE_BITS (MI);      break;
10468           case 'j': USE_BITS (MJ);      break;
10469           case 'l': USE_BITS (ML);      break;
10470           case 'm': USE_BITS (MM);      break;
10471           case 'n': USE_BITS (MN);      break;
10472           case 'p': USE_BITS (MP);      break;
10473           case 'q': USE_BITS (MQ);      break;
10474           case 'r': break;
10475           case 's': break;
10476           case 't': break;
10477           case 'x': break;
10478           case 'y': break;
10479           case 'z': break;
10480           default:
10481             as_bad (_("Internal error: bad mips opcode "
10482                       "(unknown extension operand type `%c%c'): %s %s"),
10483                     e, c, opc->name, opc->args);
10484             return 0;
10485           }
10486         break;
10487       case '.': USE_BITS (OFFSET10);    break;
10488       case '1': USE_BITS (STYPE);       break;
10489       case '<': USE_BITS (SHAMT);       break;
10490       case '>': USE_BITS (SHAMT);       break;
10491       case 'B': USE_BITS (CODE10);      break;
10492       case 'C': USE_BITS (COPZ);        break;
10493       case 'D': USE_BITS (FD);          break;
10494       case 'E': USE_BITS (RT);          break;
10495       case 'G': USE_BITS (RS);          break;
10496       case 'H': USE_BITS (SEL);         break;
10497       case 'K': USE_BITS (RS);          break;
10498       case 'M': USE_BITS (CCC);         break;
10499       case 'N': USE_BITS (BCC);         break;
10500       case 'R': USE_BITS (FR);          break;
10501       case 'S': USE_BITS (FS);          break;
10502       case 'T': USE_BITS (FT);          break;
10503       case 'V': USE_BITS (FS);          break;
10504       case '\\': USE_BITS (3BITPOS);    break;
10505       case 'a': USE_BITS (TARGET);      break;
10506       case 'b': USE_BITS (RS);          break;
10507       case 'c': USE_BITS (CODE);        break;
10508       case 'd': USE_BITS (RD);          break;
10509       case 'h': USE_BITS (PREFX);       break;
10510       case 'i': USE_BITS (IMMEDIATE);   break;
10511       case 'j': USE_BITS (DELTA);       break;
10512       case 'k': USE_BITS (CACHE);       break;
10513       case 'n': USE_BITS (RT);          break;
10514       case 'o': USE_BITS (DELTA);       break;
10515       case 'p': USE_BITS (DELTA);       break;
10516       case 'q': USE_BITS (CODE2);       break;
10517       case 'r': USE_BITS (RS);          break;
10518       case 's': USE_BITS (RS);          break;
10519       case 't': USE_BITS (RT);          break;
10520       case 'u': USE_BITS (IMMEDIATE);   break;
10521       case 'v': USE_BITS (RS);          break;
10522       case 'w': USE_BITS (RT);          break;
10523       case 'y': USE_BITS (RS3);         break;
10524       case 'z': break;
10525       case '|': USE_BITS (TRAP);        break;
10526       case '~': USE_BITS (OFFSET12);    break;
10527       default:
10528         as_bad (_("Internal error: bad microMIPS opcode "
10529                   "(unknown operand type `%c'): %s %s"),
10530                 c, opc->name, opc->args);
10531         return 0;
10532       }
10533 #undef USE_BITS
10534   if (used_bits != insn_bits)
10535     {
10536       if (~used_bits & insn_bits)
10537         as_bad (_("Internal error: bad microMIPS opcode "
10538                   "(bits 0x%lx undefined): %s %s"),
10539                 ~used_bits & insn_bits, opc->name, opc->args);
10540       if (used_bits & ~insn_bits)
10541         as_bad (_("Internal error: bad microMIPS opcode "
10542                   "(bits 0x%lx defined): %s %s"),
10543                 used_bits & ~insn_bits, opc->name, opc->args);
10544       return 0;
10545     }
10546   return 1;
10547 }
10548
10549 /* UDI immediates.  */
10550 struct mips_immed {
10551   char          type;
10552   unsigned int  shift;
10553   unsigned long mask;
10554   const char *  desc;
10555 };
10556
10557 static const struct mips_immed mips_immed[] = {
10558   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
10559   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
10560   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
10561   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
10562   { 0,0,0,0 }
10563 };
10564
10565 /* Check whether an odd floating-point register is allowed.  */
10566 static int
10567 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
10568 {
10569   const char *s = insn->name;
10570
10571   if (insn->pinfo == INSN_MACRO)
10572     /* Let a macro pass, we'll catch it later when it is expanded.  */
10573     return 1;
10574
10575   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa))
10576     {
10577       /* Allow odd registers for single-precision ops.  */
10578       switch (insn->pinfo & (FP_S | FP_D))
10579         {
10580         case FP_S:
10581         case 0:
10582           return 1;     /* both single precision - ok */
10583         case FP_D:
10584           return 0;     /* both double precision - fail */
10585         default:
10586           break;
10587         }
10588
10589       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
10590       s = strchr (insn->name, '.');
10591       if (argnum == 2)
10592         s = s != NULL ? strchr (s + 1, '.') : NULL;
10593       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
10594     } 
10595
10596   /* Single-precision coprocessor loads and moves are OK too.  */
10597   if ((insn->pinfo & FP_S)
10598       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
10599                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
10600     return 1;
10601
10602   return 0;
10603 }
10604
10605 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
10606    taking bits from BIT up.  */
10607 static int
10608 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
10609 {
10610   return (ep->X_op == O_constant
10611           && (ep->X_add_number & ((1 << bit) - 1)) == 0
10612           && ep->X_add_number >= min << bit
10613           && ep->X_add_number < max << bit);
10614 }
10615
10616 /* This routine assembles an instruction into its binary format.  As a
10617    side effect, it sets one of the global variables imm_reloc or
10618    offset_reloc to the type of relocation to do if one of the operands
10619    is an address expression.  */
10620
10621 static void
10622 mips_ip (char *str, struct mips_cl_insn *ip)
10623 {
10624   bfd_boolean wrong_delay_slot_insns = FALSE;
10625   bfd_boolean need_delay_slot_ok = TRUE;
10626   struct mips_opcode *firstinsn = NULL;
10627   const struct mips_opcode *past;
10628   struct hash_control *hash;
10629   char *s;
10630   const char *args;
10631   char c = 0;
10632   struct mips_opcode *insn;
10633   char *argsStart;
10634   unsigned int regno;
10635   unsigned int lastregno;
10636   unsigned int destregno = 0;
10637   unsigned int lastpos = 0;
10638   unsigned int limlo, limhi;
10639   char *s_reset;
10640   offsetT min_range, max_range;
10641   long opend;
10642   char *name;
10643   int argnum;
10644   unsigned int rtype;
10645   char *dot;
10646   long end;
10647
10648   insn_error = NULL;
10649
10650   if (mips_opts.micromips)
10651     {
10652       hash = micromips_op_hash;
10653       past = &micromips_opcodes[bfd_micromips_num_opcodes];
10654     }
10655   else
10656     {
10657       hash = op_hash;
10658       past = &mips_opcodes[NUMOPCODES];
10659     }
10660   forced_insn_length = 0;
10661   insn = NULL;
10662
10663   /* We first try to match an instruction up to a space or to the end.  */
10664   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
10665     continue;
10666
10667   /* Make a copy of the instruction so that we can fiddle with it.  */
10668   name = alloca (end + 1);
10669   memcpy (name, str, end);
10670   name[end] = '\0';
10671
10672   for (;;)
10673     {
10674       insn = (struct mips_opcode *) hash_find (hash, name);
10675
10676       if (insn != NULL || !mips_opts.micromips)
10677         break;
10678       if (forced_insn_length)
10679         break;
10680
10681       /* See if there's an instruction size override suffix,
10682          either `16' or `32', at the end of the mnemonic proper,
10683          that defines the operation, i.e. before the first `.'
10684          character if any.  Strip it and retry.  */
10685       dot = strchr (name, '.');
10686       opend = dot != NULL ? dot - name : end;
10687       if (opend < 3)
10688         break;
10689       if (name[opend - 2] == '1' && name[opend - 1] == '6')
10690         forced_insn_length = 2;
10691       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
10692         forced_insn_length = 4;
10693       else
10694         break;
10695       memcpy (name + opend - 2, name + opend, end - opend + 1);
10696     }
10697   if (insn == NULL)
10698     {
10699       insn_error = _("Unrecognized opcode");
10700       return;
10701     }
10702
10703   /* For microMIPS instructions placed in a fixed-length branch delay slot
10704      we make up to two passes over the relevant fragment of the opcode
10705      table.  First we try instructions that meet the delay slot's length
10706      requirement.  If none matched, then we retry with the remaining ones
10707      and if one matches, then we use it and then issue an appropriate
10708      warning later on.  */
10709   argsStart = s = str + end;
10710   for (;;)
10711     {
10712       bfd_boolean delay_slot_ok;
10713       bfd_boolean size_ok;
10714       bfd_boolean ok;
10715
10716       gas_assert (strcmp (insn->name, name) == 0);
10717
10718       ok = is_opcode_valid (insn);
10719       size_ok = is_size_valid (insn);
10720       delay_slot_ok = is_delay_slot_valid (insn);
10721       if (!delay_slot_ok && !wrong_delay_slot_insns)
10722         {
10723           firstinsn = insn;
10724           wrong_delay_slot_insns = TRUE;
10725         }
10726       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
10727         {
10728           static char buf[256];
10729
10730           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
10731             {
10732               ++insn;
10733               continue;
10734             }
10735           if (wrong_delay_slot_insns && need_delay_slot_ok)
10736             {
10737               gas_assert (firstinsn);
10738               need_delay_slot_ok = FALSE;
10739               past = insn + 1;
10740               insn = firstinsn;
10741               continue;
10742             }
10743
10744           if (insn_error)
10745             return;
10746
10747           if (!ok)
10748             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
10749                      mips_cpu_info_from_arch (mips_opts.arch)->name,
10750                      mips_cpu_info_from_isa (mips_opts.isa)->name);
10751           else
10752             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
10753                      8 * forced_insn_length);
10754           insn_error = buf;
10755
10756           return;
10757         }
10758
10759       create_insn (ip, insn);
10760       insn_error = NULL;
10761       argnum = 1;
10762       lastregno = 0xffffffff;
10763       for (args = insn->args;; ++args)
10764         {
10765           int is_mdmx;
10766
10767           s += strspn (s, " \t");
10768           is_mdmx = 0;
10769           switch (*args)
10770             {
10771             case '\0':          /* end of args */
10772               if (*s == '\0')
10773                 return;
10774               break;
10775
10776             case '2': /* DSP 2-bit unsigned immediate in bit 11.  */
10777               gas_assert (!mips_opts.micromips);
10778               my_getExpression (&imm_expr, s);
10779               check_absolute_expr (ip, &imm_expr);
10780               if ((unsigned long) imm_expr.X_add_number != 1
10781                   && (unsigned long) imm_expr.X_add_number != 3)
10782                 {
10783                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
10784                           (unsigned long) imm_expr.X_add_number);
10785                 }
10786               INSERT_OPERAND (0, BP, *ip, imm_expr.X_add_number);
10787               imm_expr.X_op = O_absent;
10788               s = expr_end;
10789               continue;
10790
10791             case '3': /* DSP 3-bit unsigned immediate in bit 21.  */
10792               gas_assert (!mips_opts.micromips);
10793               my_getExpression (&imm_expr, s);
10794               check_absolute_expr (ip, &imm_expr);
10795               if (imm_expr.X_add_number & ~OP_MASK_SA3)
10796                 {
10797                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10798                           OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
10799                 }
10800               INSERT_OPERAND (0, SA3, *ip, imm_expr.X_add_number);
10801               imm_expr.X_op = O_absent;
10802               s = expr_end;
10803               continue;
10804
10805             case '4': /* DSP 4-bit unsigned immediate in bit 21.  */
10806               gas_assert (!mips_opts.micromips);
10807               my_getExpression (&imm_expr, s);
10808               check_absolute_expr (ip, &imm_expr);
10809               if (imm_expr.X_add_number & ~OP_MASK_SA4)
10810                 {
10811                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10812                           OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
10813                 }
10814               INSERT_OPERAND (0, SA4, *ip, imm_expr.X_add_number);
10815               imm_expr.X_op = O_absent;
10816               s = expr_end;
10817               continue;
10818
10819             case '5': /* DSP 8-bit unsigned immediate in bit 16.  */
10820               gas_assert (!mips_opts.micromips);
10821               my_getExpression (&imm_expr, s);
10822               check_absolute_expr (ip, &imm_expr);
10823               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
10824                 {
10825                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10826                           OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
10827                 }
10828               INSERT_OPERAND (0, IMM8, *ip, imm_expr.X_add_number);
10829               imm_expr.X_op = O_absent;
10830               s = expr_end;
10831               continue;
10832
10833             case '6': /* DSP 5-bit unsigned immediate in bit 21.  */
10834               gas_assert (!mips_opts.micromips);
10835               my_getExpression (&imm_expr, s);
10836               check_absolute_expr (ip, &imm_expr);
10837               if (imm_expr.X_add_number & ~OP_MASK_RS)
10838                 {
10839                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10840                           OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
10841                 }
10842               INSERT_OPERAND (0, RS, *ip, imm_expr.X_add_number);
10843               imm_expr.X_op = O_absent;
10844               s = expr_end;
10845               continue;
10846
10847             case '7': /* Four DSP accumulators in bits 11,12.  */
10848               gas_assert (!mips_opts.micromips);
10849               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10850                   s[3] >= '0' && s[3] <= '3')
10851                 {
10852                   regno = s[3] - '0';
10853                   s += 4;
10854                   INSERT_OPERAND (0, DSPACC, *ip, regno);
10855                   continue;
10856                 }
10857               else
10858                 as_bad (_("Invalid dsp acc register"));
10859               break;
10860
10861             case '8': /* DSP 6-bit unsigned immediate in bit 11.  */
10862               gas_assert (!mips_opts.micromips);
10863               my_getExpression (&imm_expr, s);
10864               check_absolute_expr (ip, &imm_expr);
10865               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
10866                 {
10867                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10868                           OP_MASK_WRDSP,
10869                           (unsigned long) imm_expr.X_add_number);
10870                 }
10871               INSERT_OPERAND (0, WRDSP, *ip, imm_expr.X_add_number);
10872               imm_expr.X_op = O_absent;
10873               s = expr_end;
10874               continue;
10875
10876             case '9': /* Four DSP accumulators in bits 21,22.  */
10877               gas_assert (!mips_opts.micromips);
10878               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10879                   s[3] >= '0' && s[3] <= '3')
10880                 {
10881                   regno = s[3] - '0';
10882                   s += 4;
10883                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
10884                   continue;
10885                 }
10886               else
10887                 as_bad (_("Invalid dsp acc register"));
10888               break;
10889
10890             case '0': /* DSP 6-bit signed immediate in bit 20.  */
10891               gas_assert (!mips_opts.micromips);
10892               my_getExpression (&imm_expr, s);
10893               check_absolute_expr (ip, &imm_expr);
10894               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
10895               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
10896               if (imm_expr.X_add_number < min_range ||
10897                   imm_expr.X_add_number > max_range)
10898                 {
10899                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10900                           (long) min_range, (long) max_range,
10901                           (long) imm_expr.X_add_number);
10902                 }
10903               INSERT_OPERAND (0, DSPSFT, *ip, imm_expr.X_add_number);
10904               imm_expr.X_op = O_absent;
10905               s = expr_end;
10906               continue;
10907
10908             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
10909               gas_assert (!mips_opts.micromips);
10910               my_getExpression (&imm_expr, s);
10911               check_absolute_expr (ip, &imm_expr);
10912               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
10913                 {
10914                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10915                           OP_MASK_RDDSP,
10916                           (unsigned long) imm_expr.X_add_number);
10917                 }
10918               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
10919               imm_expr.X_op = O_absent;
10920               s = expr_end;
10921               continue;
10922
10923             case ':': /* DSP 7-bit signed immediate in bit 19.  */
10924               gas_assert (!mips_opts.micromips);
10925               my_getExpression (&imm_expr, s);
10926               check_absolute_expr (ip, &imm_expr);
10927               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
10928               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
10929               if (imm_expr.X_add_number < min_range ||
10930                   imm_expr.X_add_number > max_range)
10931                 {
10932                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10933                           (long) min_range, (long) max_range,
10934                           (long) imm_expr.X_add_number);
10935                 }
10936               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
10937               imm_expr.X_op = O_absent;
10938               s = expr_end;
10939               continue;
10940
10941             case '@': /* DSP 10-bit signed immediate in bit 16.  */
10942               gas_assert (!mips_opts.micromips);
10943               my_getExpression (&imm_expr, s);
10944               check_absolute_expr (ip, &imm_expr);
10945               min_range = -((OP_MASK_IMM10 + 1) >> 1);
10946               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
10947               if (imm_expr.X_add_number < min_range ||
10948                   imm_expr.X_add_number > max_range)
10949                 {
10950                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10951                           (long) min_range, (long) max_range,
10952                           (long) imm_expr.X_add_number);
10953                 }
10954               INSERT_OPERAND (0, IMM10, *ip, imm_expr.X_add_number);
10955               imm_expr.X_op = O_absent;
10956               s = expr_end;
10957               continue;
10958
10959             case '!': /* MT usermode flag bit.  */
10960               gas_assert (!mips_opts.micromips);
10961               my_getExpression (&imm_expr, s);
10962               check_absolute_expr (ip, &imm_expr);
10963               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
10964                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
10965                         (unsigned long) imm_expr.X_add_number);
10966               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
10967               imm_expr.X_op = O_absent;
10968               s = expr_end;
10969               continue;
10970
10971             case '$': /* MT load high flag bit.  */
10972               gas_assert (!mips_opts.micromips);
10973               my_getExpression (&imm_expr, s);
10974               check_absolute_expr (ip, &imm_expr);
10975               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
10976                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
10977                         (unsigned long) imm_expr.X_add_number);
10978               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
10979               imm_expr.X_op = O_absent;
10980               s = expr_end;
10981               continue;
10982
10983             case '*': /* Four DSP accumulators in bits 18,19.  */
10984               gas_assert (!mips_opts.micromips);
10985               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10986                   s[3] >= '0' && s[3] <= '3')
10987                 {
10988                   regno = s[3] - '0';
10989                   s += 4;
10990                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
10991                   continue;
10992                 }
10993               else
10994                 as_bad (_("Invalid dsp/smartmips acc register"));
10995               break;
10996
10997             case '&': /* Four DSP accumulators in bits 13,14.  */
10998               gas_assert (!mips_opts.micromips);
10999               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11000                   s[3] >= '0' && s[3] <= '3')
11001                 {
11002                   regno = s[3] - '0';
11003                   s += 4;
11004                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
11005                   continue;
11006                 }
11007               else
11008                 as_bad (_("Invalid dsp/smartmips acc register"));
11009               break;
11010
11011             case '\\':          /* 3-bit bit position.  */
11012               {
11013                 unsigned long mask = (mips_opts.micromips
11014                                       ? MICROMIPSOP_MASK_3BITPOS
11015                                       : OP_MASK_3BITPOS);
11016
11017                 my_getExpression (&imm_expr, s);
11018                 check_absolute_expr (ip, &imm_expr);
11019                 if ((unsigned long) imm_expr.X_add_number > mask)
11020                   as_warn (_("Bit position for %s not in range 0..%lu (%lu)"),
11021                            ip->insn_mo->name,
11022                            mask, (unsigned long) imm_expr.X_add_number);
11023                 INSERT_OPERAND (mips_opts.micromips,
11024                                 3BITPOS, *ip, imm_expr.X_add_number);
11025                 imm_expr.X_op = O_absent;
11026                 s = expr_end;
11027               }
11028               continue;
11029
11030             case ',':
11031               ++argnum;
11032               if (*s++ == *args)
11033                 continue;
11034               s--;
11035               switch (*++args)
11036                 {
11037                 case 'r':
11038                 case 'v':
11039                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11040                   continue;
11041
11042                 case 'w':
11043                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11044                   continue;
11045
11046                 case 'W':
11047                   gas_assert (!mips_opts.micromips);
11048                   INSERT_OPERAND (0, FT, *ip, lastregno);
11049                   continue;
11050
11051                 case 'V':
11052                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11053                   continue;
11054                 }
11055               break;
11056
11057             case '(':
11058               /* Handle optional base register.
11059                  Either the base register is omitted or
11060                  we must have a left paren.  */
11061               /* This is dependent on the next operand specifier
11062                  is a base register specification.  */
11063               gas_assert (args[1] == 'b'
11064                           || (mips_opts.micromips
11065                               && args[1] == 'm'
11066                               && (args[2] == 'l' || args[2] == 'n'
11067                                   || args[2] == 's' || args[2] == 'a')));
11068               if (*s == '\0' && args[1] == 'b')
11069                 return;
11070               /* Fall through.  */
11071
11072             case ')':           /* These must match exactly.  */
11073               if (*s++ == *args)
11074                 continue;
11075               break;
11076
11077             case '[':           /* These must match exactly.  */
11078             case ']':
11079               gas_assert (!mips_opts.micromips);
11080               if (*s++ == *args)
11081                 continue;
11082               break;
11083
11084             case '+':           /* Opcode extension character.  */
11085               switch (*++args)
11086                 {
11087                 case '1':       /* UDI immediates.  */
11088                 case '2':
11089                 case '3':
11090                 case '4':
11091                   gas_assert (!mips_opts.micromips);
11092                   {
11093                     const struct mips_immed *imm = mips_immed;
11094
11095                     while (imm->type && imm->type != *args)
11096                       ++imm;
11097                     if (! imm->type)
11098                       internalError ();
11099                     my_getExpression (&imm_expr, s);
11100                     check_absolute_expr (ip, &imm_expr);
11101                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11102                       {
11103                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11104                                  imm->desc ? imm->desc : ip->insn_mo->name,
11105                                  (unsigned long) imm_expr.X_add_number,
11106                                  (unsigned long) imm_expr.X_add_number);
11107                         imm_expr.X_add_number &= imm->mask;
11108                       }
11109                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11110                                         << imm->shift);
11111                     imm_expr.X_op = O_absent;
11112                     s = expr_end;
11113                   }
11114                   continue;
11115
11116                 case 'A':               /* ins/ext position, becomes LSB.  */
11117                   limlo = 0;
11118                   limhi = 31;
11119                   goto do_lsb;
11120                 case 'E':
11121                   limlo = 32;
11122                   limhi = 63;
11123                   goto do_lsb;
11124                 do_lsb:
11125                   my_getExpression (&imm_expr, s);
11126                   check_absolute_expr (ip, &imm_expr);
11127                   if ((unsigned long) imm_expr.X_add_number < limlo
11128                       || (unsigned long) imm_expr.X_add_number > limhi)
11129                     {
11130                       as_bad (_("Improper position (%lu)"),
11131                               (unsigned long) imm_expr.X_add_number);
11132                       imm_expr.X_add_number = limlo;
11133                     }
11134                   lastpos = imm_expr.X_add_number;
11135                   INSERT_OPERAND (mips_opts.micromips,
11136                                   EXTLSB, *ip, imm_expr.X_add_number);
11137                   imm_expr.X_op = O_absent;
11138                   s = expr_end;
11139                   continue;
11140
11141                 case 'B':               /* ins size, becomes MSB.  */
11142                   limlo = 1;
11143                   limhi = 32;
11144                   goto do_msb;
11145                 case 'F':
11146                   limlo = 33;
11147                   limhi = 64;
11148                   goto do_msb;
11149                 do_msb:
11150                   my_getExpression (&imm_expr, s);
11151                   check_absolute_expr (ip, &imm_expr);
11152                   /* Check for negative input so that small negative numbers
11153                      will not succeed incorrectly.  The checks against
11154                      (pos+size) transitively check "size" itself,
11155                      assuming that "pos" is reasonable.  */
11156                   if ((long) imm_expr.X_add_number < 0
11157                       || ((unsigned long) imm_expr.X_add_number
11158                           + lastpos) < limlo
11159                       || ((unsigned long) imm_expr.X_add_number
11160                           + lastpos) > limhi)
11161                     {
11162                       as_bad (_("Improper insert size (%lu, position %lu)"),
11163                               (unsigned long) imm_expr.X_add_number,
11164                               (unsigned long) lastpos);
11165                       imm_expr.X_add_number = limlo - lastpos;
11166                     }
11167                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11168                                   lastpos + imm_expr.X_add_number - 1);
11169                   imm_expr.X_op = O_absent;
11170                   s = expr_end;
11171                   continue;
11172
11173                 case 'C':               /* ext size, becomes MSBD.  */
11174                   limlo = 1;
11175                   limhi = 32;
11176                   goto do_msbd;
11177                 case 'G':
11178                   limlo = 33;
11179                   limhi = 64;
11180                   goto do_msbd;
11181                 case 'H':
11182                   limlo = 33;
11183                   limhi = 64;
11184                   goto do_msbd;
11185                 do_msbd:
11186                   my_getExpression (&imm_expr, s);
11187                   check_absolute_expr (ip, &imm_expr);
11188                   /* Check for negative input so that small negative numbers
11189                      will not succeed incorrectly.  The checks against
11190                      (pos+size) transitively check "size" itself,
11191                      assuming that "pos" is reasonable.  */
11192                   if ((long) imm_expr.X_add_number < 0
11193                       || ((unsigned long) imm_expr.X_add_number
11194                           + lastpos) < limlo
11195                       || ((unsigned long) imm_expr.X_add_number
11196                           + lastpos) > limhi)
11197                     {
11198                       as_bad (_("Improper extract size (%lu, position %lu)"),
11199                               (unsigned long) imm_expr.X_add_number,
11200                               (unsigned long) lastpos);
11201                       imm_expr.X_add_number = limlo - lastpos;
11202                     }
11203                   INSERT_OPERAND (mips_opts.micromips,
11204                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11205                   imm_expr.X_op = O_absent;
11206                   s = expr_end;
11207                   continue;
11208
11209                 case 'D':
11210                   /* +D is for disassembly only; never match.  */
11211                   break;
11212
11213                 case 'I':
11214                   /* "+I" is like "I", except that imm2_expr is used.  */
11215                   my_getExpression (&imm2_expr, s);
11216                   if (imm2_expr.X_op != O_big
11217                       && imm2_expr.X_op != O_constant)
11218                   insn_error = _("absolute expression required");
11219                   if (HAVE_32BIT_GPRS)
11220                     normalize_constant_expr (&imm2_expr);
11221                   s = expr_end;
11222                   continue;
11223
11224                 case 'T': /* Coprocessor register.  */
11225                   gas_assert (!mips_opts.micromips);
11226                   /* +T is for disassembly only; never match.  */
11227                   break;
11228
11229                 case 't': /* Coprocessor register number.  */
11230                   gas_assert (!mips_opts.micromips);
11231                   if (s[0] == '$' && ISDIGIT (s[1]))
11232                     {
11233                       ++s;
11234                       regno = 0;
11235                       do
11236                         {
11237                           regno *= 10;
11238                           regno += *s - '0';
11239                           ++s;
11240                         }
11241                       while (ISDIGIT (*s));
11242                       if (regno > 31)
11243                         as_bad (_("Invalid register number (%d)"), regno);
11244                       else
11245                         {
11246                           INSERT_OPERAND (0, RT, *ip, regno);
11247                           continue;
11248                         }
11249                     }
11250                   else
11251                     as_bad (_("Invalid coprocessor 0 register number"));
11252                   break;
11253
11254                 case 'x':
11255                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11256                      is not in the valid range.  */
11257                   gas_assert (!mips_opts.micromips);
11258                   my_getExpression (&imm_expr, s);
11259                   check_absolute_expr (ip, &imm_expr);
11260                   if ((unsigned) imm_expr.X_add_number > 31)
11261                     {
11262                       as_bad (_("Improper bit index (%lu)"),
11263                               (unsigned long) imm_expr.X_add_number);
11264                       imm_expr.X_add_number = 0;
11265                     }
11266                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11267                   imm_expr.X_op = O_absent;
11268                   s = expr_end;
11269                   continue;
11270
11271                 case 'X':
11272                   /* bbit[01] bit index when bbit is used but we generate
11273                      bbit[01]32 because the index is over 32.  Move to the
11274                      next candidate if index is not in the valid range.  */
11275                   gas_assert (!mips_opts.micromips);
11276                   my_getExpression (&imm_expr, s);
11277                   check_absolute_expr (ip, &imm_expr);
11278                   if ((unsigned) imm_expr.X_add_number < 32
11279                       || (unsigned) imm_expr.X_add_number > 63)
11280                     break;
11281                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11282                   imm_expr.X_op = O_absent;
11283                   s = expr_end;
11284                   continue;
11285
11286                 case 'p':
11287                   /* cins, cins32, exts and exts32 position field.  Give error
11288                      if it's not in the valid range.  */
11289                   gas_assert (!mips_opts.micromips);
11290                   my_getExpression (&imm_expr, s);
11291                   check_absolute_expr (ip, &imm_expr);
11292                   if ((unsigned) imm_expr.X_add_number > 31)
11293                     {
11294                       as_bad (_("Improper position (%lu)"),
11295                               (unsigned long) imm_expr.X_add_number);
11296                       imm_expr.X_add_number = 0;
11297                     }
11298                   /* Make the pos explicit to simplify +S.  */
11299                   lastpos = imm_expr.X_add_number + 32;
11300                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
11301                   imm_expr.X_op = O_absent;
11302                   s = expr_end;
11303                   continue;
11304
11305                 case 'P':
11306                   /* cins, cins32, exts and exts32 position field.  Move to
11307                      the next candidate if it's not in the valid range.  */
11308                   gas_assert (!mips_opts.micromips);
11309                   my_getExpression (&imm_expr, s);
11310                   check_absolute_expr (ip, &imm_expr);
11311                   if ((unsigned) imm_expr.X_add_number < 32
11312                       || (unsigned) imm_expr.X_add_number > 63)
11313                     break;
11314                   lastpos = imm_expr.X_add_number;
11315                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
11316                   imm_expr.X_op = O_absent;
11317                   s = expr_end;
11318                   continue;
11319
11320                 case 's':
11321                   /* cins and exts length-minus-one field.  */
11322                   gas_assert (!mips_opts.micromips);
11323                   my_getExpression (&imm_expr, s);
11324                   check_absolute_expr (ip, &imm_expr);
11325                   if ((unsigned long) imm_expr.X_add_number > 31)
11326                     {
11327                       as_bad (_("Improper size (%lu)"),
11328                               (unsigned long) imm_expr.X_add_number);
11329                       imm_expr.X_add_number = 0;
11330                     }
11331                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11332                   imm_expr.X_op = O_absent;
11333                   s = expr_end;
11334                   continue;
11335
11336                 case 'S':
11337                   /* cins32/exts32 and cins/exts aliasing cint32/exts32
11338                      length-minus-one field.  */
11339                   gas_assert (!mips_opts.micromips);
11340                   my_getExpression (&imm_expr, s);
11341                   check_absolute_expr (ip, &imm_expr);
11342                   if ((long) imm_expr.X_add_number < 0
11343                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
11344                     {
11345                       as_bad (_("Improper size (%lu)"),
11346                               (unsigned long) imm_expr.X_add_number);
11347                       imm_expr.X_add_number = 0;
11348                     }
11349                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11350                   imm_expr.X_op = O_absent;
11351                   s = expr_end;
11352                   continue;
11353
11354                 case 'Q':
11355                   /* seqi/snei immediate field.  */
11356                   gas_assert (!mips_opts.micromips);
11357                   my_getExpression (&imm_expr, s);
11358                   check_absolute_expr (ip, &imm_expr);
11359                   if ((long) imm_expr.X_add_number < -512
11360                       || (long) imm_expr.X_add_number >= 512)
11361                     {
11362                       as_bad (_("Improper immediate (%ld)"),
11363                                (long) imm_expr.X_add_number);
11364                       imm_expr.X_add_number = 0;
11365                     }
11366                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
11367                   imm_expr.X_op = O_absent;
11368                   s = expr_end;
11369                   continue;
11370
11371                 case 'a': /* 8-bit signed offset in bit 6 */
11372                   gas_assert (!mips_opts.micromips);
11373                   my_getExpression (&imm_expr, s);
11374                   check_absolute_expr (ip, &imm_expr);
11375                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
11376                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
11377                   if (imm_expr.X_add_number < min_range
11378                       || imm_expr.X_add_number > max_range)
11379                     {
11380                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11381                               (long) min_range, (long) max_range,
11382                               (long) imm_expr.X_add_number);
11383                     }
11384                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
11385                   imm_expr.X_op = O_absent;
11386                   s = expr_end;
11387                   continue;
11388
11389                 case 'b': /* 8-bit signed offset in bit 3 */
11390                   gas_assert (!mips_opts.micromips);
11391                   my_getExpression (&imm_expr, s);
11392                   check_absolute_expr (ip, &imm_expr);
11393                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
11394                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
11395                   if (imm_expr.X_add_number < min_range
11396                       || imm_expr.X_add_number > max_range)
11397                     {
11398                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11399                               (long) min_range, (long) max_range,
11400                               (long) imm_expr.X_add_number);
11401                     }
11402                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
11403                   imm_expr.X_op = O_absent;
11404                   s = expr_end;
11405                   continue;
11406
11407                 case 'c': /* 9-bit signed offset in bit 6 */
11408                   gas_assert (!mips_opts.micromips);
11409                   my_getExpression (&imm_expr, s);
11410                   check_absolute_expr (ip, &imm_expr);
11411                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
11412                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
11413                   /* We check the offset range before adjusted.  */
11414                   min_range <<= 4;
11415                   max_range <<= 4;
11416                   if (imm_expr.X_add_number < min_range
11417                       || imm_expr.X_add_number > max_range)
11418                     {
11419                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11420                               (long) min_range, (long) max_range,
11421                               (long) imm_expr.X_add_number);
11422                     }
11423                   if (imm_expr.X_add_number & 0xf)
11424                     {
11425                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
11426                               (long) imm_expr.X_add_number);
11427                     }
11428                   /* Right shift 4 bits to adjust the offset operand.  */
11429                   INSERT_OPERAND (0, OFFSET_C, *ip,
11430                                   imm_expr.X_add_number >> 4);
11431                   imm_expr.X_op = O_absent;
11432                   s = expr_end;
11433                   continue;
11434
11435                 case 'z':
11436                   gas_assert (!mips_opts.micromips);
11437                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
11438                     break;
11439                   if (regno == AT && mips_opts.at)
11440                     {
11441                       if (mips_opts.at == ATREG)
11442                         as_warn (_("used $at without \".set noat\""));
11443                       else
11444                         as_warn (_("used $%u with \".set at=$%u\""),
11445                                  regno, mips_opts.at);
11446                     }
11447                   INSERT_OPERAND (0, RZ, *ip, regno);
11448                   continue;
11449
11450                 case 'Z':
11451                   gas_assert (!mips_opts.micromips);
11452                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
11453                     break;
11454                   INSERT_OPERAND (0, FZ, *ip, regno);
11455                   continue;
11456
11457                 default:
11458                   as_bad (_("Internal error: bad %s opcode "
11459                             "(unknown extension operand type `+%c'): %s %s"),
11460                           mips_opts.micromips ? "microMIPS" : "MIPS",
11461                           *args, insn->name, insn->args);
11462                   /* Further processing is fruitless.  */
11463                   return;
11464                 }
11465               break;
11466
11467             case '.':           /* 10-bit offset.  */
11468               gas_assert (mips_opts.micromips);
11469             case '~':           /* 12-bit offset.  */
11470               {
11471                 int shift = *args == '.' ? 9 : 11;
11472                 size_t i;
11473
11474                 /* Check whether there is only a single bracketed expression
11475                    left.  If so, it must be the base register and the
11476                    constant must be zero.  */
11477                 if (*s == '(' && strchr (s + 1, '(') == 0)
11478                   continue;
11479
11480                 /* If this value won't fit into the offset, then go find
11481                    a macro that will generate a 16- or 32-bit offset code
11482                    pattern.  */
11483                 i = my_getSmallExpression (&imm_expr, imm_reloc, s);
11484                 if ((i == 0 && (imm_expr.X_op != O_constant
11485                                 || imm_expr.X_add_number >= 1 << shift
11486                                 || imm_expr.X_add_number < -1 << shift))
11487                     || i > 0)
11488                   {
11489                     imm_expr.X_op = O_absent;
11490                     break;
11491                   }
11492                 if (shift == 9)
11493                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
11494                 else
11495                   INSERT_OPERAND (mips_opts.micromips,
11496                                   OFFSET12, *ip, imm_expr.X_add_number);
11497                 imm_expr.X_op = O_absent;
11498                 s = expr_end;
11499               }
11500               continue;
11501
11502             case '<':           /* must be at least one digit */
11503               /*
11504                * According to the manual, if the shift amount is greater
11505                * than 31 or less than 0, then the shift amount should be
11506                * mod 32.  In reality the mips assembler issues an error.
11507                * We issue a warning and mask out all but the low 5 bits.
11508                */
11509               my_getExpression (&imm_expr, s);
11510               check_absolute_expr (ip, &imm_expr);
11511               if ((unsigned long) imm_expr.X_add_number > 31)
11512                 as_warn (_("Improper shift amount (%lu)"),
11513                          (unsigned long) imm_expr.X_add_number);
11514               INSERT_OPERAND (mips_opts.micromips,
11515                               SHAMT, *ip, imm_expr.X_add_number);
11516               imm_expr.X_op = O_absent;
11517               s = expr_end;
11518               continue;
11519
11520             case '>':           /* shift amount minus 32 */
11521               my_getExpression (&imm_expr, s);
11522               check_absolute_expr (ip, &imm_expr);
11523               if ((unsigned long) imm_expr.X_add_number < 32
11524                   || (unsigned long) imm_expr.X_add_number > 63)
11525                 break;
11526               INSERT_OPERAND (mips_opts.micromips,
11527                               SHAMT, *ip, imm_expr.X_add_number - 32);
11528               imm_expr.X_op = O_absent;
11529               s = expr_end;
11530               continue;
11531
11532             case 'k':           /* CACHE code.  */
11533             case 'h':           /* PREFX code.  */
11534             case '1':           /* SYNC type.  */
11535               my_getExpression (&imm_expr, s);
11536               check_absolute_expr (ip, &imm_expr);
11537               if ((unsigned long) imm_expr.X_add_number > 31)
11538                 as_warn (_("Invalid value for `%s' (%lu)"),
11539                          ip->insn_mo->name,
11540                          (unsigned long) imm_expr.X_add_number);
11541               switch (*args)
11542                 {
11543                 case 'k':
11544                   if (mips_fix_cn63xxp1
11545                       && !mips_opts.micromips
11546                       && strcmp ("pref", insn->name) == 0)
11547                     switch (imm_expr.X_add_number)
11548                       {
11549                       case 5:
11550                       case 25:
11551                       case 26:
11552                       case 27:
11553                       case 28:
11554                       case 29:
11555                       case 30:
11556                       case 31:  /* These are ok.  */
11557                         break;
11558
11559                       default:  /* The rest must be changed to 28.  */
11560                         imm_expr.X_add_number = 28;
11561                         break;
11562                       }
11563                   INSERT_OPERAND (mips_opts.micromips,
11564                                   CACHE, *ip, imm_expr.X_add_number);
11565                   break;
11566                 case 'h':
11567                   INSERT_OPERAND (mips_opts.micromips,
11568                                   PREFX, *ip, imm_expr.X_add_number);
11569                   break;
11570                 case '1':
11571                   INSERT_OPERAND (mips_opts.micromips,
11572                                   STYPE, *ip, imm_expr.X_add_number);
11573                   break;
11574                 }
11575               imm_expr.X_op = O_absent;
11576               s = expr_end;
11577               continue;
11578
11579             case 'c':           /* BREAK code.  */
11580               {
11581                 unsigned long mask = (mips_opts.micromips
11582                                       ? MICROMIPSOP_MASK_CODE
11583                                       : OP_MASK_CODE);
11584
11585                 my_getExpression (&imm_expr, s);
11586                 check_absolute_expr (ip, &imm_expr);
11587                 if ((unsigned long) imm_expr.X_add_number > mask)
11588                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11589                            ip->insn_mo->name,
11590                            mask, (unsigned long) imm_expr.X_add_number);
11591                 INSERT_OPERAND (mips_opts.micromips,
11592                                 CODE, *ip, imm_expr.X_add_number);
11593                 imm_expr.X_op = O_absent;
11594                 s = expr_end;
11595               }
11596               continue;
11597
11598             case 'q':           /* Lower BREAK code.  */
11599               {
11600                 unsigned long mask = (mips_opts.micromips
11601                                       ? MICROMIPSOP_MASK_CODE2
11602                                       : OP_MASK_CODE2);
11603
11604                 my_getExpression (&imm_expr, s);
11605                 check_absolute_expr (ip, &imm_expr);
11606                 if ((unsigned long) imm_expr.X_add_number > mask)
11607                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
11608                            ip->insn_mo->name,
11609                            mask, (unsigned long) imm_expr.X_add_number);
11610                 INSERT_OPERAND (mips_opts.micromips,
11611                                 CODE2, *ip, imm_expr.X_add_number);
11612                 imm_expr.X_op = O_absent;
11613                 s = expr_end;
11614               }
11615               continue;
11616
11617             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
11618               {
11619                 unsigned long mask = (mips_opts.micromips
11620                                       ? MICROMIPSOP_MASK_CODE10
11621                                       : OP_MASK_CODE20);
11622
11623                 my_getExpression (&imm_expr, s);
11624                 check_absolute_expr (ip, &imm_expr);
11625                 if ((unsigned long) imm_expr.X_add_number > mask)
11626                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11627                            ip->insn_mo->name,
11628                            mask, (unsigned long) imm_expr.X_add_number);
11629                 if (mips_opts.micromips)
11630                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
11631                 else
11632                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
11633                 imm_expr.X_op = O_absent;
11634                 s = expr_end;
11635               }
11636               continue;
11637
11638             case 'C':           /* 25- or 23-bit coprocessor code.  */
11639               {
11640                 unsigned long mask = (mips_opts.micromips
11641                                       ? MICROMIPSOP_MASK_COPZ
11642                                       : OP_MASK_COPZ);
11643
11644                 my_getExpression (&imm_expr, s);
11645                 check_absolute_expr (ip, &imm_expr);
11646                 if ((unsigned long) imm_expr.X_add_number > mask)
11647                   as_warn (_("Coproccesor code > %u bits (%lu)"),
11648                            mips_opts.micromips ? 23U : 25U,
11649                            (unsigned long) imm_expr.X_add_number);
11650                 INSERT_OPERAND (mips_opts.micromips,
11651                                 COPZ, *ip, imm_expr.X_add_number);
11652                 imm_expr.X_op = O_absent;
11653                 s = expr_end;
11654               }
11655               continue;
11656
11657             case 'J':           /* 19-bit WAIT code.  */
11658               gas_assert (!mips_opts.micromips);
11659               my_getExpression (&imm_expr, s);
11660               check_absolute_expr (ip, &imm_expr);
11661               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
11662                 {
11663                   as_warn (_("Illegal 19-bit code (%lu)"),
11664                            (unsigned long) imm_expr.X_add_number);
11665                   imm_expr.X_add_number &= OP_MASK_CODE19;
11666                 }
11667               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
11668               imm_expr.X_op = O_absent;
11669               s = expr_end;
11670               continue;
11671
11672             case 'P':           /* Performance register.  */
11673               gas_assert (!mips_opts.micromips);
11674               my_getExpression (&imm_expr, s);
11675               check_absolute_expr (ip, &imm_expr);
11676               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
11677                 as_warn (_("Invalid performance register (%lu)"),
11678                          (unsigned long) imm_expr.X_add_number);
11679               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
11680               imm_expr.X_op = O_absent;
11681               s = expr_end;
11682               continue;
11683
11684             case 'G':           /* Coprocessor destination register.  */
11685               {
11686                 unsigned long opcode = ip->insn_opcode;
11687                 unsigned long mask;
11688                 unsigned int types;
11689                 int cop0;
11690
11691                 if (mips_opts.micromips)
11692                   {
11693                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
11694                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
11695                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
11696                     opcode &= mask;
11697                     switch (opcode)
11698                       {
11699                       case 0x000000fc:                          /* mfc0  */
11700                       case 0x000002fc:                          /* mtc0  */
11701                       case 0x580000fc:                          /* dmfc0 */
11702                       case 0x580002fc:                          /* dmtc0 */
11703                         cop0 = 1;
11704                         break;
11705                       default:
11706                         cop0 = 0;
11707                         break;
11708                       }
11709                   }
11710                 else
11711                   {
11712                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
11713                     cop0 = opcode == OP_OP_COP0;
11714                   }
11715                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
11716                 ok = reg_lookup (&s, types, &regno);
11717                 if (mips_opts.micromips)
11718                   INSERT_OPERAND (1, RS, *ip, regno);
11719                 else
11720                   INSERT_OPERAND (0, RD, *ip, regno);
11721                 if (ok)
11722                   {
11723                     lastregno = regno;
11724                     continue;
11725                   }
11726               }
11727               break;
11728
11729             case 'y':           /* ALNV.PS source register.  */
11730               gas_assert (mips_opts.micromips);
11731               goto do_reg;
11732             case 'x':           /* Ignore register name.  */
11733             case 'U':           /* Destination register (CLO/CLZ).  */
11734             case 'g':           /* Coprocessor destination register.  */
11735               gas_assert (!mips_opts.micromips);
11736             case 'b':           /* Base register.  */
11737             case 'd':           /* Destination register.  */
11738             case 's':           /* Source register.  */
11739             case 't':           /* Target register.  */
11740             case 'r':           /* Both target and source.  */
11741             case 'v':           /* Both dest and source.  */
11742             case 'w':           /* Both dest and target.  */
11743             case 'E':           /* Coprocessor target register.  */
11744             case 'K':           /* RDHWR destination register.  */
11745             case 'z':           /* Must be zero register.  */
11746             do_reg:
11747               s_reset = s;
11748               if (*args == 'E' || *args == 'K')
11749                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
11750               else
11751                 {
11752                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
11753                   if (regno == AT && mips_opts.at)
11754                     {
11755                       if (mips_opts.at == ATREG)
11756                         as_warn (_("Used $at without \".set noat\""));
11757                       else
11758                         as_warn (_("Used $%u with \".set at=$%u\""),
11759                                  regno, mips_opts.at);
11760                     }
11761                 }
11762               if (ok)
11763                 {
11764                   c = *args;
11765                   if (*s == ' ')
11766                     ++s;
11767                   if (args[1] != *s)
11768                     {
11769                       if (c == 'r' || c == 'v' || c == 'w')
11770                         {
11771                           regno = lastregno;
11772                           s = s_reset;
11773                           ++args;
11774                         }
11775                     }
11776                   /* 'z' only matches $0.  */
11777                   if (c == 'z' && regno != 0)
11778                     break;
11779
11780                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
11781                     {
11782                       if (regno == lastregno)
11783                         {
11784                           insn_error
11785                             = _("Source and destination must be different");
11786                           continue;
11787                         }
11788                       if (regno == 31 && lastregno == 0xffffffff)
11789                         {
11790                           insn_error
11791                             = _("A destination register must be supplied");
11792                           continue;
11793                         }
11794                     }
11795                   /* Now that we have assembled one operand, we use the args
11796                      string to figure out where it goes in the instruction.  */
11797                   switch (c)
11798                     {
11799                     case 'r':
11800                     case 's':
11801                     case 'v':
11802                     case 'b':
11803                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
11804                       break;
11805
11806                     case 'K':
11807                       if (mips_opts.micromips)
11808                         INSERT_OPERAND (1, RS, *ip, regno);
11809                       else
11810                         INSERT_OPERAND (0, RD, *ip, regno);
11811                       break;
11812
11813                     case 'd':
11814                     case 'g':
11815                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
11816                       break;
11817
11818                     case 'U':
11819                       gas_assert (!mips_opts.micromips);
11820                       INSERT_OPERAND (0, RD, *ip, regno);
11821                       INSERT_OPERAND (0, RT, *ip, regno);
11822                       break;
11823
11824                     case 'w':
11825                     case 't':
11826                     case 'E':
11827                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
11828                       break;
11829
11830                     case 'y':
11831                       gas_assert (mips_opts.micromips);
11832                       INSERT_OPERAND (1, RS3, *ip, regno);
11833                       break;
11834
11835                     case 'x':
11836                       /* This case exists because on the r3000 trunc
11837                          expands into a macro which requires a gp
11838                          register.  On the r6000 or r4000 it is
11839                          assembled into a single instruction which
11840                          ignores the register.  Thus the insn version
11841                          is MIPS_ISA2 and uses 'x', and the macro
11842                          version is MIPS_ISA1 and uses 't'.  */
11843                       break;
11844
11845                     case 'z':
11846                       /* This case is for the div instruction, which
11847                          acts differently if the destination argument
11848                          is $0.  This only matches $0, and is checked
11849                          outside the switch.  */
11850                       break;
11851                     }
11852                   lastregno = regno;
11853                   continue;
11854                 }
11855               switch (*args++)
11856                 {
11857                 case 'r':
11858                 case 'v':
11859                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11860                   continue;
11861
11862                 case 'w':
11863                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11864                   continue;
11865                 }
11866               break;
11867
11868             case 'O':           /* MDMX alignment immediate constant.  */
11869               gas_assert (!mips_opts.micromips);
11870               my_getExpression (&imm_expr, s);
11871               check_absolute_expr (ip, &imm_expr);
11872               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
11873                 as_warn (_("Improper align amount (%ld), using low bits"),
11874                          (long) imm_expr.X_add_number);
11875               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
11876               imm_expr.X_op = O_absent;
11877               s = expr_end;
11878               continue;
11879
11880             case 'Q':           /* MDMX vector, element sel, or const.  */
11881               if (s[0] != '$')
11882                 {
11883                   /* MDMX Immediate.  */
11884                   gas_assert (!mips_opts.micromips);
11885                   my_getExpression (&imm_expr, s);
11886                   check_absolute_expr (ip, &imm_expr);
11887                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
11888                     as_warn (_("Invalid MDMX Immediate (%ld)"),
11889                              (long) imm_expr.X_add_number);
11890                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
11891                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11892                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
11893                   else
11894                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
11895                   imm_expr.X_op = O_absent;
11896                   s = expr_end;
11897                   continue;
11898                 }
11899               /* Not MDMX Immediate.  Fall through.  */
11900             case 'X':           /* MDMX destination register.  */
11901             case 'Y':           /* MDMX source register.  */
11902             case 'Z':           /* MDMX target register.  */
11903               is_mdmx = 1;
11904             case 'W':
11905               gas_assert (!mips_opts.micromips);
11906             case 'D':           /* Floating point destination register.  */
11907             case 'S':           /* Floating point source register.  */
11908             case 'T':           /* Floating point target register.  */
11909             case 'R':           /* Floating point source register.  */
11910             case 'V':
11911               rtype = RTYPE_FPU;
11912               if (is_mdmx
11913                   || (mips_opts.ase_mdmx
11914                       && (ip->insn_mo->pinfo & FP_D)
11915                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
11916                                                 | INSN_COPROC_MEMORY_DELAY
11917                                                 | INSN_LOAD_COPROC_DELAY
11918                                                 | INSN_LOAD_MEMORY_DELAY
11919                                                 | INSN_STORE_MEMORY))))
11920                 rtype |= RTYPE_VEC;
11921               s_reset = s;
11922               if (reg_lookup (&s, rtype, &regno))
11923                 {
11924                   if ((regno & 1) != 0
11925                       && HAVE_32BIT_FPRS
11926                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
11927                     as_warn (_("Float register should be even, was %d"),
11928                              regno);
11929
11930                   c = *args;
11931                   if (*s == ' ')
11932                     ++s;
11933                   if (args[1] != *s)
11934                     {
11935                       if (c == 'V' || c == 'W')
11936                         {
11937                           regno = lastregno;
11938                           s = s_reset;
11939                           ++args;
11940                         }
11941                     }
11942                   switch (c)
11943                     {
11944                     case 'D':
11945                     case 'X':
11946                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
11947                       break;
11948
11949                     case 'V':
11950                     case 'S':
11951                     case 'Y':
11952                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
11953                       break;
11954
11955                     case 'Q':
11956                       /* This is like 'Z', but also needs to fix the MDMX
11957                          vector/scalar select bits.  Note that the
11958                          scalar immediate case is handled above.  */
11959                       if (*s == '[')
11960                         {
11961                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
11962                           int max_el = (is_qh ? 3 : 7);
11963                           s++;
11964                           my_getExpression(&imm_expr, s);
11965                           check_absolute_expr (ip, &imm_expr);
11966                           s = expr_end;
11967                           if (imm_expr.X_add_number > max_el)
11968                             as_bad (_("Bad element selector %ld"),
11969                                     (long) imm_expr.X_add_number);
11970                           imm_expr.X_add_number &= max_el;
11971                           ip->insn_opcode |= (imm_expr.X_add_number
11972                                               << (OP_SH_VSEL +
11973                                                   (is_qh ? 2 : 1)));
11974                           imm_expr.X_op = O_absent;
11975                           if (*s != ']')
11976                             as_warn (_("Expecting ']' found '%s'"), s);
11977                           else
11978                             s++;
11979                         }
11980                       else
11981                         {
11982                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11983                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
11984                                                 << OP_SH_VSEL);
11985                           else
11986                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
11987                                                 OP_SH_VSEL);
11988                         }
11989                       /* Fall through.  */
11990                     case 'W':
11991                     case 'T':
11992                     case 'Z':
11993                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
11994                       break;
11995
11996                     case 'R':
11997                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
11998                       break;
11999                     }
12000                   lastregno = regno;
12001                   continue;
12002                 }
12003
12004               switch (*args++)
12005                 {
12006                 case 'V':
12007                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
12008                   continue;
12009
12010                 case 'W':
12011                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
12012                   continue;
12013                 }
12014               break;
12015
12016             case 'I':
12017               my_getExpression (&imm_expr, s);
12018               if (imm_expr.X_op != O_big
12019                   && imm_expr.X_op != O_constant)
12020                 insn_error = _("absolute expression required");
12021               if (HAVE_32BIT_GPRS)
12022                 normalize_constant_expr (&imm_expr);
12023               s = expr_end;
12024               continue;
12025
12026             case 'A':
12027               my_getExpression (&offset_expr, s);
12028               normalize_address_expr (&offset_expr);
12029               *imm_reloc = BFD_RELOC_32;
12030               s = expr_end;
12031               continue;
12032
12033             case 'F':
12034             case 'L':
12035             case 'f':
12036             case 'l':
12037               {
12038                 int f64;
12039                 int using_gprs;
12040                 char *save_in;
12041                 char *err;
12042                 unsigned char temp[8];
12043                 int len;
12044                 unsigned int length;
12045                 segT seg;
12046                 subsegT subseg;
12047                 char *p;
12048
12049                 /* These only appear as the last operand in an
12050                    instruction, and every instruction that accepts
12051                    them in any variant accepts them in all variants.
12052                    This means we don't have to worry about backing out
12053                    any changes if the instruction does not match.
12054
12055                    The difference between them is the size of the
12056                    floating point constant and where it goes.  For 'F'
12057                    and 'L' the constant is 64 bits; for 'f' and 'l' it
12058                    is 32 bits.  Where the constant is placed is based
12059                    on how the MIPS assembler does things:
12060                     F -- .rdata
12061                     L -- .lit8
12062                     f -- immediate value
12063                     l -- .lit4
12064
12065                     The .lit4 and .lit8 sections are only used if
12066                     permitted by the -G argument.
12067
12068                     The code below needs to know whether the target register
12069                     is 32 or 64 bits wide.  It relies on the fact 'f' and
12070                     'F' are used with GPR-based instructions and 'l' and
12071                     'L' are used with FPR-based instructions.  */
12072
12073                 f64 = *args == 'F' || *args == 'L';
12074                 using_gprs = *args == 'F' || *args == 'f';
12075
12076                 save_in = input_line_pointer;
12077                 input_line_pointer = s;
12078                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12079                 length = len;
12080                 s = input_line_pointer;
12081                 input_line_pointer = save_in;
12082                 if (err != NULL && *err != '\0')
12083                   {
12084                     as_bad (_("Bad floating point constant: %s"), err);
12085                     memset (temp, '\0', sizeof temp);
12086                     length = f64 ? 8 : 4;
12087                   }
12088
12089                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12090
12091                 if (*args == 'f'
12092                     || (*args == 'l'
12093                         && (g_switch_value < 4
12094                             || (temp[0] == 0 && temp[1] == 0)
12095                             || (temp[2] == 0 && temp[3] == 0))))
12096                   {
12097                     imm_expr.X_op = O_constant;
12098                     if (!target_big_endian)
12099                       imm_expr.X_add_number = bfd_getl32 (temp);
12100                     else
12101                       imm_expr.X_add_number = bfd_getb32 (temp);
12102                   }
12103                 else if (length > 4
12104                          && !mips_disable_float_construction
12105                          /* Constants can only be constructed in GPRs and
12106                             copied to FPRs if the GPRs are at least as wide
12107                             as the FPRs.  Force the constant into memory if
12108                             we are using 64-bit FPRs but the GPRs are only
12109                             32 bits wide.  */
12110                          && (using_gprs
12111                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12112                          && ((temp[0] == 0 && temp[1] == 0)
12113                              || (temp[2] == 0 && temp[3] == 0))
12114                          && ((temp[4] == 0 && temp[5] == 0)
12115                              || (temp[6] == 0 && temp[7] == 0)))
12116                   {
12117                     /* The value is simple enough to load with a couple of
12118                        instructions.  If using 32-bit registers, set
12119                        imm_expr to the high order 32 bits and offset_expr to
12120                        the low order 32 bits.  Otherwise, set imm_expr to
12121                        the entire 64 bit constant.  */
12122                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12123                       {
12124                         imm_expr.X_op = O_constant;
12125                         offset_expr.X_op = O_constant;
12126                         if (!target_big_endian)
12127                           {
12128                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12129                             offset_expr.X_add_number = bfd_getl32 (temp);
12130                           }
12131                         else
12132                           {
12133                             imm_expr.X_add_number = bfd_getb32 (temp);
12134                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12135                           }
12136                         if (offset_expr.X_add_number == 0)
12137                           offset_expr.X_op = O_absent;
12138                       }
12139                     else if (sizeof (imm_expr.X_add_number) > 4)
12140                       {
12141                         imm_expr.X_op = O_constant;
12142                         if (!target_big_endian)
12143                           imm_expr.X_add_number = bfd_getl64 (temp);
12144                         else
12145                           imm_expr.X_add_number = bfd_getb64 (temp);
12146                       }
12147                     else
12148                       {
12149                         imm_expr.X_op = O_big;
12150                         imm_expr.X_add_number = 4;
12151                         if (!target_big_endian)
12152                           {
12153                             generic_bignum[0] = bfd_getl16 (temp);
12154                             generic_bignum[1] = bfd_getl16 (temp + 2);
12155                             generic_bignum[2] = bfd_getl16 (temp + 4);
12156                             generic_bignum[3] = bfd_getl16 (temp + 6);
12157                           }
12158                         else
12159                           {
12160                             generic_bignum[0] = bfd_getb16 (temp + 6);
12161                             generic_bignum[1] = bfd_getb16 (temp + 4);
12162                             generic_bignum[2] = bfd_getb16 (temp + 2);
12163                             generic_bignum[3] = bfd_getb16 (temp);
12164                           }
12165                       }
12166                   }
12167                 else
12168                   {
12169                     const char *newname;
12170                     segT new_seg;
12171
12172                     /* Switch to the right section.  */
12173                     seg = now_seg;
12174                     subseg = now_subseg;
12175                     switch (*args)
12176                       {
12177                       default: /* unused default case avoids warnings.  */
12178                       case 'L':
12179                         newname = RDATA_SECTION_NAME;
12180                         if (g_switch_value >= 8)
12181                           newname = ".lit8";
12182                         break;
12183                       case 'F':
12184                         newname = RDATA_SECTION_NAME;
12185                         break;
12186                       case 'l':
12187                         gas_assert (g_switch_value >= 4);
12188                         newname = ".lit4";
12189                         break;
12190                       }
12191                     new_seg = subseg_new (newname, (subsegT) 0);
12192                     if (IS_ELF)
12193                       bfd_set_section_flags (stdoutput, new_seg,
12194                                              (SEC_ALLOC
12195                                               | SEC_LOAD
12196                                               | SEC_READONLY
12197                                               | SEC_DATA));
12198                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12199                     if (IS_ELF && strncmp (TARGET_OS, "elf", 3) != 0)
12200                       record_alignment (new_seg, 4);
12201                     else
12202                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12203                     if (seg == now_seg)
12204                       as_bad (_("Can't use floating point insn in this section"));
12205
12206                     /* Set the argument to the current address in the
12207                        section.  */
12208                     offset_expr.X_op = O_symbol;
12209                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12210                     offset_expr.X_add_number = 0;
12211
12212                     /* Put the floating point number into the section.  */
12213                     p = frag_more ((int) length);
12214                     memcpy (p, temp, length);
12215
12216                     /* Switch back to the original section.  */
12217                     subseg_set (seg, subseg);
12218                   }
12219               }
12220               continue;
12221
12222             case 'i':           /* 16-bit unsigned immediate.  */
12223             case 'j':           /* 16-bit signed immediate.  */
12224               *imm_reloc = BFD_RELOC_LO16;
12225               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
12226                 {
12227                   int more;
12228                   offsetT minval, maxval;
12229
12230                   more = (insn + 1 < past
12231                           && strcmp (insn->name, insn[1].name) == 0);
12232
12233                   /* If the expression was written as an unsigned number,
12234                      only treat it as signed if there are no more
12235                      alternatives.  */
12236                   if (more
12237                       && *args == 'j'
12238                       && sizeof (imm_expr.X_add_number) <= 4
12239                       && imm_expr.X_op == O_constant
12240                       && imm_expr.X_add_number < 0
12241                       && imm_expr.X_unsigned
12242                       && HAVE_64BIT_GPRS)
12243                     break;
12244
12245                   /* For compatibility with older assemblers, we accept
12246                      0x8000-0xffff as signed 16-bit numbers when only
12247                      signed numbers are allowed.  */
12248                   if (*args == 'i')
12249                     minval = 0, maxval = 0xffff;
12250                   else if (more)
12251                     minval = -0x8000, maxval = 0x7fff;
12252                   else
12253                     minval = -0x8000, maxval = 0xffff;
12254
12255                   if (imm_expr.X_op != O_constant
12256                       || imm_expr.X_add_number < minval
12257                       || imm_expr.X_add_number > maxval)
12258                     {
12259                       if (more)
12260                         break;
12261                       if (imm_expr.X_op == O_constant
12262                           || imm_expr.X_op == O_big)
12263                         as_bad (_("Expression out of range"));
12264                     }
12265                 }
12266               s = expr_end;
12267               continue;
12268
12269             case 'o':           /* 16-bit offset.  */
12270               offset_reloc[0] = BFD_RELOC_LO16;
12271               offset_reloc[1] = BFD_RELOC_UNUSED;
12272               offset_reloc[2] = BFD_RELOC_UNUSED;
12273
12274               /* Check whether there is only a single bracketed expression
12275                  left.  If so, it must be the base register and the
12276                  constant must be zero.  */
12277               if (*s == '(' && strchr (s + 1, '(') == 0)
12278                 {
12279                   offset_expr.X_op = O_constant;
12280                   offset_expr.X_add_number = 0;
12281                   continue;
12282                 }
12283
12284               /* If this value won't fit into a 16 bit offset, then go
12285                  find a macro that will generate the 32 bit offset
12286                  code pattern.  */
12287               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12288                   && (offset_expr.X_op != O_constant
12289                       || offset_expr.X_add_number >= 0x8000
12290                       || offset_expr.X_add_number < -0x8000))
12291                 break;
12292
12293               s = expr_end;
12294               continue;
12295
12296             case 'p':           /* PC-relative offset.  */
12297               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12298               my_getExpression (&offset_expr, s);
12299               s = expr_end;
12300               continue;
12301
12302             case 'u':           /* Upper 16 bits.  */
12303               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
12304                   && imm_expr.X_op == O_constant
12305                   && (imm_expr.X_add_number < 0
12306                       || imm_expr.X_add_number >= 0x10000))
12307                 as_bad (_("lui expression (%lu) not in range 0..65535"),
12308                         (unsigned long) imm_expr.X_add_number);
12309               s = expr_end;
12310               continue;
12311
12312             case 'a':           /* 26-bit address.  */
12313               *offset_reloc = BFD_RELOC_MIPS_JMP;
12314               my_getExpression (&offset_expr, s);
12315               s = expr_end;
12316               continue;
12317
12318             case 'N':           /* 3-bit branch condition code.  */
12319             case 'M':           /* 3-bit compare condition code.  */
12320               rtype = RTYPE_CCC;
12321               if (ip->insn_mo->pinfo & (FP_D | FP_S))
12322                 rtype |= RTYPE_FCC;
12323               if (!reg_lookup (&s, rtype, &regno))
12324                 break;
12325               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
12326                    || strcmp (str + strlen (str) - 5, "any2f") == 0
12327                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
12328                   && (regno & 1) != 0)
12329                 as_warn (_("Condition code register should be even for %s, "
12330                            "was %d"),
12331                          str, regno);
12332               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
12333                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
12334                   && (regno & 3) != 0)
12335                 as_warn (_("Condition code register should be 0 or 4 for %s, "
12336                            "was %d"),
12337                          str, regno);
12338               if (*args == 'N')
12339                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
12340               else
12341                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
12342               continue;
12343
12344             case 'H':
12345               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
12346                 s += 2;
12347               if (ISDIGIT (*s))
12348                 {
12349                   c = 0;
12350                   do
12351                     {
12352                       c *= 10;
12353                       c += *s - '0';
12354                       ++s;
12355                     }
12356                   while (ISDIGIT (*s));
12357                 }
12358               else
12359                 c = 8; /* Invalid sel value.  */
12360
12361               if (c > 7)
12362                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
12363               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
12364               continue;
12365
12366             case 'e':
12367               gas_assert (!mips_opts.micromips);
12368               /* Must be at least one digit.  */
12369               my_getExpression (&imm_expr, s);
12370               check_absolute_expr (ip, &imm_expr);
12371
12372               if ((unsigned long) imm_expr.X_add_number
12373                   > (unsigned long) OP_MASK_VECBYTE)
12374                 {
12375                   as_bad (_("bad byte vector index (%ld)"),
12376                            (long) imm_expr.X_add_number);
12377                   imm_expr.X_add_number = 0;
12378                 }
12379
12380               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
12381               imm_expr.X_op = O_absent;
12382               s = expr_end;
12383               continue;
12384
12385             case '%':
12386               gas_assert (!mips_opts.micromips);
12387               my_getExpression (&imm_expr, s);
12388               check_absolute_expr (ip, &imm_expr);
12389
12390               if ((unsigned long) imm_expr.X_add_number
12391                   > (unsigned long) OP_MASK_VECALIGN)
12392                 {
12393                   as_bad (_("bad byte vector index (%ld)"),
12394                            (long) imm_expr.X_add_number);
12395                   imm_expr.X_add_number = 0;
12396                 }
12397
12398               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
12399               imm_expr.X_op = O_absent;
12400               s = expr_end;
12401               continue;
12402
12403             case 'm':           /* Opcode extension character.  */
12404               gas_assert (mips_opts.micromips);
12405               c = *++args;
12406               switch (c)
12407                 {
12408                 case 'r':
12409                   if (strncmp (s, "$pc", 3) == 0)
12410                     {
12411                       s += 3;
12412                       continue;
12413                     }
12414                   break;
12415
12416                 case 'a':
12417                 case 'b':
12418                 case 'c':
12419                 case 'd':
12420                 case 'e':
12421                 case 'f':
12422                 case 'g':
12423                 case 'h':
12424                 case 'i':
12425                 case 'j':
12426                 case 'l':
12427                 case 'm':
12428                 case 'n':
12429                 case 'p':
12430                 case 'q':
12431                 case 's':
12432                 case 't':
12433                 case 'x':
12434                 case 'y':
12435                 case 'z':
12436                   s_reset = s;
12437                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12438                   if (regno == AT && mips_opts.at)
12439                     {
12440                       if (mips_opts.at == ATREG)
12441                         as_warn (_("Used $at without \".set noat\""));
12442                       else
12443                         as_warn (_("Used $%u with \".set at=$%u\""),
12444                                  regno, mips_opts.at);
12445                     }
12446                   if (!ok)
12447                     {
12448                       if (c == 'c')
12449                         {
12450                           gas_assert (args[1] == ',');
12451                           regno = lastregno;
12452                           ++args;
12453                         }
12454                       else if (c == 't')
12455                         {
12456                           gas_assert (args[1] == ',');
12457                           ++args;
12458                           continue;                     /* Nothing to do.  */
12459                         }
12460                       else
12461                         break;
12462                     }
12463
12464                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
12465                     {
12466                       if (regno == lastregno)
12467                         {
12468                           insn_error
12469                             = _("Source and destination must be different");
12470                           continue;
12471                         }
12472                       if (regno == 31 && lastregno == 0xffffffff)
12473                         {
12474                           insn_error
12475                             = _("A destination register must be supplied");
12476                           continue;
12477                         }
12478                     }
12479
12480                   if (*s == ' ')
12481                     ++s;
12482                   if (args[1] != *s)
12483                     {
12484                       if (c == 'e')
12485                         {
12486                           gas_assert (args[1] == ',');
12487                           regno = lastregno;
12488                           s = s_reset;
12489                           ++args;
12490                         }
12491                       else if (c == 't')
12492                         {
12493                           gas_assert (args[1] == ',');
12494                           s = s_reset;
12495                           ++args;
12496                           continue;                     /* Nothing to do.  */
12497                         }
12498                     }
12499
12500                   /* Make sure regno is the same as lastregno.  */
12501                   if (c == 't' && regno != lastregno)
12502                     break;
12503
12504                   /* Make sure regno is the same as destregno.  */
12505                   if (c == 'x' && regno != destregno)
12506                     break;
12507
12508                   /* We need to save regno, before regno maps to the
12509                      microMIPS register encoding.  */
12510                   lastregno = regno;
12511
12512                   if (c == 'f')
12513                     destregno = regno;
12514
12515                   switch (c)
12516                     {
12517                       case 'a':
12518                         if (regno != GP)
12519                           regno = ILLEGAL_REG;
12520                         break;
12521
12522                       case 'b':
12523                         regno = mips32_to_micromips_reg_b_map[regno];
12524                         break;
12525
12526                       case 'c':
12527                         regno = mips32_to_micromips_reg_c_map[regno];
12528                         break;
12529
12530                       case 'd':
12531                         regno = mips32_to_micromips_reg_d_map[regno];
12532                         break;
12533
12534                       case 'e':
12535                         regno = mips32_to_micromips_reg_e_map[regno];
12536                         break;
12537
12538                       case 'f':
12539                         regno = mips32_to_micromips_reg_f_map[regno];
12540                         break;
12541
12542                       case 'g':
12543                         regno = mips32_to_micromips_reg_g_map[regno];
12544                         break;
12545
12546                       case 'h':
12547                         regno = mips32_to_micromips_reg_h_map[regno];
12548                         break;
12549
12550                       case 'i':
12551                         switch (EXTRACT_OPERAND (1, MI, *ip))
12552                           {
12553                             case 4:
12554                               if (regno == 21)
12555                                 regno = 3;
12556                               else if (regno == 22)
12557                                 regno = 4;
12558                               else if (regno == 5)
12559                                 regno = 5;
12560                               else if (regno == 6)
12561                                 regno = 6;
12562                               else if (regno == 7)
12563                                 regno = 7;
12564                               else
12565                                 regno = ILLEGAL_REG;
12566                               break;
12567
12568                             case 5:
12569                               if (regno == 6)
12570                                 regno = 0;
12571                               else if (regno == 7)
12572                                 regno = 1;
12573                               else
12574                                 regno = ILLEGAL_REG;
12575                               break;
12576
12577                             case 6:
12578                               if (regno == 7)
12579                                 regno = 2;
12580                               else
12581                                 regno = ILLEGAL_REG;
12582                               break;
12583
12584                             default:
12585                               regno = ILLEGAL_REG;
12586                               break;
12587                           }
12588                         break;
12589
12590                       case 'l':
12591                         regno = mips32_to_micromips_reg_l_map[regno];
12592                         break;
12593
12594                       case 'm':
12595                         regno = mips32_to_micromips_reg_m_map[regno];
12596                         break;
12597
12598                       case 'n':
12599                         regno = mips32_to_micromips_reg_n_map[regno];
12600                         break;
12601
12602                       case 'q':
12603                         regno = mips32_to_micromips_reg_q_map[regno];
12604                         break;
12605
12606                       case 's':
12607                         if (regno != SP)
12608                           regno = ILLEGAL_REG;
12609                         break;
12610
12611                       case 'y':
12612                         if (regno != 31)
12613                           regno = ILLEGAL_REG;
12614                         break;
12615
12616                       case 'z':
12617                         if (regno != ZERO)
12618                           regno = ILLEGAL_REG;
12619                         break;
12620
12621                       case 'j': /* Do nothing.  */
12622                       case 'p':
12623                       case 't':
12624                       case 'x':
12625                         break;
12626
12627                       default:
12628                         internalError ();
12629                     }
12630
12631                   if (regno == ILLEGAL_REG)
12632                     break;
12633
12634                   switch (c)
12635                     {
12636                       case 'b':
12637                         INSERT_OPERAND (1, MB, *ip, regno);
12638                         break;
12639
12640                       case 'c':
12641                         INSERT_OPERAND (1, MC, *ip, regno);
12642                         break;
12643
12644                       case 'd':
12645                         INSERT_OPERAND (1, MD, *ip, regno);
12646                         break;
12647
12648                       case 'e':
12649                         INSERT_OPERAND (1, ME, *ip, regno);
12650                         break;
12651
12652                       case 'f':
12653                         INSERT_OPERAND (1, MF, *ip, regno);
12654                         break;
12655
12656                       case 'g':
12657                         INSERT_OPERAND (1, MG, *ip, regno);
12658                         break;
12659
12660                       case 'h':
12661                         INSERT_OPERAND (1, MH, *ip, regno);
12662                         break;
12663
12664                       case 'i':
12665                         INSERT_OPERAND (1, MI, *ip, regno);
12666                         break;
12667
12668                       case 'j':
12669                         INSERT_OPERAND (1, MJ, *ip, regno);
12670                         break;
12671
12672                       case 'l':
12673                         INSERT_OPERAND (1, ML, *ip, regno);
12674                         break;
12675
12676                       case 'm':
12677                         INSERT_OPERAND (1, MM, *ip, regno);
12678                         break;
12679
12680                       case 'n':
12681                         INSERT_OPERAND (1, MN, *ip, regno);
12682                         break;
12683
12684                       case 'p':
12685                         INSERT_OPERAND (1, MP, *ip, regno);
12686                         break;
12687
12688                       case 'q':
12689                         INSERT_OPERAND (1, MQ, *ip, regno);
12690                         break;
12691
12692                       case 'a': /* Do nothing.  */
12693                       case 's': /* Do nothing.  */
12694                       case 't': /* Do nothing.  */
12695                       case 'x': /* Do nothing.  */
12696                       case 'y': /* Do nothing.  */
12697                       case 'z': /* Do nothing.  */
12698                         break;
12699
12700                       default:
12701                         internalError ();
12702                     }
12703                   continue;
12704
12705                 case 'A':
12706                   {
12707                     bfd_reloc_code_real_type r[3];
12708                     expressionS ep;
12709                     int imm;
12710
12711                     /* Check whether there is only a single bracketed
12712                        expression left.  If so, it must be the base register
12713                        and the constant must be zero.  */
12714                     if (*s == '(' && strchr (s + 1, '(') == 0)
12715                       {
12716                         INSERT_OPERAND (1, IMMA, *ip, 0);
12717                         continue;
12718                       }
12719
12720                     if (my_getSmallExpression (&ep, r, s) > 0
12721                         || !expr_const_in_range (&ep, -64, 64, 2))
12722                       break;
12723
12724                     imm = ep.X_add_number >> 2;
12725                     INSERT_OPERAND (1, IMMA, *ip, imm);
12726                   }
12727                   s = expr_end;
12728                   continue;
12729
12730                 case 'B':
12731                   {
12732                     bfd_reloc_code_real_type r[3];
12733                     expressionS ep;
12734                     int imm;
12735
12736                     if (my_getSmallExpression (&ep, r, s) > 0
12737                         || ep.X_op != O_constant)
12738                       break;
12739
12740                     for (imm = 0; imm < 8; imm++)
12741                       if (micromips_imm_b_map[imm] == ep.X_add_number)
12742                         break;
12743                     if (imm >= 8)
12744                       break;
12745
12746                     INSERT_OPERAND (1, IMMB, *ip, imm);
12747                   }
12748                   s = expr_end;
12749                   continue;
12750
12751                 case 'C':
12752                   {
12753                     bfd_reloc_code_real_type r[3];
12754                     expressionS ep;
12755                     int imm;
12756
12757                     if (my_getSmallExpression (&ep, r, s) > 0
12758                         || ep.X_op != O_constant)
12759                       break;
12760
12761                     for (imm = 0; imm < 16; imm++)
12762                       if (micromips_imm_c_map[imm] == ep.X_add_number)
12763                         break;
12764                     if (imm >= 16)
12765                       break;
12766
12767                     INSERT_OPERAND (1, IMMC, *ip, imm);
12768                   }
12769                   s = expr_end;
12770                   continue;
12771
12772                 case 'D':       /* pc relative offset */
12773                 case 'E':       /* pc relative offset */
12774                   my_getExpression (&offset_expr, s);
12775                   if (offset_expr.X_op == O_register)
12776                     break;
12777
12778                   if (!forced_insn_length)
12779                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12780                   else if (c == 'D')
12781                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12782                   else
12783                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12784                   s = expr_end;
12785                   continue;
12786
12787                 case 'F':
12788                   {
12789                     bfd_reloc_code_real_type r[3];
12790                     expressionS ep;
12791                     int imm;
12792
12793                     if (my_getSmallExpression (&ep, r, s) > 0
12794                         || !expr_const_in_range (&ep, 0, 16, 0))
12795                       break;
12796
12797                     imm = ep.X_add_number;
12798                     INSERT_OPERAND (1, IMMF, *ip, imm);
12799                   }
12800                   s = expr_end;
12801                   continue;
12802
12803                 case 'G':
12804                   {
12805                     bfd_reloc_code_real_type r[3];
12806                     expressionS ep;
12807                     int imm;
12808
12809                     /* Check whether there is only a single bracketed
12810                        expression left.  If so, it must be the base register
12811                        and the constant must be zero.  */
12812                     if (*s == '(' && strchr (s + 1, '(') == 0)
12813                       {
12814                         INSERT_OPERAND (1, IMMG, *ip, 0);
12815                         continue;
12816                       }
12817
12818                     if (my_getSmallExpression (&ep, r, s) > 0
12819                         || !expr_const_in_range (&ep, -1, 15, 0))
12820                       break;
12821
12822                     imm = ep.X_add_number & 15;
12823                     INSERT_OPERAND (1, IMMG, *ip, imm);
12824                   }
12825                   s = expr_end;
12826                   continue;
12827
12828                 case 'H':
12829                   {
12830                     bfd_reloc_code_real_type r[3];
12831                     expressionS ep;
12832                     int imm;
12833
12834                     /* Check whether there is only a single bracketed
12835                        expression left.  If so, it must be the base register
12836                        and the constant must be zero.  */
12837                     if (*s == '(' && strchr (s + 1, '(') == 0)
12838                       {
12839                         INSERT_OPERAND (1, IMMH, *ip, 0);
12840                         continue;
12841                       }
12842
12843                     if (my_getSmallExpression (&ep, r, s) > 0
12844                         || !expr_const_in_range (&ep, 0, 16, 1))
12845                       break;
12846
12847                     imm = ep.X_add_number >> 1;
12848                     INSERT_OPERAND (1, IMMH, *ip, imm);
12849                   }
12850                   s = expr_end;
12851                   continue;
12852
12853                 case 'I':
12854                   {
12855                     bfd_reloc_code_real_type r[3];
12856                     expressionS ep;
12857                     int imm;
12858
12859                     if (my_getSmallExpression (&ep, r, s) > 0
12860                         || !expr_const_in_range (&ep, -1, 127, 0))
12861                       break;
12862
12863                     imm = ep.X_add_number & 127;
12864                     INSERT_OPERAND (1, IMMI, *ip, imm);
12865                   }
12866                   s = expr_end;
12867                   continue;
12868
12869                 case 'J':
12870                   {
12871                     bfd_reloc_code_real_type r[3];
12872                     expressionS ep;
12873                     int imm;
12874
12875                     /* Check whether there is only a single bracketed
12876                        expression left.  If so, it must be the base register
12877                        and the constant must be zero.  */
12878                     if (*s == '(' && strchr (s + 1, '(') == 0)
12879                       {
12880                         INSERT_OPERAND (1, IMMJ, *ip, 0);
12881                         continue;
12882                       }
12883
12884                     if (my_getSmallExpression (&ep, r, s) > 0
12885                         || !expr_const_in_range (&ep, 0, 16, 2))
12886                       break;
12887
12888                     imm = ep.X_add_number >> 2;
12889                     INSERT_OPERAND (1, IMMJ, *ip, imm);
12890                   }
12891                   s = expr_end;
12892                   continue;
12893
12894                 case 'L':
12895                   {
12896                     bfd_reloc_code_real_type r[3];
12897                     expressionS ep;
12898                     int imm;
12899
12900                     /* Check whether there is only a single bracketed
12901                        expression left.  If so, it must be the base register
12902                        and the constant must be zero.  */
12903                     if (*s == '(' && strchr (s + 1, '(') == 0)
12904                       {
12905                         INSERT_OPERAND (1, IMML, *ip, 0);
12906                         continue;
12907                       }
12908
12909                     if (my_getSmallExpression (&ep, r, s) > 0
12910                         || !expr_const_in_range (&ep, 0, 16, 0))
12911                       break;
12912
12913                     imm = ep.X_add_number;
12914                     INSERT_OPERAND (1, IMML, *ip, imm);
12915                   }
12916                   s = expr_end;
12917                   continue;
12918
12919                 case 'M':
12920                   {
12921                     bfd_reloc_code_real_type r[3];
12922                     expressionS ep;
12923                     int imm;
12924
12925                     if (my_getSmallExpression (&ep, r, s) > 0
12926                         || !expr_const_in_range (&ep, 1, 9, 0))
12927                       break;
12928
12929                     imm = ep.X_add_number & 7;
12930                     INSERT_OPERAND (1, IMMM, *ip, imm);
12931                   }
12932                   s = expr_end;
12933                   continue;
12934
12935                 case 'N':       /* Register list for lwm and swm.  */
12936                   {
12937                     /* A comma-separated list of registers and/or
12938                        dash-separated contiguous ranges including
12939                        both ra and a set of one or more registers
12940                        starting at s0 up to s3 which have to be
12941                        consecutive, e.g.:
12942
12943                        s0, ra
12944                        s0, s1, ra, s2, s3
12945                        s0-s2, ra
12946
12947                        and any permutations of these.  */
12948                     unsigned int reglist;
12949                     int imm;
12950
12951                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
12952                       break;
12953
12954                     if ((reglist & 0xfff1ffff) != 0x80010000)
12955                       break;
12956
12957                     reglist = (reglist >> 17) & 7;
12958                     reglist += 1;
12959                     if ((reglist & -reglist) != reglist)
12960                       break;
12961
12962                     imm = ffs (reglist) - 1;
12963                     INSERT_OPERAND (1, IMMN, *ip, imm);
12964                   }
12965                   continue;
12966
12967                 case 'O':       /* sdbbp 4-bit code.  */
12968                   {
12969                     bfd_reloc_code_real_type r[3];
12970                     expressionS ep;
12971                     int imm;
12972
12973                     if (my_getSmallExpression (&ep, r, s) > 0
12974                         || !expr_const_in_range (&ep, 0, 16, 0))
12975                       break;
12976
12977                     imm = ep.X_add_number;
12978                     INSERT_OPERAND (1, IMMO, *ip, imm);
12979                   }
12980                   s = expr_end;
12981                   continue;
12982
12983                 case 'P':
12984                   {
12985                     bfd_reloc_code_real_type r[3];
12986                     expressionS ep;
12987                     int imm;
12988
12989                     if (my_getSmallExpression (&ep, r, s) > 0
12990                         || !expr_const_in_range (&ep, 0, 32, 2))
12991                       break;
12992
12993                     imm = ep.X_add_number >> 2;
12994                     INSERT_OPERAND (1, IMMP, *ip, imm);
12995                   }
12996                   s = expr_end;
12997                   continue;
12998
12999                 case 'Q':
13000                   {
13001                     bfd_reloc_code_real_type r[3];
13002                     expressionS ep;
13003                     int imm;
13004
13005                     if (my_getSmallExpression (&ep, r, s) > 0
13006                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
13007                       break;
13008
13009                     imm = ep.X_add_number >> 2;
13010                     INSERT_OPERAND (1, IMMQ, *ip, imm);
13011                   }
13012                   s = expr_end;
13013                   continue;
13014
13015                 case 'U':
13016                   {
13017                     bfd_reloc_code_real_type r[3];
13018                     expressionS ep;
13019                     int imm;
13020
13021                     /* Check whether there is only a single bracketed
13022                        expression left.  If so, it must be the base register
13023                        and the constant must be zero.  */
13024                     if (*s == '(' && strchr (s + 1, '(') == 0)
13025                       {
13026                         INSERT_OPERAND (1, IMMU, *ip, 0);
13027                         continue;
13028                       }
13029
13030                     if (my_getSmallExpression (&ep, r, s) > 0
13031                         || !expr_const_in_range (&ep, 0, 32, 2))
13032                       break;
13033
13034                     imm = ep.X_add_number >> 2;
13035                     INSERT_OPERAND (1, IMMU, *ip, imm);
13036                   }
13037                   s = expr_end;
13038                   continue;
13039
13040                 case 'W':
13041                   {
13042                     bfd_reloc_code_real_type r[3];
13043                     expressionS ep;
13044                     int imm;
13045
13046                     if (my_getSmallExpression (&ep, r, s) > 0
13047                         || !expr_const_in_range (&ep, 0, 64, 2))
13048                       break;
13049
13050                     imm = ep.X_add_number >> 2;
13051                     INSERT_OPERAND (1, IMMW, *ip, imm);
13052                   }
13053                   s = expr_end;
13054                   continue;
13055
13056                 case 'X':
13057                   {
13058                     bfd_reloc_code_real_type r[3];
13059                     expressionS ep;
13060                     int imm;
13061
13062                     if (my_getSmallExpression (&ep, r, s) > 0
13063                         || !expr_const_in_range (&ep, -8, 8, 0))
13064                       break;
13065
13066                     imm = ep.X_add_number;
13067                     INSERT_OPERAND (1, IMMX, *ip, imm);
13068                   }
13069                   s = expr_end;
13070                   continue;
13071
13072                 case 'Y':
13073                   {
13074                     bfd_reloc_code_real_type r[3];
13075                     expressionS ep;
13076                     int imm;
13077
13078                     if (my_getSmallExpression (&ep, r, s) > 0
13079                         || expr_const_in_range (&ep, -2, 2, 2)
13080                         || !expr_const_in_range (&ep, -258, 258, 2))
13081                       break;
13082
13083                     imm = ep.X_add_number >> 2;
13084                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
13085                     INSERT_OPERAND (1, IMMY, *ip, imm);
13086                   }
13087                   s = expr_end;
13088                   continue;
13089
13090                 case 'Z':
13091                   {
13092                     bfd_reloc_code_real_type r[3];
13093                     expressionS ep;
13094
13095                     if (my_getSmallExpression (&ep, r, s) > 0
13096                         || !expr_const_in_range (&ep, 0, 1, 0))
13097                       break;
13098                   }
13099                   s = expr_end;
13100                   continue;
13101
13102                 default:
13103                   as_bad (_("Internal error: bad microMIPS opcode "
13104                             "(unknown extension operand type `m%c'): %s %s"),
13105                           *args, insn->name, insn->args);
13106                   /* Further processing is fruitless.  */
13107                   return;
13108                 }
13109               break;
13110
13111             case 'n':           /* Register list for 32-bit lwm and swm.  */
13112               gas_assert (mips_opts.micromips);
13113               {
13114                 /* A comma-separated list of registers and/or
13115                    dash-separated contiguous ranges including
13116                    at least one of ra and a set of one or more
13117                    registers starting at s0 up to s7 and then
13118                    s8 which have to be consecutive, e.g.:
13119
13120                    ra
13121                    s0
13122                    ra, s0, s1, s2
13123                    s0-s8
13124                    s0-s5, ra
13125
13126                    and any permutations of these.  */
13127                 unsigned int reglist;
13128                 int imm;
13129                 int ra;
13130
13131                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13132                   break;
13133
13134                 if ((reglist & 0x3f00ffff) != 0)
13135                   break;
13136
13137                 ra = (reglist >> 27) & 0x10;
13138                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13139                 reglist += 1;
13140                 if ((reglist & -reglist) != reglist)
13141                   break;
13142
13143                 imm = (ffs (reglist) - 1) | ra;
13144                 INSERT_OPERAND (1, RT, *ip, imm);
13145                 imm_expr.X_op = O_absent;
13146               }
13147               continue;
13148
13149             case '|':           /* 4-bit trap code.  */
13150               gas_assert (mips_opts.micromips);
13151               my_getExpression (&imm_expr, s);
13152               check_absolute_expr (ip, &imm_expr);
13153               if ((unsigned long) imm_expr.X_add_number
13154                   > MICROMIPSOP_MASK_TRAP)
13155                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13156                         (unsigned long) imm_expr.X_add_number,
13157                         ip->insn_mo->name);
13158               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13159               imm_expr.X_op = O_absent;
13160               s = expr_end;
13161               continue;
13162
13163             default:
13164               as_bad (_("Bad char = '%c'\n"), *args);
13165               internalError ();
13166             }
13167           break;
13168         }
13169       /* Args don't match.  */
13170       s = argsStart;
13171       insn_error = _("Illegal operands");
13172       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13173         {
13174           ++insn;
13175           continue;
13176         }
13177       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13178         {
13179           gas_assert (firstinsn);
13180           need_delay_slot_ok = FALSE;
13181           past = insn + 1;
13182           insn = firstinsn;
13183           continue;
13184         }
13185       return;
13186     }
13187 }
13188
13189 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13190
13191 /* This routine assembles an instruction into its binary format when
13192    assembling for the mips16.  As a side effect, it sets one of the
13193    global variables imm_reloc or offset_reloc to the type of relocation
13194    to do if one of the operands is an address expression.  It also sets
13195    forced_insn_length to the resulting instruction size in bytes if the
13196    user explicitly requested a small or extended instruction.  */
13197
13198 static void
13199 mips16_ip (char *str, struct mips_cl_insn *ip)
13200 {
13201   char *s;
13202   const char *args;
13203   struct mips_opcode *insn;
13204   char *argsstart;
13205   unsigned int regno;
13206   unsigned int lastregno = 0;
13207   char *s_reset;
13208   size_t i;
13209
13210   insn_error = NULL;
13211
13212   forced_insn_length = 0;
13213
13214   for (s = str; ISLOWER (*s); ++s)
13215     ;
13216   switch (*s)
13217     {
13218     case '\0':
13219       break;
13220
13221     case ' ':
13222       *s++ = '\0';
13223       break;
13224
13225     case '.':
13226       if (s[1] == 't' && s[2] == ' ')
13227         {
13228           *s = '\0';
13229           forced_insn_length = 2;
13230           s += 3;
13231           break;
13232         }
13233       else if (s[1] == 'e' && s[2] == ' ')
13234         {
13235           *s = '\0';
13236           forced_insn_length = 4;
13237           s += 3;
13238           break;
13239         }
13240       /* Fall through.  */
13241     default:
13242       insn_error = _("unknown opcode");
13243       return;
13244     }
13245
13246   if (mips_opts.noautoextend && !forced_insn_length)
13247     forced_insn_length = 2;
13248
13249   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
13250     {
13251       insn_error = _("unrecognized opcode");
13252       return;
13253     }
13254
13255   argsstart = s;
13256   for (;;)
13257     {
13258       bfd_boolean ok;
13259
13260       gas_assert (strcmp (insn->name, str) == 0);
13261
13262       ok = is_opcode_valid_16 (insn);
13263       if (! ok)
13264         {
13265           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13266               && strcmp (insn->name, insn[1].name) == 0)
13267             {
13268               ++insn;
13269               continue;
13270             }
13271           else
13272             {
13273               if (!insn_error)
13274                 {
13275                   static char buf[100];
13276                   sprintf (buf,
13277                            _("Opcode not supported on this processor: %s (%s)"),
13278                            mips_cpu_info_from_arch (mips_opts.arch)->name,
13279                            mips_cpu_info_from_isa (mips_opts.isa)->name);
13280                   insn_error = buf;
13281                 }
13282               return;
13283             }
13284         }
13285
13286       create_insn (ip, insn);
13287       imm_expr.X_op = O_absent;
13288       imm_reloc[0] = BFD_RELOC_UNUSED;
13289       imm_reloc[1] = BFD_RELOC_UNUSED;
13290       imm_reloc[2] = BFD_RELOC_UNUSED;
13291       imm2_expr.X_op = O_absent;
13292       offset_expr.X_op = O_absent;
13293       offset_reloc[0] = BFD_RELOC_UNUSED;
13294       offset_reloc[1] = BFD_RELOC_UNUSED;
13295       offset_reloc[2] = BFD_RELOC_UNUSED;
13296       for (args = insn->args; 1; ++args)
13297         {
13298           int c;
13299
13300           if (*s == ' ')
13301             ++s;
13302
13303           /* In this switch statement we call break if we did not find
13304              a match, continue if we did find a match, or return if we
13305              are done.  */
13306
13307           c = *args;
13308           switch (c)
13309             {
13310             case '\0':
13311               if (*s == '\0')
13312                 {
13313                   /* Stuff the immediate value in now, if we can.  */
13314                   if (imm_expr.X_op == O_constant
13315                       && *imm_reloc > BFD_RELOC_UNUSED
13316                       && *imm_reloc != BFD_RELOC_MIPS16_GOT16
13317                       && *imm_reloc != BFD_RELOC_MIPS16_CALL16
13318                       && insn->pinfo != INSN_MACRO)
13319                     {
13320                       valueT tmp;
13321
13322                       switch (*offset_reloc)
13323                         {
13324                           case BFD_RELOC_MIPS16_HI16_S:
13325                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
13326                             break;
13327
13328                           case BFD_RELOC_MIPS16_HI16:
13329                             tmp = imm_expr.X_add_number >> 16;
13330                             break;
13331
13332                           case BFD_RELOC_MIPS16_LO16:
13333                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
13334                                   - 0x8000;
13335                             break;
13336
13337                           case BFD_RELOC_UNUSED:
13338                             tmp = imm_expr.X_add_number;
13339                             break;
13340
13341                           default:
13342                             internalError ();
13343                         }
13344                       *offset_reloc = BFD_RELOC_UNUSED;
13345
13346                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
13347                                     tmp, TRUE, forced_insn_length == 2,
13348                                     forced_insn_length == 4, &ip->insn_opcode,
13349                                     &ip->use_extend, &ip->extend);
13350                       imm_expr.X_op = O_absent;
13351                       *imm_reloc = BFD_RELOC_UNUSED;
13352                     }
13353
13354                   return;
13355                 }
13356               break;
13357
13358             case ',':
13359               if (*s++ == c)
13360                 continue;
13361               s--;
13362               switch (*++args)
13363                 {
13364                 case 'v':
13365                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13366                   continue;
13367                 case 'w':
13368                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13369                   continue;
13370                 }
13371               break;
13372
13373             case '(':
13374             case ')':
13375               if (*s++ == c)
13376                 continue;
13377               break;
13378
13379             case 'v':
13380             case 'w':
13381               if (s[0] != '$')
13382                 {
13383                   if (c == 'v')
13384                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13385                   else
13386                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13387                   ++args;
13388                   continue;
13389                 }
13390               /* Fall through.  */
13391             case 'x':
13392             case 'y':
13393             case 'z':
13394             case 'Z':
13395             case '0':
13396             case 'S':
13397             case 'R':
13398             case 'X':
13399             case 'Y':
13400               s_reset = s;
13401               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
13402                 {
13403                   if (c == 'v' || c == 'w')
13404                     {
13405                       if (c == 'v')
13406                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13407                       else
13408                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13409                       ++args;
13410                       continue;
13411                     }
13412                   break;
13413                 }
13414
13415               if (*s == ' ')
13416                 ++s;
13417               if (args[1] != *s)
13418                 {
13419                   if (c == 'v' || c == 'w')
13420                     {
13421                       regno = mips16_to_32_reg_map[lastregno];
13422                       s = s_reset;
13423                       ++args;
13424                     }
13425                 }
13426
13427               switch (c)
13428                 {
13429                 case 'x':
13430                 case 'y':
13431                 case 'z':
13432                 case 'v':
13433                 case 'w':
13434                 case 'Z':
13435                   regno = mips32_to_16_reg_map[regno];
13436                   break;
13437
13438                 case '0':
13439                   if (regno != 0)
13440                     regno = ILLEGAL_REG;
13441                   break;
13442
13443                 case 'S':
13444                   if (regno != SP)
13445                     regno = ILLEGAL_REG;
13446                   break;
13447
13448                 case 'R':
13449                   if (regno != RA)
13450                     regno = ILLEGAL_REG;
13451                   break;
13452
13453                 case 'X':
13454                 case 'Y':
13455                   if (regno == AT && mips_opts.at)
13456                     {
13457                       if (mips_opts.at == ATREG)
13458                         as_warn (_("used $at without \".set noat\""));
13459                       else
13460                         as_warn (_("used $%u with \".set at=$%u\""),
13461                                  regno, mips_opts.at);
13462                     }
13463                   break;
13464
13465                 default:
13466                   internalError ();
13467                 }
13468
13469               if (regno == ILLEGAL_REG)
13470                 break;
13471
13472               switch (c)
13473                 {
13474                 case 'x':
13475                 case 'v':
13476                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
13477                   break;
13478                 case 'y':
13479                 case 'w':
13480                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
13481                   break;
13482                 case 'z':
13483                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
13484                   break;
13485                 case 'Z':
13486                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
13487                 case '0':
13488                 case 'S':
13489                 case 'R':
13490                   break;
13491                 case 'X':
13492                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
13493                   break;
13494                 case 'Y':
13495                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
13496                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
13497                   break;
13498                 default:
13499                   internalError ();
13500                 }
13501
13502               lastregno = regno;
13503               continue;
13504
13505             case 'P':
13506               if (strncmp (s, "$pc", 3) == 0)
13507                 {
13508                   s += 3;
13509                   continue;
13510                 }
13511               break;
13512
13513             case '5':
13514             case 'H':
13515             case 'W':
13516             case 'D':
13517             case 'j':
13518             case 'V':
13519             case 'C':
13520             case 'U':
13521             case 'k':
13522             case 'K':
13523               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
13524               if (i > 0)
13525                 {
13526                   if (imm_expr.X_op != O_constant)
13527                     {
13528                       forced_insn_length = 4;
13529                       ip->use_extend = TRUE;
13530                       ip->extend = 0;
13531                     }
13532                   else
13533                     {
13534                       /* We need to relax this instruction.  */
13535                       *offset_reloc = *imm_reloc;
13536                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13537                     }
13538                   s = expr_end;
13539                   continue;
13540                 }
13541               *imm_reloc = BFD_RELOC_UNUSED;
13542               /* Fall through.  */
13543             case '<':
13544             case '>':
13545             case '[':
13546             case ']':
13547             case '4':
13548             case '8':
13549               my_getExpression (&imm_expr, s);
13550               if (imm_expr.X_op == O_register)
13551                 {
13552                   /* What we thought was an expression turned out to
13553                      be a register.  */
13554
13555                   if (s[0] == '(' && args[1] == '(')
13556                     {
13557                       /* It looks like the expression was omitted
13558                          before a register indirection, which means
13559                          that the expression is implicitly zero.  We
13560                          still set up imm_expr, so that we handle
13561                          explicit extensions correctly.  */
13562                       imm_expr.X_op = O_constant;
13563                       imm_expr.X_add_number = 0;
13564                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13565                       continue;
13566                     }
13567
13568                   break;
13569                 }
13570
13571               /* We need to relax this instruction.  */
13572               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13573               s = expr_end;
13574               continue;
13575
13576             case 'p':
13577             case 'q':
13578             case 'A':
13579             case 'B':
13580             case 'E':
13581               /* We use offset_reloc rather than imm_reloc for the PC
13582                  relative operands.  This lets macros with both
13583                  immediate and address operands work correctly.  */
13584               my_getExpression (&offset_expr, s);
13585
13586               if (offset_expr.X_op == O_register)
13587                 break;
13588
13589               /* We need to relax this instruction.  */
13590               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13591               s = expr_end;
13592               continue;
13593
13594             case '6':           /* break code */
13595               my_getExpression (&imm_expr, s);
13596               check_absolute_expr (ip, &imm_expr);
13597               if ((unsigned long) imm_expr.X_add_number > 63)
13598                 as_warn (_("Invalid value for `%s' (%lu)"),
13599                          ip->insn_mo->name,
13600                          (unsigned long) imm_expr.X_add_number);
13601               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
13602               imm_expr.X_op = O_absent;
13603               s = expr_end;
13604               continue;
13605
13606             case 'a':           /* 26 bit address */
13607               my_getExpression (&offset_expr, s);
13608               s = expr_end;
13609               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13610               ip->insn_opcode <<= 16;
13611               continue;
13612
13613             case 'l':           /* register list for entry macro */
13614             case 'L':           /* register list for exit macro */
13615               {
13616                 int mask;
13617
13618                 if (c == 'l')
13619                   mask = 0;
13620                 else
13621                   mask = 7 << 3;
13622                 while (*s != '\0')
13623                   {
13624                     unsigned int freg, reg1, reg2;
13625
13626                     while (*s == ' ' || *s == ',')
13627                       ++s;
13628                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13629                       freg = 0;
13630                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
13631                       freg = 1;
13632                     else
13633                       {
13634                         as_bad (_("can't parse register list"));
13635                         break;
13636                       }
13637                     if (*s == ' ')
13638                       ++s;
13639                     if (*s != '-')
13640                       reg2 = reg1;
13641                     else
13642                       {
13643                         ++s;
13644                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
13645                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
13646                           {
13647                             as_bad (_("invalid register list"));
13648                             break;
13649                           }
13650                       }
13651                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
13652                       {
13653                         mask &= ~ (7 << 3);
13654                         mask |= 5 << 3;
13655                       }
13656                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
13657                       {
13658                         mask &= ~ (7 << 3);
13659                         mask |= 6 << 3;
13660                       }
13661                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
13662                       mask |= (reg2 - 3) << 3;
13663                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
13664                       mask |= (reg2 - 15) << 1;
13665                     else if (reg1 == RA && reg2 == RA)
13666                       mask |= 1;
13667                     else
13668                       {
13669                         as_bad (_("invalid register list"));
13670                         break;
13671                       }
13672                   }
13673                 /* The mask is filled in in the opcode table for the
13674                    benefit of the disassembler.  We remove it before
13675                    applying the actual mask.  */
13676                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
13677                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
13678               }
13679             continue;
13680
13681             case 'm':           /* Register list for save insn.  */
13682             case 'M':           /* Register list for restore insn.  */
13683               {
13684                 int opcode = 0;
13685                 int framesz = 0, seen_framesz = 0;
13686                 int nargs = 0, statics = 0, sregs = 0;
13687
13688                 while (*s != '\0')
13689                   {
13690                     unsigned int reg1, reg2;
13691
13692                     SKIP_SPACE_TABS (s);
13693                     while (*s == ',')
13694                       ++s;
13695                     SKIP_SPACE_TABS (s);
13696
13697                     my_getExpression (&imm_expr, s);
13698                     if (imm_expr.X_op == O_constant)
13699                       {
13700                         /* Handle the frame size.  */
13701                         if (seen_framesz)
13702                           {
13703                             as_bad (_("more than one frame size in list"));
13704                             break;
13705                           }
13706                         seen_framesz = 1;
13707                         framesz = imm_expr.X_add_number;
13708                         imm_expr.X_op = O_absent;
13709                         s = expr_end;
13710                         continue;
13711                       }
13712
13713                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13714                       {
13715                         as_bad (_("can't parse register list"));
13716                         break;
13717                       }
13718
13719                     while (*s == ' ')
13720                       ++s;
13721
13722                     if (*s != '-')
13723                       reg2 = reg1;
13724                     else
13725                       {
13726                         ++s;
13727                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
13728                             || reg2 < reg1)
13729                           {
13730                             as_bad (_("can't parse register list"));
13731                             break;
13732                           }
13733                       }
13734
13735                     while (reg1 <= reg2)
13736                       {
13737                         if (reg1 >= 4 && reg1 <= 7)
13738                           {
13739                             if (!seen_framesz)
13740                                 /* args $a0-$a3 */
13741                                 nargs |= 1 << (reg1 - 4);
13742                             else
13743                                 /* statics $a0-$a3 */
13744                                 statics |= 1 << (reg1 - 4);
13745                           }
13746                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
13747                           {
13748                             /* $s0-$s8 */
13749                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
13750                           }
13751                         else if (reg1 == 31)
13752                           {
13753                             /* Add $ra to insn.  */
13754                             opcode |= 0x40;
13755                           }
13756                         else
13757                           {
13758                             as_bad (_("unexpected register in list"));
13759                             break;
13760                           }
13761                         if (++reg1 == 24)
13762                           reg1 = 30;
13763                       }
13764                   }
13765
13766                 /* Encode args/statics combination.  */
13767                 if (nargs & statics)
13768                   as_bad (_("arg/static registers overlap"));
13769                 else if (nargs == 0xf)
13770                   /* All $a0-$a3 are args.  */
13771                   opcode |= MIPS16_ALL_ARGS << 16;
13772                 else if (statics == 0xf)
13773                   /* All $a0-$a3 are statics.  */
13774                   opcode |= MIPS16_ALL_STATICS << 16;
13775                 else 
13776                   {
13777                     int narg = 0, nstat = 0;
13778
13779                     /* Count arg registers.  */
13780                     while (nargs & 0x1)
13781                       {
13782                         nargs >>= 1;
13783                         narg++;
13784                       }
13785                     if (nargs != 0)
13786                       as_bad (_("invalid arg register list"));
13787
13788                     /* Count static registers.  */
13789                     while (statics & 0x8)
13790                       {
13791                         statics = (statics << 1) & 0xf;
13792                         nstat++;
13793                       }
13794                     if (statics != 0) 
13795                       as_bad (_("invalid static register list"));
13796
13797                     /* Encode args/statics.  */
13798                     opcode |= ((narg << 2) | nstat) << 16;
13799                   }
13800
13801                 /* Encode $s0/$s1.  */
13802                 if (sregs & (1 << 0))           /* $s0 */
13803                   opcode |= 0x20;
13804                 if (sregs & (1 << 1))           /* $s1 */
13805                   opcode |= 0x10;
13806                 sregs >>= 2;
13807
13808                 if (sregs != 0)
13809                   {
13810                     /* Count regs $s2-$s8.  */
13811                     int nsreg = 0;
13812                     while (sregs & 1)
13813                       {
13814                         sregs >>= 1;
13815                         nsreg++;
13816                       }
13817                     if (sregs != 0)
13818                       as_bad (_("invalid static register list"));
13819                     /* Encode $s2-$s8. */
13820                     opcode |= nsreg << 24;
13821                   }
13822
13823                 /* Encode frame size.  */
13824                 if (!seen_framesz)
13825                   as_bad (_("missing frame size"));
13826                 else if ((framesz & 7) != 0 || framesz < 0
13827                          || framesz > 0xff * 8)
13828                   as_bad (_("invalid frame size"));
13829                 else if (framesz != 128 || (opcode >> 16) != 0)
13830                   {
13831                     framesz /= 8;
13832                     opcode |= (((framesz & 0xf0) << 16)
13833                              | (framesz & 0x0f));
13834                   }
13835
13836                 /* Finally build the instruction.  */
13837                 if ((opcode >> 16) != 0 || framesz == 0)
13838                   {
13839                     ip->use_extend = TRUE;
13840                     ip->extend = opcode >> 16;
13841                   }
13842                 ip->insn_opcode |= opcode & 0x7f;
13843               }
13844             continue;
13845
13846             case 'e':           /* extend code */
13847               my_getExpression (&imm_expr, s);
13848               check_absolute_expr (ip, &imm_expr);
13849               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
13850                 {
13851                   as_warn (_("Invalid value for `%s' (%lu)"),
13852                            ip->insn_mo->name,
13853                            (unsigned long) imm_expr.X_add_number);
13854                   imm_expr.X_add_number &= 0x7ff;
13855                 }
13856               ip->insn_opcode |= imm_expr.X_add_number;
13857               imm_expr.X_op = O_absent;
13858               s = expr_end;
13859               continue;
13860
13861             default:
13862               internalError ();
13863             }
13864           break;
13865         }
13866
13867       /* Args don't match.  */
13868       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
13869           strcmp (insn->name, insn[1].name) == 0)
13870         {
13871           ++insn;
13872           s = argsstart;
13873           continue;
13874         }
13875
13876       insn_error = _("illegal operands");
13877
13878       return;
13879     }
13880 }
13881
13882 /* This structure holds information we know about a mips16 immediate
13883    argument type.  */
13884
13885 struct mips16_immed_operand
13886 {
13887   /* The type code used in the argument string in the opcode table.  */
13888   int type;
13889   /* The number of bits in the short form of the opcode.  */
13890   int nbits;
13891   /* The number of bits in the extended form of the opcode.  */
13892   int extbits;
13893   /* The amount by which the short form is shifted when it is used;
13894      for example, the sw instruction has a shift count of 2.  */
13895   int shift;
13896   /* The amount by which the short form is shifted when it is stored
13897      into the instruction code.  */
13898   int op_shift;
13899   /* Non-zero if the short form is unsigned.  */
13900   int unsp;
13901   /* Non-zero if the extended form is unsigned.  */
13902   int extu;
13903   /* Non-zero if the value is PC relative.  */
13904   int pcrel;
13905 };
13906
13907 /* The mips16 immediate operand types.  */
13908
13909 static const struct mips16_immed_operand mips16_immed_operands[] =
13910 {
13911   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13912   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13913   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13914   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13915   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
13916   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
13917   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
13918   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
13919   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
13920   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
13921   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
13922   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
13923   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
13924   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
13925   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
13926   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
13927   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13928   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13929   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
13930   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
13931   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
13932 };
13933
13934 #define MIPS16_NUM_IMMED \
13935   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
13936
13937 /* Handle a mips16 instruction with an immediate value.  This or's the
13938    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
13939    whether an extended value is needed; if one is needed, it sets
13940    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
13941    If SMALL is true, an unextended opcode was explicitly requested.
13942    If EXT is true, an extended opcode was explicitly requested.  If
13943    WARN is true, warn if EXT does not match reality.  */
13944
13945 static void
13946 mips16_immed (char *file, unsigned int line, int type, offsetT val,
13947               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
13948               unsigned long *insn, bfd_boolean *use_extend,
13949               unsigned short *extend)
13950 {
13951   const struct mips16_immed_operand *op;
13952   int mintiny, maxtiny;
13953   bfd_boolean needext;
13954
13955   op = mips16_immed_operands;
13956   while (op->type != type)
13957     {
13958       ++op;
13959       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
13960     }
13961
13962   if (op->unsp)
13963     {
13964       if (type == '<' || type == '>' || type == '[' || type == ']')
13965         {
13966           mintiny = 1;
13967           maxtiny = 1 << op->nbits;
13968         }
13969       else
13970         {
13971           mintiny = 0;
13972           maxtiny = (1 << op->nbits) - 1;
13973         }
13974     }
13975   else
13976     {
13977       mintiny = - (1 << (op->nbits - 1));
13978       maxtiny = (1 << (op->nbits - 1)) - 1;
13979     }
13980
13981   /* Branch offsets have an implicit 0 in the lowest bit.  */
13982   if (type == 'p' || type == 'q')
13983     val /= 2;
13984
13985   if ((val & ((1 << op->shift) - 1)) != 0
13986       || val < (mintiny << op->shift)
13987       || val > (maxtiny << op->shift))
13988     needext = TRUE;
13989   else
13990     needext = FALSE;
13991
13992   if (warn && ext && ! needext)
13993     as_warn_where (file, line,
13994                    _("extended operand requested but not required"));
13995   if (small && needext)
13996     as_bad_where (file, line, _("invalid unextended operand value"));
13997
13998   if (small || (! ext && ! needext))
13999     {
14000       int insnval;
14001
14002       *use_extend = FALSE;
14003       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
14004       insnval <<= op->op_shift;
14005       *insn |= insnval;
14006     }
14007   else
14008     {
14009       long minext, maxext;
14010       int extval;
14011
14012       if (op->extu)
14013         {
14014           minext = 0;
14015           maxext = (1 << op->extbits) - 1;
14016         }
14017       else
14018         {
14019           minext = - (1 << (op->extbits - 1));
14020           maxext = (1 << (op->extbits - 1)) - 1;
14021         }
14022       if (val < minext || val > maxext)
14023         as_bad_where (file, line,
14024                       _("operand value out of range for instruction"));
14025
14026       *use_extend = TRUE;
14027       if (op->extbits == 16)
14028         {
14029           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14030           val &= 0x1f;
14031         }
14032       else if (op->extbits == 15)
14033         {
14034           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14035           val &= 0xf;
14036         }
14037       else
14038         {
14039           extval = ((val & 0x1f) << 6) | (val & 0x20);
14040           val = 0;
14041         }
14042
14043       *extend = (unsigned short) extval;
14044       *insn |= val;
14045     }
14046 }
14047 \f
14048 struct percent_op_match
14049 {
14050   const char *str;
14051   bfd_reloc_code_real_type reloc;
14052 };
14053
14054 static const struct percent_op_match mips_percent_op[] =
14055 {
14056   {"%lo", BFD_RELOC_LO16},
14057 #ifdef OBJ_ELF
14058   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14059   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14060   {"%call16", BFD_RELOC_MIPS_CALL16},
14061   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14062   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14063   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14064   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14065   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14066   {"%got", BFD_RELOC_MIPS_GOT16},
14067   {"%gp_rel", BFD_RELOC_GPREL16},
14068   {"%half", BFD_RELOC_16},
14069   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14070   {"%higher", BFD_RELOC_MIPS_HIGHER},
14071   {"%neg", BFD_RELOC_MIPS_SUB},
14072   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14073   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14074   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14075   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14076   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14077   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14078   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14079 #endif
14080   {"%hi", BFD_RELOC_HI16_S}
14081 };
14082
14083 static const struct percent_op_match mips16_percent_op[] =
14084 {
14085   {"%lo", BFD_RELOC_MIPS16_LO16},
14086   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14087   {"%got", BFD_RELOC_MIPS16_GOT16},
14088   {"%call16", BFD_RELOC_MIPS16_CALL16},
14089   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14090   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14091   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14092   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14093   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14094   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14095   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14096   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14097 };
14098
14099
14100 /* Return true if *STR points to a relocation operator.  When returning true,
14101    move *STR over the operator and store its relocation code in *RELOC.
14102    Leave both *STR and *RELOC alone when returning false.  */
14103
14104 static bfd_boolean
14105 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14106 {
14107   const struct percent_op_match *percent_op;
14108   size_t limit, i;
14109
14110   if (mips_opts.mips16)
14111     {
14112       percent_op = mips16_percent_op;
14113       limit = ARRAY_SIZE (mips16_percent_op);
14114     }
14115   else
14116     {
14117       percent_op = mips_percent_op;
14118       limit = ARRAY_SIZE (mips_percent_op);
14119     }
14120
14121   for (i = 0; i < limit; i++)
14122     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14123       {
14124         int len = strlen (percent_op[i].str);
14125
14126         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14127           continue;
14128
14129         *str += strlen (percent_op[i].str);
14130         *reloc = percent_op[i].reloc;
14131
14132         /* Check whether the output BFD supports this relocation.
14133            If not, issue an error and fall back on something safe.  */
14134         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14135           {
14136             as_bad (_("relocation %s isn't supported by the current ABI"),
14137                     percent_op[i].str);
14138             *reloc = BFD_RELOC_UNUSED;
14139           }
14140         return TRUE;
14141       }
14142   return FALSE;
14143 }
14144
14145
14146 /* Parse string STR as a 16-bit relocatable operand.  Store the
14147    expression in *EP and the relocations in the array starting
14148    at RELOC.  Return the number of relocation operators used.
14149
14150    On exit, EXPR_END points to the first character after the expression.  */
14151
14152 static size_t
14153 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14154                        char *str)
14155 {
14156   bfd_reloc_code_real_type reversed_reloc[3];
14157   size_t reloc_index, i;
14158   int crux_depth, str_depth;
14159   char *crux;
14160
14161   /* Search for the start of the main expression, recoding relocations
14162      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14163      of the main expression and with CRUX_DEPTH containing the number
14164      of open brackets at that point.  */
14165   reloc_index = -1;
14166   str_depth = 0;
14167   do
14168     {
14169       reloc_index++;
14170       crux = str;
14171       crux_depth = str_depth;
14172
14173       /* Skip over whitespace and brackets, keeping count of the number
14174          of brackets.  */
14175       while (*str == ' ' || *str == '\t' || *str == '(')
14176         if (*str++ == '(')
14177           str_depth++;
14178     }
14179   while (*str == '%'
14180          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14181          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14182
14183   my_getExpression (ep, crux);
14184   str = expr_end;
14185
14186   /* Match every open bracket.  */
14187   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14188     if (*str++ == ')')
14189       crux_depth--;
14190
14191   if (crux_depth > 0)
14192     as_bad (_("unclosed '('"));
14193
14194   expr_end = str;
14195
14196   if (reloc_index != 0)
14197     {
14198       prev_reloc_op_frag = frag_now;
14199       for (i = 0; i < reloc_index; i++)
14200         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14201     }
14202
14203   return reloc_index;
14204 }
14205
14206 static void
14207 my_getExpression (expressionS *ep, char *str)
14208 {
14209   char *save_in;
14210
14211   save_in = input_line_pointer;
14212   input_line_pointer = str;
14213   expression (ep);
14214   expr_end = input_line_pointer;
14215   input_line_pointer = save_in;
14216 }
14217
14218 char *
14219 md_atof (int type, char *litP, int *sizeP)
14220 {
14221   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14222 }
14223
14224 void
14225 md_number_to_chars (char *buf, valueT val, int n)
14226 {
14227   if (target_big_endian)
14228     number_to_chars_bigendian (buf, val, n);
14229   else
14230     number_to_chars_littleendian (buf, val, n);
14231 }
14232 \f
14233 #ifdef OBJ_ELF
14234 static int support_64bit_objects(void)
14235 {
14236   const char **list, **l;
14237   int yes;
14238
14239   list = bfd_target_list ();
14240   for (l = list; *l != NULL; l++)
14241     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14242         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14243       break;
14244   yes = (*l != NULL);
14245   free (list);
14246   return yes;
14247 }
14248 #endif /* OBJ_ELF */
14249
14250 const char *md_shortopts = "O::g::G:";
14251
14252 enum options
14253   {
14254     OPTION_MARCH = OPTION_MD_BASE,
14255     OPTION_MTUNE,
14256     OPTION_MIPS1,
14257     OPTION_MIPS2,
14258     OPTION_MIPS3,
14259     OPTION_MIPS4,
14260     OPTION_MIPS5,
14261     OPTION_MIPS32,
14262     OPTION_MIPS64,
14263     OPTION_MIPS32R2,
14264     OPTION_MIPS64R2,
14265     OPTION_MIPS16,
14266     OPTION_NO_MIPS16,
14267     OPTION_MIPS3D,
14268     OPTION_NO_MIPS3D,
14269     OPTION_MDMX,
14270     OPTION_NO_MDMX,
14271     OPTION_DSP,
14272     OPTION_NO_DSP,
14273     OPTION_MT,
14274     OPTION_NO_MT,
14275     OPTION_SMARTMIPS,
14276     OPTION_NO_SMARTMIPS,
14277     OPTION_DSPR2,
14278     OPTION_NO_DSPR2,
14279     OPTION_MICROMIPS,
14280     OPTION_NO_MICROMIPS,
14281     OPTION_MCU,
14282     OPTION_NO_MCU,
14283     OPTION_COMPAT_ARCH_BASE,
14284     OPTION_M4650,
14285     OPTION_NO_M4650,
14286     OPTION_M4010,
14287     OPTION_NO_M4010,
14288     OPTION_M4100,
14289     OPTION_NO_M4100,
14290     OPTION_M3900,
14291     OPTION_NO_M3900,
14292     OPTION_M7000_HILO_FIX,
14293     OPTION_MNO_7000_HILO_FIX, 
14294     OPTION_FIX_24K,
14295     OPTION_NO_FIX_24K,
14296     OPTION_FIX_LOONGSON2F_JUMP,
14297     OPTION_NO_FIX_LOONGSON2F_JUMP,
14298     OPTION_FIX_LOONGSON2F_NOP,
14299     OPTION_NO_FIX_LOONGSON2F_NOP,
14300     OPTION_FIX_VR4120,
14301     OPTION_NO_FIX_VR4120,
14302     OPTION_FIX_VR4130,
14303     OPTION_NO_FIX_VR4130,
14304     OPTION_FIX_CN63XXP1,
14305     OPTION_NO_FIX_CN63XXP1,
14306     OPTION_TRAP,
14307     OPTION_BREAK,
14308     OPTION_EB,
14309     OPTION_EL,
14310     OPTION_FP32,
14311     OPTION_GP32,
14312     OPTION_CONSTRUCT_FLOATS,
14313     OPTION_NO_CONSTRUCT_FLOATS,
14314     OPTION_FP64,
14315     OPTION_GP64,
14316     OPTION_RELAX_BRANCH,
14317     OPTION_NO_RELAX_BRANCH,
14318     OPTION_MSHARED,
14319     OPTION_MNO_SHARED,
14320     OPTION_MSYM32,
14321     OPTION_MNO_SYM32,
14322     OPTION_SOFT_FLOAT,
14323     OPTION_HARD_FLOAT,
14324     OPTION_SINGLE_FLOAT,
14325     OPTION_DOUBLE_FLOAT,
14326     OPTION_32,
14327 #ifdef OBJ_ELF
14328     OPTION_CALL_SHARED,
14329     OPTION_CALL_NONPIC,
14330     OPTION_NON_SHARED,
14331     OPTION_XGOT,
14332     OPTION_MABI,
14333     OPTION_N32,
14334     OPTION_64,
14335     OPTION_MDEBUG,
14336     OPTION_NO_MDEBUG,
14337     OPTION_PDR,
14338     OPTION_NO_PDR,
14339     OPTION_MVXWORKS_PIC,
14340 #endif /* OBJ_ELF */
14341     OPTION_END_OF_ENUM    
14342   };
14343   
14344 struct option md_longopts[] =
14345 {
14346   /* Options which specify architecture.  */
14347   {"march", required_argument, NULL, OPTION_MARCH},
14348   {"mtune", required_argument, NULL, OPTION_MTUNE},
14349   {"mips0", no_argument, NULL, OPTION_MIPS1},
14350   {"mips1", no_argument, NULL, OPTION_MIPS1},
14351   {"mips2", no_argument, NULL, OPTION_MIPS2},
14352   {"mips3", no_argument, NULL, OPTION_MIPS3},
14353   {"mips4", no_argument, NULL, OPTION_MIPS4},
14354   {"mips5", no_argument, NULL, OPTION_MIPS5},
14355   {"mips32", no_argument, NULL, OPTION_MIPS32},
14356   {"mips64", no_argument, NULL, OPTION_MIPS64},
14357   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
14358   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
14359
14360   /* Options which specify Application Specific Extensions (ASEs).  */
14361   {"mips16", no_argument, NULL, OPTION_MIPS16},
14362   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
14363   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
14364   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
14365   {"mdmx", no_argument, NULL, OPTION_MDMX},
14366   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
14367   {"mdsp", no_argument, NULL, OPTION_DSP},
14368   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
14369   {"mmt", no_argument, NULL, OPTION_MT},
14370   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
14371   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
14372   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
14373   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
14374   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
14375   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
14376   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
14377   {"mmcu", no_argument, NULL, OPTION_MCU},
14378   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
14379
14380   /* Old-style architecture options.  Don't add more of these.  */
14381   {"m4650", no_argument, NULL, OPTION_M4650},
14382   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
14383   {"m4010", no_argument, NULL, OPTION_M4010},
14384   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
14385   {"m4100", no_argument, NULL, OPTION_M4100},
14386   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
14387   {"m3900", no_argument, NULL, OPTION_M3900},
14388   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
14389
14390   /* Options which enable bug fixes.  */
14391   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
14392   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14393   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14394   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
14395   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
14396   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
14397   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
14398   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
14399   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
14400   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
14401   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
14402   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
14403   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
14404   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
14405   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
14406
14407   /* Miscellaneous options.  */
14408   {"trap", no_argument, NULL, OPTION_TRAP},
14409   {"no-break", no_argument, NULL, OPTION_TRAP},
14410   {"break", no_argument, NULL, OPTION_BREAK},
14411   {"no-trap", no_argument, NULL, OPTION_BREAK},
14412   {"EB", no_argument, NULL, OPTION_EB},
14413   {"EL", no_argument, NULL, OPTION_EL},
14414   {"mfp32", no_argument, NULL, OPTION_FP32},
14415   {"mgp32", no_argument, NULL, OPTION_GP32},
14416   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
14417   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
14418   {"mfp64", no_argument, NULL, OPTION_FP64},
14419   {"mgp64", no_argument, NULL, OPTION_GP64},
14420   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
14421   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
14422   {"mshared", no_argument, NULL, OPTION_MSHARED},
14423   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
14424   {"msym32", no_argument, NULL, OPTION_MSYM32},
14425   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
14426   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
14427   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
14428   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
14429   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
14430
14431   /* Strictly speaking this next option is ELF specific,
14432      but we allow it for other ports as well in order to
14433      make testing easier.  */
14434   {"32",          no_argument, NULL, OPTION_32},
14435   
14436   /* ELF-specific options.  */
14437 #ifdef OBJ_ELF
14438   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
14439   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
14440   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
14441   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
14442   {"xgot",        no_argument, NULL, OPTION_XGOT},
14443   {"mabi", required_argument, NULL, OPTION_MABI},
14444   {"n32",         no_argument, NULL, OPTION_N32},
14445   {"64",          no_argument, NULL, OPTION_64},
14446   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
14447   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
14448   {"mpdr", no_argument, NULL, OPTION_PDR},
14449   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
14450   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
14451 #endif /* OBJ_ELF */
14452
14453   {NULL, no_argument, NULL, 0}
14454 };
14455 size_t md_longopts_size = sizeof (md_longopts);
14456
14457 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14458    NEW_VALUE.  Warn if another value was already specified.  Note:
14459    we have to defer parsing the -march and -mtune arguments in order
14460    to handle 'from-abi' correctly, since the ABI might be specified
14461    in a later argument.  */
14462
14463 static void
14464 mips_set_option_string (const char **string_ptr, const char *new_value)
14465 {
14466   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14467     as_warn (_("A different %s was already specified, is now %s"),
14468              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14469              new_value);
14470
14471   *string_ptr = new_value;
14472 }
14473
14474 int
14475 md_parse_option (int c, char *arg)
14476 {
14477   switch (c)
14478     {
14479     case OPTION_CONSTRUCT_FLOATS:
14480       mips_disable_float_construction = 0;
14481       break;
14482
14483     case OPTION_NO_CONSTRUCT_FLOATS:
14484       mips_disable_float_construction = 1;
14485       break;
14486
14487     case OPTION_TRAP:
14488       mips_trap = 1;
14489       break;
14490
14491     case OPTION_BREAK:
14492       mips_trap = 0;
14493       break;
14494
14495     case OPTION_EB:
14496       target_big_endian = 1;
14497       break;
14498
14499     case OPTION_EL:
14500       target_big_endian = 0;
14501       break;
14502
14503     case 'O':
14504       if (arg == NULL)
14505         mips_optimize = 1;
14506       else if (arg[0] == '0')
14507         mips_optimize = 0;
14508       else if (arg[0] == '1')
14509         mips_optimize = 1;
14510       else
14511         mips_optimize = 2;
14512       break;
14513
14514     case 'g':
14515       if (arg == NULL)
14516         mips_debug = 2;
14517       else
14518         mips_debug = atoi (arg);
14519       break;
14520
14521     case OPTION_MIPS1:
14522       file_mips_isa = ISA_MIPS1;
14523       break;
14524
14525     case OPTION_MIPS2:
14526       file_mips_isa = ISA_MIPS2;
14527       break;
14528
14529     case OPTION_MIPS3:
14530       file_mips_isa = ISA_MIPS3;
14531       break;
14532
14533     case OPTION_MIPS4:
14534       file_mips_isa = ISA_MIPS4;
14535       break;
14536
14537     case OPTION_MIPS5:
14538       file_mips_isa = ISA_MIPS5;
14539       break;
14540
14541     case OPTION_MIPS32:
14542       file_mips_isa = ISA_MIPS32;
14543       break;
14544
14545     case OPTION_MIPS32R2:
14546       file_mips_isa = ISA_MIPS32R2;
14547       break;
14548
14549     case OPTION_MIPS64R2:
14550       file_mips_isa = ISA_MIPS64R2;
14551       break;
14552
14553     case OPTION_MIPS64:
14554       file_mips_isa = ISA_MIPS64;
14555       break;
14556
14557     case OPTION_MTUNE:
14558       mips_set_option_string (&mips_tune_string, arg);
14559       break;
14560
14561     case OPTION_MARCH:
14562       mips_set_option_string (&mips_arch_string, arg);
14563       break;
14564
14565     case OPTION_M4650:
14566       mips_set_option_string (&mips_arch_string, "4650");
14567       mips_set_option_string (&mips_tune_string, "4650");
14568       break;
14569
14570     case OPTION_NO_M4650:
14571       break;
14572
14573     case OPTION_M4010:
14574       mips_set_option_string (&mips_arch_string, "4010");
14575       mips_set_option_string (&mips_tune_string, "4010");
14576       break;
14577
14578     case OPTION_NO_M4010:
14579       break;
14580
14581     case OPTION_M4100:
14582       mips_set_option_string (&mips_arch_string, "4100");
14583       mips_set_option_string (&mips_tune_string, "4100");
14584       break;
14585
14586     case OPTION_NO_M4100:
14587       break;
14588
14589     case OPTION_M3900:
14590       mips_set_option_string (&mips_arch_string, "3900");
14591       mips_set_option_string (&mips_tune_string, "3900");
14592       break;
14593
14594     case OPTION_NO_M3900:
14595       break;
14596
14597     case OPTION_MDMX:
14598       mips_opts.ase_mdmx = 1;
14599       break;
14600
14601     case OPTION_NO_MDMX:
14602       mips_opts.ase_mdmx = 0;
14603       break;
14604
14605     case OPTION_DSP:
14606       mips_opts.ase_dsp = 1;
14607       mips_opts.ase_dspr2 = 0;
14608       break;
14609
14610     case OPTION_NO_DSP:
14611       mips_opts.ase_dsp = 0;
14612       mips_opts.ase_dspr2 = 0;
14613       break;
14614
14615     case OPTION_DSPR2:
14616       mips_opts.ase_dspr2 = 1;
14617       mips_opts.ase_dsp = 1;
14618       break;
14619
14620     case OPTION_NO_DSPR2:
14621       mips_opts.ase_dspr2 = 0;
14622       mips_opts.ase_dsp = 0;
14623       break;
14624
14625     case OPTION_MT:
14626       mips_opts.ase_mt = 1;
14627       break;
14628
14629     case OPTION_NO_MT:
14630       mips_opts.ase_mt = 0;
14631       break;
14632
14633     case OPTION_MCU:
14634       mips_opts.ase_mcu = 1;
14635       break;
14636
14637     case OPTION_NO_MCU:
14638       mips_opts.ase_mcu = 0;
14639       break;
14640
14641     case OPTION_MICROMIPS:
14642       if (mips_opts.mips16 == 1)
14643         {
14644           as_bad (_("-mmicromips cannot be used with -mips16"));
14645           return 0;
14646         }
14647       mips_opts.micromips = 1;
14648       mips_no_prev_insn ();
14649       break;
14650
14651     case OPTION_NO_MICROMIPS:
14652       mips_opts.micromips = 0;
14653       mips_no_prev_insn ();
14654       break;
14655
14656     case OPTION_MIPS16:
14657       if (mips_opts.micromips == 1)
14658         {
14659           as_bad (_("-mips16 cannot be used with -micromips"));
14660           return 0;
14661         }
14662       mips_opts.mips16 = 1;
14663       mips_no_prev_insn ();
14664       break;
14665
14666     case OPTION_NO_MIPS16:
14667       mips_opts.mips16 = 0;
14668       mips_no_prev_insn ();
14669       break;
14670
14671     case OPTION_MIPS3D:
14672       mips_opts.ase_mips3d = 1;
14673       break;
14674
14675     case OPTION_NO_MIPS3D:
14676       mips_opts.ase_mips3d = 0;
14677       break;
14678
14679     case OPTION_SMARTMIPS:
14680       mips_opts.ase_smartmips = 1;
14681       break;
14682
14683     case OPTION_NO_SMARTMIPS:
14684       mips_opts.ase_smartmips = 0;
14685       break;
14686
14687     case OPTION_FIX_24K:
14688       mips_fix_24k = 1;
14689       break;
14690
14691     case OPTION_NO_FIX_24K:
14692       mips_fix_24k = 0;
14693       break;
14694
14695     case OPTION_FIX_LOONGSON2F_JUMP:
14696       mips_fix_loongson2f_jump = TRUE;
14697       break;
14698
14699     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14700       mips_fix_loongson2f_jump = FALSE;
14701       break;
14702
14703     case OPTION_FIX_LOONGSON2F_NOP:
14704       mips_fix_loongson2f_nop = TRUE;
14705       break;
14706
14707     case OPTION_NO_FIX_LOONGSON2F_NOP:
14708       mips_fix_loongson2f_nop = FALSE;
14709       break;
14710
14711     case OPTION_FIX_VR4120:
14712       mips_fix_vr4120 = 1;
14713       break;
14714
14715     case OPTION_NO_FIX_VR4120:
14716       mips_fix_vr4120 = 0;
14717       break;
14718
14719     case OPTION_FIX_VR4130:
14720       mips_fix_vr4130 = 1;
14721       break;
14722
14723     case OPTION_NO_FIX_VR4130:
14724       mips_fix_vr4130 = 0;
14725       break;
14726
14727     case OPTION_FIX_CN63XXP1:
14728       mips_fix_cn63xxp1 = TRUE;
14729       break;
14730
14731     case OPTION_NO_FIX_CN63XXP1:
14732       mips_fix_cn63xxp1 = FALSE;
14733       break;
14734
14735     case OPTION_RELAX_BRANCH:
14736       mips_relax_branch = 1;
14737       break;
14738
14739     case OPTION_NO_RELAX_BRANCH:
14740       mips_relax_branch = 0;
14741       break;
14742
14743     case OPTION_MSHARED:
14744       mips_in_shared = TRUE;
14745       break;
14746
14747     case OPTION_MNO_SHARED:
14748       mips_in_shared = FALSE;
14749       break;
14750
14751     case OPTION_MSYM32:
14752       mips_opts.sym32 = TRUE;
14753       break;
14754
14755     case OPTION_MNO_SYM32:
14756       mips_opts.sym32 = FALSE;
14757       break;
14758
14759 #ifdef OBJ_ELF
14760       /* When generating ELF code, we permit -KPIC and -call_shared to
14761          select SVR4_PIC, and -non_shared to select no PIC.  This is
14762          intended to be compatible with Irix 5.  */
14763     case OPTION_CALL_SHARED:
14764       if (!IS_ELF)
14765         {
14766           as_bad (_("-call_shared is supported only for ELF format"));
14767           return 0;
14768         }
14769       mips_pic = SVR4_PIC;
14770       mips_abicalls = TRUE;
14771       break;
14772
14773     case OPTION_CALL_NONPIC:
14774       if (!IS_ELF)
14775         {
14776           as_bad (_("-call_nonpic is supported only for ELF format"));
14777           return 0;
14778         }
14779       mips_pic = NO_PIC;
14780       mips_abicalls = TRUE;
14781       break;
14782
14783     case OPTION_NON_SHARED:
14784       if (!IS_ELF)
14785         {
14786           as_bad (_("-non_shared is supported only for ELF format"));
14787           return 0;
14788         }
14789       mips_pic = NO_PIC;
14790       mips_abicalls = FALSE;
14791       break;
14792
14793       /* The -xgot option tells the assembler to use 32 bit offsets
14794          when accessing the got in SVR4_PIC mode.  It is for Irix
14795          compatibility.  */
14796     case OPTION_XGOT:
14797       mips_big_got = 1;
14798       break;
14799 #endif /* OBJ_ELF */
14800
14801     case 'G':
14802       g_switch_value = atoi (arg);
14803       g_switch_seen = 1;
14804       break;
14805
14806       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14807          and -mabi=64.  */
14808     case OPTION_32:
14809       if (IS_ELF)
14810         mips_abi = O32_ABI;
14811       /* We silently ignore -32 for non-ELF targets.  This greatly
14812          simplifies the construction of the MIPS GAS test cases.  */
14813       break;
14814
14815 #ifdef OBJ_ELF
14816     case OPTION_N32:
14817       if (!IS_ELF)
14818         {
14819           as_bad (_("-n32 is supported for ELF format only"));
14820           return 0;
14821         }
14822       mips_abi = N32_ABI;
14823       break;
14824
14825     case OPTION_64:
14826       if (!IS_ELF)
14827         {
14828           as_bad (_("-64 is supported for ELF format only"));
14829           return 0;
14830         }
14831       mips_abi = N64_ABI;
14832       if (!support_64bit_objects())
14833         as_fatal (_("No compiled in support for 64 bit object file format"));
14834       break;
14835 #endif /* OBJ_ELF */
14836
14837     case OPTION_GP32:
14838       file_mips_gp32 = 1;
14839       break;
14840
14841     case OPTION_GP64:
14842       file_mips_gp32 = 0;
14843       break;
14844
14845     case OPTION_FP32:
14846       file_mips_fp32 = 1;
14847       break;
14848
14849     case OPTION_FP64:
14850       file_mips_fp32 = 0;
14851       break;
14852
14853     case OPTION_SINGLE_FLOAT:
14854       file_mips_single_float = 1;
14855       break;
14856
14857     case OPTION_DOUBLE_FLOAT:
14858       file_mips_single_float = 0;
14859       break;
14860
14861     case OPTION_SOFT_FLOAT:
14862       file_mips_soft_float = 1;
14863       break;
14864
14865     case OPTION_HARD_FLOAT:
14866       file_mips_soft_float = 0;
14867       break;
14868
14869 #ifdef OBJ_ELF
14870     case OPTION_MABI:
14871       if (!IS_ELF)
14872         {
14873           as_bad (_("-mabi is supported for ELF format only"));
14874           return 0;
14875         }
14876       if (strcmp (arg, "32") == 0)
14877         mips_abi = O32_ABI;
14878       else if (strcmp (arg, "o64") == 0)
14879         mips_abi = O64_ABI;
14880       else if (strcmp (arg, "n32") == 0)
14881         mips_abi = N32_ABI;
14882       else if (strcmp (arg, "64") == 0)
14883         {
14884           mips_abi = N64_ABI;
14885           if (! support_64bit_objects())
14886             as_fatal (_("No compiled in support for 64 bit object file "
14887                         "format"));
14888         }
14889       else if (strcmp (arg, "eabi") == 0)
14890         mips_abi = EABI_ABI;
14891       else
14892         {
14893           as_fatal (_("invalid abi -mabi=%s"), arg);
14894           return 0;
14895         }
14896       break;
14897 #endif /* OBJ_ELF */
14898
14899     case OPTION_M7000_HILO_FIX:
14900       mips_7000_hilo_fix = TRUE;
14901       break;
14902
14903     case OPTION_MNO_7000_HILO_FIX:
14904       mips_7000_hilo_fix = FALSE;
14905       break;
14906
14907 #ifdef OBJ_ELF
14908     case OPTION_MDEBUG:
14909       mips_flag_mdebug = TRUE;
14910       break;
14911
14912     case OPTION_NO_MDEBUG:
14913       mips_flag_mdebug = FALSE;
14914       break;
14915
14916     case OPTION_PDR:
14917       mips_flag_pdr = TRUE;
14918       break;
14919
14920     case OPTION_NO_PDR:
14921       mips_flag_pdr = FALSE;
14922       break;
14923
14924     case OPTION_MVXWORKS_PIC:
14925       mips_pic = VXWORKS_PIC;
14926       break;
14927 #endif /* OBJ_ELF */
14928
14929     default:
14930       return 0;
14931     }
14932
14933     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14934
14935   return 1;
14936 }
14937 \f
14938 /* Set up globals to generate code for the ISA or processor
14939    described by INFO.  */
14940
14941 static void
14942 mips_set_architecture (const struct mips_cpu_info *info)
14943 {
14944   if (info != 0)
14945     {
14946       file_mips_arch = info->cpu;
14947       mips_opts.arch = info->cpu;
14948       mips_opts.isa = info->isa;
14949     }
14950 }
14951
14952
14953 /* Likewise for tuning.  */
14954
14955 static void
14956 mips_set_tune (const struct mips_cpu_info *info)
14957 {
14958   if (info != 0)
14959     mips_tune = info->cpu;
14960 }
14961
14962
14963 void
14964 mips_after_parse_args (void)
14965 {
14966   const struct mips_cpu_info *arch_info = 0;
14967   const struct mips_cpu_info *tune_info = 0;
14968
14969   /* GP relative stuff not working for PE */
14970   if (strncmp (TARGET_OS, "pe", 2) == 0)
14971     {
14972       if (g_switch_seen && g_switch_value != 0)
14973         as_bad (_("-G not supported in this configuration."));
14974       g_switch_value = 0;
14975     }
14976
14977   if (mips_abi == NO_ABI)
14978     mips_abi = MIPS_DEFAULT_ABI;
14979
14980   /* The following code determines the architecture and register size.
14981      Similar code was added to GCC 3.3 (see override_options() in
14982      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14983      as much as possible.  */
14984
14985   if (mips_arch_string != 0)
14986     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14987
14988   if (file_mips_isa != ISA_UNKNOWN)
14989     {
14990       /* Handle -mipsN.  At this point, file_mips_isa contains the
14991          ISA level specified by -mipsN, while arch_info->isa contains
14992          the -march selection (if any).  */
14993       if (arch_info != 0)
14994         {
14995           /* -march takes precedence over -mipsN, since it is more descriptive.
14996              There's no harm in specifying both as long as the ISA levels
14997              are the same.  */
14998           if (file_mips_isa != arch_info->isa)
14999             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
15000                     mips_cpu_info_from_isa (file_mips_isa)->name,
15001                     mips_cpu_info_from_isa (arch_info->isa)->name);
15002         }
15003       else
15004         arch_info = mips_cpu_info_from_isa (file_mips_isa);
15005     }
15006
15007   if (arch_info == 0)
15008     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15009
15010   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15011     as_bad (_("-march=%s is not compatible with the selected ABI"),
15012             arch_info->name);
15013
15014   mips_set_architecture (arch_info);
15015
15016   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
15017   if (mips_tune_string != 0)
15018     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15019
15020   if (tune_info == 0)
15021     mips_set_tune (arch_info);
15022   else
15023     mips_set_tune (tune_info);
15024
15025   if (file_mips_gp32 >= 0)
15026     {
15027       /* The user specified the size of the integer registers.  Make sure
15028          it agrees with the ABI and ISA.  */
15029       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
15030         as_bad (_("-mgp64 used with a 32-bit processor"));
15031       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
15032         as_bad (_("-mgp32 used with a 64-bit ABI"));
15033       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
15034         as_bad (_("-mgp64 used with a 32-bit ABI"));
15035     }
15036   else
15037     {
15038       /* Infer the integer register size from the ABI and processor.
15039          Restrict ourselves to 32-bit registers if that's all the
15040          processor has, or if the ABI cannot handle 64-bit registers.  */
15041       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
15042                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
15043     }
15044
15045   switch (file_mips_fp32)
15046     {
15047     default:
15048     case -1:
15049       /* No user specified float register size.
15050          ??? GAS treats single-float processors as though they had 64-bit
15051          float registers (although it complains when double-precision
15052          instructions are used).  As things stand, saying they have 32-bit
15053          registers would lead to spurious "register must be even" messages.
15054          So here we assume float registers are never smaller than the
15055          integer ones.  */
15056       if (file_mips_gp32 == 0)
15057         /* 64-bit integer registers implies 64-bit float registers.  */
15058         file_mips_fp32 = 0;
15059       else if ((mips_opts.ase_mips3d > 0 || mips_opts.ase_mdmx > 0)
15060                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
15061         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
15062         file_mips_fp32 = 0;
15063       else
15064         /* 32-bit float registers.  */
15065         file_mips_fp32 = 1;
15066       break;
15067
15068     /* The user specified the size of the float registers.  Check if it
15069        agrees with the ABI and ISA.  */
15070     case 0:
15071       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15072         as_bad (_("-mfp64 used with a 32-bit fpu"));
15073       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
15074                && !ISA_HAS_MXHC1 (mips_opts.isa))
15075         as_warn (_("-mfp64 used with a 32-bit ABI"));
15076       break;
15077     case 1:
15078       if (ABI_NEEDS_64BIT_REGS (mips_abi))
15079         as_warn (_("-mfp32 used with a 64-bit ABI"));
15080       break;
15081     }
15082
15083   /* End of GCC-shared inference code.  */
15084
15085   /* This flag is set when we have a 64-bit capable CPU but use only
15086      32-bit wide registers.  Note that EABI does not use it.  */
15087   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
15088       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
15089           || mips_abi == O32_ABI))
15090     mips_32bitmode = 1;
15091
15092   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
15093     as_bad (_("trap exception not supported at ISA 1"));
15094
15095   /* If the selected architecture includes support for ASEs, enable
15096      generation of code for them.  */
15097   if (mips_opts.mips16 == -1)
15098     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
15099   if (mips_opts.micromips == -1)
15100     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15101   if (mips_opts.ase_mips3d == -1)
15102     mips_opts.ase_mips3d = ((arch_info->flags & MIPS_CPU_ASE_MIPS3D)
15103                             && file_mips_fp32 == 0) ? 1 : 0;
15104   if (mips_opts.ase_mips3d && file_mips_fp32 == 1)
15105     as_bad (_("-mfp32 used with -mips3d"));
15106
15107   if (mips_opts.ase_mdmx == -1)
15108     mips_opts.ase_mdmx = ((arch_info->flags & MIPS_CPU_ASE_MDMX)
15109                           && file_mips_fp32 == 0) ? 1 : 0;
15110   if (mips_opts.ase_mdmx && file_mips_fp32 == 1)
15111     as_bad (_("-mfp32 used with -mdmx"));
15112
15113   if (mips_opts.ase_smartmips == -1)
15114     mips_opts.ase_smartmips = (arch_info->flags & MIPS_CPU_ASE_SMARTMIPS) ? 1 : 0;
15115   if (mips_opts.ase_smartmips && !ISA_SUPPORTS_SMARTMIPS)
15116     as_warn (_("%s ISA does not support SmartMIPS"), 
15117              mips_cpu_info_from_isa (mips_opts.isa)->name);
15118
15119   if (mips_opts.ase_dsp == -1)
15120     mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15121   if (mips_opts.ase_dsp && !ISA_SUPPORTS_DSP_ASE)
15122     as_warn (_("%s ISA does not support DSP ASE"), 
15123              mips_cpu_info_from_isa (mips_opts.isa)->name);
15124
15125   if (mips_opts.ase_dspr2 == -1)
15126     {
15127       mips_opts.ase_dspr2 = (arch_info->flags & MIPS_CPU_ASE_DSPR2) ? 1 : 0;
15128       mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15129     }
15130   if (mips_opts.ase_dspr2 && !ISA_SUPPORTS_DSPR2_ASE)
15131     as_warn (_("%s ISA does not support DSP R2 ASE"),
15132              mips_cpu_info_from_isa (mips_opts.isa)->name);
15133
15134   if (mips_opts.ase_mt == -1)
15135     mips_opts.ase_mt = (arch_info->flags & MIPS_CPU_ASE_MT) ? 1 : 0;
15136   if (mips_opts.ase_mt && !ISA_SUPPORTS_MT_ASE)
15137     as_warn (_("%s ISA does not support MT ASE"),
15138              mips_cpu_info_from_isa (mips_opts.isa)->name);
15139
15140   if (mips_opts.ase_mcu == -1)
15141     mips_opts.ase_mcu = (arch_info->flags & MIPS_CPU_ASE_MCU) ? 1 : 0;
15142   if (mips_opts.ase_mcu && !ISA_SUPPORTS_MCU_ASE)
15143       as_warn (_("%s ISA does not support MCU ASE"),
15144                mips_cpu_info_from_isa (mips_opts.isa)->name);
15145
15146   file_mips_isa = mips_opts.isa;
15147   file_ase_mips3d = mips_opts.ase_mips3d;
15148   file_ase_mdmx = mips_opts.ase_mdmx;
15149   file_ase_smartmips = mips_opts.ase_smartmips;
15150   file_ase_dsp = mips_opts.ase_dsp;
15151   file_ase_dspr2 = mips_opts.ase_dspr2;
15152   file_ase_mt = mips_opts.ase_mt;
15153   mips_opts.gp32 = file_mips_gp32;
15154   mips_opts.fp32 = file_mips_fp32;
15155   mips_opts.soft_float = file_mips_soft_float;
15156   mips_opts.single_float = file_mips_single_float;
15157
15158   if (mips_flag_mdebug < 0)
15159     {
15160 #ifdef OBJ_MAYBE_ECOFF
15161       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
15162         mips_flag_mdebug = 1;
15163       else
15164 #endif /* OBJ_MAYBE_ECOFF */
15165         mips_flag_mdebug = 0;
15166     }
15167 }
15168 \f
15169 void
15170 mips_init_after_args (void)
15171 {
15172   /* initialize opcodes */
15173   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15174   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15175 }
15176
15177 long
15178 md_pcrel_from (fixS *fixP)
15179 {
15180   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15181   switch (fixP->fx_r_type)
15182     {
15183     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15184     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15185       /* Return the address of the delay slot.  */
15186       return addr + 2;
15187
15188     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15189     case BFD_RELOC_MICROMIPS_JMP:
15190     case BFD_RELOC_16_PCREL_S2:
15191     case BFD_RELOC_MIPS_JMP:
15192       /* Return the address of the delay slot.  */
15193       return addr + 4;
15194
15195     default:
15196       /* We have no relocation type for PC relative MIPS16 instructions.  */
15197       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15198         as_bad_where (fixP->fx_file, fixP->fx_line,
15199                       _("PC relative MIPS16 instruction references a different section"));
15200       return addr;
15201     }
15202 }
15203
15204 /* This is called before the symbol table is processed.  In order to
15205    work with gcc when using mips-tfile, we must keep all local labels.
15206    However, in other cases, we want to discard them.  If we were
15207    called with -g, but we didn't see any debugging information, it may
15208    mean that gcc is smuggling debugging information through to
15209    mips-tfile, in which case we must generate all local labels.  */
15210
15211 void
15212 mips_frob_file_before_adjust (void)
15213 {
15214 #ifndef NO_ECOFF_DEBUGGING
15215   if (ECOFF_DEBUGGING
15216       && mips_debug != 0
15217       && ! ecoff_debugging_seen)
15218     flag_keep_locals = 1;
15219 #endif
15220 }
15221
15222 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15223    the corresponding LO16 reloc.  This is called before md_apply_fix and
15224    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15225    relocation operators.
15226
15227    For our purposes, a %lo() expression matches a %got() or %hi()
15228    expression if:
15229
15230       (a) it refers to the same symbol; and
15231       (b) the offset applied in the %lo() expression is no lower than
15232           the offset applied in the %got() or %hi().
15233
15234    (b) allows us to cope with code like:
15235
15236         lui     $4,%hi(foo)
15237         lh      $4,%lo(foo+2)($4)
15238
15239    ...which is legal on RELA targets, and has a well-defined behaviour
15240    if the user knows that adding 2 to "foo" will not induce a carry to
15241    the high 16 bits.
15242
15243    When several %lo()s match a particular %got() or %hi(), we use the
15244    following rules to distinguish them:
15245
15246      (1) %lo()s with smaller offsets are a better match than %lo()s with
15247          higher offsets.
15248
15249      (2) %lo()s with no matching %got() or %hi() are better than those
15250          that already have a matching %got() or %hi().
15251
15252      (3) later %lo()s are better than earlier %lo()s.
15253
15254    These rules are applied in order.
15255
15256    (1) means, among other things, that %lo()s with identical offsets are
15257    chosen if they exist.
15258
15259    (2) means that we won't associate several high-part relocations with
15260    the same low-part relocation unless there's no alternative.  Having
15261    several high parts for the same low part is a GNU extension; this rule
15262    allows careful users to avoid it.
15263
15264    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15265    with the last high-part relocation being at the front of the list.
15266    It therefore makes sense to choose the last matching low-part
15267    relocation, all other things being equal.  It's also easier
15268    to code that way.  */
15269
15270 void
15271 mips_frob_file (void)
15272 {
15273   struct mips_hi_fixup *l;
15274   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15275
15276   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15277     {
15278       segment_info_type *seginfo;
15279       bfd_boolean matched_lo_p;
15280       fixS **hi_pos, **lo_pos, **pos;
15281
15282       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15283
15284       /* If a GOT16 relocation turns out to be against a global symbol,
15285          there isn't supposed to be a matching LO.  */
15286       if (got16_reloc_p (l->fixp->fx_r_type)
15287           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
15288         continue;
15289
15290       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15291       if (fixup_has_matching_lo_p (l->fixp))
15292         continue;
15293
15294       seginfo = seg_info (l->seg);
15295
15296       /* Set HI_POS to the position of this relocation in the chain.
15297          Set LO_POS to the position of the chosen low-part relocation.
15298          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15299          relocation that matches an immediately-preceding high-part
15300          relocation.  */
15301       hi_pos = NULL;
15302       lo_pos = NULL;
15303       matched_lo_p = FALSE;
15304       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15305
15306       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15307         {
15308           if (*pos == l->fixp)
15309             hi_pos = pos;
15310
15311           if ((*pos)->fx_r_type == looking_for_rtype
15312               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15313               && (*pos)->fx_offset >= l->fixp->fx_offset
15314               && (lo_pos == NULL
15315                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15316                   || (!matched_lo_p
15317                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15318             lo_pos = pos;
15319
15320           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15321                           && fixup_has_matching_lo_p (*pos));
15322         }
15323
15324       /* If we found a match, remove the high-part relocation from its
15325          current position and insert it before the low-part relocation.
15326          Make the offsets match so that fixup_has_matching_lo_p()
15327          will return true.
15328
15329          We don't warn about unmatched high-part relocations since some
15330          versions of gcc have been known to emit dead "lui ...%hi(...)"
15331          instructions.  */
15332       if (lo_pos != NULL)
15333         {
15334           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15335           if (l->fixp->fx_next != *lo_pos)
15336             {
15337               *hi_pos = l->fixp->fx_next;
15338               l->fixp->fx_next = *lo_pos;
15339               *lo_pos = l->fixp;
15340             }
15341         }
15342     }
15343 }
15344
15345 /* We may have combined relocations without symbols in the N32/N64 ABI.
15346    We have to prevent gas from dropping them.  */
15347
15348 int
15349 mips_force_relocation (fixS *fixp)
15350 {
15351   if (generic_force_reloc (fixp))
15352     return 1;
15353
15354   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15355      so that the linker relaxation can update targets.  */
15356   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15357       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15358       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15359     return 1;
15360
15361   if (HAVE_NEWABI
15362       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
15363       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
15364           || hi16_reloc_p (fixp->fx_r_type)
15365           || lo16_reloc_p (fixp->fx_r_type)))
15366     return 1;
15367
15368   return 0;
15369 }
15370
15371 /* Apply a fixup to the object file.  */
15372
15373 void
15374 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15375 {
15376   bfd_byte *buf;
15377   long insn;
15378   reloc_howto_type *howto;
15379
15380   /* We ignore generic BFD relocations we don't know about.  */
15381   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15382   if (! howto)
15383     return;
15384
15385   gas_assert (fixP->fx_size == 2
15386               || fixP->fx_size == 4
15387               || fixP->fx_r_type == BFD_RELOC_16
15388               || fixP->fx_r_type == BFD_RELOC_64
15389               || fixP->fx_r_type == BFD_RELOC_CTOR
15390               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15391               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15392               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15393               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15394               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15395
15396   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
15397
15398   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15399               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15400               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15401               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
15402
15403   /* Don't treat parts of a composite relocation as done.  There are two
15404      reasons for this:
15405
15406      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15407          should nevertheless be emitted if the first part is.
15408
15409      (2) In normal usage, composite relocations are never assembly-time
15410          constants.  The easiest way of dealing with the pathological
15411          exceptions is to generate a relocation against STN_UNDEF and
15412          leave everything up to the linker.  */
15413   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15414     fixP->fx_done = 1;
15415
15416   switch (fixP->fx_r_type)
15417     {
15418     case BFD_RELOC_MIPS_TLS_GD:
15419     case BFD_RELOC_MIPS_TLS_LDM:
15420     case BFD_RELOC_MIPS_TLS_DTPREL32:
15421     case BFD_RELOC_MIPS_TLS_DTPREL64:
15422     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15423     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15424     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15425     case BFD_RELOC_MIPS_TLS_TPREL32:
15426     case BFD_RELOC_MIPS_TLS_TPREL64:
15427     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15428     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15429     case BFD_RELOC_MICROMIPS_TLS_GD:
15430     case BFD_RELOC_MICROMIPS_TLS_LDM:
15431     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15432     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15433     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15434     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15435     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15436     case BFD_RELOC_MIPS16_TLS_GD:
15437     case BFD_RELOC_MIPS16_TLS_LDM:
15438     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15439     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15440     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15441     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15442     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15443       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15444       /* fall through */
15445
15446     case BFD_RELOC_MIPS_JMP:
15447     case BFD_RELOC_MIPS_SHIFT5:
15448     case BFD_RELOC_MIPS_SHIFT6:
15449     case BFD_RELOC_MIPS_GOT_DISP:
15450     case BFD_RELOC_MIPS_GOT_PAGE:
15451     case BFD_RELOC_MIPS_GOT_OFST:
15452     case BFD_RELOC_MIPS_SUB:
15453     case BFD_RELOC_MIPS_INSERT_A:
15454     case BFD_RELOC_MIPS_INSERT_B:
15455     case BFD_RELOC_MIPS_DELETE:
15456     case BFD_RELOC_MIPS_HIGHEST:
15457     case BFD_RELOC_MIPS_HIGHER:
15458     case BFD_RELOC_MIPS_SCN_DISP:
15459     case BFD_RELOC_MIPS_REL16:
15460     case BFD_RELOC_MIPS_RELGOT:
15461     case BFD_RELOC_MIPS_JALR:
15462     case BFD_RELOC_HI16:
15463     case BFD_RELOC_HI16_S:
15464     case BFD_RELOC_GPREL16:
15465     case BFD_RELOC_MIPS_LITERAL:
15466     case BFD_RELOC_MIPS_CALL16:
15467     case BFD_RELOC_MIPS_GOT16:
15468     case BFD_RELOC_GPREL32:
15469     case BFD_RELOC_MIPS_GOT_HI16:
15470     case BFD_RELOC_MIPS_GOT_LO16:
15471     case BFD_RELOC_MIPS_CALL_HI16:
15472     case BFD_RELOC_MIPS_CALL_LO16:
15473     case BFD_RELOC_MIPS16_GPREL:
15474     case BFD_RELOC_MIPS16_GOT16:
15475     case BFD_RELOC_MIPS16_CALL16:
15476     case BFD_RELOC_MIPS16_HI16:
15477     case BFD_RELOC_MIPS16_HI16_S:
15478     case BFD_RELOC_MIPS16_JMP:
15479     case BFD_RELOC_MICROMIPS_JMP:
15480     case BFD_RELOC_MICROMIPS_GOT_DISP:
15481     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15482     case BFD_RELOC_MICROMIPS_GOT_OFST:
15483     case BFD_RELOC_MICROMIPS_SUB:
15484     case BFD_RELOC_MICROMIPS_HIGHEST:
15485     case BFD_RELOC_MICROMIPS_HIGHER:
15486     case BFD_RELOC_MICROMIPS_SCN_DISP:
15487     case BFD_RELOC_MICROMIPS_JALR:
15488     case BFD_RELOC_MICROMIPS_HI16:
15489     case BFD_RELOC_MICROMIPS_HI16_S:
15490     case BFD_RELOC_MICROMIPS_GPREL16:
15491     case BFD_RELOC_MICROMIPS_LITERAL:
15492     case BFD_RELOC_MICROMIPS_CALL16:
15493     case BFD_RELOC_MICROMIPS_GOT16:
15494     case BFD_RELOC_MICROMIPS_GOT_HI16:
15495     case BFD_RELOC_MICROMIPS_GOT_LO16:
15496     case BFD_RELOC_MICROMIPS_CALL_HI16:
15497     case BFD_RELOC_MICROMIPS_CALL_LO16:
15498       /* Nothing needed to do.  The value comes from the reloc entry.  */
15499       break;
15500
15501     case BFD_RELOC_64:
15502       /* This is handled like BFD_RELOC_32, but we output a sign
15503          extended value if we are only 32 bits.  */
15504       if (fixP->fx_done)
15505         {
15506           if (8 <= sizeof (valueT))
15507             md_number_to_chars ((char *) buf, *valP, 8);
15508           else
15509             {
15510               valueT hiv;
15511
15512               if ((*valP & 0x80000000) != 0)
15513                 hiv = 0xffffffff;
15514               else
15515                 hiv = 0;
15516               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
15517                                   *valP, 4);
15518               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
15519                                   hiv, 4);
15520             }
15521         }
15522       break;
15523
15524     case BFD_RELOC_RVA:
15525     case BFD_RELOC_32:
15526     case BFD_RELOC_16:
15527       /* If we are deleting this reloc entry, we must fill in the
15528          value now.  This can happen if we have a .word which is not
15529          resolved when it appears but is later defined.  */
15530       if (fixP->fx_done)
15531         md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
15532       break;
15533
15534     case BFD_RELOC_LO16:
15535     case BFD_RELOC_MIPS16_LO16:
15536     case BFD_RELOC_MICROMIPS_LO16:
15537       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
15538          may be safe to remove, but if so it's not obvious.  */
15539       /* When handling an embedded PIC switch statement, we can wind
15540          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
15541       if (fixP->fx_done)
15542         {
15543           if (*valP + 0x8000 > 0xffff)
15544             as_bad_where (fixP->fx_file, fixP->fx_line,
15545                           _("relocation overflow"));
15546           /* 32-bit microMIPS instructions are divided into two halfwords.
15547              Relocations always refer to the second halfword, regardless
15548              of endianness.  */
15549           if (target_big_endian || fixP->fx_r_type == BFD_RELOC_MICROMIPS_LO16)
15550             buf += 2;
15551           md_number_to_chars ((char *) buf, *valP, 2);
15552         }
15553       break;
15554
15555     case BFD_RELOC_16_PCREL_S2:
15556       if ((*valP & 0x3) != 0)
15557         as_bad_where (fixP->fx_file, fixP->fx_line,
15558                       _("Branch to misaligned address (%lx)"), (long) *valP);
15559
15560       /* We need to save the bits in the instruction since fixup_segment()
15561          might be deleting the relocation entry (i.e., a branch within
15562          the current segment).  */
15563       if (! fixP->fx_done)
15564         break;
15565
15566       /* Update old instruction data.  */
15567       if (target_big_endian)
15568         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
15569       else
15570         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
15571
15572       if (*valP + 0x20000 <= 0x3ffff)
15573         {
15574           insn |= (*valP >> 2) & 0xffff;
15575           md_number_to_chars ((char *) buf, insn, 4);
15576         }
15577       else if (mips_pic == NO_PIC
15578                && fixP->fx_done
15579                && fixP->fx_frag->fr_address >= text_section->vma
15580                && (fixP->fx_frag->fr_address
15581                    < text_section->vma + bfd_get_section_size (text_section))
15582                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15583                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15584                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15585         {
15586           /* The branch offset is too large.  If this is an
15587              unconditional branch, and we are not generating PIC code,
15588              we can convert it to an absolute jump instruction.  */
15589           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15590             insn = 0x0c000000;  /* jal */
15591           else
15592             insn = 0x08000000;  /* j */
15593           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15594           fixP->fx_done = 0;
15595           fixP->fx_addsy = section_symbol (text_section);
15596           *valP += md_pcrel_from (fixP);
15597           md_number_to_chars ((char *) buf, insn, 4);
15598         }
15599       else
15600         {
15601           /* If we got here, we have branch-relaxation disabled,
15602              and there's nothing we can do to fix this instruction
15603              without turning it into a longer sequence.  */
15604           as_bad_where (fixP->fx_file, fixP->fx_line,
15605                         _("Branch out of range"));
15606         }
15607       break;
15608
15609     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15610     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15611     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15612       /* We adjust the offset back to even.  */
15613       if ((*valP & 0x1) != 0)
15614         --(*valP);
15615
15616       if (! fixP->fx_done)
15617         break;
15618
15619       /* Should never visit here, because we keep the relocation.  */
15620       abort ();
15621       break;
15622
15623     case BFD_RELOC_VTABLE_INHERIT:
15624       fixP->fx_done = 0;
15625       if (fixP->fx_addsy
15626           && !S_IS_DEFINED (fixP->fx_addsy)
15627           && !S_IS_WEAK (fixP->fx_addsy))
15628         S_SET_WEAK (fixP->fx_addsy);
15629       break;
15630
15631     case BFD_RELOC_VTABLE_ENTRY:
15632       fixP->fx_done = 0;
15633       break;
15634
15635     default:
15636       internalError ();
15637     }
15638
15639   /* Remember value for tc_gen_reloc.  */
15640   fixP->fx_addnumber = *valP;
15641 }
15642
15643 static symbolS *
15644 get_symbol (void)
15645 {
15646   int c;
15647   char *name;
15648   symbolS *p;
15649
15650   name = input_line_pointer;
15651   c = get_symbol_end ();
15652   p = (symbolS *) symbol_find_or_make (name);
15653   *input_line_pointer = c;
15654   return p;
15655 }
15656
15657 /* Align the current frag to a given power of two.  If a particular
15658    fill byte should be used, FILL points to an integer that contains
15659    that byte, otherwise FILL is null.
15660
15661    This function used to have the comment:
15662
15663       The MIPS assembler also automatically adjusts any preceding label.
15664
15665    The implementation therefore applied the adjustment to a maximum of
15666    one label.  However, other label adjustments are applied to batches
15667    of labels, and adjusting just one caused problems when new labels
15668    were added for the sake of debugging or unwind information.
15669    We therefore adjust all preceding labels (given as LABELS) instead.  */
15670
15671 static void
15672 mips_align (int to, int *fill, struct insn_label_list *labels)
15673 {
15674   mips_emit_delays ();
15675   mips_record_compressed_mode ();
15676   if (fill == NULL && subseg_text_p (now_seg))
15677     frag_align_code (to, 0);
15678   else
15679     frag_align (to, fill ? *fill : 0, 0);
15680   record_alignment (now_seg, to);
15681   mips_move_labels (labels, FALSE);
15682 }
15683
15684 /* Align to a given power of two.  .align 0 turns off the automatic
15685    alignment used by the data creating pseudo-ops.  */
15686
15687 static void
15688 s_align (int x ATTRIBUTE_UNUSED)
15689 {
15690   int temp, fill_value, *fill_ptr;
15691   long max_alignment = 28;
15692
15693   /* o Note that the assembler pulls down any immediately preceding label
15694        to the aligned address.
15695      o It's not documented but auto alignment is reinstated by
15696        a .align pseudo instruction.
15697      o Note also that after auto alignment is turned off the mips assembler
15698        issues an error on attempt to assemble an improperly aligned data item.
15699        We don't.  */
15700
15701   temp = get_absolute_expression ();
15702   if (temp > max_alignment)
15703     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
15704   else if (temp < 0)
15705     {
15706       as_warn (_("Alignment negative: 0 assumed."));
15707       temp = 0;
15708     }
15709   if (*input_line_pointer == ',')
15710     {
15711       ++input_line_pointer;
15712       fill_value = get_absolute_expression ();
15713       fill_ptr = &fill_value;
15714     }
15715   else
15716     fill_ptr = 0;
15717   if (temp)
15718     {
15719       segment_info_type *si = seg_info (now_seg);
15720       struct insn_label_list *l = si->label_list;
15721       /* Auto alignment should be switched on by next section change.  */
15722       auto_align = 1;
15723       mips_align (temp, fill_ptr, l);
15724     }
15725   else
15726     {
15727       auto_align = 0;
15728     }
15729
15730   demand_empty_rest_of_line ();
15731 }
15732
15733 static void
15734 s_change_sec (int sec)
15735 {
15736   segT seg;
15737
15738 #ifdef OBJ_ELF
15739   /* The ELF backend needs to know that we are changing sections, so
15740      that .previous works correctly.  We could do something like check
15741      for an obj_section_change_hook macro, but that might be confusing
15742      as it would not be appropriate to use it in the section changing
15743      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15744      This should be cleaner, somehow.  */
15745   if (IS_ELF)
15746     obj_elf_section_change_hook ();
15747 #endif
15748
15749   mips_emit_delays ();
15750
15751   switch (sec)
15752     {
15753     case 't':
15754       s_text (0);
15755       break;
15756     case 'd':
15757       s_data (0);
15758       break;
15759     case 'b':
15760       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15761       demand_empty_rest_of_line ();
15762       break;
15763
15764     case 'r':
15765       seg = subseg_new (RDATA_SECTION_NAME,
15766                         (subsegT) get_absolute_expression ());
15767       if (IS_ELF)
15768         {
15769           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15770                                                   | SEC_READONLY | SEC_RELOC
15771                                                   | SEC_DATA));
15772           if (strncmp (TARGET_OS, "elf", 3) != 0)
15773             record_alignment (seg, 4);
15774         }
15775       demand_empty_rest_of_line ();
15776       break;
15777
15778     case 's':
15779       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15780       if (IS_ELF)
15781         {
15782           bfd_set_section_flags (stdoutput, seg,
15783                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15784           if (strncmp (TARGET_OS, "elf", 3) != 0)
15785             record_alignment (seg, 4);
15786         }
15787       demand_empty_rest_of_line ();
15788       break;
15789
15790     case 'B':
15791       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15792       if (IS_ELF)
15793         {
15794           bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15795           if (strncmp (TARGET_OS, "elf", 3) != 0)
15796             record_alignment (seg, 4);
15797         }
15798       demand_empty_rest_of_line ();
15799       break;
15800     }
15801
15802   auto_align = 1;
15803 }
15804
15805 void
15806 s_change_section (int ignore ATTRIBUTE_UNUSED)
15807 {
15808 #ifdef OBJ_ELF
15809   char *section_name;
15810   char c;
15811   char next_c = 0;
15812   int section_type;
15813   int section_flag;
15814   int section_entry_size;
15815   int section_alignment;
15816
15817   if (!IS_ELF)
15818     return;
15819
15820   section_name = input_line_pointer;
15821   c = get_symbol_end ();
15822   if (c)
15823     next_c = *(input_line_pointer + 1);
15824
15825   /* Do we have .section Name<,"flags">?  */
15826   if (c != ',' || (c == ',' && next_c == '"'))
15827     {
15828       /* just after name is now '\0'.  */
15829       *input_line_pointer = c;
15830       input_line_pointer = section_name;
15831       obj_elf_section (ignore);
15832       return;
15833     }
15834   input_line_pointer++;
15835
15836   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15837   if (c == ',')
15838     section_type = get_absolute_expression ();
15839   else
15840     section_type = 0;
15841   if (*input_line_pointer++ == ',')
15842     section_flag = get_absolute_expression ();
15843   else
15844     section_flag = 0;
15845   if (*input_line_pointer++ == ',')
15846     section_entry_size = get_absolute_expression ();
15847   else
15848     section_entry_size = 0;
15849   if (*input_line_pointer++ == ',')
15850     section_alignment = get_absolute_expression ();
15851   else
15852     section_alignment = 0;
15853   /* FIXME: really ignore?  */
15854   (void) section_alignment;
15855
15856   section_name = xstrdup (section_name);
15857
15858   /* When using the generic form of .section (as implemented by obj-elf.c),
15859      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15860      traditionally had to fall back on the more common @progbits instead.
15861
15862      There's nothing really harmful in this, since bfd will correct
15863      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15864      means that, for backwards compatibility, the special_section entries
15865      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15866
15867      Even so, we shouldn't force users of the MIPS .section syntax to
15868      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15869      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15870      generic type-checking code.  */
15871   if (section_type == SHT_MIPS_DWARF)
15872     section_type = SHT_PROGBITS;
15873
15874   obj_elf_change_section (section_name, section_type, section_flag,
15875                           section_entry_size, 0, 0, 0);
15876
15877   if (now_seg->name != section_name)
15878     free (section_name);
15879 #endif /* OBJ_ELF */
15880 }
15881
15882 void
15883 mips_enable_auto_align (void)
15884 {
15885   auto_align = 1;
15886 }
15887
15888 static void
15889 s_cons (int log_size)
15890 {
15891   segment_info_type *si = seg_info (now_seg);
15892   struct insn_label_list *l = si->label_list;
15893
15894   mips_emit_delays ();
15895   if (log_size > 0 && auto_align)
15896     mips_align (log_size, 0, l);
15897   cons (1 << log_size);
15898   mips_clear_insn_labels ();
15899 }
15900
15901 static void
15902 s_float_cons (int type)
15903 {
15904   segment_info_type *si = seg_info (now_seg);
15905   struct insn_label_list *l = si->label_list;
15906
15907   mips_emit_delays ();
15908
15909   if (auto_align)
15910     {
15911       if (type == 'd')
15912         mips_align (3, 0, l);
15913       else
15914         mips_align (2, 0, l);
15915     }
15916
15917   float_cons (type);
15918   mips_clear_insn_labels ();
15919 }
15920
15921 /* Handle .globl.  We need to override it because on Irix 5 you are
15922    permitted to say
15923        .globl foo .text
15924    where foo is an undefined symbol, to mean that foo should be
15925    considered to be the address of a function.  */
15926
15927 static void
15928 s_mips_globl (int x ATTRIBUTE_UNUSED)
15929 {
15930   char *name;
15931   int c;
15932   symbolS *symbolP;
15933   flagword flag;
15934
15935   do
15936     {
15937       name = input_line_pointer;
15938       c = get_symbol_end ();
15939       symbolP = symbol_find_or_make (name);
15940       S_SET_EXTERNAL (symbolP);
15941
15942       *input_line_pointer = c;
15943       SKIP_WHITESPACE ();
15944
15945       /* On Irix 5, every global symbol that is not explicitly labelled as
15946          being a function is apparently labelled as being an object.  */
15947       flag = BSF_OBJECT;
15948
15949       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15950           && (*input_line_pointer != ','))
15951         {
15952           char *secname;
15953           asection *sec;
15954
15955           secname = input_line_pointer;
15956           c = get_symbol_end ();
15957           sec = bfd_get_section_by_name (stdoutput, secname);
15958           if (sec == NULL)
15959             as_bad (_("%s: no such section"), secname);
15960           *input_line_pointer = c;
15961
15962           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15963             flag = BSF_FUNCTION;
15964         }
15965
15966       symbol_get_bfdsym (symbolP)->flags |= flag;
15967
15968       c = *input_line_pointer;
15969       if (c == ',')
15970         {
15971           input_line_pointer++;
15972           SKIP_WHITESPACE ();
15973           if (is_end_of_line[(unsigned char) *input_line_pointer])
15974             c = '\n';
15975         }
15976     }
15977   while (c == ',');
15978
15979   demand_empty_rest_of_line ();
15980 }
15981
15982 static void
15983 s_option (int x ATTRIBUTE_UNUSED)
15984 {
15985   char *opt;
15986   char c;
15987
15988   opt = input_line_pointer;
15989   c = get_symbol_end ();
15990
15991   if (*opt == 'O')
15992     {
15993       /* FIXME: What does this mean?  */
15994     }
15995   else if (strncmp (opt, "pic", 3) == 0)
15996     {
15997       int i;
15998
15999       i = atoi (opt + 3);
16000       if (i == 0)
16001         mips_pic = NO_PIC;
16002       else if (i == 2)
16003         {
16004           mips_pic = SVR4_PIC;
16005           mips_abicalls = TRUE;
16006         }
16007       else
16008         as_bad (_(".option pic%d not supported"), i);
16009
16010       if (mips_pic == SVR4_PIC)
16011         {
16012           if (g_switch_seen && g_switch_value != 0)
16013             as_warn (_("-G may not be used with SVR4 PIC code"));
16014           g_switch_value = 0;
16015           bfd_set_gp_size (stdoutput, 0);
16016         }
16017     }
16018   else
16019     as_warn (_("Unrecognized option \"%s\""), opt);
16020
16021   *input_line_pointer = c;
16022   demand_empty_rest_of_line ();
16023 }
16024
16025 /* This structure is used to hold a stack of .set values.  */
16026
16027 struct mips_option_stack
16028 {
16029   struct mips_option_stack *next;
16030   struct mips_set_options options;
16031 };
16032
16033 static struct mips_option_stack *mips_opts_stack;
16034
16035 /* Handle the .set pseudo-op.  */
16036
16037 static void
16038 s_mipsset (int x ATTRIBUTE_UNUSED)
16039 {
16040   char *name = input_line_pointer, ch;
16041
16042   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16043     ++input_line_pointer;
16044   ch = *input_line_pointer;
16045   *input_line_pointer = '\0';
16046
16047   if (strcmp (name, "reorder") == 0)
16048     {
16049       if (mips_opts.noreorder)
16050         end_noreorder ();
16051     }
16052   else if (strcmp (name, "noreorder") == 0)
16053     {
16054       if (!mips_opts.noreorder)
16055         start_noreorder ();
16056     }
16057   else if (strncmp (name, "at=", 3) == 0)
16058     {
16059       char *s = name + 3;
16060
16061       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16062         as_bad (_("Unrecognized register name `%s'"), s);
16063     }
16064   else if (strcmp (name, "at") == 0)
16065     {
16066       mips_opts.at = ATREG;
16067     }
16068   else if (strcmp (name, "noat") == 0)
16069     {
16070       mips_opts.at = ZERO;
16071     }
16072   else if (strcmp (name, "macro") == 0)
16073     {
16074       mips_opts.warn_about_macros = 0;
16075     }
16076   else if (strcmp (name, "nomacro") == 0)
16077     {
16078       if (mips_opts.noreorder == 0)
16079         as_bad (_("`noreorder' must be set before `nomacro'"));
16080       mips_opts.warn_about_macros = 1;
16081     }
16082   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16083     {
16084       mips_opts.nomove = 0;
16085     }
16086   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16087     {
16088       mips_opts.nomove = 1;
16089     }
16090   else if (strcmp (name, "bopt") == 0)
16091     {
16092       mips_opts.nobopt = 0;
16093     }
16094   else if (strcmp (name, "nobopt") == 0)
16095     {
16096       mips_opts.nobopt = 1;
16097     }
16098   else if (strcmp (name, "gp=default") == 0)
16099     mips_opts.gp32 = file_mips_gp32;
16100   else if (strcmp (name, "gp=32") == 0)
16101     mips_opts.gp32 = 1;
16102   else if (strcmp (name, "gp=64") == 0)
16103     {
16104       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
16105         as_warn (_("%s isa does not support 64-bit registers"),
16106                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16107       mips_opts.gp32 = 0;
16108     }
16109   else if (strcmp (name, "fp=default") == 0)
16110     mips_opts.fp32 = file_mips_fp32;
16111   else if (strcmp (name, "fp=32") == 0)
16112     mips_opts.fp32 = 1;
16113   else if (strcmp (name, "fp=64") == 0)
16114     {
16115       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
16116         as_warn (_("%s isa does not support 64-bit floating point registers"),
16117                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16118       mips_opts.fp32 = 0;
16119     }
16120   else if (strcmp (name, "softfloat") == 0)
16121     mips_opts.soft_float = 1;
16122   else if (strcmp (name, "hardfloat") == 0)
16123     mips_opts.soft_float = 0;
16124   else if (strcmp (name, "singlefloat") == 0)
16125     mips_opts.single_float = 1;
16126   else if (strcmp (name, "doublefloat") == 0)
16127     mips_opts.single_float = 0;
16128   else if (strcmp (name, "mips16") == 0
16129            || strcmp (name, "MIPS-16") == 0)
16130     {
16131       if (mips_opts.micromips == 1)
16132         as_fatal (_("`mips16' cannot be used with `micromips'"));
16133       mips_opts.mips16 = 1;
16134     }
16135   else if (strcmp (name, "nomips16") == 0
16136            || strcmp (name, "noMIPS-16") == 0)
16137     mips_opts.mips16 = 0;
16138   else if (strcmp (name, "micromips") == 0)
16139     {
16140       if (mips_opts.mips16 == 1)
16141         as_fatal (_("`micromips' cannot be used with `mips16'"));
16142       mips_opts.micromips = 1;
16143     }
16144   else if (strcmp (name, "nomicromips") == 0)
16145     mips_opts.micromips = 0;
16146   else if (strcmp (name, "smartmips") == 0)
16147     {
16148       if (!ISA_SUPPORTS_SMARTMIPS)
16149         as_warn (_("%s ISA does not support SmartMIPS ASE"), 
16150                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16151       mips_opts.ase_smartmips = 1;
16152     }
16153   else if (strcmp (name, "nosmartmips") == 0)
16154     mips_opts.ase_smartmips = 0;
16155   else if (strcmp (name, "mips3d") == 0)
16156     mips_opts.ase_mips3d = 1;
16157   else if (strcmp (name, "nomips3d") == 0)
16158     mips_opts.ase_mips3d = 0;
16159   else if (strcmp (name, "mdmx") == 0)
16160     mips_opts.ase_mdmx = 1;
16161   else if (strcmp (name, "nomdmx") == 0)
16162     mips_opts.ase_mdmx = 0;
16163   else if (strcmp (name, "dsp") == 0)
16164     {
16165       if (!ISA_SUPPORTS_DSP_ASE)
16166         as_warn (_("%s ISA does not support DSP ASE"), 
16167                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16168       mips_opts.ase_dsp = 1;
16169       mips_opts.ase_dspr2 = 0;
16170     }
16171   else if (strcmp (name, "nodsp") == 0)
16172     {
16173       mips_opts.ase_dsp = 0;
16174       mips_opts.ase_dspr2 = 0;
16175     }
16176   else if (strcmp (name, "dspr2") == 0)
16177     {
16178       if (!ISA_SUPPORTS_DSPR2_ASE)
16179         as_warn (_("%s ISA does not support DSP R2 ASE"),
16180                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16181       mips_opts.ase_dspr2 = 1;
16182       mips_opts.ase_dsp = 1;
16183     }
16184   else if (strcmp (name, "nodspr2") == 0)
16185     {
16186       mips_opts.ase_dspr2 = 0;
16187       mips_opts.ase_dsp = 0;
16188     }
16189   else if (strcmp (name, "mt") == 0)
16190     {
16191       if (!ISA_SUPPORTS_MT_ASE)
16192         as_warn (_("%s ISA does not support MT ASE"), 
16193                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16194       mips_opts.ase_mt = 1;
16195     }
16196   else if (strcmp (name, "nomt") == 0)
16197     mips_opts.ase_mt = 0;
16198   else if (strcmp (name, "mcu") == 0)
16199     mips_opts.ase_mcu = 1;
16200   else if (strcmp (name, "nomcu") == 0)
16201     mips_opts.ase_mcu = 0;
16202   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16203     {
16204       int reset = 0;
16205
16206       /* Permit the user to change the ISA and architecture on the fly.
16207          Needless to say, misuse can cause serious problems.  */
16208       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16209         {
16210           reset = 1;
16211           mips_opts.isa = file_mips_isa;
16212           mips_opts.arch = file_mips_arch;
16213         }
16214       else if (strncmp (name, "arch=", 5) == 0)
16215         {
16216           const struct mips_cpu_info *p;
16217
16218           p = mips_parse_cpu("internal use", name + 5);
16219           if (!p)
16220             as_bad (_("unknown architecture %s"), name + 5);
16221           else
16222             {
16223               mips_opts.arch = p->cpu;
16224               mips_opts.isa = p->isa;
16225             }
16226         }
16227       else if (strncmp (name, "mips", 4) == 0)
16228         {
16229           const struct mips_cpu_info *p;
16230
16231           p = mips_parse_cpu("internal use", name);
16232           if (!p)
16233             as_bad (_("unknown ISA level %s"), name + 4);
16234           else
16235             {
16236               mips_opts.arch = p->cpu;
16237               mips_opts.isa = p->isa;
16238             }
16239         }
16240       else
16241         as_bad (_("unknown ISA or architecture %s"), name);
16242
16243       switch (mips_opts.isa)
16244         {
16245         case  0:
16246           break;
16247         case ISA_MIPS1:
16248         case ISA_MIPS2:
16249         case ISA_MIPS32:
16250         case ISA_MIPS32R2:
16251           mips_opts.gp32 = 1;
16252           mips_opts.fp32 = 1;
16253           break;
16254         case ISA_MIPS3:
16255         case ISA_MIPS4:
16256         case ISA_MIPS5:
16257         case ISA_MIPS64:
16258         case ISA_MIPS64R2:
16259           mips_opts.gp32 = 0;
16260           mips_opts.fp32 = 0;
16261           break;
16262         default:
16263           as_bad (_("unknown ISA level %s"), name + 4);
16264           break;
16265         }
16266       if (reset)
16267         {
16268           mips_opts.gp32 = file_mips_gp32;
16269           mips_opts.fp32 = file_mips_fp32;
16270         }
16271     }
16272   else if (strcmp (name, "autoextend") == 0)
16273     mips_opts.noautoextend = 0;
16274   else if (strcmp (name, "noautoextend") == 0)
16275     mips_opts.noautoextend = 1;
16276   else if (strcmp (name, "push") == 0)
16277     {
16278       struct mips_option_stack *s;
16279
16280       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16281       s->next = mips_opts_stack;
16282       s->options = mips_opts;
16283       mips_opts_stack = s;
16284     }
16285   else if (strcmp (name, "pop") == 0)
16286     {
16287       struct mips_option_stack *s;
16288
16289       s = mips_opts_stack;
16290       if (s == NULL)
16291         as_bad (_(".set pop with no .set push"));
16292       else
16293         {
16294           /* If we're changing the reorder mode we need to handle
16295              delay slots correctly.  */
16296           if (s->options.noreorder && ! mips_opts.noreorder)
16297             start_noreorder ();
16298           else if (! s->options.noreorder && mips_opts.noreorder)
16299             end_noreorder ();
16300
16301           mips_opts = s->options;
16302           mips_opts_stack = s->next;
16303           free (s);
16304         }
16305     }
16306   else if (strcmp (name, "sym32") == 0)
16307     mips_opts.sym32 = TRUE;
16308   else if (strcmp (name, "nosym32") == 0)
16309     mips_opts.sym32 = FALSE;
16310   else if (strchr (name, ','))
16311     {
16312       /* Generic ".set" directive; use the generic handler.  */
16313       *input_line_pointer = ch;
16314       input_line_pointer = name;
16315       s_set (0);
16316       return;
16317     }
16318   else
16319     {
16320       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16321     }
16322   *input_line_pointer = ch;
16323   demand_empty_rest_of_line ();
16324 }
16325
16326 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16327    .option pic2.  It means to generate SVR4 PIC calls.  */
16328
16329 static void
16330 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16331 {
16332   mips_pic = SVR4_PIC;
16333   mips_abicalls = TRUE;
16334
16335   if (g_switch_seen && g_switch_value != 0)
16336     as_warn (_("-G may not be used with SVR4 PIC code"));
16337   g_switch_value = 0;
16338
16339   bfd_set_gp_size (stdoutput, 0);
16340   demand_empty_rest_of_line ();
16341 }
16342
16343 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16344    PIC code.  It sets the $gp register for the function based on the
16345    function address, which is in the register named in the argument.
16346    This uses a relocation against _gp_disp, which is handled specially
16347    by the linker.  The result is:
16348         lui     $gp,%hi(_gp_disp)
16349         addiu   $gp,$gp,%lo(_gp_disp)
16350         addu    $gp,$gp,.cpload argument
16351    The .cpload argument is normally $25 == $t9.
16352
16353    The -mno-shared option changes this to:
16354         lui     $gp,%hi(__gnu_local_gp)
16355         addiu   $gp,$gp,%lo(__gnu_local_gp)
16356    and the argument is ignored.  This saves an instruction, but the
16357    resulting code is not position independent; it uses an absolute
16358    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16359    can go into an ordinary executable, but not into a shared library.  */
16360
16361 static void
16362 s_cpload (int ignore ATTRIBUTE_UNUSED)
16363 {
16364   expressionS ex;
16365   int reg;
16366   int in_shared;
16367
16368   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16369      .cpload is ignored.  */
16370   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16371     {
16372       s_ignore (0);
16373       return;
16374     }
16375
16376   /* .cpload should be in a .set noreorder section.  */
16377   if (mips_opts.noreorder == 0)
16378     as_warn (_(".cpload not in noreorder section"));
16379
16380   reg = tc_get_register (0);
16381
16382   /* If we need to produce a 64-bit address, we are better off using
16383      the default instruction sequence.  */
16384   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16385
16386   ex.X_op = O_symbol;
16387   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16388                                          "__gnu_local_gp");
16389   ex.X_op_symbol = NULL;
16390   ex.X_add_number = 0;
16391
16392   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16393   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16394
16395   macro_start ();
16396   macro_build_lui (&ex, mips_gp_register);
16397   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16398                mips_gp_register, BFD_RELOC_LO16);
16399   if (in_shared)
16400     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16401                  mips_gp_register, reg);
16402   macro_end ();
16403
16404   demand_empty_rest_of_line ();
16405 }
16406
16407 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16408      .cpsetup $reg1, offset|$reg2, label
16409
16410    If offset is given, this results in:
16411      sd         $gp, offset($sp)
16412      lui        $gp, %hi(%neg(%gp_rel(label)))
16413      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16414      daddu      $gp, $gp, $reg1
16415
16416    If $reg2 is given, this results in:
16417      daddu      $reg2, $gp, $0
16418      lui        $gp, %hi(%neg(%gp_rel(label)))
16419      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16420      daddu      $gp, $gp, $reg1
16421    $reg1 is normally $25 == $t9.
16422
16423    The -mno-shared option replaces the last three instructions with
16424         lui     $gp,%hi(_gp)
16425         addiu   $gp,$gp,%lo(_gp)  */
16426
16427 static void
16428 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16429 {
16430   expressionS ex_off;
16431   expressionS ex_sym;
16432   int reg1;
16433
16434   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16435      We also need NewABI support.  */
16436   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16437     {
16438       s_ignore (0);
16439       return;
16440     }
16441
16442   reg1 = tc_get_register (0);
16443   SKIP_WHITESPACE ();
16444   if (*input_line_pointer != ',')
16445     {
16446       as_bad (_("missing argument separator ',' for .cpsetup"));
16447       return;
16448     }
16449   else
16450     ++input_line_pointer;
16451   SKIP_WHITESPACE ();
16452   if (*input_line_pointer == '$')
16453     {
16454       mips_cpreturn_register = tc_get_register (0);
16455       mips_cpreturn_offset = -1;
16456     }
16457   else
16458     {
16459       mips_cpreturn_offset = get_absolute_expression ();
16460       mips_cpreturn_register = -1;
16461     }
16462   SKIP_WHITESPACE ();
16463   if (*input_line_pointer != ',')
16464     {
16465       as_bad (_("missing argument separator ',' for .cpsetup"));
16466       return;
16467     }
16468   else
16469     ++input_line_pointer;
16470   SKIP_WHITESPACE ();
16471   expression (&ex_sym);
16472
16473   macro_start ();
16474   if (mips_cpreturn_register == -1)
16475     {
16476       ex_off.X_op = O_constant;
16477       ex_off.X_add_symbol = NULL;
16478       ex_off.X_op_symbol = NULL;
16479       ex_off.X_add_number = mips_cpreturn_offset;
16480
16481       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16482                    BFD_RELOC_LO16, SP);
16483     }
16484   else
16485     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16486                  mips_gp_register, 0);
16487
16488   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16489     {
16490       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16491                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16492                    BFD_RELOC_HI16_S);
16493
16494       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16495                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16496                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16497
16498       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16499                    mips_gp_register, reg1);
16500     }
16501   else
16502     {
16503       expressionS ex;
16504
16505       ex.X_op = O_symbol;
16506       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16507       ex.X_op_symbol = NULL;
16508       ex.X_add_number = 0;
16509
16510       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16511       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16512
16513       macro_build_lui (&ex, mips_gp_register);
16514       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16515                    mips_gp_register, BFD_RELOC_LO16);
16516     }
16517
16518   macro_end ();
16519
16520   demand_empty_rest_of_line ();
16521 }
16522
16523 static void
16524 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16525 {
16526   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16527      .cplocal is ignored.  */
16528   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16529     {
16530       s_ignore (0);
16531       return;
16532     }
16533
16534   mips_gp_register = tc_get_register (0);
16535   demand_empty_rest_of_line ();
16536 }
16537
16538 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16539    offset from $sp.  The offset is remembered, and after making a PIC
16540    call $gp is restored from that location.  */
16541
16542 static void
16543 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16544 {
16545   expressionS ex;
16546
16547   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16548      .cprestore is ignored.  */
16549   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16550     {
16551       s_ignore (0);
16552       return;
16553     }
16554
16555   mips_cprestore_offset = get_absolute_expression ();
16556   mips_cprestore_valid = 1;
16557
16558   ex.X_op = O_constant;
16559   ex.X_add_symbol = NULL;
16560   ex.X_op_symbol = NULL;
16561   ex.X_add_number = mips_cprestore_offset;
16562
16563   macro_start ();
16564   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16565                                 SP, HAVE_64BIT_ADDRESSES);
16566   macro_end ();
16567
16568   demand_empty_rest_of_line ();
16569 }
16570
16571 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16572    was given in the preceding .cpsetup, it results in:
16573      ld         $gp, offset($sp)
16574
16575    If a register $reg2 was given there, it results in:
16576      daddu      $gp, $reg2, $0  */
16577
16578 static void
16579 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16580 {
16581   expressionS ex;
16582
16583   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16584      We also need NewABI support.  */
16585   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16586     {
16587       s_ignore (0);
16588       return;
16589     }
16590
16591   macro_start ();
16592   if (mips_cpreturn_register == -1)
16593     {
16594       ex.X_op = O_constant;
16595       ex.X_add_symbol = NULL;
16596       ex.X_op_symbol = NULL;
16597       ex.X_add_number = mips_cpreturn_offset;
16598
16599       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16600     }
16601   else
16602     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
16603                  mips_cpreturn_register, 0);
16604   macro_end ();
16605
16606   demand_empty_rest_of_line ();
16607 }
16608
16609 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16610    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16611    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16612    debug information or MIPS16 TLS.  */
16613
16614 static void
16615 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16616                      bfd_reloc_code_real_type rtype)
16617 {
16618   expressionS ex;
16619   char *p;
16620
16621   expression (&ex);
16622
16623   if (ex.X_op != O_symbol)
16624     {
16625       as_bad (_("Unsupported use of %s"), dirstr);
16626       ignore_rest_of_line ();
16627     }
16628
16629   p = frag_more (bytes);
16630   md_number_to_chars (p, 0, bytes);
16631   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16632   demand_empty_rest_of_line ();
16633   mips_clear_insn_labels ();
16634 }
16635
16636 /* Handle .dtprelword.  */
16637
16638 static void
16639 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16640 {
16641   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16642 }
16643
16644 /* Handle .dtpreldword.  */
16645
16646 static void
16647 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16648 {
16649   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16650 }
16651
16652 /* Handle .tprelword.  */
16653
16654 static void
16655 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16656 {
16657   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16658 }
16659
16660 /* Handle .tpreldword.  */
16661
16662 static void
16663 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16664 {
16665   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16666 }
16667
16668 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16669    code.  It sets the offset to use in gp_rel relocations.  */
16670
16671 static void
16672 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16673 {
16674   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16675      We also need NewABI support.  */
16676   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16677     {
16678       s_ignore (0);
16679       return;
16680     }
16681
16682   mips_gprel_offset = get_absolute_expression ();
16683
16684   demand_empty_rest_of_line ();
16685 }
16686
16687 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16688    code.  It generates a 32 bit GP relative reloc.  */
16689
16690 static void
16691 s_gpword (int ignore ATTRIBUTE_UNUSED)
16692 {
16693   segment_info_type *si;
16694   struct insn_label_list *l;
16695   expressionS ex;
16696   char *p;
16697
16698   /* When not generating PIC code, this is treated as .word.  */
16699   if (mips_pic != SVR4_PIC)
16700     {
16701       s_cons (2);
16702       return;
16703     }
16704
16705   si = seg_info (now_seg);
16706   l = si->label_list;
16707   mips_emit_delays ();
16708   if (auto_align)
16709     mips_align (2, 0, l);
16710
16711   expression (&ex);
16712   mips_clear_insn_labels ();
16713
16714   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16715     {
16716       as_bad (_("Unsupported use of .gpword"));
16717       ignore_rest_of_line ();
16718     }
16719
16720   p = frag_more (4);
16721   md_number_to_chars (p, 0, 4);
16722   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16723                BFD_RELOC_GPREL32);
16724
16725   demand_empty_rest_of_line ();
16726 }
16727
16728 static void
16729 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16730 {
16731   segment_info_type *si;
16732   struct insn_label_list *l;
16733   expressionS ex;
16734   char *p;
16735
16736   /* When not generating PIC code, this is treated as .dword.  */
16737   if (mips_pic != SVR4_PIC)
16738     {
16739       s_cons (3);
16740       return;
16741     }
16742
16743   si = seg_info (now_seg);
16744   l = si->label_list;
16745   mips_emit_delays ();
16746   if (auto_align)
16747     mips_align (3, 0, l);
16748
16749   expression (&ex);
16750   mips_clear_insn_labels ();
16751
16752   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16753     {
16754       as_bad (_("Unsupported use of .gpdword"));
16755       ignore_rest_of_line ();
16756     }
16757
16758   p = frag_more (8);
16759   md_number_to_chars (p, 0, 8);
16760   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16761                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16762
16763   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16764   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16765            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16766
16767   demand_empty_rest_of_line ();
16768 }
16769
16770 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16771    tables in SVR4 PIC code.  */
16772
16773 static void
16774 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16775 {
16776   int reg;
16777
16778   /* This is ignored when not generating SVR4 PIC code.  */
16779   if (mips_pic != SVR4_PIC)
16780     {
16781       s_ignore (0);
16782       return;
16783     }
16784
16785   /* Add $gp to the register named as an argument.  */
16786   macro_start ();
16787   reg = tc_get_register (0);
16788   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16789   macro_end ();
16790
16791   demand_empty_rest_of_line ();
16792 }
16793
16794 /* Handle the .insn pseudo-op.  This marks instruction labels in
16795    mips16/micromips mode.  This permits the linker to handle them specially,
16796    such as generating jalx instructions when needed.  We also make
16797    them odd for the duration of the assembly, in order to generate the
16798    right sort of code.  We will make them even in the adjust_symtab
16799    routine, while leaving them marked.  This is convenient for the
16800    debugger and the disassembler.  The linker knows to make them odd
16801    again.  */
16802
16803 static void
16804 s_insn (int ignore ATTRIBUTE_UNUSED)
16805 {
16806   mips_mark_labels ();
16807
16808   demand_empty_rest_of_line ();
16809 }
16810
16811 /* Handle a .stabn directive.  We need these in order to mark a label
16812    as being a mips16 text label correctly.  Sometimes the compiler
16813    will emit a label, followed by a .stabn, and then switch sections.
16814    If the label and .stabn are in mips16 mode, then the label is
16815    really a mips16 text label.  */
16816
16817 static void
16818 s_mips_stab (int type)
16819 {
16820   if (type == 'n')
16821     mips_mark_labels ();
16822
16823   s_stab (type);
16824 }
16825
16826 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16827
16828 static void
16829 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16830 {
16831   char *name;
16832   int c;
16833   symbolS *symbolP;
16834   expressionS exp;
16835
16836   name = input_line_pointer;
16837   c = get_symbol_end ();
16838   symbolP = symbol_find_or_make (name);
16839   S_SET_WEAK (symbolP);
16840   *input_line_pointer = c;
16841
16842   SKIP_WHITESPACE ();
16843
16844   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16845     {
16846       if (S_IS_DEFINED (symbolP))
16847         {
16848           as_bad (_("ignoring attempt to redefine symbol %s"),
16849                   S_GET_NAME (symbolP));
16850           ignore_rest_of_line ();
16851           return;
16852         }
16853
16854       if (*input_line_pointer == ',')
16855         {
16856           ++input_line_pointer;
16857           SKIP_WHITESPACE ();
16858         }
16859
16860       expression (&exp);
16861       if (exp.X_op != O_symbol)
16862         {
16863           as_bad (_("bad .weakext directive"));
16864           ignore_rest_of_line ();
16865           return;
16866         }
16867       symbol_set_value_expression (symbolP, &exp);
16868     }
16869
16870   demand_empty_rest_of_line ();
16871 }
16872
16873 /* Parse a register string into a number.  Called from the ECOFF code
16874    to parse .frame.  The argument is non-zero if this is the frame
16875    register, so that we can record it in mips_frame_reg.  */
16876
16877 int
16878 tc_get_register (int frame)
16879 {
16880   unsigned int reg;
16881
16882   SKIP_WHITESPACE ();
16883   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16884     reg = 0;
16885   if (frame)
16886     {
16887       mips_frame_reg = reg != 0 ? reg : SP;
16888       mips_frame_reg_valid = 1;
16889       mips_cprestore_valid = 0;
16890     }
16891   return reg;
16892 }
16893
16894 valueT
16895 md_section_align (asection *seg, valueT addr)
16896 {
16897   int align = bfd_get_section_alignment (stdoutput, seg);
16898
16899   if (IS_ELF)
16900     {
16901       /* We don't need to align ELF sections to the full alignment.
16902          However, Irix 5 may prefer that we align them at least to a 16
16903          byte boundary.  We don't bother to align the sections if we
16904          are targeted for an embedded system.  */
16905       if (strncmp (TARGET_OS, "elf", 3) == 0)
16906         return addr;
16907       if (align > 4)
16908         align = 4;
16909     }
16910
16911   return ((addr + (1 << align) - 1) & (-1 << align));
16912 }
16913
16914 /* Utility routine, called from above as well.  If called while the
16915    input file is still being read, it's only an approximation.  (For
16916    example, a symbol may later become defined which appeared to be
16917    undefined earlier.)  */
16918
16919 static int
16920 nopic_need_relax (symbolS *sym, int before_relaxing)
16921 {
16922   if (sym == 0)
16923     return 0;
16924
16925   if (g_switch_value > 0)
16926     {
16927       const char *symname;
16928       int change;
16929
16930       /* Find out whether this symbol can be referenced off the $gp
16931          register.  It can be if it is smaller than the -G size or if
16932          it is in the .sdata or .sbss section.  Certain symbols can
16933          not be referenced off the $gp, although it appears as though
16934          they can.  */
16935       symname = S_GET_NAME (sym);
16936       if (symname != (const char *) NULL
16937           && (strcmp (symname, "eprol") == 0
16938               || strcmp (symname, "etext") == 0
16939               || strcmp (symname, "_gp") == 0
16940               || strcmp (symname, "edata") == 0
16941               || strcmp (symname, "_fbss") == 0
16942               || strcmp (symname, "_fdata") == 0
16943               || strcmp (symname, "_ftext") == 0
16944               || strcmp (symname, "end") == 0
16945               || strcmp (symname, "_gp_disp") == 0))
16946         change = 1;
16947       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16948                && (0
16949 #ifndef NO_ECOFF_DEBUGGING
16950                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16951                        && (symbol_get_obj (sym)->ecoff_extern_size
16952                            <= g_switch_value))
16953 #endif
16954                    /* We must defer this decision until after the whole
16955                       file has been read, since there might be a .extern
16956                       after the first use of this symbol.  */
16957                    || (before_relaxing
16958 #ifndef NO_ECOFF_DEBUGGING
16959                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16960 #endif
16961                        && S_GET_VALUE (sym) == 0)
16962                    || (S_GET_VALUE (sym) != 0
16963                        && S_GET_VALUE (sym) <= g_switch_value)))
16964         change = 0;
16965       else
16966         {
16967           const char *segname;
16968
16969           segname = segment_name (S_GET_SEGMENT (sym));
16970           gas_assert (strcmp (segname, ".lit8") != 0
16971                   && strcmp (segname, ".lit4") != 0);
16972           change = (strcmp (segname, ".sdata") != 0
16973                     && strcmp (segname, ".sbss") != 0
16974                     && strncmp (segname, ".sdata.", 7) != 0
16975                     && strncmp (segname, ".sbss.", 6) != 0
16976                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16977                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16978         }
16979       return change;
16980     }
16981   else
16982     /* We are not optimizing for the $gp register.  */
16983     return 1;
16984 }
16985
16986
16987 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16988
16989 static bfd_boolean
16990 pic_need_relax (symbolS *sym, asection *segtype)
16991 {
16992   asection *symsec;
16993
16994   /* Handle the case of a symbol equated to another symbol.  */
16995   while (symbol_equated_reloc_p (sym))
16996     {
16997       symbolS *n;
16998
16999       /* It's possible to get a loop here in a badly written program.  */
17000       n = symbol_get_value_expression (sym)->X_add_symbol;
17001       if (n == sym)
17002         break;
17003       sym = n;
17004     }
17005
17006   if (symbol_section_p (sym))
17007     return TRUE;
17008
17009   symsec = S_GET_SEGMENT (sym);
17010
17011   /* This must duplicate the test in adjust_reloc_syms.  */
17012   return (symsec != &bfd_und_section
17013           && symsec != &bfd_abs_section
17014           && !bfd_is_com_section (symsec)
17015           && !s_is_linkonce (sym, segtype)
17016 #ifdef OBJ_ELF
17017           /* A global or weak symbol is treated as external.  */
17018           && (!IS_ELF || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
17019 #endif
17020           );
17021 }
17022
17023
17024 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17025    extended opcode.  SEC is the section the frag is in.  */
17026
17027 static int
17028 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17029 {
17030   int type;
17031   const struct mips16_immed_operand *op;
17032   offsetT val;
17033   int mintiny, maxtiny;
17034   segT symsec;
17035   fragS *sym_frag;
17036
17037   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17038     return 0;
17039   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17040     return 1;
17041
17042   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17043   op = mips16_immed_operands;
17044   while (op->type != type)
17045     {
17046       ++op;
17047       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
17048     }
17049
17050   if (op->unsp)
17051     {
17052       if (type == '<' || type == '>' || type == '[' || type == ']')
17053         {
17054           mintiny = 1;
17055           maxtiny = 1 << op->nbits;
17056         }
17057       else
17058         {
17059           mintiny = 0;
17060           maxtiny = (1 << op->nbits) - 1;
17061         }
17062     }
17063   else
17064     {
17065       mintiny = - (1 << (op->nbits - 1));
17066       maxtiny = (1 << (op->nbits - 1)) - 1;
17067     }
17068
17069   sym_frag = symbol_get_frag (fragp->fr_symbol);
17070   val = S_GET_VALUE (fragp->fr_symbol);
17071   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17072
17073   if (op->pcrel)
17074     {
17075       addressT addr;
17076
17077       /* We won't have the section when we are called from
17078          mips_relax_frag.  However, we will always have been called
17079          from md_estimate_size_before_relax first.  If this is a
17080          branch to a different section, we mark it as such.  If SEC is
17081          NULL, and the frag is not marked, then it must be a branch to
17082          the same section.  */
17083       if (sec == NULL)
17084         {
17085           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17086             return 1;
17087         }
17088       else
17089         {
17090           /* Must have been called from md_estimate_size_before_relax.  */
17091           if (symsec != sec)
17092             {
17093               fragp->fr_subtype =
17094                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17095
17096               /* FIXME: We should support this, and let the linker
17097                  catch branches and loads that are out of range.  */
17098               as_bad_where (fragp->fr_file, fragp->fr_line,
17099                             _("unsupported PC relative reference to different section"));
17100
17101               return 1;
17102             }
17103           if (fragp != sym_frag && sym_frag->fr_address == 0)
17104             /* Assume non-extended on the first relaxation pass.
17105                The address we have calculated will be bogus if this is
17106                a forward branch to another frag, as the forward frag
17107                will have fr_address == 0.  */
17108             return 0;
17109         }
17110
17111       /* In this case, we know for sure that the symbol fragment is in
17112          the same section.  If the relax_marker of the symbol fragment
17113          differs from the relax_marker of this fragment, we have not
17114          yet adjusted the symbol fragment fr_address.  We want to add
17115          in STRETCH in order to get a better estimate of the address.
17116          This particularly matters because of the shift bits.  */
17117       if (stretch != 0
17118           && sym_frag->relax_marker != fragp->relax_marker)
17119         {
17120           fragS *f;
17121
17122           /* Adjust stretch for any alignment frag.  Note that if have
17123              been expanding the earlier code, the symbol may be
17124              defined in what appears to be an earlier frag.  FIXME:
17125              This doesn't handle the fr_subtype field, which specifies
17126              a maximum number of bytes to skip when doing an
17127              alignment.  */
17128           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17129             {
17130               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17131                 {
17132                   if (stretch < 0)
17133                     stretch = - ((- stretch)
17134                                  & ~ ((1 << (int) f->fr_offset) - 1));
17135                   else
17136                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17137                   if (stretch == 0)
17138                     break;
17139                 }
17140             }
17141           if (f != NULL)
17142             val += stretch;
17143         }
17144
17145       addr = fragp->fr_address + fragp->fr_fix;
17146
17147       /* The base address rules are complicated.  The base address of
17148          a branch is the following instruction.  The base address of a
17149          PC relative load or add is the instruction itself, but if it
17150          is in a delay slot (in which case it can not be extended) use
17151          the address of the instruction whose delay slot it is in.  */
17152       if (type == 'p' || type == 'q')
17153         {
17154           addr += 2;
17155
17156           /* If we are currently assuming that this frag should be
17157              extended, then, the current address is two bytes
17158              higher.  */
17159           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17160             addr += 2;
17161
17162           /* Ignore the low bit in the target, since it will be set
17163              for a text label.  */
17164           if ((val & 1) != 0)
17165             --val;
17166         }
17167       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17168         addr -= 4;
17169       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17170         addr -= 2;
17171
17172       val -= addr & ~ ((1 << op->shift) - 1);
17173
17174       /* Branch offsets have an implicit 0 in the lowest bit.  */
17175       if (type == 'p' || type == 'q')
17176         val /= 2;
17177
17178       /* If any of the shifted bits are set, we must use an extended
17179          opcode.  If the address depends on the size of this
17180          instruction, this can lead to a loop, so we arrange to always
17181          use an extended opcode.  We only check this when we are in
17182          the main relaxation loop, when SEC is NULL.  */
17183       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17184         {
17185           fragp->fr_subtype =
17186             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17187           return 1;
17188         }
17189
17190       /* If we are about to mark a frag as extended because the value
17191          is precisely maxtiny + 1, then there is a chance of an
17192          infinite loop as in the following code:
17193              la $4,foo
17194              .skip      1020
17195              .align     2
17196            foo:
17197          In this case when the la is extended, foo is 0x3fc bytes
17198          away, so the la can be shrunk, but then foo is 0x400 away, so
17199          the la must be extended.  To avoid this loop, we mark the
17200          frag as extended if it was small, and is about to become
17201          extended with a value of maxtiny + 1.  */
17202       if (val == ((maxtiny + 1) << op->shift)
17203           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17204           && sec == NULL)
17205         {
17206           fragp->fr_subtype =
17207             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17208           return 1;
17209         }
17210     }
17211   else if (symsec != absolute_section && sec != NULL)
17212     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17213
17214   if ((val & ((1 << op->shift) - 1)) != 0
17215       || val < (mintiny << op->shift)
17216       || val > (maxtiny << op->shift))
17217     return 1;
17218   else
17219     return 0;
17220 }
17221
17222 /* Compute the length of a branch sequence, and adjust the
17223    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17224    worst-case length is computed, with UPDATE being used to indicate
17225    whether an unconditional (-1), branch-likely (+1) or regular (0)
17226    branch is to be computed.  */
17227 static int
17228 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17229 {
17230   bfd_boolean toofar;
17231   int length;
17232
17233   if (fragp
17234       && S_IS_DEFINED (fragp->fr_symbol)
17235       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17236     {
17237       addressT addr;
17238       offsetT val;
17239
17240       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17241
17242       addr = fragp->fr_address + fragp->fr_fix + 4;
17243
17244       val -= addr;
17245
17246       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17247     }
17248   else if (fragp)
17249     /* If the symbol is not defined or it's in a different segment,
17250        assume the user knows what's going on and emit a short
17251        branch.  */
17252     toofar = FALSE;
17253   else
17254     toofar = TRUE;
17255
17256   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17257     fragp->fr_subtype
17258       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17259                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17260                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17261                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17262                              toofar);
17263
17264   length = 4;
17265   if (toofar)
17266     {
17267       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17268         length += 8;
17269
17270       if (mips_pic != NO_PIC)
17271         {
17272           /* Additional space for PIC loading of target address.  */
17273           length += 8;
17274           if (mips_opts.isa == ISA_MIPS1)
17275             /* Additional space for $at-stabilizing nop.  */
17276             length += 4;
17277         }
17278
17279       /* If branch is conditional.  */
17280       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17281         length += 8;
17282     }
17283
17284   return length;
17285 }
17286
17287 /* Compute the length of a branch sequence, and adjust the
17288    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17289    worst-case length is computed, with UPDATE being used to indicate
17290    whether an unconditional (-1), or regular (0) branch is to be
17291    computed.  */
17292
17293 static int
17294 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17295 {
17296   bfd_boolean toofar;
17297   int length;
17298
17299   if (fragp
17300       && S_IS_DEFINED (fragp->fr_symbol)
17301       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17302     {
17303       addressT addr;
17304       offsetT val;
17305
17306       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17307       /* Ignore the low bit in the target, since it will be set
17308          for a text label.  */
17309       if ((val & 1) != 0)
17310         --val;
17311
17312       addr = fragp->fr_address + fragp->fr_fix + 4;
17313
17314       val -= addr;
17315
17316       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17317     }
17318   else if (fragp)
17319     /* If the symbol is not defined or it's in a different segment,
17320        assume the user knows what's going on and emit a short
17321        branch.  */
17322     toofar = FALSE;
17323   else
17324     toofar = TRUE;
17325
17326   if (fragp && update
17327       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17328     fragp->fr_subtype = (toofar
17329                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17330                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17331
17332   length = 4;
17333   if (toofar)
17334     {
17335       bfd_boolean compact_known = fragp != NULL;
17336       bfd_boolean compact = FALSE;
17337       bfd_boolean uncond;
17338
17339       if (compact_known)
17340         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17341       if (fragp)
17342         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17343       else
17344         uncond = update < 0;
17345
17346       /* If label is out of range, we turn branch <br>:
17347
17348                 <br>    label                   # 4 bytes
17349             0:
17350
17351          into:
17352
17353                 j       label                   # 4 bytes
17354                 nop                             # 2 bytes if compact && !PIC
17355             0:
17356        */
17357       if (mips_pic == NO_PIC && (!compact_known || compact))
17358         length += 2;
17359
17360       /* If assembling PIC code, we further turn:
17361
17362                         j       label                   # 4 bytes
17363
17364          into:
17365
17366                         lw/ld   at, %got(label)(gp)     # 4 bytes
17367                         d/addiu at, %lo(label)          # 4 bytes
17368                         jr/c    at                      # 2 bytes
17369        */
17370       if (mips_pic != NO_PIC)
17371         length += 6;
17372
17373       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17374
17375                         <brneg> 0f                      # 4 bytes
17376                         nop                             # 2 bytes if !compact
17377        */
17378       if (!uncond)
17379         length += (compact_known && compact) ? 4 : 6;
17380     }
17381
17382   return length;
17383 }
17384
17385 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17386    bit accordingly.  */
17387
17388 static int
17389 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17390 {
17391   bfd_boolean toofar;
17392
17393   if (fragp
17394       && S_IS_DEFINED (fragp->fr_symbol)
17395       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17396     {
17397       addressT addr;
17398       offsetT val;
17399       int type;
17400
17401       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17402       /* Ignore the low bit in the target, since it will be set
17403          for a text label.  */
17404       if ((val & 1) != 0)
17405         --val;
17406
17407       /* Assume this is a 2-byte branch.  */
17408       addr = fragp->fr_address + fragp->fr_fix + 2;
17409
17410       /* We try to avoid the infinite loop by not adding 2 more bytes for
17411          long branches.  */
17412
17413       val -= addr;
17414
17415       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17416       if (type == 'D')
17417         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17418       else if (type == 'E')
17419         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17420       else
17421         abort ();
17422     }
17423   else
17424     /* If the symbol is not defined or it's in a different segment,
17425        we emit a normal 32-bit branch.  */
17426     toofar = TRUE;
17427
17428   if (fragp && update
17429       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17430     fragp->fr_subtype
17431       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17432                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17433
17434   if (toofar)
17435     return 4;
17436
17437   return 2;
17438 }
17439
17440 /* Estimate the size of a frag before relaxing.  Unless this is the
17441    mips16, we are not really relaxing here, and the final size is
17442    encoded in the subtype information.  For the mips16, we have to
17443    decide whether we are using an extended opcode or not.  */
17444
17445 int
17446 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17447 {
17448   int change;
17449
17450   if (RELAX_BRANCH_P (fragp->fr_subtype))
17451     {
17452
17453       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17454
17455       return fragp->fr_var;
17456     }
17457
17458   if (RELAX_MIPS16_P (fragp->fr_subtype))
17459     /* We don't want to modify the EXTENDED bit here; it might get us
17460        into infinite loops.  We change it only in mips_relax_frag().  */
17461     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17462
17463   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17464     {
17465       int length = 4;
17466
17467       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17468         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17469       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17470         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17471       fragp->fr_var = length;
17472
17473       return length;
17474     }
17475
17476   if (mips_pic == NO_PIC)
17477     change = nopic_need_relax (fragp->fr_symbol, 0);
17478   else if (mips_pic == SVR4_PIC)
17479     change = pic_need_relax (fragp->fr_symbol, segtype);
17480   else if (mips_pic == VXWORKS_PIC)
17481     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17482     change = 0;
17483   else
17484     abort ();
17485
17486   if (change)
17487     {
17488       fragp->fr_subtype |= RELAX_USE_SECOND;
17489       return -RELAX_FIRST (fragp->fr_subtype);
17490     }
17491   else
17492     return -RELAX_SECOND (fragp->fr_subtype);
17493 }
17494
17495 /* This is called to see whether a reloc against a defined symbol
17496    should be converted into a reloc against a section.  */
17497
17498 int
17499 mips_fix_adjustable (fixS *fixp)
17500 {
17501   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17502       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17503     return 0;
17504
17505   if (fixp->fx_addsy == NULL)
17506     return 1;
17507
17508   /* If symbol SYM is in a mergeable section, relocations of the form
17509      SYM + 0 can usually be made section-relative.  The mergeable data
17510      is then identified by the section offset rather than by the symbol.
17511
17512      However, if we're generating REL LO16 relocations, the offset is split
17513      between the LO16 and parterning high part relocation.  The linker will
17514      need to recalculate the complete offset in order to correctly identify
17515      the merge data.
17516
17517      The linker has traditionally not looked for the parterning high part
17518      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17519      placed anywhere.  Rather than break backwards compatibility by changing
17520      this, it seems better not to force the issue, and instead keep the
17521      original symbol.  This will work with either linker behavior.  */
17522   if ((lo16_reloc_p (fixp->fx_r_type)
17523        || reloc_needs_lo_p (fixp->fx_r_type))
17524       && HAVE_IN_PLACE_ADDENDS
17525       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17526     return 0;
17527
17528   /* There is no place to store an in-place offset for JALR relocations.
17529      Likewise an in-range offset of PC-relative relocations may overflow
17530      the in-place relocatable field if recalculated against the start
17531      address of the symbol's containing section.  */
17532   if (HAVE_IN_PLACE_ADDENDS
17533       && (fixp->fx_pcrel || jalr_reloc_p (fixp->fx_r_type)))
17534     return 0;
17535
17536 #ifdef OBJ_ELF
17537   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17538      to a floating-point stub.  The same is true for non-R_MIPS16_26
17539      relocations against MIPS16 functions; in this case, the stub becomes
17540      the function's canonical address.
17541
17542      Floating-point stubs are stored in unique .mips16.call.* or
17543      .mips16.fn.* sections.  If a stub T for function F is in section S,
17544      the first relocation in section S must be against F; this is how the
17545      linker determines the target function.  All relocations that might
17546      resolve to T must also be against F.  We therefore have the following
17547      restrictions, which are given in an intentionally-redundant way:
17548
17549        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17550           symbols.
17551
17552        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17553           if that stub might be used.
17554
17555        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17556           symbols.
17557
17558        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17559           that stub might be used.
17560
17561      There is a further restriction:
17562
17563        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17564           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
17565           targets with in-place addends; the relocation field cannot
17566           encode the low bit.
17567
17568      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17569      against a MIPS16 symbol.  We deal with (5) by by not reducing any
17570      such relocations on REL targets.
17571
17572      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17573      relocation against some symbol R, no relocation against R may be
17574      reduced.  (Note that this deals with (2) as well as (1) because
17575      relocations against global symbols will never be reduced on ELF
17576      targets.)  This approach is a little simpler than trying to detect
17577      stub sections, and gives the "all or nothing" per-symbol consistency
17578      that we have for MIPS16 symbols.  */
17579   if (IS_ELF
17580       && fixp->fx_subsy == NULL
17581       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17582           || *symbol_get_tc (fixp->fx_addsy)
17583           || (HAVE_IN_PLACE_ADDENDS
17584               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17585               && jmp_reloc_p (fixp->fx_r_type))))
17586     return 0;
17587 #endif
17588
17589   return 1;
17590 }
17591
17592 /* Translate internal representation of relocation info to BFD target
17593    format.  */
17594
17595 arelent **
17596 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17597 {
17598   static arelent *retval[4];
17599   arelent *reloc;
17600   bfd_reloc_code_real_type code;
17601
17602   memset (retval, 0, sizeof(retval));
17603   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
17604   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
17605   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17606   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17607
17608   if (fixp->fx_pcrel)
17609     {
17610       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17611                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17612                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17613                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
17614
17615       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17616          Relocations want only the symbol offset.  */
17617       reloc->addend = fixp->fx_addnumber + reloc->address;
17618       if (!IS_ELF)
17619         {
17620           /* A gruesome hack which is a result of the gruesome gas
17621              reloc handling.  What's worse, for COFF (as opposed to
17622              ECOFF), we might need yet another copy of reloc->address.
17623              See bfd_install_relocation.  */
17624           reloc->addend += reloc->address;
17625         }
17626     }
17627   else
17628     reloc->addend = fixp->fx_addnumber;
17629
17630   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17631      entry to be used in the relocation's section offset.  */
17632   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17633     {
17634       reloc->address = reloc->addend;
17635       reloc->addend = 0;
17636     }
17637
17638   code = fixp->fx_r_type;
17639
17640   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17641   if (reloc->howto == NULL)
17642     {
17643       as_bad_where (fixp->fx_file, fixp->fx_line,
17644                     _("Can not represent %s relocation in this object file format"),
17645                     bfd_get_reloc_code_name (code));
17646       retval[0] = NULL;
17647     }
17648
17649   return retval;
17650 }
17651
17652 /* Relax a machine dependent frag.  This returns the amount by which
17653    the current size of the frag should change.  */
17654
17655 int
17656 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17657 {
17658   if (RELAX_BRANCH_P (fragp->fr_subtype))
17659     {
17660       offsetT old_var = fragp->fr_var;
17661
17662       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17663
17664       return fragp->fr_var - old_var;
17665     }
17666
17667   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17668     {
17669       offsetT old_var = fragp->fr_var;
17670       offsetT new_var = 4;
17671
17672       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17673         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17674       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17675         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17676       fragp->fr_var = new_var;
17677
17678       return new_var - old_var;
17679     }
17680
17681   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17682     return 0;
17683
17684   if (mips16_extended_frag (fragp, NULL, stretch))
17685     {
17686       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17687         return 0;
17688       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17689       return 2;
17690     }
17691   else
17692     {
17693       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17694         return 0;
17695       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17696       return -2;
17697     }
17698
17699   return 0;
17700 }
17701
17702 /* Convert a machine dependent frag.  */
17703
17704 void
17705 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17706 {
17707   if (RELAX_BRANCH_P (fragp->fr_subtype))
17708     {
17709       bfd_byte *buf;
17710       unsigned long insn;
17711       expressionS exp;
17712       fixS *fixp;
17713
17714       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
17715
17716       if (target_big_endian)
17717         insn = bfd_getb32 (buf);
17718       else
17719         insn = bfd_getl32 (buf);
17720
17721       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17722         {
17723           /* We generate a fixup instead of applying it right now
17724              because, if there are linker relaxations, we're going to
17725              need the relocations.  */
17726           exp.X_op = O_symbol;
17727           exp.X_add_symbol = fragp->fr_symbol;
17728           exp.X_add_number = fragp->fr_offset;
17729
17730           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17731                               4, &exp, TRUE, BFD_RELOC_16_PCREL_S2);
17732           fixp->fx_file = fragp->fr_file;
17733           fixp->fx_line = fragp->fr_line;
17734
17735           md_number_to_chars ((char *) buf, insn, 4);
17736           buf += 4;
17737         }
17738       else
17739         {
17740           int i;
17741
17742           as_warn_where (fragp->fr_file, fragp->fr_line,
17743                          _("Relaxed out-of-range branch into a jump"));
17744
17745           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17746             goto uncond;
17747
17748           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17749             {
17750               /* Reverse the branch.  */
17751               switch ((insn >> 28) & 0xf)
17752                 {
17753                 case 4:
17754                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
17755                      have the condition reversed by tweaking a single
17756                      bit, and their opcodes all have 0x4???????.  */
17757                   gas_assert ((insn & 0xf1000000) == 0x41000000);
17758                   insn ^= 0x00010000;
17759                   break;
17760
17761                 case 0:
17762                   /* bltz       0x04000000      bgez    0x04010000
17763                      bltzal     0x04100000      bgezal  0x04110000  */
17764                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17765                   insn ^= 0x00010000;
17766                   break;
17767
17768                 case 1:
17769                   /* beq        0x10000000      bne     0x14000000
17770                      blez       0x18000000      bgtz    0x1c000000  */
17771                   insn ^= 0x04000000;
17772                   break;
17773
17774                 default:
17775                   abort ();
17776                 }
17777             }
17778
17779           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17780             {
17781               /* Clear the and-link bit.  */
17782               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17783
17784               /* bltzal         0x04100000      bgezal  0x04110000
17785                  bltzall        0x04120000      bgezall 0x04130000  */
17786               insn &= ~0x00100000;
17787             }
17788
17789           /* Branch over the branch (if the branch was likely) or the
17790              full jump (not likely case).  Compute the offset from the
17791              current instruction to branch to.  */
17792           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17793             i = 16;
17794           else
17795             {
17796               /* How many bytes in instructions we've already emitted?  */
17797               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17798               /* How many bytes in instructions from here to the end?  */
17799               i = fragp->fr_var - i;
17800             }
17801           /* Convert to instruction count.  */
17802           i >>= 2;
17803           /* Branch counts from the next instruction.  */
17804           i--;
17805           insn |= i;
17806           /* Branch over the jump.  */
17807           md_number_to_chars ((char *) buf, insn, 4);
17808           buf += 4;
17809
17810           /* nop */
17811           md_number_to_chars ((char *) buf, 0, 4);
17812           buf += 4;
17813
17814           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17815             {
17816               /* beql $0, $0, 2f */
17817               insn = 0x50000000;
17818               /* Compute the PC offset from the current instruction to
17819                  the end of the variable frag.  */
17820               /* How many bytes in instructions we've already emitted?  */
17821               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17822               /* How many bytes in instructions from here to the end?  */
17823               i = fragp->fr_var - i;
17824               /* Convert to instruction count.  */
17825               i >>= 2;
17826               /* Don't decrement i, because we want to branch over the
17827                  delay slot.  */
17828
17829               insn |= i;
17830               md_number_to_chars ((char *) buf, insn, 4);
17831               buf += 4;
17832
17833               md_number_to_chars ((char *) buf, 0, 4);
17834               buf += 4;
17835             }
17836
17837         uncond:
17838           if (mips_pic == NO_PIC)
17839             {
17840               /* j or jal.  */
17841               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17842                       ? 0x0c000000 : 0x08000000);
17843               exp.X_op = O_symbol;
17844               exp.X_add_symbol = fragp->fr_symbol;
17845               exp.X_add_number = fragp->fr_offset;
17846
17847               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17848                                   4, &exp, FALSE, BFD_RELOC_MIPS_JMP);
17849               fixp->fx_file = fragp->fr_file;
17850               fixp->fx_line = fragp->fr_line;
17851
17852               md_number_to_chars ((char *) buf, insn, 4);
17853               buf += 4;
17854             }
17855           else
17856             {
17857               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17858
17859               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17860               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17861               insn |= at << OP_SH_RT;
17862               exp.X_op = O_symbol;
17863               exp.X_add_symbol = fragp->fr_symbol;
17864               exp.X_add_number = fragp->fr_offset;
17865
17866               if (fragp->fr_offset)
17867                 {
17868                   exp.X_add_symbol = make_expr_symbol (&exp);
17869                   exp.X_add_number = 0;
17870                 }
17871
17872               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17873                                   4, &exp, FALSE, BFD_RELOC_MIPS_GOT16);
17874               fixp->fx_file = fragp->fr_file;
17875               fixp->fx_line = fragp->fr_line;
17876
17877               md_number_to_chars ((char *) buf, insn, 4);
17878               buf += 4;
17879
17880               if (mips_opts.isa == ISA_MIPS1)
17881                 {
17882                   /* nop */
17883                   md_number_to_chars ((char *) buf, 0, 4);
17884                   buf += 4;
17885                 }
17886
17887               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17888               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17889               insn |= at << OP_SH_RS | at << OP_SH_RT;
17890
17891               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17892                                   4, &exp, FALSE, BFD_RELOC_LO16);
17893               fixp->fx_file = fragp->fr_file;
17894               fixp->fx_line = fragp->fr_line;
17895
17896               md_number_to_chars ((char *) buf, insn, 4);
17897               buf += 4;
17898
17899               /* j(al)r $at.  */
17900               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17901                 insn = 0x0000f809;
17902               else
17903                 insn = 0x00000008;
17904               insn |= at << OP_SH_RS;
17905
17906               md_number_to_chars ((char *) buf, insn, 4);
17907               buf += 4;
17908             }
17909         }
17910
17911       gas_assert (buf == (bfd_byte *)fragp->fr_literal
17912               + fragp->fr_fix + fragp->fr_var);
17913
17914       fragp->fr_fix += fragp->fr_var;
17915
17916       return;
17917     }
17918
17919   /* Relax microMIPS branches.  */
17920   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17921     {
17922       bfd_byte *buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
17923       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17924       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17925       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17926       bfd_boolean short_ds;
17927       unsigned long insn;
17928       expressionS exp;
17929       fixS *fixp;
17930
17931       exp.X_op = O_symbol;
17932       exp.X_add_symbol = fragp->fr_symbol;
17933       exp.X_add_number = fragp->fr_offset;
17934
17935       fragp->fr_fix += fragp->fr_var;
17936
17937       /* Handle 16-bit branches that fit or are forced to fit.  */
17938       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17939         {
17940           /* We generate a fixup instead of applying it right now,
17941              because if there is linker relaxation, we're going to
17942              need the relocations.  */
17943           if (type == 'D')
17944             fixp = fix_new_exp (fragp,
17945                                 buf - (bfd_byte *) fragp->fr_literal,
17946                                 2, &exp, TRUE,
17947                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17948           else if (type == 'E')
17949             fixp = fix_new_exp (fragp,
17950                                 buf - (bfd_byte *) fragp->fr_literal,
17951                                 2, &exp, TRUE,
17952                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17953           else
17954             abort ();
17955
17956           fixp->fx_file = fragp->fr_file;
17957           fixp->fx_line = fragp->fr_line;
17958
17959           /* These relocations can have an addend that won't fit in
17960              2 octets.  */
17961           fixp->fx_no_overflow = 1;
17962
17963           return;
17964         }
17965
17966       /* Handle 32-bit branches that fit or are forced to fit.  */
17967       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17968           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17969         {
17970           /* We generate a fixup instead of applying it right now,
17971              because if there is linker relaxation, we're going to
17972              need the relocations.  */
17973           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
17974                               4, &exp, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
17975           fixp->fx_file = fragp->fr_file;
17976           fixp->fx_line = fragp->fr_line;
17977
17978           if (type == 0)
17979             return;
17980         }
17981
17982       /* Relax 16-bit branches to 32-bit branches.  */
17983       if (type != 0)
17984         {
17985           if (target_big_endian)
17986             insn = bfd_getb16 (buf);
17987           else
17988             insn = bfd_getl16 (buf);
17989
17990           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17991             insn = 0x94000000;                          /* beq  */
17992           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17993             {
17994               unsigned long regno;
17995
17996               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17997               regno = micromips_to_32_reg_d_map [regno];
17998               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17999               insn |= regno << MICROMIPSOP_SH_RS;
18000             }
18001           else
18002             abort ();
18003
18004           /* Nothing else to do, just write it out.  */
18005           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18006               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18007             {
18008               md_number_to_chars ((char *) buf, insn >> 16, 2);
18009               buf += 2;
18010               md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18011               buf += 2;
18012
18013               gas_assert (buf == ((bfd_byte *) fragp->fr_literal
18014                                   + fragp->fr_fix));
18015               return;
18016             }
18017         }
18018       else
18019         {
18020           unsigned long next;
18021
18022           if (target_big_endian)
18023             {
18024               insn = bfd_getb16 (buf);
18025               next = bfd_getb16 (buf + 2);
18026             }
18027           else
18028             {
18029               insn = bfd_getl16 (buf);
18030               next = bfd_getl16 (buf + 2);
18031             }
18032           insn = (insn << 16) | next;
18033         }
18034
18035       /* Relax 32-bit branches to a sequence of instructions.  */
18036       as_warn_where (fragp->fr_file, fragp->fr_line,
18037                      _("Relaxed out-of-range branch into a jump"));
18038
18039       /* Set the short-delay-slot bit.  */
18040       short_ds = al && (insn & 0x02000000) != 0;
18041
18042       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18043         {
18044           symbolS *l;
18045
18046           /* Reverse the branch.  */
18047           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18048               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18049             insn ^= 0x20000000;
18050           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18051                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18052                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18053                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18054                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18055                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18056                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18057                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18058                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18059                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18060             insn ^= 0x00400000;
18061           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18062                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18063                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18064                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18065             insn ^= 0x00200000;
18066           else
18067             abort ();
18068
18069           if (al)
18070             {
18071               /* Clear the and-link and short-delay-slot bits.  */
18072               gas_assert ((insn & 0xfda00000) == 0x40200000);
18073
18074               /* bltzal  0x40200000     bgezal  0x40600000  */
18075               /* bltzals 0x42200000     bgezals 0x42600000  */
18076               insn &= ~0x02200000;
18077             }
18078
18079           /* Make a label at the end for use with the branch.  */
18080           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18081           micromips_label_inc ();
18082 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
18083           if (IS_ELF)
18084             S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18085 #endif
18086
18087           /* Refer to it.  */
18088           fixp = fix_new (fragp, buf - (bfd_byte *) fragp->fr_literal,
18089                           4, l, 0, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
18090           fixp->fx_file = fragp->fr_file;
18091           fixp->fx_line = fragp->fr_line;
18092
18093           /* Branch over the jump.  */
18094           md_number_to_chars ((char *) buf, insn >> 16, 2);
18095           buf += 2;
18096           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18097           buf += 2;
18098
18099           if (!compact)
18100             {
18101               /* nop  */
18102               insn = 0x0c00;
18103               md_number_to_chars ((char *) buf, insn, 2);
18104               buf += 2;
18105             }
18106         }
18107
18108       if (mips_pic == NO_PIC)
18109         {
18110           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
18111
18112           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18113           insn = al ? jal : 0xd4000000;
18114
18115           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18116                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_JMP);
18117           fixp->fx_file = fragp->fr_file;
18118           fixp->fx_line = fragp->fr_line;
18119
18120           md_number_to_chars ((char *) buf, insn >> 16, 2);
18121           buf += 2;
18122           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18123           buf += 2;
18124
18125           if (compact)
18126             {
18127               /* nop  */
18128               insn = 0x0c00;
18129               md_number_to_chars ((char *) buf, insn, 2);
18130               buf += 2;
18131             }
18132         }
18133       else
18134         {
18135           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18136           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18137           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18138
18139           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18140           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18141           insn |= at << MICROMIPSOP_SH_RT;
18142
18143           if (exp.X_add_number)
18144             {
18145               exp.X_add_symbol = make_expr_symbol (&exp);
18146               exp.X_add_number = 0;
18147             }
18148
18149           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18150                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_GOT16);
18151           fixp->fx_file = fragp->fr_file;
18152           fixp->fx_line = fragp->fr_line;
18153
18154           md_number_to_chars ((char *) buf, insn >> 16, 2);
18155           buf += 2;
18156           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18157           buf += 2;
18158
18159           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18160           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18161           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18162
18163           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18164                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_LO16);
18165           fixp->fx_file = fragp->fr_file;
18166           fixp->fx_line = fragp->fr_line;
18167
18168           md_number_to_chars ((char *) buf, insn >> 16, 2);
18169           buf += 2;
18170           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18171           buf += 2;
18172
18173           /* jr/jrc/jalr/jalrs $at  */
18174           insn = al ? jalr : jr;
18175           insn |= at << MICROMIPSOP_SH_MJ;
18176
18177           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18178           buf += 2;
18179         }
18180
18181       gas_assert (buf == (bfd_byte *) fragp->fr_literal + fragp->fr_fix);
18182       return;
18183     }
18184
18185   if (RELAX_MIPS16_P (fragp->fr_subtype))
18186     {
18187       int type;
18188       const struct mips16_immed_operand *op;
18189       bfd_boolean small, ext;
18190       offsetT val;
18191       bfd_byte *buf;
18192       unsigned long insn;
18193       bfd_boolean use_extend;
18194       unsigned short extend;
18195
18196       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18197       op = mips16_immed_operands;
18198       while (op->type != type)
18199         ++op;
18200
18201       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18202         {
18203           small = FALSE;
18204           ext = TRUE;
18205         }
18206       else
18207         {
18208           small = TRUE;
18209           ext = FALSE;
18210         }
18211
18212       val = resolve_symbol_value (fragp->fr_symbol);
18213       if (op->pcrel)
18214         {
18215           addressT addr;
18216
18217           addr = fragp->fr_address + fragp->fr_fix;
18218
18219           /* The rules for the base address of a PC relative reloc are
18220              complicated; see mips16_extended_frag.  */
18221           if (type == 'p' || type == 'q')
18222             {
18223               addr += 2;
18224               if (ext)
18225                 addr += 2;
18226               /* Ignore the low bit in the target, since it will be
18227                  set for a text label.  */
18228               if ((val & 1) != 0)
18229                 --val;
18230             }
18231           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18232             addr -= 4;
18233           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18234             addr -= 2;
18235
18236           addr &= ~ (addressT) ((1 << op->shift) - 1);
18237           val -= addr;
18238
18239           /* Make sure the section winds up with the alignment we have
18240              assumed.  */
18241           if (op->shift > 0)
18242             record_alignment (asec, op->shift);
18243         }
18244
18245       if (ext
18246           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18247               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18248         as_warn_where (fragp->fr_file, fragp->fr_line,
18249                        _("extended instruction in delay slot"));
18250
18251       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
18252
18253       if (target_big_endian)
18254         insn = bfd_getb16 (buf);
18255       else
18256         insn = bfd_getl16 (buf);
18257
18258       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
18259                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
18260                     small, ext, &insn, &use_extend, &extend);
18261
18262       if (use_extend)
18263         {
18264           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
18265           fragp->fr_fix += 2;
18266           buf += 2;
18267         }
18268
18269       md_number_to_chars ((char *) buf, insn, 2);
18270       fragp->fr_fix += 2;
18271       buf += 2;
18272     }
18273   else
18274     {
18275       relax_substateT subtype = fragp->fr_subtype;
18276       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18277       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18278       int first, second;
18279       fixS *fixp;
18280
18281       first = RELAX_FIRST (subtype);
18282       second = RELAX_SECOND (subtype);
18283       fixp = (fixS *) fragp->fr_opcode;
18284
18285       /* If the delay slot chosen does not match the size of the instruction,
18286          then emit a warning.  */
18287       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18288            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18289         {
18290           relax_substateT s;
18291           const char *msg;
18292
18293           s = subtype & (RELAX_DELAY_SLOT_16BIT
18294                          | RELAX_DELAY_SLOT_SIZE_FIRST
18295                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18296           msg = macro_warning (s);
18297           if (msg != NULL)
18298             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18299           subtype &= ~s;
18300         }
18301
18302       /* Possibly emit a warning if we've chosen the longer option.  */
18303       if (use_second == second_longer)
18304         {
18305           relax_substateT s;
18306           const char *msg;
18307
18308           s = (subtype
18309                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18310           msg = macro_warning (s);
18311           if (msg != NULL)
18312             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18313           subtype &= ~s;
18314         }
18315
18316       /* Go through all the fixups for the first sequence.  Disable them
18317          (by marking them as done) if we're going to use the second
18318          sequence instead.  */
18319       while (fixp
18320              && fixp->fx_frag == fragp
18321              && fixp->fx_where < fragp->fr_fix - second)
18322         {
18323           if (subtype & RELAX_USE_SECOND)
18324             fixp->fx_done = 1;
18325           fixp = fixp->fx_next;
18326         }
18327
18328       /* Go through the fixups for the second sequence.  Disable them if
18329          we're going to use the first sequence, otherwise adjust their
18330          addresses to account for the relaxation.  */
18331       while (fixp && fixp->fx_frag == fragp)
18332         {
18333           if (subtype & RELAX_USE_SECOND)
18334             fixp->fx_where -= first;
18335           else
18336             fixp->fx_done = 1;
18337           fixp = fixp->fx_next;
18338         }
18339
18340       /* Now modify the frag contents.  */
18341       if (subtype & RELAX_USE_SECOND)
18342         {
18343           char *start;
18344
18345           start = fragp->fr_literal + fragp->fr_fix - first - second;
18346           memmove (start, start + first, second);
18347           fragp->fr_fix -= first;
18348         }
18349       else
18350         fragp->fr_fix -= second;
18351     }
18352 }
18353
18354 #ifdef OBJ_ELF
18355
18356 /* This function is called after the relocs have been generated.
18357    We've been storing mips16 text labels as odd.  Here we convert them
18358    back to even for the convenience of the debugger.  */
18359
18360 void
18361 mips_frob_file_after_relocs (void)
18362 {
18363   asymbol **syms;
18364   unsigned int count, i;
18365
18366   if (!IS_ELF)
18367     return;
18368
18369   syms = bfd_get_outsymbols (stdoutput);
18370   count = bfd_get_symcount (stdoutput);
18371   for (i = 0; i < count; i++, syms++)
18372     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18373         && ((*syms)->value & 1) != 0)
18374       {
18375         (*syms)->value &= ~1;
18376         /* If the symbol has an odd size, it was probably computed
18377            incorrectly, so adjust that as well.  */
18378         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18379           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18380       }
18381 }
18382
18383 #endif
18384
18385 /* This function is called whenever a label is defined, including fake
18386    labels instantiated off the dot special symbol.  It is used when
18387    handling branch delays; if a branch has a label, we assume we cannot
18388    move it.  This also bumps the value of the symbol by 1 in compressed
18389    code.  */
18390
18391 void
18392 mips_record_label (symbolS *sym)
18393 {
18394   segment_info_type *si = seg_info (now_seg);
18395   struct insn_label_list *l;
18396
18397   if (free_insn_labels == NULL)
18398     l = (struct insn_label_list *) xmalloc (sizeof *l);
18399   else
18400     {
18401       l = free_insn_labels;
18402       free_insn_labels = l->next;
18403     }
18404
18405   l->label = sym;
18406   l->next = si->label_list;
18407   si->label_list = l;
18408 }
18409
18410 /* This function is called as tc_frob_label() whenever a label is defined
18411    and adds a DWARF-2 record we only want for true labels.  */
18412
18413 void
18414 mips_define_label (symbolS *sym)
18415 {
18416   mips_record_label (sym);
18417 #ifdef OBJ_ELF
18418   dwarf2_emit_label (sym);
18419 #endif
18420 }
18421 \f
18422 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
18423
18424 /* Some special processing for a MIPS ELF file.  */
18425
18426 void
18427 mips_elf_final_processing (void)
18428 {
18429   /* Write out the register information.  */
18430   if (mips_abi != N64_ABI)
18431     {
18432       Elf32_RegInfo s;
18433
18434       s.ri_gprmask = mips_gprmask;
18435       s.ri_cprmask[0] = mips_cprmask[0];
18436       s.ri_cprmask[1] = mips_cprmask[1];
18437       s.ri_cprmask[2] = mips_cprmask[2];
18438       s.ri_cprmask[3] = mips_cprmask[3];
18439       /* The gp_value field is set by the MIPS ELF backend.  */
18440
18441       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18442                                        ((Elf32_External_RegInfo *)
18443                                         mips_regmask_frag));
18444     }
18445   else
18446     {
18447       Elf64_Internal_RegInfo s;
18448
18449       s.ri_gprmask = mips_gprmask;
18450       s.ri_pad = 0;
18451       s.ri_cprmask[0] = mips_cprmask[0];
18452       s.ri_cprmask[1] = mips_cprmask[1];
18453       s.ri_cprmask[2] = mips_cprmask[2];
18454       s.ri_cprmask[3] = mips_cprmask[3];
18455       /* The gp_value field is set by the MIPS ELF backend.  */
18456
18457       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18458                                        ((Elf64_External_RegInfo *)
18459                                         mips_regmask_frag));
18460     }
18461
18462   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18463      sort of BFD interface for this.  */
18464   if (mips_any_noreorder)
18465     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18466   if (mips_pic != NO_PIC)
18467     {
18468       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18469       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18470     }
18471   if (mips_abicalls)
18472     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18473
18474   /* Set MIPS ELF flags for ASEs.  */
18475   /* We may need to define a new flag for DSP ASE, and set this flag when
18476      file_ase_dsp is true.  */
18477   /* Same for DSP R2.  */
18478   /* We may need to define a new flag for MT ASE, and set this flag when
18479      file_ase_mt is true.  */
18480   if (file_ase_mips16)
18481     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18482   if (file_ase_micromips)
18483     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18484 #if 0 /* XXX FIXME */
18485   if (file_ase_mips3d)
18486     elf_elfheader (stdoutput)->e_flags |= ???;
18487 #endif
18488   if (file_ase_mdmx)
18489     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18490
18491   /* Set the MIPS ELF ABI flags.  */
18492   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18493     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18494   else if (mips_abi == O64_ABI)
18495     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18496   else if (mips_abi == EABI_ABI)
18497     {
18498       if (!file_mips_gp32)
18499         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18500       else
18501         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18502     }
18503   else if (mips_abi == N32_ABI)
18504     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18505
18506   /* Nothing to do for N64_ABI.  */
18507
18508   if (mips_32bitmode)
18509     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18510
18511 #if 0 /* XXX FIXME */
18512   /* 32 bit code with 64 bit FP registers.  */
18513   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18514     elf_elfheader (stdoutput)->e_flags |= ???;
18515 #endif
18516 }
18517
18518 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
18519 \f
18520 typedef struct proc {
18521   symbolS *func_sym;
18522   symbolS *func_end_sym;
18523   unsigned long reg_mask;
18524   unsigned long reg_offset;
18525   unsigned long fpreg_mask;
18526   unsigned long fpreg_offset;
18527   unsigned long frame_offset;
18528   unsigned long frame_reg;
18529   unsigned long pc_reg;
18530 } procS;
18531
18532 static procS cur_proc;
18533 static procS *cur_proc_ptr;
18534 static int numprocs;
18535
18536 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18537    as "2", and a normal nop as "0".  */
18538
18539 #define NOP_OPCODE_MIPS         0
18540 #define NOP_OPCODE_MIPS16       1
18541 #define NOP_OPCODE_MICROMIPS    2
18542
18543 char
18544 mips_nop_opcode (void)
18545 {
18546   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18547     return NOP_OPCODE_MICROMIPS;
18548   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18549     return NOP_OPCODE_MIPS16;
18550   else
18551     return NOP_OPCODE_MIPS;
18552 }
18553
18554 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18555    32-bit microMIPS NOPs here (if applicable).  */
18556
18557 void
18558 mips_handle_align (fragS *fragp)
18559 {
18560   char nop_opcode;
18561   char *p;
18562   int bytes, size, excess;
18563   valueT opcode;
18564
18565   if (fragp->fr_type != rs_align_code)
18566     return;
18567
18568   p = fragp->fr_literal + fragp->fr_fix;
18569   nop_opcode = *p;
18570   switch (nop_opcode)
18571     {
18572     case NOP_OPCODE_MICROMIPS:
18573       opcode = micromips_nop32_insn.insn_opcode;
18574       size = 4;
18575       break;
18576     case NOP_OPCODE_MIPS16:
18577       opcode = mips16_nop_insn.insn_opcode;
18578       size = 2;
18579       break;
18580     case NOP_OPCODE_MIPS:
18581     default:
18582       opcode = nop_insn.insn_opcode;
18583       size = 4;
18584       break;
18585     }
18586
18587   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18588   excess = bytes % size;
18589
18590   /* Handle the leading part if we're not inserting a whole number of
18591      instructions, and make it the end of the fixed part of the frag.
18592      Try to fit in a short microMIPS NOP if applicable and possible,
18593      and use zeroes otherwise.  */
18594   gas_assert (excess < 4);
18595   fragp->fr_fix += excess;
18596   switch (excess)
18597     {
18598     case 3:
18599       *p++ = '\0';
18600       /* Fall through.  */
18601     case 2:
18602       if (nop_opcode == NOP_OPCODE_MICROMIPS)
18603         {
18604           md_number_to_chars (p, micromips_nop16_insn.insn_opcode, 2);
18605           p += 2;
18606           break;
18607         }
18608       *p++ = '\0';
18609       /* Fall through.  */
18610     case 1:
18611       *p++ = '\0';
18612       /* Fall through.  */
18613     case 0:
18614       break;
18615     }
18616
18617   md_number_to_chars (p, opcode, size);
18618   fragp->fr_var = size;
18619 }
18620
18621 static void
18622 md_obj_begin (void)
18623 {
18624 }
18625
18626 static void
18627 md_obj_end (void)
18628 {
18629   /* Check for premature end, nesting errors, etc.  */
18630   if (cur_proc_ptr)
18631     as_warn (_("missing .end at end of assembly"));
18632 }
18633
18634 static long
18635 get_number (void)
18636 {
18637   int negative = 0;
18638   long val = 0;
18639
18640   if (*input_line_pointer == '-')
18641     {
18642       ++input_line_pointer;
18643       negative = 1;
18644     }
18645   if (!ISDIGIT (*input_line_pointer))
18646     as_bad (_("expected simple number"));
18647   if (input_line_pointer[0] == '0')
18648     {
18649       if (input_line_pointer[1] == 'x')
18650         {
18651           input_line_pointer += 2;
18652           while (ISXDIGIT (*input_line_pointer))
18653             {
18654               val <<= 4;
18655               val |= hex_value (*input_line_pointer++);
18656             }
18657           return negative ? -val : val;
18658         }
18659       else
18660         {
18661           ++input_line_pointer;
18662           while (ISDIGIT (*input_line_pointer))
18663             {
18664               val <<= 3;
18665               val |= *input_line_pointer++ - '0';
18666             }
18667           return negative ? -val : val;
18668         }
18669     }
18670   if (!ISDIGIT (*input_line_pointer))
18671     {
18672       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18673               *input_line_pointer, *input_line_pointer);
18674       as_warn (_("invalid number"));
18675       return -1;
18676     }
18677   while (ISDIGIT (*input_line_pointer))
18678     {
18679       val *= 10;
18680       val += *input_line_pointer++ - '0';
18681     }
18682   return negative ? -val : val;
18683 }
18684
18685 /* The .file directive; just like the usual .file directive, but there
18686    is an initial number which is the ECOFF file index.  In the non-ECOFF
18687    case .file implies DWARF-2.  */
18688
18689 static void
18690 s_mips_file (int x ATTRIBUTE_UNUSED)
18691 {
18692   static int first_file_directive = 0;
18693
18694   if (ECOFF_DEBUGGING)
18695     {
18696       get_number ();
18697       s_app_file (0);
18698     }
18699   else
18700     {
18701       char *filename;
18702
18703       filename = dwarf2_directive_file (0);
18704
18705       /* Versions of GCC up to 3.1 start files with a ".file"
18706          directive even for stabs output.  Make sure that this
18707          ".file" is handled.  Note that you need a version of GCC
18708          after 3.1 in order to support DWARF-2 on MIPS.  */
18709       if (filename != NULL && ! first_file_directive)
18710         {
18711           (void) new_logical_line (filename, -1);
18712           s_app_file_string (filename, 0);
18713         }
18714       first_file_directive = 1;
18715     }
18716 }
18717
18718 /* The .loc directive, implying DWARF-2.  */
18719
18720 static void
18721 s_mips_loc (int x ATTRIBUTE_UNUSED)
18722 {
18723   if (!ECOFF_DEBUGGING)
18724     dwarf2_directive_loc (0);
18725 }
18726
18727 /* The .end directive.  */
18728
18729 static void
18730 s_mips_end (int x ATTRIBUTE_UNUSED)
18731 {
18732   symbolS *p;
18733
18734   /* Following functions need their own .frame and .cprestore directives.  */
18735   mips_frame_reg_valid = 0;
18736   mips_cprestore_valid = 0;
18737
18738   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18739     {
18740       p = get_symbol ();
18741       demand_empty_rest_of_line ();
18742     }
18743   else
18744     p = NULL;
18745
18746   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18747     as_warn (_(".end not in text section"));
18748
18749   if (!cur_proc_ptr)
18750     {
18751       as_warn (_(".end directive without a preceding .ent directive."));
18752       demand_empty_rest_of_line ();
18753       return;
18754     }
18755
18756   if (p != NULL)
18757     {
18758       gas_assert (S_GET_NAME (p));
18759       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18760         as_warn (_(".end symbol does not match .ent symbol."));
18761
18762       if (debug_type == DEBUG_STABS)
18763         stabs_generate_asm_endfunc (S_GET_NAME (p),
18764                                     S_GET_NAME (p));
18765     }
18766   else
18767     as_warn (_(".end directive missing or unknown symbol"));
18768
18769 #ifdef OBJ_ELF
18770   /* Create an expression to calculate the size of the function.  */
18771   if (p && cur_proc_ptr)
18772     {
18773       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18774       expressionS *exp = xmalloc (sizeof (expressionS));
18775
18776       obj->size = exp;
18777       exp->X_op = O_subtract;
18778       exp->X_add_symbol = symbol_temp_new_now ();
18779       exp->X_op_symbol = p;
18780       exp->X_add_number = 0;
18781
18782       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18783     }
18784
18785   /* Generate a .pdr section.  */
18786   if (IS_ELF && !ECOFF_DEBUGGING && mips_flag_pdr)
18787     {
18788       segT saved_seg = now_seg;
18789       subsegT saved_subseg = now_subseg;
18790       expressionS exp;
18791       char *fragp;
18792
18793 #ifdef md_flush_pending_output
18794       md_flush_pending_output ();
18795 #endif
18796
18797       gas_assert (pdr_seg);
18798       subseg_set (pdr_seg, 0);
18799
18800       /* Write the symbol.  */
18801       exp.X_op = O_symbol;
18802       exp.X_add_symbol = p;
18803       exp.X_add_number = 0;
18804       emit_expr (&exp, 4);
18805
18806       fragp = frag_more (7 * 4);
18807
18808       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18809       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18810       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18811       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18812       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18813       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18814       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18815
18816       subseg_set (saved_seg, saved_subseg);
18817     }
18818 #endif /* OBJ_ELF */
18819
18820   cur_proc_ptr = NULL;
18821 }
18822
18823 /* The .aent and .ent directives.  */
18824
18825 static void
18826 s_mips_ent (int aent)
18827 {
18828   symbolS *symbolP;
18829
18830   symbolP = get_symbol ();
18831   if (*input_line_pointer == ',')
18832     ++input_line_pointer;
18833   SKIP_WHITESPACE ();
18834   if (ISDIGIT (*input_line_pointer)
18835       || *input_line_pointer == '-')
18836     get_number ();
18837
18838   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18839     as_warn (_(".ent or .aent not in text section."));
18840
18841   if (!aent && cur_proc_ptr)
18842     as_warn (_("missing .end"));
18843
18844   if (!aent)
18845     {
18846       /* This function needs its own .frame and .cprestore directives.  */
18847       mips_frame_reg_valid = 0;
18848       mips_cprestore_valid = 0;
18849
18850       cur_proc_ptr = &cur_proc;
18851       memset (cur_proc_ptr, '\0', sizeof (procS));
18852
18853       cur_proc_ptr->func_sym = symbolP;
18854
18855       ++numprocs;
18856
18857       if (debug_type == DEBUG_STABS)
18858         stabs_generate_asm_func (S_GET_NAME (symbolP),
18859                                  S_GET_NAME (symbolP));
18860     }
18861
18862   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18863
18864   demand_empty_rest_of_line ();
18865 }
18866
18867 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18868    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18869    s_mips_frame is used so that we can set the PDR information correctly.
18870    We can't use the ecoff routines because they make reference to the ecoff
18871    symbol table (in the mdebug section).  */
18872
18873 static void
18874 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18875 {
18876 #ifdef OBJ_ELF
18877   if (IS_ELF && !ECOFF_DEBUGGING)
18878     {
18879       long val;
18880
18881       if (cur_proc_ptr == (procS *) NULL)
18882         {
18883           as_warn (_(".frame outside of .ent"));
18884           demand_empty_rest_of_line ();
18885           return;
18886         }
18887
18888       cur_proc_ptr->frame_reg = tc_get_register (1);
18889
18890       SKIP_WHITESPACE ();
18891       if (*input_line_pointer++ != ','
18892           || get_absolute_expression_and_terminator (&val) != ',')
18893         {
18894           as_warn (_("Bad .frame directive"));
18895           --input_line_pointer;
18896           demand_empty_rest_of_line ();
18897           return;
18898         }
18899
18900       cur_proc_ptr->frame_offset = val;
18901       cur_proc_ptr->pc_reg = tc_get_register (0);
18902
18903       demand_empty_rest_of_line ();
18904     }
18905   else
18906 #endif /* OBJ_ELF */
18907     s_ignore (ignore);
18908 }
18909
18910 /* The .fmask and .mask directives. If the mdebug section is present
18911    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18912    embedded targets, s_mips_mask is used so that we can set the PDR
18913    information correctly. We can't use the ecoff routines because they
18914    make reference to the ecoff symbol table (in the mdebug section).  */
18915
18916 static void
18917 s_mips_mask (int reg_type)
18918 {
18919 #ifdef OBJ_ELF
18920   if (IS_ELF && !ECOFF_DEBUGGING)
18921     {
18922       long mask, off;
18923
18924       if (cur_proc_ptr == (procS *) NULL)
18925         {
18926           as_warn (_(".mask/.fmask outside of .ent"));
18927           demand_empty_rest_of_line ();
18928           return;
18929         }
18930
18931       if (get_absolute_expression_and_terminator (&mask) != ',')
18932         {
18933           as_warn (_("Bad .mask/.fmask directive"));
18934           --input_line_pointer;
18935           demand_empty_rest_of_line ();
18936           return;
18937         }
18938
18939       off = get_absolute_expression ();
18940
18941       if (reg_type == 'F')
18942         {
18943           cur_proc_ptr->fpreg_mask = mask;
18944           cur_proc_ptr->fpreg_offset = off;
18945         }
18946       else
18947         {
18948           cur_proc_ptr->reg_mask = mask;
18949           cur_proc_ptr->reg_offset = off;
18950         }
18951
18952       demand_empty_rest_of_line ();
18953     }
18954   else
18955 #endif /* OBJ_ELF */
18956     s_ignore (reg_type);
18957 }
18958
18959 /* A table describing all the processors gas knows about.  Names are
18960    matched in the order listed.
18961
18962    To ease comparison, please keep this table in the same order as
18963    gcc's mips_cpu_info_table[].  */
18964 static const struct mips_cpu_info mips_cpu_info_table[] =
18965 {
18966   /* Entries for generic ISAs */
18967   { "mips1",          MIPS_CPU_IS_ISA,          ISA_MIPS1,      CPU_R3000 },
18968   { "mips2",          MIPS_CPU_IS_ISA,          ISA_MIPS2,      CPU_R6000 },
18969   { "mips3",          MIPS_CPU_IS_ISA,          ISA_MIPS3,      CPU_R4000 },
18970   { "mips4",          MIPS_CPU_IS_ISA,          ISA_MIPS4,      CPU_R8000 },
18971   { "mips5",          MIPS_CPU_IS_ISA,          ISA_MIPS5,      CPU_MIPS5 },
18972   { "mips32",         MIPS_CPU_IS_ISA,          ISA_MIPS32,     CPU_MIPS32 },
18973   { "mips32r2",       MIPS_CPU_IS_ISA,          ISA_MIPS32R2,   CPU_MIPS32R2 },
18974   { "mips64",         MIPS_CPU_IS_ISA,          ISA_MIPS64,     CPU_MIPS64 },
18975   { "mips64r2",       MIPS_CPU_IS_ISA,          ISA_MIPS64R2,   CPU_MIPS64R2 },
18976
18977   /* MIPS I */
18978   { "r3000",          0,                        ISA_MIPS1,      CPU_R3000 },
18979   { "r2000",          0,                        ISA_MIPS1,      CPU_R3000 },
18980   { "r3900",          0,                        ISA_MIPS1,      CPU_R3900 },
18981
18982   /* MIPS II */
18983   { "r6000",          0,                        ISA_MIPS2,      CPU_R6000 },
18984
18985   /* MIPS III */
18986   { "r4000",          0,                        ISA_MIPS3,      CPU_R4000 },
18987   { "r4010",          0,                        ISA_MIPS2,      CPU_R4010 },
18988   { "vr4100",         0,                        ISA_MIPS3,      CPU_VR4100 },
18989   { "vr4111",         0,                        ISA_MIPS3,      CPU_R4111 },
18990   { "vr4120",         0,                        ISA_MIPS3,      CPU_VR4120 },
18991   { "vr4130",         0,                        ISA_MIPS3,      CPU_VR4120 },
18992   { "vr4181",         0,                        ISA_MIPS3,      CPU_R4111 },
18993   { "vr4300",         0,                        ISA_MIPS3,      CPU_R4300 },
18994   { "r4400",          0,                        ISA_MIPS3,      CPU_R4400 },
18995   { "r4600",          0,                        ISA_MIPS3,      CPU_R4600 },
18996   { "orion",          0,                        ISA_MIPS3,      CPU_R4600 },
18997   { "r4650",          0,                        ISA_MIPS3,      CPU_R4650 },
18998   /* ST Microelectronics Loongson 2E and 2F cores */
18999   { "loongson2e",     0,                        ISA_MIPS3,   CPU_LOONGSON_2E },
19000   { "loongson2f",     0,                        ISA_MIPS3,   CPU_LOONGSON_2F },
19001
19002   /* MIPS IV */
19003   { "r8000",          0,                        ISA_MIPS4,      CPU_R8000 },
19004   { "r10000",         0,                        ISA_MIPS4,      CPU_R10000 },
19005   { "r12000",         0,                        ISA_MIPS4,      CPU_R12000 },
19006   { "r14000",         0,                        ISA_MIPS4,      CPU_R14000 },
19007   { "r16000",         0,                        ISA_MIPS4,      CPU_R16000 },
19008   { "vr5000",         0,                        ISA_MIPS4,      CPU_R5000 },
19009   { "vr5400",         0,                        ISA_MIPS4,      CPU_VR5400 },
19010   { "vr5500",         0,                        ISA_MIPS4,      CPU_VR5500 },
19011   { "rm5200",         0,                        ISA_MIPS4,      CPU_R5000 },
19012   { "rm5230",         0,                        ISA_MIPS4,      CPU_R5000 },
19013   { "rm5231",         0,                        ISA_MIPS4,      CPU_R5000 },
19014   { "rm5261",         0,                        ISA_MIPS4,      CPU_R5000 },
19015   { "rm5721",         0,                        ISA_MIPS4,      CPU_R5000 },
19016   { "rm7000",         0,                        ISA_MIPS4,      CPU_RM7000 },
19017   { "rm9000",         0,                        ISA_MIPS4,      CPU_RM9000 },
19018
19019   /* MIPS 32 */
19020   { "4kc",            0,                        ISA_MIPS32,     CPU_MIPS32 },
19021   { "4km",            0,                        ISA_MIPS32,     CPU_MIPS32 },
19022   { "4kp",            0,                        ISA_MIPS32,     CPU_MIPS32 },
19023   { "4ksc",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32,     CPU_MIPS32 },
19024
19025   /* MIPS 32 Release 2 */
19026   { "4kec",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19027   { "4kem",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19028   { "4kep",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19029   { "4ksd",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32R2,   CPU_MIPS32R2 },
19030   { "m4k",            0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19031   { "m4kp",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19032   { "m14k",           MIPS_CPU_ASE_MCU,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19033   { "m14kc",          MIPS_CPU_ASE_MCU,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19034   { "m14ke",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2 | MIPS_CPU_ASE_MCU,
19035                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19036   { "m14kec",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2 | MIPS_CPU_ASE_MCU,
19037                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19038   { "24kc",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19039   { "24kf2_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19040   { "24kf",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19041   { "24kf1_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19042   /* Deprecated forms of the above.  */
19043   { "24kfx",          0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19044   { "24kx",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
19045   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19046   { "24kec",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19047   { "24kef2_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19048   { "24kef",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19049   { "24kef1_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19050   /* Deprecated forms of the above.  */
19051   { "24kefx",         MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19052   { "24kex",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
19053   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19054   { "34kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19055                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19056   { "34kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19057                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19058   { "34kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19059                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19060   { "34kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19061                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19062   /* Deprecated forms of the above.  */
19063   { "34kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19064                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19065   { "34kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19066                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19067   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19068   { "74kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19069                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19070   { "74kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19071                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19072   { "74kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19073                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19074   { "74kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19075                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19076   { "74kf3_2",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19077                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19078   /* Deprecated forms of the above.  */
19079   { "74kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19080                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19081   { "74kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
19082                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19083   /* 1004K cores are multiprocessor versions of the 34K.  */
19084   { "1004kc",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19085                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19086   { "1004kf2_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19087                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19088   { "1004kf",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19089                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19090   { "1004kf1_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
19091                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
19092
19093   /* MIPS 64 */
19094   { "5kc",            0,                        ISA_MIPS64,     CPU_MIPS64 },
19095   { "5kf",            0,                        ISA_MIPS64,     CPU_MIPS64 },
19096   { "20kc",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
19097   { "25kf",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
19098
19099   /* Broadcom SB-1 CPU core */
19100   { "sb1",            MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
19101                                                 ISA_MIPS64,     CPU_SB1 },
19102   /* Broadcom SB-1A CPU core */
19103   { "sb1a",           MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
19104                                                 ISA_MIPS64,     CPU_SB1 },
19105   
19106   { "loongson3a",     0,                        ISA_MIPS64,     CPU_LOONGSON_3A },
19107
19108   /* MIPS 64 Release 2 */
19109
19110   /* Cavium Networks Octeon CPU core */
19111   { "octeon",         0,      ISA_MIPS64R2,   CPU_OCTEON },
19112   { "octeon+",        0,      ISA_MIPS64R2,   CPU_OCTEONP },
19113   { "octeon2",        0,      ISA_MIPS64R2,   CPU_OCTEON2 },
19114
19115   /* RMI Xlr */
19116   { "xlr",            0,      ISA_MIPS64,     CPU_XLR },
19117
19118   /* Broadcom XLP.
19119      XLP is mostly like XLR, with the prominent exception that it is
19120      MIPS64R2 rather than MIPS64.  */
19121   { "xlp",            0,      ISA_MIPS64R2,     CPU_XLR },
19122
19123   /* End marker */
19124   { NULL, 0, 0, 0 }
19125 };
19126
19127
19128 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19129    with a final "000" replaced by "k".  Ignore case.
19130
19131    Note: this function is shared between GCC and GAS.  */
19132
19133 static bfd_boolean
19134 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19135 {
19136   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19137     given++, canonical++;
19138
19139   return ((*given == 0 && *canonical == 0)
19140           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19141 }
19142
19143
19144 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19145    CPU name.  We've traditionally allowed a lot of variation here.
19146
19147    Note: this function is shared between GCC and GAS.  */
19148
19149 static bfd_boolean
19150 mips_matching_cpu_name_p (const char *canonical, const char *given)
19151 {
19152   /* First see if the name matches exactly, or with a final "000"
19153      turned into "k".  */
19154   if (mips_strict_matching_cpu_name_p (canonical, given))
19155     return TRUE;
19156
19157   /* If not, try comparing based on numerical designation alone.
19158      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19159   if (TOLOWER (*given) == 'r')
19160     given++;
19161   if (!ISDIGIT (*given))
19162     return FALSE;
19163
19164   /* Skip over some well-known prefixes in the canonical name,
19165      hoping to find a number there too.  */
19166   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19167     canonical += 2;
19168   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19169     canonical += 2;
19170   else if (TOLOWER (canonical[0]) == 'r')
19171     canonical += 1;
19172
19173   return mips_strict_matching_cpu_name_p (canonical, given);
19174 }
19175
19176
19177 /* Parse an option that takes the name of a processor as its argument.
19178    OPTION is the name of the option and CPU_STRING is the argument.
19179    Return the corresponding processor enumeration if the CPU_STRING is
19180    recognized, otherwise report an error and return null.
19181
19182    A similar function exists in GCC.  */
19183
19184 static const struct mips_cpu_info *
19185 mips_parse_cpu (const char *option, const char *cpu_string)
19186 {
19187   const struct mips_cpu_info *p;
19188
19189   /* 'from-abi' selects the most compatible architecture for the given
19190      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19191      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19192      version.  Look first at the -mgp options, if given, otherwise base
19193      the choice on MIPS_DEFAULT_64BIT.
19194
19195      Treat NO_ABI like the EABIs.  One reason to do this is that the
19196      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19197      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19198      'mips64', just as we did in the days before 'from-abi'.  */
19199   if (strcasecmp (cpu_string, "from-abi") == 0)
19200     {
19201       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19202         return mips_cpu_info_from_isa (ISA_MIPS1);
19203
19204       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19205         return mips_cpu_info_from_isa (ISA_MIPS3);
19206
19207       if (file_mips_gp32 >= 0)
19208         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19209
19210       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19211                                      ? ISA_MIPS3
19212                                      : ISA_MIPS1);
19213     }
19214
19215   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19216   if (strcasecmp (cpu_string, "default") == 0)
19217     return 0;
19218
19219   for (p = mips_cpu_info_table; p->name != 0; p++)
19220     if (mips_matching_cpu_name_p (p->name, cpu_string))
19221       return p;
19222
19223   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19224   return 0;
19225 }
19226
19227 /* Return the canonical processor information for ISA (a member of the
19228    ISA_MIPS* enumeration).  */
19229
19230 static const struct mips_cpu_info *
19231 mips_cpu_info_from_isa (int isa)
19232 {
19233   int i;
19234
19235   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19236     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19237         && isa == mips_cpu_info_table[i].isa)
19238       return (&mips_cpu_info_table[i]);
19239
19240   return NULL;
19241 }
19242
19243 static const struct mips_cpu_info *
19244 mips_cpu_info_from_arch (int arch)
19245 {
19246   int i;
19247
19248   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19249     if (arch == mips_cpu_info_table[i].cpu)
19250       return (&mips_cpu_info_table[i]);
19251
19252   return NULL;
19253 }
19254 \f
19255 static void
19256 show (FILE *stream, const char *string, int *col_p, int *first_p)
19257 {
19258   if (*first_p)
19259     {
19260       fprintf (stream, "%24s", "");
19261       *col_p = 24;
19262     }
19263   else
19264     {
19265       fprintf (stream, ", ");
19266       *col_p += 2;
19267     }
19268
19269   if (*col_p + strlen (string) > 72)
19270     {
19271       fprintf (stream, "\n%24s", "");
19272       *col_p = 24;
19273     }
19274
19275   fprintf (stream, "%s", string);
19276   *col_p += strlen (string);
19277
19278   *first_p = 0;
19279 }
19280
19281 void
19282 md_show_usage (FILE *stream)
19283 {
19284   int column, first;
19285   size_t i;
19286
19287   fprintf (stream, _("\
19288 MIPS options:\n\
19289 -EB                     generate big endian output\n\
19290 -EL                     generate little endian output\n\
19291 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19292 -G NUM                  allow referencing objects up to NUM bytes\n\
19293                         implicitly with the gp register [default 8]\n"));
19294   fprintf (stream, _("\
19295 -mips1                  generate MIPS ISA I instructions\n\
19296 -mips2                  generate MIPS ISA II instructions\n\
19297 -mips3                  generate MIPS ISA III instructions\n\
19298 -mips4                  generate MIPS ISA IV instructions\n\
19299 -mips5                  generate MIPS ISA V instructions\n\
19300 -mips32                 generate MIPS32 ISA instructions\n\
19301 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19302 -mips64                 generate MIPS64 ISA instructions\n\
19303 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19304 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19305
19306   first = 1;
19307
19308   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19309     show (stream, mips_cpu_info_table[i].name, &column, &first);
19310   show (stream, "from-abi", &column, &first);
19311   fputc ('\n', stream);
19312
19313   fprintf (stream, _("\
19314 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19315 -no-mCPU                don't generate code specific to CPU.\n\
19316                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19317
19318   first = 1;
19319
19320   show (stream, "3900", &column, &first);
19321   show (stream, "4010", &column, &first);
19322   show (stream, "4100", &column, &first);
19323   show (stream, "4650", &column, &first);
19324   fputc ('\n', stream);
19325
19326   fprintf (stream, _("\
19327 -mips16                 generate mips16 instructions\n\
19328 -no-mips16              do not generate mips16 instructions\n"));
19329   fprintf (stream, _("\
19330 -mmicromips             generate microMIPS instructions\n\
19331 -mno-micromips          do not generate microMIPS instructions\n"));
19332   fprintf (stream, _("\
19333 -msmartmips             generate smartmips instructions\n\
19334 -mno-smartmips          do not generate smartmips instructions\n"));  
19335   fprintf (stream, _("\
19336 -mdsp                   generate DSP instructions\n\
19337 -mno-dsp                do not generate DSP instructions\n"));
19338   fprintf (stream, _("\
19339 -mdspr2                 generate DSP R2 instructions\n\
19340 -mno-dspr2              do not generate DSP R2 instructions\n"));
19341   fprintf (stream, _("\
19342 -mmt                    generate MT instructions\n\
19343 -mno-mt                 do not generate MT instructions\n"));
19344   fprintf (stream, _("\
19345 -mmcu                   generate MCU instructions\n\
19346 -mno-mcu                do not generate MCU instructions\n"));
19347   fprintf (stream, _("\
19348 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19349 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19350 -mfix-vr4120            work around certain VR4120 errata\n\
19351 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19352 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19353 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19354 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19355 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19356 -msym32                 assume all symbols have 32-bit values\n\
19357 -O0                     remove unneeded NOPs, do not swap branches\n\
19358 -O                      remove unneeded NOPs and swap branches\n\
19359 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19360 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19361   fprintf (stream, _("\
19362 -mhard-float            allow floating-point instructions\n\
19363 -msoft-float            do not allow floating-point instructions\n\
19364 -msingle-float          only allow 32-bit floating-point operations\n\
19365 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19366 --[no-]construct-floats [dis]allow floating point values to be constructed\n"
19367                      ));
19368 #ifdef OBJ_ELF
19369   fprintf (stream, _("\
19370 -KPIC, -call_shared     generate SVR4 position independent code\n\
19371 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19372 -mvxworks-pic           generate VxWorks position independent code\n\
19373 -non_shared             do not generate code that can operate with DSOs\n\
19374 -xgot                   assume a 32 bit GOT\n\
19375 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19376 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19377                         position dependent (non shared) code\n\
19378 -mabi=ABI               create ABI conformant object file for:\n"));
19379
19380   first = 1;
19381
19382   show (stream, "32", &column, &first);
19383   show (stream, "o64", &column, &first);
19384   show (stream, "n32", &column, &first);
19385   show (stream, "64", &column, &first);
19386   show (stream, "eabi", &column, &first);
19387
19388   fputc ('\n', stream);
19389
19390   fprintf (stream, _("\
19391 -32                     create o32 ABI object file (default)\n\
19392 -n32                    create n32 ABI object file\n\
19393 -64                     create 64 ABI object file\n"));
19394 #endif
19395 }
19396
19397 #ifdef TE_IRIX
19398 enum dwarf2_format
19399 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19400 {
19401   if (HAVE_64BIT_SYMBOLS)
19402     return dwarf2_format_64bit_irix;
19403   else
19404     return dwarf2_format_32bit;
19405 }
19406 #endif
19407
19408 int
19409 mips_dwarf2_addr_size (void)
19410 {
19411   if (HAVE_64BIT_OBJECTS)
19412     return 8;
19413   else
19414     return 4;
19415 }
19416
19417 /* Standard calling conventions leave the CFA at SP on entry.  */
19418 void
19419 mips_cfi_frame_initial_instructions (void)
19420 {
19421   cfi_add_CFA_def_cfa_register (SP);
19422 }
19423
19424 int
19425 tc_mips_regname_to_dw2regnum (char *regname)
19426 {
19427   unsigned int regnum = -1;
19428   unsigned int reg;
19429
19430   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19431     regnum = reg;
19432
19433   return regnum;
19434 }