bfd/
[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
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   /* Whether we are assembling for the mips16 processor.  0 if we are
222      not, 1 if we are, and -1 if the value has not been initialized.
223      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
224      -nomips16 command line options, and the default CPU.  */
225   int mips16;
226   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
227      1 if we are, and -1 if the value has not been initialized.  Changed
228      by `.set micromips' and `.set nomicromips', and the -mmicromips
229      and -mno-micromips command line options, and the default CPU.  */
230   int micromips;
231   /* Non-zero if we should not reorder instructions.  Changed by `.set
232      reorder' and `.set noreorder'.  */
233   int noreorder;
234   /* Non-zero if we should not permit the register designated "assembler
235      temporary" to be used in instructions.  The value is the register
236      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
237      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
238   unsigned int at;
239   /* Non-zero if we should warn when a macro instruction expands into
240      more than one machine instruction.  Changed by `.set nomacro' and
241      `.set macro'.  */
242   int warn_about_macros;
243   /* Non-zero if we should not move instructions.  Changed by `.set
244      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
245   int nomove;
246   /* Non-zero if we should not optimize branches by moving the target
247      of the branch into the delay slot.  Actually, we don't perform
248      this optimization anyhow.  Changed by `.set bopt' and `.set
249      nobopt'.  */
250   int nobopt;
251   /* Non-zero if we should not autoextend mips16 instructions.
252      Changed by `.set autoextend' and `.set noautoextend'.  */
253   int noautoextend;
254   /* Restrict general purpose registers and floating point registers
255      to 32 bit.  This is initially determined when -mgp32 or -mfp32
256      is passed but can changed if the assembler code uses .set mipsN.  */
257   int gp32;
258   int fp32;
259   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
260      command line option, and the default CPU.  */
261   int arch;
262   /* True if ".set sym32" is in effect.  */
263   bfd_boolean sym32;
264   /* True if floating-point operations are not allowed.  Changed by .set
265      softfloat or .set hardfloat, by command line options -msoft-float or
266      -mhard-float.  The default is false.  */
267   bfd_boolean soft_float;
268
269   /* True if only single-precision floating-point operations are allowed.
270      Changed by .set singlefloat or .set doublefloat, command-line options
271      -msingle-float or -mdouble-float.  The default is false.  */
272   bfd_boolean single_float;
273 };
274
275 /* This is the struct we use to hold the current set of options.  Note
276    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
277    -1 to indicate that they have not been initialized.  */
278
279 /* True if -mgp32 was passed.  */
280 static int file_mips_gp32 = -1;
281
282 /* True if -mfp32 was passed.  */
283 static int file_mips_fp32 = -1;
284
285 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
286 static int file_mips_soft_float = 0;
287
288 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
289 static int file_mips_single_float = 0;
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase_mips3d */ -1, /* ase_mdmx */ -1,
294   /* ase_smartmips */ 0, /* ase_dsp */ -1, /* ase_dspr2 */ -1, /* ase_mt */ -1,
295   /* mips16 */ -1, /* micromips */ -1, /* noreorder */ 0, /* at */ ATREG,
296   /* warn_about_macros */ 0, /* nomove */ 0, /* nobopt */ 0,
297   /* noautoextend */ 0, /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN,
298   /* sym32 */ FALSE, /* soft_float */ FALSE, /* single_float */ FALSE
299 };
300
301 /* These variables are filled in with the masks of registers used.
302    The object format code reads them and puts them in the appropriate
303    place.  */
304 unsigned long mips_gprmask;
305 unsigned long mips_cprmask[4];
306
307 /* MIPS ISA we are using for this output file.  */
308 static int file_mips_isa = ISA_UNKNOWN;
309
310 /* True if any MIPS16 code was produced.  */
311 static int file_ase_mips16;
312
313 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
314                               || mips_opts.isa == ISA_MIPS32R2          \
315                               || mips_opts.isa == ISA_MIPS64            \
316                               || mips_opts.isa == ISA_MIPS64R2)
317
318 /* True if any microMIPS code was produced.  */
319 static int file_ase_micromips;
320
321 /* True if we want to create R_MIPS_JALR for jalr $25.  */
322 #ifdef TE_IRIX
323 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
324 #else
325 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
326    because there's no place for any addend, the only acceptable
327    expression is a bare symbol.  */
328 #define MIPS_JALR_HINT_P(EXPR) \
329   (!HAVE_IN_PLACE_ADDENDS \
330    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
331 #endif
332
333 /* True if -mips3d was passed or implied by arguments passed on the
334    command line (e.g., by -march).  */
335 static int file_ase_mips3d;
336
337 /* True if -mdmx was passed or implied by arguments passed on the
338    command line (e.g., by -march).  */
339 static int file_ase_mdmx;
340
341 /* True if -msmartmips was passed or implied by arguments passed on the
342    command line (e.g., by -march).  */
343 static int file_ase_smartmips;
344
345 #define ISA_SUPPORTS_SMARTMIPS (mips_opts.isa == ISA_MIPS32             \
346                                 || mips_opts.isa == ISA_MIPS32R2)
347
348 /* True if -mdsp was passed or implied by arguments passed on the
349    command line (e.g., by -march).  */
350 static int file_ase_dsp;
351
352 #define ISA_SUPPORTS_DSP_ASE (mips_opts.isa == ISA_MIPS32R2             \
353                               || mips_opts.isa == ISA_MIPS64R2)
354
355 #define ISA_SUPPORTS_DSP64_ASE (mips_opts.isa == ISA_MIPS64R2)
356
357 /* True if -mdspr2 was passed or implied by arguments passed on the
358    command line (e.g., by -march).  */
359 static int file_ase_dspr2;
360
361 #define ISA_SUPPORTS_DSPR2_ASE (mips_opts.isa == ISA_MIPS32R2           \
362                                 || mips_opts.isa == ISA_MIPS64R2)
363
364 /* True if -mmt was passed or implied by arguments passed on the
365    command line (e.g., by -march).  */
366 static int file_ase_mt;
367
368 #define ISA_SUPPORTS_MT_ASE (mips_opts.isa == ISA_MIPS32R2              \
369                              || mips_opts.isa == ISA_MIPS64R2)
370
371 /* The argument of the -march= flag.  The architecture we are assembling.  */
372 static int file_mips_arch = CPU_UNKNOWN;
373 static const char *mips_arch_string;
374
375 /* The argument of the -mtune= flag.  The architecture for which we
376    are optimizing.  */
377 static int mips_tune = CPU_UNKNOWN;
378 static const char *mips_tune_string;
379
380 /* True when generating 32-bit code for a 64-bit processor.  */
381 static int mips_32bitmode = 0;
382
383 /* True if the given ABI requires 32-bit registers.  */
384 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
385
386 /* Likewise 64-bit registers.  */
387 #define ABI_NEEDS_64BIT_REGS(ABI)       \
388   ((ABI) == N32_ABI                     \
389    || (ABI) == N64_ABI                  \
390    || (ABI) == O64_ABI)
391
392 /*  Return true if ISA supports 64 bit wide gp registers.  */
393 #define ISA_HAS_64BIT_REGS(ISA)         \
394   ((ISA) == ISA_MIPS3                   \
395    || (ISA) == ISA_MIPS4                \
396    || (ISA) == ISA_MIPS5                \
397    || (ISA) == ISA_MIPS64               \
398    || (ISA) == ISA_MIPS64R2)
399
400 /*  Return true if ISA supports 64 bit wide float registers.  */
401 #define ISA_HAS_64BIT_FPRS(ISA)         \
402   ((ISA) == ISA_MIPS3                   \
403    || (ISA) == ISA_MIPS4                \
404    || (ISA) == ISA_MIPS5                \
405    || (ISA) == ISA_MIPS32R2             \
406    || (ISA) == ISA_MIPS64               \
407    || (ISA) == ISA_MIPS64R2)
408
409 /* Return true if ISA supports 64-bit right rotate (dror et al.)
410    instructions.  */
411 #define ISA_HAS_DROR(ISA)               \
412   ((ISA) == ISA_MIPS64R2                \
413    || (mips_opts.micromips              \
414        && ISA_HAS_64BIT_REGS (ISA))     \
415    )
416
417 /* Return true if ISA supports 32-bit right rotate (ror et al.)
418    instructions.  */
419 #define ISA_HAS_ROR(ISA)                \
420   ((ISA) == ISA_MIPS32R2                \
421    || (ISA) == ISA_MIPS64R2             \
422    || mips_opts.ase_smartmips           \
423    || mips_opts.micromips               \
424    )
425
426 /* Return true if ISA supports single-precision floats in odd registers.  */
427 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
428   ((ISA) == ISA_MIPS32                  \
429    || (ISA) == ISA_MIPS32R2             \
430    || (ISA) == ISA_MIPS64               \
431    || (ISA) == ISA_MIPS64R2)
432
433 /* Return true if ISA supports move to/from high part of a 64-bit
434    floating-point register. */
435 #define ISA_HAS_MXHC1(ISA)              \
436   ((ISA) == ISA_MIPS32R2                \
437    || (ISA) == ISA_MIPS64R2)
438
439 #define HAVE_32BIT_GPRS                            \
440     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
441
442 #define HAVE_32BIT_FPRS                            \
443     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
444
445 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
446 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
447
448 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
449
450 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
451
452 /* True if relocations are stored in-place.  */
453 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
454
455 /* The ABI-derived address size.  */
456 #define HAVE_64BIT_ADDRESSES \
457   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
458 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
459
460 /* The size of symbolic constants (i.e., expressions of the form
461    "SYMBOL" or "SYMBOL + OFFSET").  */
462 #define HAVE_32BIT_SYMBOLS \
463   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
464 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
465
466 /* Addresses are loaded in different ways, depending on the address size
467    in use.  The n32 ABI Documentation also mandates the use of additions
468    with overflow checking, but existing implementations don't follow it.  */
469 #define ADDRESS_ADD_INSN                                                \
470    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
471
472 #define ADDRESS_ADDI_INSN                                               \
473    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
474
475 #define ADDRESS_LOAD_INSN                                               \
476    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
477
478 #define ADDRESS_STORE_INSN                                              \
479    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
480
481 /* Return true if the given CPU supports the MIPS16 ASE.  */
482 #define CPU_HAS_MIPS16(cpu)                                             \
483    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
484     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
485
486 /* Return true if the given CPU supports microMIPS.  */
487 #define CPU_HAS_MICROMIPS(cpu)  0
488
489 /* True if CPU has a dror instruction.  */
490 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
491
492 /* True if CPU has a ror instruction.  */
493 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
494
495 /* True if CPU has seq/sne and seqi/snei instructions.  */
496 #define CPU_HAS_SEQ(CPU)        ((CPU) == CPU_OCTEON)
497
498 /* True if CPU does not implement the all the coprocessor insns.  For these
499    CPUs only those COP insns are accepted that are explicitly marked to be
500    available on the CPU.  ISA membership for COP insns is ignored.  */
501 #define NO_ISA_COP(CPU)         ((CPU) == CPU_OCTEON)
502
503 /* True if mflo and mfhi can be immediately followed by instructions
504    which write to the HI and LO registers.
505
506    According to MIPS specifications, MIPS ISAs I, II, and III need
507    (at least) two instructions between the reads of HI/LO and
508    instructions which write them, and later ISAs do not.  Contradicting
509    the MIPS specifications, some MIPS IV processor user manuals (e.g.
510    the UM for the NEC Vr5000) document needing the instructions between
511    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
512    MIPS64 and later ISAs to have the interlocks, plus any specific
513    earlier-ISA CPUs for which CPU documentation declares that the
514    instructions are really interlocked.  */
515 #define hilo_interlocks \
516   (mips_opts.isa == ISA_MIPS32                        \
517    || mips_opts.isa == ISA_MIPS32R2                   \
518    || mips_opts.isa == ISA_MIPS64                     \
519    || mips_opts.isa == ISA_MIPS64R2                   \
520    || mips_opts.arch == CPU_R4010                     \
521    || mips_opts.arch == CPU_R10000                    \
522    || mips_opts.arch == CPU_R12000                    \
523    || mips_opts.arch == CPU_R14000                    \
524    || mips_opts.arch == CPU_R16000                    \
525    || mips_opts.arch == CPU_RM7000                    \
526    || mips_opts.arch == CPU_VR5500                    \
527    || mips_opts.micromips                             \
528    )
529
530 /* Whether the processor uses hardware interlocks to protect reads
531    from the GPRs after they are loaded from memory, and thus does not
532    require nops to be inserted.  This applies to instructions marked
533    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
534    level I and microMIPS mode instructions are always interlocked.  */
535 #define gpr_interlocks                                \
536   (mips_opts.isa != ISA_MIPS1                         \
537    || mips_opts.arch == CPU_R3900                     \
538    || mips_opts.micromips                             \
539    )
540
541 /* Whether the processor uses hardware interlocks to avoid delays
542    required by coprocessor instructions, and thus does not require
543    nops to be inserted.  This applies to instructions marked
544    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
545    between instructions marked INSN_WRITE_COND_CODE and ones marked
546    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
547    levels I, II, and III and microMIPS mode instructions are always
548    interlocked.  */
549 /* Itbl support may require additional care here.  */
550 #define cop_interlocks                                \
551   ((mips_opts.isa != ISA_MIPS1                        \
552     && mips_opts.isa != ISA_MIPS2                     \
553     && mips_opts.isa != ISA_MIPS3)                    \
554    || mips_opts.arch == CPU_R4300                     \
555    || mips_opts.micromips                             \
556    )
557
558 /* Whether the processor uses hardware interlocks to protect reads
559    from coprocessor registers after they are loaded from memory, and
560    thus does not require nops to be inserted.  This applies to
561    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
562    requires at MIPS ISA level I and microMIPS mode instructions are
563    always interlocked.  */
564 #define cop_mem_interlocks                            \
565   (mips_opts.isa != ISA_MIPS1                         \
566    || mips_opts.micromips                             \
567    )
568
569 /* Is this a mfhi or mflo instruction?  */
570 #define MF_HILO_INSN(PINFO) \
571   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
572
573 /* Returns true for a (non floating-point) coprocessor instruction.  Reading
574    or writing the condition code is only possible on the coprocessors and
575    these insns are not marked with INSN_COP.  Thus for these insns use the
576    condition-code flags.  */
577 #define COP_INSN(PINFO)                                                 \
578   (PINFO != INSN_MACRO                                                  \
579    && ((PINFO) & (FP_S | FP_D)) == 0                                    \
580    && ((PINFO) & (INSN_COP | INSN_READ_COND_CODE | INSN_WRITE_COND_CODE)))
581
582 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
583    has been selected.  This implies, in particular, that addresses of text
584    labels have their LSB set.  */
585 #define HAVE_CODE_COMPRESSION                                           \
586   ((mips_opts.mips16 | mips_opts.micromips) != 0)
587
588 /* MIPS PIC level.  */
589
590 enum mips_pic_level mips_pic;
591
592 /* 1 if we should generate 32 bit offsets from the $gp register in
593    SVR4_PIC mode.  Currently has no meaning in other modes.  */
594 static int mips_big_got = 0;
595
596 /* 1 if trap instructions should used for overflow rather than break
597    instructions.  */
598 static int mips_trap = 0;
599
600 /* 1 if double width floating point constants should not be constructed
601    by assembling two single width halves into two single width floating
602    point registers which just happen to alias the double width destination
603    register.  On some architectures this aliasing can be disabled by a bit
604    in the status register, and the setting of this bit cannot be determined
605    automatically at assemble time.  */
606 static int mips_disable_float_construction;
607
608 /* Non-zero if any .set noreorder directives were used.  */
609
610 static int mips_any_noreorder;
611
612 /* Non-zero if nops should be inserted when the register referenced in
613    an mfhi/mflo instruction is read in the next two instructions.  */
614 static int mips_7000_hilo_fix;
615
616 /* The size of objects in the small data section.  */
617 static unsigned int g_switch_value = 8;
618 /* Whether the -G option was used.  */
619 static int g_switch_seen = 0;
620
621 #define N_RMASK 0xc4
622 #define N_VFP   0xd4
623
624 /* If we can determine in advance that GP optimization won't be
625    possible, we can skip the relaxation stuff that tries to produce
626    GP-relative references.  This makes delay slot optimization work
627    better.
628
629    This function can only provide a guess, but it seems to work for
630    gcc output.  It needs to guess right for gcc, otherwise gcc
631    will put what it thinks is a GP-relative instruction in a branch
632    delay slot.
633
634    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
635    fixed it for the non-PIC mode.  KR 95/04/07  */
636 static int nopic_need_relax (symbolS *, int);
637
638 /* handle of the OPCODE hash table */
639 static struct hash_control *op_hash = NULL;
640
641 /* The opcode hash table we use for the mips16.  */
642 static struct hash_control *mips16_op_hash = NULL;
643
644 /* The opcode hash table we use for the microMIPS ASE.  */
645 static struct hash_control *micromips_op_hash = NULL;
646
647 /* This array holds the chars that always start a comment.  If the
648     pre-processor is disabled, these aren't very useful */
649 const char comment_chars[] = "#";
650
651 /* This array holds the chars that only start a comment at the beginning of
652    a line.  If the line seems to have the form '# 123 filename'
653    .line and .file directives will appear in the pre-processed output */
654 /* Note that input_file.c hand checks for '#' at the beginning of the
655    first line of the input file.  This is because the compiler outputs
656    #NO_APP at the beginning of its output.  */
657 /* Also note that C style comments are always supported.  */
658 const char line_comment_chars[] = "#";
659
660 /* This array holds machine specific line separator characters.  */
661 const char line_separator_chars[] = ";";
662
663 /* Chars that can be used to separate mant from exp in floating point nums */
664 const char EXP_CHARS[] = "eE";
665
666 /* Chars that mean this number is a floating point constant */
667 /* As in 0f12.456 */
668 /* or    0d1.2345e12 */
669 const char FLT_CHARS[] = "rRsSfFdDxXpP";
670
671 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
672    changed in read.c .  Ideally it shouldn't have to know about it at all,
673    but nothing is ideal around here.
674  */
675
676 static char *insn_error;
677
678 static int auto_align = 1;
679
680 /* When outputting SVR4 PIC code, the assembler needs to know the
681    offset in the stack frame from which to restore the $gp register.
682    This is set by the .cprestore pseudo-op, and saved in this
683    variable.  */
684 static offsetT mips_cprestore_offset = -1;
685
686 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
687    more optimizations, it can use a register value instead of a memory-saved
688    offset and even an other register than $gp as global pointer.  */
689 static offsetT mips_cpreturn_offset = -1;
690 static int mips_cpreturn_register = -1;
691 static int mips_gp_register = GP;
692 static int mips_gprel_offset = 0;
693
694 /* Whether mips_cprestore_offset has been set in the current function
695    (or whether it has already been warned about, if not).  */
696 static int mips_cprestore_valid = 0;
697
698 /* This is the register which holds the stack frame, as set by the
699    .frame pseudo-op.  This is needed to implement .cprestore.  */
700 static int mips_frame_reg = SP;
701
702 /* Whether mips_frame_reg has been set in the current function
703    (or whether it has already been warned about, if not).  */
704 static int mips_frame_reg_valid = 0;
705
706 /* To output NOP instructions correctly, we need to keep information
707    about the previous two instructions.  */
708
709 /* Whether we are optimizing.  The default value of 2 means to remove
710    unneeded NOPs and swap branch instructions when possible.  A value
711    of 1 means to not swap branches.  A value of 0 means to always
712    insert NOPs.  */
713 static int mips_optimize = 2;
714
715 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
716    equivalent to seeing no -g option at all.  */
717 static int mips_debug = 0;
718
719 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
720 #define MAX_VR4130_NOPS 4
721
722 /* The maximum number of NOPs needed to fill delay slots.  */
723 #define MAX_DELAY_NOPS 2
724
725 /* The maximum number of NOPs needed for any purpose.  */
726 #define MAX_NOPS 4
727
728 /* A list of previous instructions, with index 0 being the most recent.
729    We need to look back MAX_NOPS instructions when filling delay slots
730    or working around processor errata.  We need to look back one
731    instruction further if we're thinking about using history[0] to
732    fill a branch delay slot.  */
733 static struct mips_cl_insn history[1 + MAX_NOPS];
734
735 /* Nop instructions used by emit_nop.  */
736 static struct mips_cl_insn nop_insn;
737 static struct mips_cl_insn mips16_nop_insn;
738 static struct mips_cl_insn micromips_nop16_insn;
739 static struct mips_cl_insn micromips_nop32_insn;
740
741 /* The appropriate nop for the current mode.  */
742 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn \
743                   : (mips_opts.micromips ? &micromips_nop16_insn : &nop_insn))
744
745 /* The size of NOP_INSN in bytes.  */
746 #define NOP_INSN_SIZE (HAVE_CODE_COMPRESSION ? 2 : 4)
747
748 /* If this is set, it points to a frag holding nop instructions which
749    were inserted before the start of a noreorder section.  If those
750    nops turn out to be unnecessary, the size of the frag can be
751    decreased.  */
752 static fragS *prev_nop_frag;
753
754 /* The number of nop instructions we created in prev_nop_frag.  */
755 static int prev_nop_frag_holds;
756
757 /* The number of nop instructions that we know we need in
758    prev_nop_frag.  */
759 static int prev_nop_frag_required;
760
761 /* The number of instructions we've seen since prev_nop_frag.  */
762 static int prev_nop_frag_since;
763
764 /* For ECOFF and ELF, relocations against symbols are done in two
765    parts, with a HI relocation and a LO relocation.  Each relocation
766    has only 16 bits of space to store an addend.  This means that in
767    order for the linker to handle carries correctly, it must be able
768    to locate both the HI and the LO relocation.  This means that the
769    relocations must appear in order in the relocation table.
770
771    In order to implement this, we keep track of each unmatched HI
772    relocation.  We then sort them so that they immediately precede the
773    corresponding LO relocation.  */
774
775 struct mips_hi_fixup
776 {
777   /* Next HI fixup.  */
778   struct mips_hi_fixup *next;
779   /* This fixup.  */
780   fixS *fixp;
781   /* The section this fixup is in.  */
782   segT seg;
783 };
784
785 /* The list of unmatched HI relocs.  */
786
787 static struct mips_hi_fixup *mips_hi_fixup_list;
788
789 /* The frag containing the last explicit relocation operator.
790    Null if explicit relocations have not been used.  */
791
792 static fragS *prev_reloc_op_frag;
793
794 /* Map normal MIPS register numbers to mips16 register numbers.  */
795
796 #define X ILLEGAL_REG
797 static const int mips32_to_16_reg_map[] =
798 {
799   X, X, 2, 3, 4, 5, 6, 7,
800   X, X, X, X, X, X, X, X,
801   0, 1, X, X, X, X, X, X,
802   X, X, X, X, X, X, X, X
803 };
804 #undef X
805
806 /* Map mips16 register numbers to normal MIPS register numbers.  */
807
808 static const unsigned int mips16_to_32_reg_map[] =
809 {
810   16, 17, 2, 3, 4, 5, 6, 7
811 };
812
813 /* Map normal MIPS register numbers to microMIPS register numbers.  */
814
815 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
816 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
817 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
818 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
819 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
820 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
821 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
822
823 #define X ILLEGAL_REG
824 /* reg type h: 4, 5, 6.  */
825 static const int mips32_to_micromips_reg_h_map[] =
826 {
827   X, X, X, X, 4, 5, 6, X,
828   X, X, X, X, X, X, X, X,
829   X, X, X, X, X, X, X, X,
830   X, X, X, X, X, X, X, X
831 };
832
833 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
834 static const int mips32_to_micromips_reg_m_map[] =
835 {
836   0, X, 2, 3, X, X, X, X,
837   X, X, X, X, X, X, X, X,
838   4, 1, 5, 6, 7, X, X, X,
839   X, X, X, X, X, X, X, X
840 };
841
842 /* reg type q: 0, 2-7. 17.  */
843 static const int mips32_to_micromips_reg_q_map[] =
844 {
845   0, X, 2, 3, 4, 5, 6, 7,
846   X, X, X, X, X, X, X, X,
847   X, 1, X, X, X, X, X, X,
848   X, X, X, X, X, X, X, X
849 };
850
851 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
852 #undef X
853
854 /* Map microMIPS register numbers to normal MIPS register numbers.  */
855
856 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
857 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
858 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
859 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
860 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
861 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
862
863 /* The microMIPS registers with type h.  */
864 static const unsigned int micromips_to_32_reg_h_map[] =
865 {
866   5, 5, 6, 4, 4, 4, 4, 4
867 };
868
869 /* The microMIPS registers with type i.  */
870 static const unsigned int micromips_to_32_reg_i_map[] =
871 {
872   6, 7, 7, 21, 22, 5, 6, 7
873 };
874
875 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
876
877 /* The microMIPS registers with type m.  */
878 static const unsigned int micromips_to_32_reg_m_map[] =
879 {
880   0, 17, 2, 3, 16, 18, 19, 20
881 };
882
883 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
884
885 /* The microMIPS registers with type q.  */
886 static const unsigned int micromips_to_32_reg_q_map[] =
887 {
888   0, 17, 2, 3, 4, 5, 6, 7
889 };
890
891 /* microMIPS imm type B.  */
892 static const int micromips_imm_b_map[] =
893 {
894   1, 4, 8, 12, 16, 20, 24, -1
895 };
896
897 /* microMIPS imm type C.  */
898 static const int micromips_imm_c_map[] =
899 {
900   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
901 };
902
903 /* Classifies the kind of instructions we're interested in when
904    implementing -mfix-vr4120.  */
905 enum fix_vr4120_class
906 {
907   FIX_VR4120_MACC,
908   FIX_VR4120_DMACC,
909   FIX_VR4120_MULT,
910   FIX_VR4120_DMULT,
911   FIX_VR4120_DIV,
912   FIX_VR4120_MTHILO,
913   NUM_FIX_VR4120_CLASSES
914 };
915
916 /* ...likewise -mfix-loongson2f-jump.  */
917 static bfd_boolean mips_fix_loongson2f_jump;
918
919 /* ...likewise -mfix-loongson2f-nop.  */
920 static bfd_boolean mips_fix_loongson2f_nop;
921
922 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
923 static bfd_boolean mips_fix_loongson2f;
924
925 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
926    there must be at least one other instruction between an instruction
927    of type X and an instruction of type Y.  */
928 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
929
930 /* True if -mfix-vr4120 is in force.  */
931 static int mips_fix_vr4120;
932
933 /* ...likewise -mfix-vr4130.  */
934 static int mips_fix_vr4130;
935
936 /* ...likewise -mfix-24k.  */
937 static int mips_fix_24k;
938
939 /* ...likewise -mfix-cn63xxp1 */
940 static bfd_boolean mips_fix_cn63xxp1;
941
942 /* We don't relax branches by default, since this causes us to expand
943    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
944    fail to compute the offset before expanding the macro to the most
945    efficient expansion.  */
946
947 static int mips_relax_branch;
948 \f
949 /* The expansion of many macros depends on the type of symbol that
950    they refer to.  For example, when generating position-dependent code,
951    a macro that refers to a symbol may have two different expansions,
952    one which uses GP-relative addresses and one which uses absolute
953    addresses.  When generating SVR4-style PIC, a macro may have
954    different expansions for local and global symbols.
955
956    We handle these situations by generating both sequences and putting
957    them in variant frags.  In position-dependent code, the first sequence
958    will be the GP-relative one and the second sequence will be the
959    absolute one.  In SVR4 PIC, the first sequence will be for global
960    symbols and the second will be for local symbols.
961
962    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
963    SECOND are the lengths of the two sequences in bytes.  These fields
964    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
965    the subtype has the following flags:
966
967    RELAX_USE_SECOND
968         Set if it has been decided that we should use the second
969         sequence instead of the first.
970
971    RELAX_SECOND_LONGER
972         Set in the first variant frag if the macro's second implementation
973         is longer than its first.  This refers to the macro as a whole,
974         not an individual relaxation.
975
976    RELAX_NOMACRO
977         Set in the first variant frag if the macro appeared in a .set nomacro
978         block and if one alternative requires a warning but the other does not.
979
980    RELAX_DELAY_SLOT
981         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
982         delay slot.
983
984    RELAX_DELAY_SLOT_16BIT
985         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
986         16-bit instruction.
987
988    RELAX_DELAY_SLOT_SIZE_FIRST
989         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
990         the macro is of the wrong size for the branch delay slot.
991
992    RELAX_DELAY_SLOT_SIZE_SECOND
993         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
994         the macro is of the wrong size for the branch delay slot.
995
996    The frag's "opcode" points to the first fixup for relaxable code.
997
998    Relaxable macros are generated using a sequence such as:
999
1000       relax_start (SYMBOL);
1001       ... generate first expansion ...
1002       relax_switch ();
1003       ... generate second expansion ...
1004       relax_end ();
1005
1006    The code and fixups for the unwanted alternative are discarded
1007    by md_convert_frag.  */
1008 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
1009
1010 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1011 #define RELAX_SECOND(X) ((X) & 0xff)
1012 #define RELAX_USE_SECOND 0x10000
1013 #define RELAX_SECOND_LONGER 0x20000
1014 #define RELAX_NOMACRO 0x40000
1015 #define RELAX_DELAY_SLOT 0x80000
1016 #define RELAX_DELAY_SLOT_16BIT 0x100000
1017 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
1018 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
1019
1020 /* Branch without likely bit.  If label is out of range, we turn:
1021
1022         beq reg1, reg2, label
1023         delay slot
1024
1025    into
1026
1027         bne reg1, reg2, 0f
1028         nop
1029         j label
1030      0: delay slot
1031
1032    with the following opcode replacements:
1033
1034         beq <-> bne
1035         blez <-> bgtz
1036         bltz <-> bgez
1037         bc1f <-> bc1t
1038
1039         bltzal <-> bgezal  (with jal label instead of j label)
1040
1041    Even though keeping the delay slot instruction in the delay slot of
1042    the branch would be more efficient, it would be very tricky to do
1043    correctly, because we'd have to introduce a variable frag *after*
1044    the delay slot instruction, and expand that instead.  Let's do it
1045    the easy way for now, even if the branch-not-taken case now costs
1046    one additional instruction.  Out-of-range branches are not supposed
1047    to be common, anyway.
1048
1049    Branch likely.  If label is out of range, we turn:
1050
1051         beql reg1, reg2, label
1052         delay slot (annulled if branch not taken)
1053
1054    into
1055
1056         beql reg1, reg2, 1f
1057         nop
1058         beql $0, $0, 2f
1059         nop
1060      1: j[al] label
1061         delay slot (executed only if branch taken)
1062      2:
1063
1064    It would be possible to generate a shorter sequence by losing the
1065    likely bit, generating something like:
1066
1067         bne reg1, reg2, 0f
1068         nop
1069         j[al] label
1070         delay slot (executed only if branch taken)
1071      0:
1072
1073         beql -> bne
1074         bnel -> beq
1075         blezl -> bgtz
1076         bgtzl -> blez
1077         bltzl -> bgez
1078         bgezl -> bltz
1079         bc1fl -> bc1t
1080         bc1tl -> bc1f
1081
1082         bltzall -> bgezal  (with jal label instead of j label)
1083         bgezall -> bltzal  (ditto)
1084
1085
1086    but it's not clear that it would actually improve performance.  */
1087 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1088   ((relax_substateT)                                            \
1089    (0xc0000000                                                  \
1090     | ((at) & 0x1f)                                             \
1091     | ((toofar) ? 0x20 : 0)                                     \
1092     | ((link) ? 0x40 : 0)                                       \
1093     | ((likely) ? 0x80 : 0)                                     \
1094     | ((uncond) ? 0x100 : 0)))
1095 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1096 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1097 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1098 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1099 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1100 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1101
1102 /* For mips16 code, we use an entirely different form of relaxation.
1103    mips16 supports two versions of most instructions which take
1104    immediate values: a small one which takes some small value, and a
1105    larger one which takes a 16 bit value.  Since branches also follow
1106    this pattern, relaxing these values is required.
1107
1108    We can assemble both mips16 and normal MIPS code in a single
1109    object.  Therefore, we need to support this type of relaxation at
1110    the same time that we support the relaxation described above.  We
1111    use the high bit of the subtype field to distinguish these cases.
1112
1113    The information we store for this type of relaxation is the
1114    argument code found in the opcode file for this relocation, whether
1115    the user explicitly requested a small or extended form, and whether
1116    the relocation is in a jump or jal delay slot.  That tells us the
1117    size of the value, and how it should be stored.  We also store
1118    whether the fragment is considered to be extended or not.  We also
1119    store whether this is known to be a branch to a different section,
1120    whether we have tried to relax this frag yet, and whether we have
1121    ever extended a PC relative fragment because of a shift count.  */
1122 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1123   (0x80000000                                                   \
1124    | ((type) & 0xff)                                            \
1125    | ((small) ? 0x100 : 0)                                      \
1126    | ((ext) ? 0x200 : 0)                                        \
1127    | ((dslot) ? 0x400 : 0)                                      \
1128    | ((jal_dslot) ? 0x800 : 0))
1129 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1130 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1131 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1132 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1133 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1134 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1135 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1136 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1137 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1138 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1139 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1140 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1141
1142 /* For microMIPS code, we use relaxation similar to one we use for
1143    MIPS16 code.  Some instructions that take immediate values support
1144    two encodings: a small one which takes some small value, and a
1145    larger one which takes a 16 bit value.  As some branches also follow
1146    this pattern, relaxing these values is required.
1147
1148    We can assemble both microMIPS and normal MIPS code in a single
1149    object.  Therefore, we need to support this type of relaxation at
1150    the same time that we support the relaxation described above.  We
1151    use one of the high bits of the subtype field to distinguish these
1152    cases.
1153
1154    The information we store for this type of relaxation is the argument
1155    code found in the opcode file for this relocation, the register
1156    selected as the assembler temporary, whether the user explicitly
1157    requested a 16-bit form, whether the branch is unconditional, whether
1158    it is compact, whether it stores the link address implicitly in $ra,
1159    whether relaxation of out-of-range 32-bit branches to a sequence of
1160    instructions is enabled, and whether the displacement of a branch is
1161    too large to fit as an immediate argument of a 16-bit and a 32-bit
1162    branch, respectively.  */
1163 #define RELAX_MICROMIPS_ENCODE(type, at, u16bit, uncond, compact, link, \
1164                                relax32, toofar16, toofar32)             \
1165   (0x40000000                                                           \
1166    | ((type) & 0xff)                                                    \
1167    | (((at) & 0x1f) << 8)                                               \
1168    | ((u16bit) ? 0x2000 : 0)                                            \
1169    | ((uncond) ? 0x4000 : 0)                                            \
1170    | ((compact) ? 0x8000 : 0)                                           \
1171    | ((link) ? 0x10000 : 0)                                             \
1172    | ((relax32) ? 0x20000 : 0)                                          \
1173    | ((toofar16) ? 0x40000 : 0)                                         \
1174    | ((toofar32) ? 0x80000 : 0))
1175 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1176 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1177 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1178 #define RELAX_MICROMIPS_U16BIT(i) (((i) & 0x2000) != 0)
1179 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x4000) != 0)
1180 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x8000) != 0)
1181 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x10000) != 0)
1182 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x20000) != 0)
1183
1184 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x40000) != 0)
1185 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x40000)
1186 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x40000)
1187 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x80000) != 0)
1188 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x80000)
1189 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x80000)
1190
1191 /* Is the given value a sign-extended 32-bit value?  */
1192 #define IS_SEXT_32BIT_NUM(x)                                            \
1193   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1194    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1195
1196 /* Is the given value a sign-extended 16-bit value?  */
1197 #define IS_SEXT_16BIT_NUM(x)                                            \
1198   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1199    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1200
1201 /* Is the given value a sign-extended 12-bit value?  */
1202 #define IS_SEXT_12BIT_NUM(x)                                            \
1203   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1204
1205 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1206 #define IS_ZEXT_32BIT_NUM(x)                                            \
1207   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1208    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1209
1210 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1211    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1212 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1213   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1214               | (((VALUE) & (MASK)) << (SHIFT)))
1215
1216 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1217    SHIFT places.  */
1218 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1219   (((STRUCT) >> (SHIFT)) & (MASK))
1220
1221 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1222    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1223
1224    include/opcode/mips.h specifies operand fields using the macros
1225    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1226    with "MIPS16OP" instead of "OP".  */
1227 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1228   do \
1229     if (!(MICROMIPS)) \
1230       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1231                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1232     else \
1233       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1234                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1235   while (0)
1236 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1237   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1238                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1239
1240 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1241 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1242   (!(MICROMIPS) \
1243    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1244    : EXTRACT_BITS ((INSN).insn_opcode, \
1245                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1246 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1247   EXTRACT_BITS ((INSN).insn_opcode, \
1248                 MIPS16OP_MASK_##FIELD, \
1249                 MIPS16OP_SH_##FIELD)
1250 \f
1251 /* Whether or not we are emitting a branch-likely macro.  */
1252 static bfd_boolean emit_branch_likely_macro = FALSE;
1253
1254 /* Global variables used when generating relaxable macros.  See the
1255    comment above RELAX_ENCODE for more details about how relaxation
1256    is used.  */
1257 static struct {
1258   /* 0 if we're not emitting a relaxable macro.
1259      1 if we're emitting the first of the two relaxation alternatives.
1260      2 if we're emitting the second alternative.  */
1261   int sequence;
1262
1263   /* The first relaxable fixup in the current frag.  (In other words,
1264      the first fixup that refers to relaxable code.)  */
1265   fixS *first_fixup;
1266
1267   /* sizes[0] says how many bytes of the first alternative are stored in
1268      the current frag.  Likewise sizes[1] for the second alternative.  */
1269   unsigned int sizes[2];
1270
1271   /* The symbol on which the choice of sequence depends.  */
1272   symbolS *symbol;
1273 } mips_relax;
1274 \f
1275 /* Global variables used to decide whether a macro needs a warning.  */
1276 static struct {
1277   /* True if the macro is in a branch delay slot.  */
1278   bfd_boolean delay_slot_p;
1279
1280   /* Set to the length in bytes required if the macro is in a delay slot
1281      that requires a specific length of instruction, otherwise zero.  */
1282   unsigned int delay_slot_length;
1283
1284   /* For relaxable macros, sizes[0] is the length of the first alternative
1285      in bytes and sizes[1] is the length of the second alternative.
1286      For non-relaxable macros, both elements give the length of the
1287      macro in bytes.  */
1288   unsigned int sizes[2];
1289
1290   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1291      instruction of the first alternative in bytes and first_insn_sizes[1]
1292      is the length of the first instruction of the second alternative.
1293      For non-relaxable macros, both elements give the length of the first
1294      instruction in bytes.
1295
1296      Set to zero if we haven't yet seen the first instruction.  */
1297   unsigned int first_insn_sizes[2];
1298
1299   /* For relaxable macros, insns[0] is the number of instructions for the
1300      first alternative and insns[1] is the number of instructions for the
1301      second alternative.
1302
1303      For non-relaxable macros, both elements give the number of
1304      instructions for the macro.  */
1305   unsigned int insns[2];
1306
1307   /* The first variant frag for this macro.  */
1308   fragS *first_frag;
1309 } mips_macro_warning;
1310 \f
1311 /* Prototypes for static functions.  */
1312
1313 #define internalError()                                                 \
1314     as_fatal (_("internal Error, line %d, %s"), __LINE__, __FILE__)
1315
1316 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1317
1318 static void append_insn
1319   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1320    bfd_boolean expansionp);
1321 static void mips_no_prev_insn (void);
1322 static void macro_build (expressionS *, const char *, const char *, ...);
1323 static void mips16_macro_build
1324   (expressionS *, const char *, const char *, va_list *);
1325 static void load_register (int, expressionS *, int);
1326 static void macro_start (void);
1327 static void macro_end (void);
1328 static void macro (struct mips_cl_insn * ip);
1329 static void mips16_macro (struct mips_cl_insn * ip);
1330 static void mips_ip (char *str, struct mips_cl_insn * ip);
1331 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1332 static void mips16_immed
1333   (char *, unsigned int, int, offsetT, bfd_boolean, bfd_boolean, bfd_boolean,
1334    unsigned long *, bfd_boolean *, unsigned short *);
1335 static size_t my_getSmallExpression
1336   (expressionS *, bfd_reloc_code_real_type *, char *);
1337 static void my_getExpression (expressionS *, char *);
1338 static void s_align (int);
1339 static void s_change_sec (int);
1340 static void s_change_section (int);
1341 static void s_cons (int);
1342 static void s_float_cons (int);
1343 static void s_mips_globl (int);
1344 static void s_option (int);
1345 static void s_mipsset (int);
1346 static void s_abicalls (int);
1347 static void s_cpload (int);
1348 static void s_cpsetup (int);
1349 static void s_cplocal (int);
1350 static void s_cprestore (int);
1351 static void s_cpreturn (int);
1352 static void s_dtprelword (int);
1353 static void s_dtpreldword (int);
1354 static void s_gpvalue (int);
1355 static void s_gpword (int);
1356 static void s_gpdword (int);
1357 static void s_cpadd (int);
1358 static void s_insn (int);
1359 static void md_obj_begin (void);
1360 static void md_obj_end (void);
1361 static void s_mips_ent (int);
1362 static void s_mips_end (int);
1363 static void s_mips_frame (int);
1364 static void s_mips_mask (int reg_type);
1365 static void s_mips_stab (int);
1366 static void s_mips_weakext (int);
1367 static void s_mips_file (int);
1368 static void s_mips_loc (int);
1369 static bfd_boolean pic_need_relax (symbolS *, asection *);
1370 static int relaxed_branch_length (fragS *, asection *, int);
1371 static int validate_mips_insn (const struct mips_opcode *);
1372 static int validate_micromips_insn (const struct mips_opcode *);
1373 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1374 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1375
1376 /* Table and functions used to map between CPU/ISA names, and
1377    ISA levels, and CPU numbers.  */
1378
1379 struct mips_cpu_info
1380 {
1381   const char *name;           /* CPU or ISA name.  */
1382   int flags;                  /* ASEs available, or ISA flag.  */
1383   int isa;                    /* ISA level.  */
1384   int cpu;                    /* CPU number (default CPU if ISA).  */
1385 };
1386
1387 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1388 #define MIPS_CPU_ASE_SMARTMIPS  0x0002  /* CPU implements SmartMIPS ASE */
1389 #define MIPS_CPU_ASE_DSP        0x0004  /* CPU implements DSP ASE */
1390 #define MIPS_CPU_ASE_MT         0x0008  /* CPU implements MT ASE */
1391 #define MIPS_CPU_ASE_MIPS3D     0x0010  /* CPU implements MIPS-3D ASE */
1392 #define MIPS_CPU_ASE_MDMX       0x0020  /* CPU implements MDMX ASE */
1393 #define MIPS_CPU_ASE_DSPR2      0x0040  /* CPU implements DSP R2 ASE */
1394
1395 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1396 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1397 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1398 \f
1399 /* Pseudo-op table.
1400
1401    The following pseudo-ops from the Kane and Heinrich MIPS book
1402    should be defined here, but are currently unsupported: .alias,
1403    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1404
1405    The following pseudo-ops from the Kane and Heinrich MIPS book are
1406    specific to the type of debugging information being generated, and
1407    should be defined by the object format: .aent, .begin, .bend,
1408    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1409    .vreg.
1410
1411    The following pseudo-ops from the Kane and Heinrich MIPS book are
1412    not MIPS CPU specific, but are also not specific to the object file
1413    format.  This file is probably the best place to define them, but
1414    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1415
1416 static const pseudo_typeS mips_pseudo_table[] =
1417 {
1418   /* MIPS specific pseudo-ops.  */
1419   {"option", s_option, 0},
1420   {"set", s_mipsset, 0},
1421   {"rdata", s_change_sec, 'r'},
1422   {"sdata", s_change_sec, 's'},
1423   {"livereg", s_ignore, 0},
1424   {"abicalls", s_abicalls, 0},
1425   {"cpload", s_cpload, 0},
1426   {"cpsetup", s_cpsetup, 0},
1427   {"cplocal", s_cplocal, 0},
1428   {"cprestore", s_cprestore, 0},
1429   {"cpreturn", s_cpreturn, 0},
1430   {"dtprelword", s_dtprelword, 0},
1431   {"dtpreldword", s_dtpreldword, 0},
1432   {"gpvalue", s_gpvalue, 0},
1433   {"gpword", s_gpword, 0},
1434   {"gpdword", s_gpdword, 0},
1435   {"cpadd", s_cpadd, 0},
1436   {"insn", s_insn, 0},
1437
1438   /* Relatively generic pseudo-ops that happen to be used on MIPS
1439      chips.  */
1440   {"asciiz", stringer, 8 + 1},
1441   {"bss", s_change_sec, 'b'},
1442   {"err", s_err, 0},
1443   {"half", s_cons, 1},
1444   {"dword", s_cons, 3},
1445   {"weakext", s_mips_weakext, 0},
1446   {"origin", s_org, 0},
1447   {"repeat", s_rept, 0},
1448
1449   /* For MIPS this is non-standard, but we define it for consistency.  */
1450   {"sbss", s_change_sec, 'B'},
1451
1452   /* These pseudo-ops are defined in read.c, but must be overridden
1453      here for one reason or another.  */
1454   {"align", s_align, 0},
1455   {"byte", s_cons, 0},
1456   {"data", s_change_sec, 'd'},
1457   {"double", s_float_cons, 'd'},
1458   {"float", s_float_cons, 'f'},
1459   {"globl", s_mips_globl, 0},
1460   {"global", s_mips_globl, 0},
1461   {"hword", s_cons, 1},
1462   {"int", s_cons, 2},
1463   {"long", s_cons, 2},
1464   {"octa", s_cons, 4},
1465   {"quad", s_cons, 3},
1466   {"section", s_change_section, 0},
1467   {"short", s_cons, 1},
1468   {"single", s_float_cons, 'f'},
1469   {"stabn", s_mips_stab, 'n'},
1470   {"text", s_change_sec, 't'},
1471   {"word", s_cons, 2},
1472
1473   { "extern", ecoff_directive_extern, 0},
1474
1475   { NULL, NULL, 0 },
1476 };
1477
1478 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1479 {
1480   /* These pseudo-ops should be defined by the object file format.
1481      However, a.out doesn't support them, so we have versions here.  */
1482   {"aent", s_mips_ent, 1},
1483   {"bgnb", s_ignore, 0},
1484   {"end", s_mips_end, 0},
1485   {"endb", s_ignore, 0},
1486   {"ent", s_mips_ent, 0},
1487   {"file", s_mips_file, 0},
1488   {"fmask", s_mips_mask, 'F'},
1489   {"frame", s_mips_frame, 0},
1490   {"loc", s_mips_loc, 0},
1491   {"mask", s_mips_mask, 'R'},
1492   {"verstamp", s_ignore, 0},
1493   { NULL, NULL, 0 },
1494 };
1495
1496 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1497    purpose of the `.dc.a' internal pseudo-op.  */
1498
1499 int
1500 mips_address_bytes (void)
1501 {
1502   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1503 }
1504
1505 extern void pop_insert (const pseudo_typeS *);
1506
1507 void
1508 mips_pop_insert (void)
1509 {
1510   pop_insert (mips_pseudo_table);
1511   if (! ECOFF_DEBUGGING)
1512     pop_insert (mips_nonecoff_pseudo_table);
1513 }
1514 \f
1515 /* Symbols labelling the current insn.  */
1516
1517 struct insn_label_list
1518 {
1519   struct insn_label_list *next;
1520   symbolS *label;
1521 };
1522
1523 static struct insn_label_list *free_insn_labels;
1524 #define label_list tc_segment_info_data.labels
1525
1526 static void mips_clear_insn_labels (void);
1527 static void mips_mark_labels (void);
1528 static void mips_compressed_mark_labels (void);
1529
1530 static inline void
1531 mips_clear_insn_labels (void)
1532 {
1533   register struct insn_label_list **pl;
1534   segment_info_type *si;
1535
1536   if (now_seg)
1537     {
1538       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1539         ;
1540       
1541       si = seg_info (now_seg);
1542       *pl = si->label_list;
1543       si->label_list = NULL;
1544     }
1545 }
1546
1547 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1548
1549 static inline void
1550 mips_mark_labels (void)
1551 {
1552   if (HAVE_CODE_COMPRESSION)
1553     mips_compressed_mark_labels ();
1554 }
1555 \f
1556 static char *expr_end;
1557
1558 /* Expressions which appear in instructions.  These are set by
1559    mips_ip.  */
1560
1561 static expressionS imm_expr;
1562 static expressionS imm2_expr;
1563 static expressionS offset_expr;
1564
1565 /* Relocs associated with imm_expr and offset_expr.  */
1566
1567 static bfd_reloc_code_real_type imm_reloc[3]
1568   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1569 static bfd_reloc_code_real_type offset_reloc[3]
1570   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1571
1572 /* This is set to the resulting size of the instruction to be produced
1573    by mips16_ip if an explicit extension is used or by mips_ip if an
1574    explicit size is supplied.  */
1575
1576 static unsigned int forced_insn_length;
1577
1578 #ifdef OBJ_ELF
1579 /* The pdr segment for per procedure frame/regmask info.  Not used for
1580    ECOFF debugging.  */
1581
1582 static segT pdr_seg;
1583 #endif
1584
1585 /* The default target format to use.  */
1586
1587 #if defined (TE_FreeBSD)
1588 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1589 #elif defined (TE_TMIPS)
1590 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1591 #else
1592 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1593 #endif
1594
1595 const char *
1596 mips_target_format (void)
1597 {
1598   switch (OUTPUT_FLAVOR)
1599     {
1600     case bfd_target_ecoff_flavour:
1601       return target_big_endian ? "ecoff-bigmips" : ECOFF_LITTLE_FORMAT;
1602     case bfd_target_coff_flavour:
1603       return "pe-mips";
1604     case bfd_target_elf_flavour:
1605 #ifdef TE_VXWORKS
1606       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1607         return (target_big_endian
1608                 ? "elf32-bigmips-vxworks"
1609                 : "elf32-littlemips-vxworks");
1610 #endif
1611       return (target_big_endian
1612               ? (HAVE_64BIT_OBJECTS
1613                  ? ELF_TARGET ("elf64-", "big")
1614                  : (HAVE_NEWABI
1615                     ? ELF_TARGET ("elf32-n", "big")
1616                     : ELF_TARGET ("elf32-", "big")))
1617               : (HAVE_64BIT_OBJECTS
1618                  ? ELF_TARGET ("elf64-", "little")
1619                  : (HAVE_NEWABI
1620                     ? ELF_TARGET ("elf32-n", "little")
1621                     : ELF_TARGET ("elf32-", "little"))));
1622     default:
1623       abort ();
1624       return NULL;
1625     }
1626 }
1627
1628 /* Return the length of a microMIPS instruction in bytes.  If bits of
1629    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1630    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1631    major opcode) will require further modifications to the opcode
1632    table.  */
1633
1634 static inline unsigned int
1635 micromips_insn_length (const struct mips_opcode *mo)
1636 {
1637   return (mo->mask >> 16) == 0 ? 2 : 4;
1638 }
1639
1640 /* Return the length of instruction INSN.  */
1641
1642 static inline unsigned int
1643 insn_length (const struct mips_cl_insn *insn)
1644 {
1645   if (mips_opts.micromips)
1646     return micromips_insn_length (insn->insn_mo);
1647   else if (mips_opts.mips16)
1648     return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1649   else
1650     return 4;
1651 }
1652
1653 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1654
1655 static void
1656 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1657 {
1658   size_t i;
1659
1660   insn->insn_mo = mo;
1661   insn->use_extend = FALSE;
1662   insn->extend = 0;
1663   insn->insn_opcode = mo->match;
1664   insn->frag = NULL;
1665   insn->where = 0;
1666   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1667     insn->fixp[i] = NULL;
1668   insn->fixed_p = (mips_opts.noreorder > 0);
1669   insn->noreorder_p = (mips_opts.noreorder > 0);
1670   insn->mips16_absolute_jump_p = 0;
1671   insn->complete_p = 0;
1672 }
1673
1674 /* Record the current MIPS16/microMIPS mode in now_seg.  */
1675
1676 static void
1677 mips_record_compressed_mode (void)
1678 {
1679   segment_info_type *si;
1680
1681   si = seg_info (now_seg);
1682   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
1683     si->tc_segment_info_data.mips16 = mips_opts.mips16;
1684   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
1685     si->tc_segment_info_data.micromips = mips_opts.micromips;
1686 }
1687
1688 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1689
1690 static void
1691 install_insn (const struct mips_cl_insn *insn)
1692 {
1693   char *f = insn->frag->fr_literal + insn->where;
1694   if (!HAVE_CODE_COMPRESSION)
1695     md_number_to_chars (f, insn->insn_opcode, 4);
1696   else if (mips_opts.micromips)
1697     {
1698       unsigned int length = insn_length (insn);
1699       if (length == 2)
1700         md_number_to_chars (f, insn->insn_opcode, 2);
1701       else if (length == 4)
1702         {
1703           md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1704           f += 2;
1705           md_number_to_chars (f, insn->insn_opcode & 0xffff, 2);
1706         }
1707       else
1708         as_bad (_("48-bit microMIPS instructions are not supported"));
1709     }
1710   else if (insn->mips16_absolute_jump_p)
1711     {
1712       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1713       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1714     }
1715   else
1716     {
1717       if (insn->use_extend)
1718         {
1719           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1720           f += 2;
1721         }
1722       md_number_to_chars (f, insn->insn_opcode, 2);
1723     }
1724   mips_record_compressed_mode ();
1725 }
1726
1727 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1728    and install the opcode in the new location.  */
1729
1730 static void
1731 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1732 {
1733   size_t i;
1734
1735   insn->frag = frag;
1736   insn->where = where;
1737   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1738     if (insn->fixp[i] != NULL)
1739       {
1740         insn->fixp[i]->fx_frag = frag;
1741         insn->fixp[i]->fx_where = where;
1742       }
1743   install_insn (insn);
1744 }
1745
1746 /* Add INSN to the end of the output.  */
1747
1748 static void
1749 add_fixed_insn (struct mips_cl_insn *insn)
1750 {
1751   char *f = frag_more (insn_length (insn));
1752   move_insn (insn, frag_now, f - frag_now->fr_literal);
1753 }
1754
1755 /* Start a variant frag and move INSN to the start of the variant part,
1756    marking it as fixed.  The other arguments are as for frag_var.  */
1757
1758 static void
1759 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1760                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1761 {
1762   frag_grow (max_chars);
1763   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1764   insn->fixed_p = 1;
1765   frag_var (rs_machine_dependent, max_chars, var,
1766             subtype, symbol, offset, NULL);
1767 }
1768
1769 /* Insert N copies of INSN into the history buffer, starting at
1770    position FIRST.  Neither FIRST nor N need to be clipped.  */
1771
1772 static void
1773 insert_into_history (unsigned int first, unsigned int n,
1774                      const struct mips_cl_insn *insn)
1775 {
1776   if (mips_relax.sequence != 2)
1777     {
1778       unsigned int i;
1779
1780       for (i = ARRAY_SIZE (history); i-- > first;)
1781         if (i >= first + n)
1782           history[i] = history[i - n];
1783         else
1784           history[i] = *insn;
1785     }
1786 }
1787
1788 /* Emit a nop instruction, recording it in the history buffer.  */
1789
1790 static void
1791 emit_nop (void)
1792 {
1793   add_fixed_insn (NOP_INSN);
1794   insert_into_history (0, 1, NOP_INSN);
1795 }
1796
1797 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1798    the idea is to make it obvious at a glance that each errata is
1799    included.  */
1800
1801 static void
1802 init_vr4120_conflicts (void)
1803 {
1804 #define CONFLICT(FIRST, SECOND) \
1805     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1806
1807   /* Errata 21 - [D]DIV[U] after [D]MACC */
1808   CONFLICT (MACC, DIV);
1809   CONFLICT (DMACC, DIV);
1810
1811   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1812   CONFLICT (DMULT, DMULT);
1813   CONFLICT (DMULT, DMACC);
1814   CONFLICT (DMACC, DMULT);
1815   CONFLICT (DMACC, DMACC);
1816
1817   /* Errata 24 - MT{LO,HI} after [D]MACC */
1818   CONFLICT (MACC, MTHILO);
1819   CONFLICT (DMACC, MTHILO);
1820
1821   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1822      instruction is executed immediately after a MACC or DMACC
1823      instruction, the result of [either instruction] is incorrect."  */
1824   CONFLICT (MACC, MULT);
1825   CONFLICT (MACC, DMULT);
1826   CONFLICT (DMACC, MULT);
1827   CONFLICT (DMACC, DMULT);
1828
1829   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1830      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1831      DDIV or DDIVU instruction, the result of the MACC or
1832      DMACC instruction is incorrect.".  */
1833   CONFLICT (DMULT, MACC);
1834   CONFLICT (DMULT, DMACC);
1835   CONFLICT (DIV, MACC);
1836   CONFLICT (DIV, DMACC);
1837
1838 #undef CONFLICT
1839 }
1840
1841 struct regname {
1842   const char *name;
1843   unsigned int num;
1844 };
1845
1846 #define RTYPE_MASK      0x1ff00
1847 #define RTYPE_NUM       0x00100
1848 #define RTYPE_FPU       0x00200
1849 #define RTYPE_FCC       0x00400
1850 #define RTYPE_VEC       0x00800
1851 #define RTYPE_GP        0x01000
1852 #define RTYPE_CP0       0x02000
1853 #define RTYPE_PC        0x04000
1854 #define RTYPE_ACC       0x08000
1855 #define RTYPE_CCC       0x10000
1856 #define RNUM_MASK       0x000ff
1857 #define RWARN           0x80000
1858
1859 #define GENERIC_REGISTER_NUMBERS \
1860     {"$0",      RTYPE_NUM | 0},  \
1861     {"$1",      RTYPE_NUM | 1},  \
1862     {"$2",      RTYPE_NUM | 2},  \
1863     {"$3",      RTYPE_NUM | 3},  \
1864     {"$4",      RTYPE_NUM | 4},  \
1865     {"$5",      RTYPE_NUM | 5},  \
1866     {"$6",      RTYPE_NUM | 6},  \
1867     {"$7",      RTYPE_NUM | 7},  \
1868     {"$8",      RTYPE_NUM | 8},  \
1869     {"$9",      RTYPE_NUM | 9},  \
1870     {"$10",     RTYPE_NUM | 10}, \
1871     {"$11",     RTYPE_NUM | 11}, \
1872     {"$12",     RTYPE_NUM | 12}, \
1873     {"$13",     RTYPE_NUM | 13}, \
1874     {"$14",     RTYPE_NUM | 14}, \
1875     {"$15",     RTYPE_NUM | 15}, \
1876     {"$16",     RTYPE_NUM | 16}, \
1877     {"$17",     RTYPE_NUM | 17}, \
1878     {"$18",     RTYPE_NUM | 18}, \
1879     {"$19",     RTYPE_NUM | 19}, \
1880     {"$20",     RTYPE_NUM | 20}, \
1881     {"$21",     RTYPE_NUM | 21}, \
1882     {"$22",     RTYPE_NUM | 22}, \
1883     {"$23",     RTYPE_NUM | 23}, \
1884     {"$24",     RTYPE_NUM | 24}, \
1885     {"$25",     RTYPE_NUM | 25}, \
1886     {"$26",     RTYPE_NUM | 26}, \
1887     {"$27",     RTYPE_NUM | 27}, \
1888     {"$28",     RTYPE_NUM | 28}, \
1889     {"$29",     RTYPE_NUM | 29}, \
1890     {"$30",     RTYPE_NUM | 30}, \
1891     {"$31",     RTYPE_NUM | 31} 
1892
1893 #define FPU_REGISTER_NAMES       \
1894     {"$f0",     RTYPE_FPU | 0},  \
1895     {"$f1",     RTYPE_FPU | 1},  \
1896     {"$f2",     RTYPE_FPU | 2},  \
1897     {"$f3",     RTYPE_FPU | 3},  \
1898     {"$f4",     RTYPE_FPU | 4},  \
1899     {"$f5",     RTYPE_FPU | 5},  \
1900     {"$f6",     RTYPE_FPU | 6},  \
1901     {"$f7",     RTYPE_FPU | 7},  \
1902     {"$f8",     RTYPE_FPU | 8},  \
1903     {"$f9",     RTYPE_FPU | 9},  \
1904     {"$f10",    RTYPE_FPU | 10}, \
1905     {"$f11",    RTYPE_FPU | 11}, \
1906     {"$f12",    RTYPE_FPU | 12}, \
1907     {"$f13",    RTYPE_FPU | 13}, \
1908     {"$f14",    RTYPE_FPU | 14}, \
1909     {"$f15",    RTYPE_FPU | 15}, \
1910     {"$f16",    RTYPE_FPU | 16}, \
1911     {"$f17",    RTYPE_FPU | 17}, \
1912     {"$f18",    RTYPE_FPU | 18}, \
1913     {"$f19",    RTYPE_FPU | 19}, \
1914     {"$f20",    RTYPE_FPU | 20}, \
1915     {"$f21",    RTYPE_FPU | 21}, \
1916     {"$f22",    RTYPE_FPU | 22}, \
1917     {"$f23",    RTYPE_FPU | 23}, \
1918     {"$f24",    RTYPE_FPU | 24}, \
1919     {"$f25",    RTYPE_FPU | 25}, \
1920     {"$f26",    RTYPE_FPU | 26}, \
1921     {"$f27",    RTYPE_FPU | 27}, \
1922     {"$f28",    RTYPE_FPU | 28}, \
1923     {"$f29",    RTYPE_FPU | 29}, \
1924     {"$f30",    RTYPE_FPU | 30}, \
1925     {"$f31",    RTYPE_FPU | 31}
1926
1927 #define FPU_CONDITION_CODE_NAMES \
1928     {"$fcc0",   RTYPE_FCC | 0},  \
1929     {"$fcc1",   RTYPE_FCC | 1},  \
1930     {"$fcc2",   RTYPE_FCC | 2},  \
1931     {"$fcc3",   RTYPE_FCC | 3},  \
1932     {"$fcc4",   RTYPE_FCC | 4},  \
1933     {"$fcc5",   RTYPE_FCC | 5},  \
1934     {"$fcc6",   RTYPE_FCC | 6},  \
1935     {"$fcc7",   RTYPE_FCC | 7}
1936
1937 #define COPROC_CONDITION_CODE_NAMES         \
1938     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
1939     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
1940     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
1941     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
1942     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
1943     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
1944     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
1945     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
1946
1947 #define N32N64_SYMBOLIC_REGISTER_NAMES \
1948     {"$a4",     RTYPE_GP | 8},  \
1949     {"$a5",     RTYPE_GP | 9},  \
1950     {"$a6",     RTYPE_GP | 10}, \
1951     {"$a7",     RTYPE_GP | 11}, \
1952     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
1953     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
1954     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
1955     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
1956     {"$t0",     RTYPE_GP | 12}, \
1957     {"$t1",     RTYPE_GP | 13}, \
1958     {"$t2",     RTYPE_GP | 14}, \
1959     {"$t3",     RTYPE_GP | 15}
1960
1961 #define O32_SYMBOLIC_REGISTER_NAMES \
1962     {"$t0",     RTYPE_GP | 8},  \
1963     {"$t1",     RTYPE_GP | 9},  \
1964     {"$t2",     RTYPE_GP | 10}, \
1965     {"$t3",     RTYPE_GP | 11}, \
1966     {"$t4",     RTYPE_GP | 12}, \
1967     {"$t5",     RTYPE_GP | 13}, \
1968     {"$t6",     RTYPE_GP | 14}, \
1969     {"$t7",     RTYPE_GP | 15}, \
1970     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
1971     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
1972     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
1973     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
1974
1975 /* Remaining symbolic register names */
1976 #define SYMBOLIC_REGISTER_NAMES \
1977     {"$zero",   RTYPE_GP | 0},  \
1978     {"$at",     RTYPE_GP | 1},  \
1979     {"$AT",     RTYPE_GP | 1},  \
1980     {"$v0",     RTYPE_GP | 2},  \
1981     {"$v1",     RTYPE_GP | 3},  \
1982     {"$a0",     RTYPE_GP | 4},  \
1983     {"$a1",     RTYPE_GP | 5},  \
1984     {"$a2",     RTYPE_GP | 6},  \
1985     {"$a3",     RTYPE_GP | 7},  \
1986     {"$s0",     RTYPE_GP | 16}, \
1987     {"$s1",     RTYPE_GP | 17}, \
1988     {"$s2",     RTYPE_GP | 18}, \
1989     {"$s3",     RTYPE_GP | 19}, \
1990     {"$s4",     RTYPE_GP | 20}, \
1991     {"$s5",     RTYPE_GP | 21}, \
1992     {"$s6",     RTYPE_GP | 22}, \
1993     {"$s7",     RTYPE_GP | 23}, \
1994     {"$t8",     RTYPE_GP | 24}, \
1995     {"$t9",     RTYPE_GP | 25}, \
1996     {"$k0",     RTYPE_GP | 26}, \
1997     {"$kt0",    RTYPE_GP | 26}, \
1998     {"$k1",     RTYPE_GP | 27}, \
1999     {"$kt1",    RTYPE_GP | 27}, \
2000     {"$gp",     RTYPE_GP | 28}, \
2001     {"$sp",     RTYPE_GP | 29}, \
2002     {"$s8",     RTYPE_GP | 30}, \
2003     {"$fp",     RTYPE_GP | 30}, \
2004     {"$ra",     RTYPE_GP | 31}
2005
2006 #define MIPS16_SPECIAL_REGISTER_NAMES \
2007     {"$pc",     RTYPE_PC | 0}
2008
2009 #define MDMX_VECTOR_REGISTER_NAMES \
2010     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2011     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2012     {"$v2",     RTYPE_VEC | 2},  \
2013     {"$v3",     RTYPE_VEC | 3},  \
2014     {"$v4",     RTYPE_VEC | 4},  \
2015     {"$v5",     RTYPE_VEC | 5},  \
2016     {"$v6",     RTYPE_VEC | 6},  \
2017     {"$v7",     RTYPE_VEC | 7},  \
2018     {"$v8",     RTYPE_VEC | 8},  \
2019     {"$v9",     RTYPE_VEC | 9},  \
2020     {"$v10",    RTYPE_VEC | 10}, \
2021     {"$v11",    RTYPE_VEC | 11}, \
2022     {"$v12",    RTYPE_VEC | 12}, \
2023     {"$v13",    RTYPE_VEC | 13}, \
2024     {"$v14",    RTYPE_VEC | 14}, \
2025     {"$v15",    RTYPE_VEC | 15}, \
2026     {"$v16",    RTYPE_VEC | 16}, \
2027     {"$v17",    RTYPE_VEC | 17}, \
2028     {"$v18",    RTYPE_VEC | 18}, \
2029     {"$v19",    RTYPE_VEC | 19}, \
2030     {"$v20",    RTYPE_VEC | 20}, \
2031     {"$v21",    RTYPE_VEC | 21}, \
2032     {"$v22",    RTYPE_VEC | 22}, \
2033     {"$v23",    RTYPE_VEC | 23}, \
2034     {"$v24",    RTYPE_VEC | 24}, \
2035     {"$v25",    RTYPE_VEC | 25}, \
2036     {"$v26",    RTYPE_VEC | 26}, \
2037     {"$v27",    RTYPE_VEC | 27}, \
2038     {"$v28",    RTYPE_VEC | 28}, \
2039     {"$v29",    RTYPE_VEC | 29}, \
2040     {"$v30",    RTYPE_VEC | 30}, \
2041     {"$v31",    RTYPE_VEC | 31}
2042
2043 #define MIPS_DSP_ACCUMULATOR_NAMES \
2044     {"$ac0",    RTYPE_ACC | 0}, \
2045     {"$ac1",    RTYPE_ACC | 1}, \
2046     {"$ac2",    RTYPE_ACC | 2}, \
2047     {"$ac3",    RTYPE_ACC | 3}
2048
2049 static const struct regname reg_names[] = {
2050   GENERIC_REGISTER_NUMBERS,
2051   FPU_REGISTER_NAMES,
2052   FPU_CONDITION_CODE_NAMES,
2053   COPROC_CONDITION_CODE_NAMES,
2054
2055   /* The $txx registers depends on the abi,
2056      these will be added later into the symbol table from
2057      one of the tables below once mips_abi is set after 
2058      parsing of arguments from the command line. */
2059   SYMBOLIC_REGISTER_NAMES,
2060
2061   MIPS16_SPECIAL_REGISTER_NAMES,
2062   MDMX_VECTOR_REGISTER_NAMES,
2063   MIPS_DSP_ACCUMULATOR_NAMES,
2064   {0, 0}
2065 };
2066
2067 static const struct regname reg_names_o32[] = {
2068   O32_SYMBOLIC_REGISTER_NAMES,
2069   {0, 0}
2070 };
2071
2072 static const struct regname reg_names_n32n64[] = {
2073   N32N64_SYMBOLIC_REGISTER_NAMES,
2074   {0, 0}
2075 };
2076
2077 /* Check if S points at a valid register specifier according to TYPES.
2078    If so, then return 1, advance S to consume the specifier and store
2079    the register's number in REGNOP, otherwise return 0.  */
2080
2081 static int
2082 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2083 {
2084   symbolS *symbolP;
2085   char *e;
2086   char save_c;
2087   int reg = -1;
2088
2089   /* Find end of name.  */
2090   e = *s;
2091   if (is_name_beginner (*e))
2092     ++e;
2093   while (is_part_of_name (*e))
2094     ++e;
2095
2096   /* Terminate name.  */
2097   save_c = *e;
2098   *e = '\0';
2099
2100   /* Look for a register symbol.  */
2101   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2102     {
2103       int r = S_GET_VALUE (symbolP);
2104       if (r & types)
2105         reg = r & RNUM_MASK;
2106       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2107         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2108         reg = (r & RNUM_MASK) - 2;
2109     }
2110   /* Else see if this is a register defined in an itbl entry.  */
2111   else if ((types & RTYPE_GP) && itbl_have_entries)
2112     {
2113       char *n = *s;
2114       unsigned long r;
2115
2116       if (*n == '$')
2117         ++n;
2118       if (itbl_get_reg_val (n, &r))
2119         reg = r & RNUM_MASK;
2120     }
2121
2122   /* Advance to next token if a register was recognised.  */
2123   if (reg >= 0)
2124     *s = e;
2125   else if (types & RWARN)
2126     as_warn (_("Unrecognized register name `%s'"), *s);
2127
2128   *e = save_c;
2129   if (regnop)
2130     *regnop = reg;
2131   return reg >= 0;
2132 }
2133
2134 /* Check if S points at a valid register list according to TYPES.
2135    If so, then return 1, advance S to consume the list and store
2136    the registers present on the list as a bitmask of ones in REGLISTP,
2137    otherwise return 0.  A valid list comprises a comma-separated
2138    enumeration of valid single registers and/or dash-separated
2139    contiguous register ranges as determined by their numbers.
2140
2141    As a special exception if one of s0-s7 registers is specified as
2142    the range's lower delimiter and s8 (fp) is its upper one, then no
2143    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2144    are selected; they have to be named separately if needed.  */
2145
2146 static int
2147 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2148 {
2149   unsigned int reglist = 0;
2150   unsigned int lastregno;
2151   bfd_boolean ok = TRUE;
2152   unsigned int regmask;
2153   unsigned int regno;
2154   char *s_reset = *s;
2155   char *s_end_of_list = *s;
2156
2157   while (reg_lookup (s, types, &regno))
2158     {
2159       lastregno = regno;
2160       if (**s == '-')
2161         {
2162           (*s)++;
2163           ok = reg_lookup (s, types, &lastregno);
2164           if (ok && lastregno < regno)
2165             ok = FALSE;
2166           if (!ok)
2167             break;
2168         }
2169
2170       if (lastregno == FP && regno >= S0 && regno <= S7)
2171         {
2172           lastregno = S7;
2173           reglist |= 1 << FP;
2174         }
2175       regmask = 1 << lastregno;
2176       regmask = (regmask << 1) - 1;
2177       regmask ^= (1 << regno) - 1;
2178       reglist |= regmask;
2179
2180       s_end_of_list = *s;
2181       if (**s != ',')
2182         break;
2183       (*s)++;
2184     }
2185
2186   if (ok)
2187     *s = s_end_of_list;
2188   else
2189     *s = s_reset;
2190   if (reglistp)
2191     *reglistp = reglist;
2192   return ok && reglist != 0;
2193 }
2194
2195 /* Return TRUE if opcode MO is valid on the currently selected ISA and
2196    architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2197
2198 static bfd_boolean
2199 is_opcode_valid (const struct mips_opcode *mo)
2200 {
2201   int isa = mips_opts.isa;
2202   int fp_s, fp_d;
2203
2204   if (mips_opts.ase_mdmx)
2205     isa |= INSN_MDMX;
2206   if (mips_opts.ase_dsp)
2207     isa |= INSN_DSP;
2208   if (mips_opts.ase_dsp && ISA_SUPPORTS_DSP64_ASE)
2209     isa |= INSN_DSP64;
2210   if (mips_opts.ase_dspr2)
2211     isa |= INSN_DSPR2;
2212   if (mips_opts.ase_mt)
2213     isa |= INSN_MT;
2214   if (mips_opts.ase_mips3d)
2215     isa |= INSN_MIPS3D;
2216   if (mips_opts.ase_smartmips)
2217     isa |= INSN_SMARTMIPS;
2218
2219   /* Don't accept instructions based on the ISA if the CPU does not implement
2220      all the coprocessor insns. */
2221   if (NO_ISA_COP (mips_opts.arch)
2222       && COP_INSN (mo->pinfo))
2223     isa = 0;
2224
2225   if (!OPCODE_IS_MEMBER (mo, isa, mips_opts.arch))
2226     return FALSE;
2227
2228   /* Check whether the instruction or macro requires single-precision or
2229      double-precision floating-point support.  Note that this information is
2230      stored differently in the opcode table for insns and macros.  */
2231   if (mo->pinfo == INSN_MACRO)
2232     {
2233       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2234       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2235     }
2236   else
2237     {
2238       fp_s = mo->pinfo & FP_S;
2239       fp_d = mo->pinfo & FP_D;
2240     }
2241
2242   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2243     return FALSE;
2244
2245   if (fp_s && mips_opts.soft_float)
2246     return FALSE;
2247
2248   return TRUE;
2249 }
2250
2251 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2252    selected ISA and architecture.  */
2253
2254 static bfd_boolean
2255 is_opcode_valid_16 (const struct mips_opcode *mo)
2256 {
2257   return OPCODE_IS_MEMBER (mo, mips_opts.isa, mips_opts.arch) ? TRUE : FALSE;
2258 }
2259
2260 /* Return TRUE if the size of the microMIPS opcode MO matches one
2261    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2262
2263 static bfd_boolean
2264 is_size_valid (const struct mips_opcode *mo)
2265 {
2266   if (!mips_opts.micromips)
2267     return TRUE;
2268
2269   if (!forced_insn_length)
2270     return TRUE;
2271   if (mo->pinfo == INSN_MACRO)
2272     return FALSE;
2273   return forced_insn_length == micromips_insn_length (mo);
2274 }
2275
2276 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2277    of the preceding instruction.  Always TRUE in the standard MIPS mode.  */
2278
2279 static bfd_boolean
2280 is_delay_slot_valid (const struct mips_opcode *mo)
2281 {
2282   if (!mips_opts.micromips)
2283     return TRUE;
2284
2285   if (mo->pinfo == INSN_MACRO)
2286     return TRUE;
2287   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2288       && micromips_insn_length (mo) != 4)
2289     return FALSE;
2290   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2291       && micromips_insn_length (mo) != 2)
2292     return FALSE;
2293
2294   return TRUE;
2295 }
2296
2297 /* This function is called once, at assembler startup time.  It should set up
2298    all the tables, etc. that the MD part of the assembler will need.  */
2299
2300 void
2301 md_begin (void)
2302 {
2303   const char *retval = NULL;
2304   int i = 0;
2305   int broken = 0;
2306
2307   if (mips_pic != NO_PIC)
2308     {
2309       if (g_switch_seen && g_switch_value != 0)
2310         as_bad (_("-G may not be used in position-independent code"));
2311       g_switch_value = 0;
2312     }
2313
2314   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2315     as_warn (_("Could not set architecture and machine"));
2316
2317   op_hash = hash_new ();
2318
2319   for (i = 0; i < NUMOPCODES;)
2320     {
2321       const char *name = mips_opcodes[i].name;
2322
2323       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2324       if (retval != NULL)
2325         {
2326           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2327                    mips_opcodes[i].name, retval);
2328           /* Probably a memory allocation problem?  Give up now.  */
2329           as_fatal (_("Broken assembler.  No assembly attempted."));
2330         }
2331       do
2332         {
2333           if (mips_opcodes[i].pinfo != INSN_MACRO)
2334             {
2335               if (!validate_mips_insn (&mips_opcodes[i]))
2336                 broken = 1;
2337               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2338                 {
2339                   create_insn (&nop_insn, mips_opcodes + i);
2340                   if (mips_fix_loongson2f_nop)
2341                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2342                   nop_insn.fixed_p = 1;
2343                 }
2344             }
2345           ++i;
2346         }
2347       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2348     }
2349
2350   mips16_op_hash = hash_new ();
2351
2352   i = 0;
2353   while (i < bfd_mips16_num_opcodes)
2354     {
2355       const char *name = mips16_opcodes[i].name;
2356
2357       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2358       if (retval != NULL)
2359         as_fatal (_("internal: can't hash `%s': %s"),
2360                   mips16_opcodes[i].name, retval);
2361       do
2362         {
2363           if (mips16_opcodes[i].pinfo != INSN_MACRO
2364               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2365                   != mips16_opcodes[i].match))
2366             {
2367               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2368                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2369               broken = 1;
2370             }
2371           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2372             {
2373               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2374               mips16_nop_insn.fixed_p = 1;
2375             }
2376           ++i;
2377         }
2378       while (i < bfd_mips16_num_opcodes
2379              && strcmp (mips16_opcodes[i].name, name) == 0);
2380     }
2381
2382   micromips_op_hash = hash_new ();
2383
2384   i = 0;
2385   while (i < bfd_micromips_num_opcodes)
2386     {
2387       const char *name = micromips_opcodes[i].name;
2388
2389       retval = hash_insert (micromips_op_hash, name,
2390                             (void *) &micromips_opcodes[i]);
2391       if (retval != NULL)
2392         as_fatal (_("internal: can't hash `%s': %s"),
2393                   micromips_opcodes[i].name, retval);
2394       do
2395         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2396           {
2397             struct mips_cl_insn *micromips_nop_insn;
2398
2399             if (!validate_micromips_insn (&micromips_opcodes[i]))
2400               broken = 1;
2401
2402             if (micromips_insn_length (micromips_opcodes + i) == 2)
2403               micromips_nop_insn = &micromips_nop16_insn;
2404             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2405               micromips_nop_insn = &micromips_nop32_insn;
2406             else
2407               continue;
2408
2409             if (micromips_nop_insn->insn_mo == NULL
2410                 && strcmp (name, "nop") == 0)
2411               {
2412                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2413                 micromips_nop_insn->fixed_p = 1;
2414               }
2415           }
2416       while (++i < bfd_micromips_num_opcodes
2417              && strcmp (micromips_opcodes[i].name, name) == 0);
2418     }
2419
2420   if (broken)
2421     as_fatal (_("Broken assembler.  No assembly attempted."));
2422
2423   /* We add all the general register names to the symbol table.  This
2424      helps us detect invalid uses of them.  */
2425   for (i = 0; reg_names[i].name; i++) 
2426     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2427                                      reg_names[i].num, /* & RNUM_MASK, */
2428                                      &zero_address_frag));
2429   if (HAVE_NEWABI)
2430     for (i = 0; reg_names_n32n64[i].name; i++) 
2431       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2432                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2433                                        &zero_address_frag));
2434   else
2435     for (i = 0; reg_names_o32[i].name; i++) 
2436       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2437                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2438                                        &zero_address_frag));
2439
2440   mips_no_prev_insn ();
2441
2442   mips_gprmask = 0;
2443   mips_cprmask[0] = 0;
2444   mips_cprmask[1] = 0;
2445   mips_cprmask[2] = 0;
2446   mips_cprmask[3] = 0;
2447
2448   /* set the default alignment for the text section (2**2) */
2449   record_alignment (text_section, 2);
2450
2451   bfd_set_gp_size (stdoutput, g_switch_value);
2452
2453 #ifdef OBJ_ELF
2454   if (IS_ELF)
2455     {
2456       /* On a native system other than VxWorks, sections must be aligned
2457          to 16 byte boundaries.  When configured for an embedded ELF
2458          target, we don't bother.  */
2459       if (strncmp (TARGET_OS, "elf", 3) != 0
2460           && strncmp (TARGET_OS, "vxworks", 7) != 0)
2461         {
2462           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2463           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2464           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2465         }
2466
2467       /* Create a .reginfo section for register masks and a .mdebug
2468          section for debugging information.  */
2469       {
2470         segT seg;
2471         subsegT subseg;
2472         flagword flags;
2473         segT sec;
2474
2475         seg = now_seg;
2476         subseg = now_subseg;
2477
2478         /* The ABI says this section should be loaded so that the
2479            running program can access it.  However, we don't load it
2480            if we are configured for an embedded target */
2481         flags = SEC_READONLY | SEC_DATA;
2482         if (strncmp (TARGET_OS, "elf", 3) != 0)
2483           flags |= SEC_ALLOC | SEC_LOAD;
2484
2485         if (mips_abi != N64_ABI)
2486           {
2487             sec = subseg_new (".reginfo", (subsegT) 0);
2488
2489             bfd_set_section_flags (stdoutput, sec, flags);
2490             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2491
2492             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2493           }
2494         else
2495           {
2496             /* The 64-bit ABI uses a .MIPS.options section rather than
2497                .reginfo section.  */
2498             sec = subseg_new (".MIPS.options", (subsegT) 0);
2499             bfd_set_section_flags (stdoutput, sec, flags);
2500             bfd_set_section_alignment (stdoutput, sec, 3);
2501
2502             /* Set up the option header.  */
2503             {
2504               Elf_Internal_Options opthdr;
2505               char *f;
2506
2507               opthdr.kind = ODK_REGINFO;
2508               opthdr.size = (sizeof (Elf_External_Options)
2509                              + sizeof (Elf64_External_RegInfo));
2510               opthdr.section = 0;
2511               opthdr.info = 0;
2512               f = frag_more (sizeof (Elf_External_Options));
2513               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2514                                              (Elf_External_Options *) f);
2515
2516               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2517             }
2518           }
2519
2520         if (ECOFF_DEBUGGING)
2521           {
2522             sec = subseg_new (".mdebug", (subsegT) 0);
2523             (void) bfd_set_section_flags (stdoutput, sec,
2524                                           SEC_HAS_CONTENTS | SEC_READONLY);
2525             (void) bfd_set_section_alignment (stdoutput, sec, 2);
2526           }
2527         else if (mips_flag_pdr)
2528           {
2529             pdr_seg = subseg_new (".pdr", (subsegT) 0);
2530             (void) bfd_set_section_flags (stdoutput, pdr_seg,
2531                                           SEC_READONLY | SEC_RELOC
2532                                           | SEC_DEBUGGING);
2533             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2534           }
2535
2536         subseg_set (seg, subseg);
2537       }
2538     }
2539 #endif /* OBJ_ELF */
2540
2541   if (! ECOFF_DEBUGGING)
2542     md_obj_begin ();
2543
2544   if (mips_fix_vr4120)
2545     init_vr4120_conflicts ();
2546 }
2547
2548 void
2549 md_mips_end (void)
2550 {
2551   mips_emit_delays ();
2552   if (! ECOFF_DEBUGGING)
2553     md_obj_end ();
2554 }
2555
2556 void
2557 md_assemble (char *str)
2558 {
2559   struct mips_cl_insn insn;
2560   bfd_reloc_code_real_type unused_reloc[3]
2561     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2562
2563   imm_expr.X_op = O_absent;
2564   imm2_expr.X_op = O_absent;
2565   offset_expr.X_op = O_absent;
2566   imm_reloc[0] = BFD_RELOC_UNUSED;
2567   imm_reloc[1] = BFD_RELOC_UNUSED;
2568   imm_reloc[2] = BFD_RELOC_UNUSED;
2569   offset_reloc[0] = BFD_RELOC_UNUSED;
2570   offset_reloc[1] = BFD_RELOC_UNUSED;
2571   offset_reloc[2] = BFD_RELOC_UNUSED;
2572
2573   if (mips_opts.mips16)
2574     mips16_ip (str, &insn);
2575   else
2576     {
2577       mips_ip (str, &insn);
2578       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
2579             str, insn.insn_opcode));
2580     }
2581
2582   if (insn_error)
2583     {
2584       as_bad ("%s `%s'", insn_error, str);
2585       return;
2586     }
2587
2588   if (insn.insn_mo->pinfo == INSN_MACRO)
2589     {
2590       macro_start ();
2591       if (mips_opts.mips16)
2592         mips16_macro (&insn);
2593       else
2594         macro (&insn);
2595       macro_end ();
2596     }
2597   else
2598     {
2599       if (imm_expr.X_op != O_absent)
2600         append_insn (&insn, &imm_expr, imm_reloc, FALSE);
2601       else if (offset_expr.X_op != O_absent)
2602         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
2603       else
2604         append_insn (&insn, NULL, unused_reloc, FALSE);
2605     }
2606 }
2607
2608 /* Convenience functions for abstracting away the differences between
2609    MIPS16 and non-MIPS16 relocations.  */
2610
2611 static inline bfd_boolean
2612 mips16_reloc_p (bfd_reloc_code_real_type reloc)
2613 {
2614   switch (reloc)
2615     {
2616     case BFD_RELOC_MIPS16_JMP:
2617     case BFD_RELOC_MIPS16_GPREL:
2618     case BFD_RELOC_MIPS16_GOT16:
2619     case BFD_RELOC_MIPS16_CALL16:
2620     case BFD_RELOC_MIPS16_HI16_S:
2621     case BFD_RELOC_MIPS16_HI16:
2622     case BFD_RELOC_MIPS16_LO16:
2623       return TRUE;
2624
2625     default:
2626       return FALSE;
2627     }
2628 }
2629
2630 static inline bfd_boolean
2631 micromips_reloc_p (bfd_reloc_code_real_type reloc)
2632 {
2633   switch (reloc)
2634     {
2635     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
2636     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
2637     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
2638     case BFD_RELOC_MICROMIPS_GPREL16:
2639     case BFD_RELOC_MICROMIPS_JMP:
2640     case BFD_RELOC_MICROMIPS_HI16:
2641     case BFD_RELOC_MICROMIPS_HI16_S:
2642     case BFD_RELOC_MICROMIPS_LO16:
2643     case BFD_RELOC_MICROMIPS_LITERAL:
2644     case BFD_RELOC_MICROMIPS_GOT16:
2645     case BFD_RELOC_MICROMIPS_CALL16:
2646     case BFD_RELOC_MICROMIPS_GOT_HI16:
2647     case BFD_RELOC_MICROMIPS_GOT_LO16:
2648     case BFD_RELOC_MICROMIPS_CALL_HI16:
2649     case BFD_RELOC_MICROMIPS_CALL_LO16:
2650     case BFD_RELOC_MICROMIPS_SUB:
2651     case BFD_RELOC_MICROMIPS_GOT_PAGE:
2652     case BFD_RELOC_MICROMIPS_GOT_OFST:
2653     case BFD_RELOC_MICROMIPS_GOT_DISP:
2654     case BFD_RELOC_MICROMIPS_HIGHEST:
2655     case BFD_RELOC_MICROMIPS_HIGHER:
2656     case BFD_RELOC_MICROMIPS_SCN_DISP:
2657     case BFD_RELOC_MICROMIPS_JALR:
2658       return TRUE;
2659
2660     default:
2661       return FALSE;
2662     }
2663 }
2664
2665 static inline bfd_boolean
2666 got16_reloc_p (bfd_reloc_code_real_type reloc)
2667 {
2668   return (reloc == BFD_RELOC_MIPS_GOT16
2669           || reloc == BFD_RELOC_MIPS16_GOT16
2670           || reloc == BFD_RELOC_MICROMIPS_GOT16);
2671 }
2672
2673 static inline bfd_boolean
2674 hi16_reloc_p (bfd_reloc_code_real_type reloc)
2675 {
2676   return (reloc == BFD_RELOC_HI16_S
2677           || reloc == BFD_RELOC_MIPS16_HI16_S
2678           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
2679 }
2680
2681 static inline bfd_boolean
2682 lo16_reloc_p (bfd_reloc_code_real_type reloc)
2683 {
2684   return (reloc == BFD_RELOC_LO16
2685           || reloc == BFD_RELOC_MIPS16_LO16
2686           || reloc == BFD_RELOC_MICROMIPS_LO16);
2687 }
2688
2689 static inline bfd_boolean
2690 jmp_reloc_p (bfd_reloc_code_real_type reloc)
2691 {
2692   return (reloc == BFD_RELOC_MIPS_JMP
2693           || reloc == BFD_RELOC_MICROMIPS_JMP);
2694 }
2695
2696 static inline bfd_boolean
2697 jalr_reloc_p (bfd_reloc_code_real_type reloc)
2698 {
2699   return (reloc == BFD_RELOC_MIPS_JALR
2700           || reloc == BFD_RELOC_MICROMIPS_JALR);
2701 }
2702
2703 /* Return true if the given relocation might need a matching %lo().
2704    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
2705    need a matching %lo() when applied to local symbols.  */
2706
2707 static inline bfd_boolean
2708 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
2709 {
2710   return (HAVE_IN_PLACE_ADDENDS
2711           && (hi16_reloc_p (reloc)
2712               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
2713                  all GOT16 relocations evaluate to "G".  */
2714               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
2715 }
2716
2717 /* Return the type of %lo() reloc needed by RELOC, given that
2718    reloc_needs_lo_p.  */
2719
2720 static inline bfd_reloc_code_real_type
2721 matching_lo_reloc (bfd_reloc_code_real_type reloc)
2722 {
2723   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
2724           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
2725              : BFD_RELOC_LO16));
2726 }
2727
2728 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
2729    relocation.  */
2730
2731 static inline bfd_boolean
2732 fixup_has_matching_lo_p (fixS *fixp)
2733 {
2734   return (fixp->fx_next != NULL
2735           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
2736           && fixp->fx_addsy == fixp->fx_next->fx_addsy
2737           && fixp->fx_offset == fixp->fx_next->fx_offset);
2738 }
2739
2740 /* This function returns true if modifying a register requires a
2741    delay.  */
2742
2743 static int
2744 reg_needs_delay (unsigned int reg)
2745 {
2746   unsigned long prev_pinfo;
2747
2748   prev_pinfo = history[0].insn_mo->pinfo;
2749   if (! mips_opts.noreorder
2750       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
2751            && ! gpr_interlocks)
2752           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
2753               && ! cop_interlocks)))
2754     {
2755       /* A load from a coprocessor or from memory.  All load delays
2756          delay the use of general register rt for one instruction.  */
2757       /* Itbl support may require additional care here.  */
2758       know (prev_pinfo & INSN_WRITE_GPR_T);
2759       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
2760         return 1;
2761     }
2762
2763   return 0;
2764 }
2765
2766 /* Move all labels in insn_labels to the current insertion point.  */
2767
2768 static void
2769 mips_move_labels (void)
2770 {
2771   segment_info_type *si = seg_info (now_seg);
2772   struct insn_label_list *l;
2773   valueT val;
2774
2775   for (l = si->label_list; l != NULL; l = l->next)
2776     {
2777       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
2778       symbol_set_frag (l->label, frag_now);
2779       val = (valueT) frag_now_fix ();
2780       /* MIPS16/microMIPS text labels are stored as odd.  */
2781       if (HAVE_CODE_COMPRESSION)
2782         ++val;
2783       S_SET_VALUE (l->label, val);
2784     }
2785 }
2786
2787 static bfd_boolean
2788 s_is_linkonce (symbolS *sym, segT from_seg)
2789 {
2790   bfd_boolean linkonce = FALSE;
2791   segT symseg = S_GET_SEGMENT (sym);
2792
2793   if (symseg != from_seg && !S_IS_LOCAL (sym))
2794     {
2795       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
2796         linkonce = TRUE;
2797 #ifdef OBJ_ELF
2798       /* The GNU toolchain uses an extension for ELF: a section
2799          beginning with the magic string .gnu.linkonce is a
2800          linkonce section.  */
2801       if (strncmp (segment_name (symseg), ".gnu.linkonce",
2802                    sizeof ".gnu.linkonce" - 1) == 0)
2803         linkonce = TRUE;
2804 #endif
2805     }
2806   return linkonce;
2807 }
2808
2809 /* Mark instruction labels in MIPS16/microMIPS mode.  This permits the
2810    linker to handle them specially, such as generating jalx instructions
2811    when needed.  We also make them odd for the duration of the assembly,
2812    in order to generate the right sort of code.  We will make them even
2813    in the adjust_symtab routine, while leaving them marked.  This is
2814    convenient for the debugger and the disassembler.  The linker knows
2815    to make them odd again.  */
2816
2817 static void
2818 mips_compressed_mark_labels (void)
2819 {
2820   segment_info_type *si = seg_info (now_seg);
2821   struct insn_label_list *l;
2822
2823   gas_assert (HAVE_CODE_COMPRESSION);
2824
2825   for (l = si->label_list; l != NULL; l = l->next)
2826    {
2827       symbolS *label = l->label;
2828
2829 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
2830       if (IS_ELF)
2831         {
2832           if (mips_opts.mips16)
2833             S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
2834           else
2835             S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
2836         }
2837 #endif
2838       if ((S_GET_VALUE (label) & 1) == 0
2839         /* Don't adjust the address if the label is global or weak, or
2840            in a link-once section, since we'll be emitting symbol reloc
2841            references to it which will be patched up by the linker, and
2842            the final value of the symbol may or may not be MIPS16/microMIPS.  */
2843           && ! S_IS_WEAK (label)
2844           && ! S_IS_EXTERNAL (label)
2845           && ! s_is_linkonce (label, now_seg))
2846         S_SET_VALUE (label, S_GET_VALUE (label) | 1);
2847     }
2848 }
2849
2850 /* End the current frag.  Make it a variant frag and record the
2851    relaxation info.  */
2852
2853 static void
2854 relax_close_frag (void)
2855 {
2856   mips_macro_warning.first_frag = frag_now;
2857   frag_var (rs_machine_dependent, 0, 0,
2858             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
2859             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
2860
2861   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
2862   mips_relax.first_fixup = 0;
2863 }
2864
2865 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
2866    See the comment above RELAX_ENCODE for more details.  */
2867
2868 static void
2869 relax_start (symbolS *symbol)
2870 {
2871   gas_assert (mips_relax.sequence == 0);
2872   mips_relax.sequence = 1;
2873   mips_relax.symbol = symbol;
2874 }
2875
2876 /* Start generating the second version of a relaxable sequence.
2877    See the comment above RELAX_ENCODE for more details.  */
2878
2879 static void
2880 relax_switch (void)
2881 {
2882   gas_assert (mips_relax.sequence == 1);
2883   mips_relax.sequence = 2;
2884 }
2885
2886 /* End the current relaxable sequence.  */
2887
2888 static void
2889 relax_end (void)
2890 {
2891   gas_assert (mips_relax.sequence == 2);
2892   relax_close_frag ();
2893   mips_relax.sequence = 0;
2894 }
2895
2896 /* Return the mask of core registers that instruction IP may
2897    read or write.  */
2898
2899 static unsigned int
2900 gpr_mod_mask (const struct mips_cl_insn *ip)
2901 {
2902   unsigned long pinfo, pinfo2;
2903   unsigned int mask;
2904
2905   mask = 0;
2906   pinfo = ip->insn_mo->pinfo;
2907   pinfo2 = ip->insn_mo->pinfo2;
2908   if (mips_opts.micromips)
2909     {
2910       if (pinfo2 & INSN2_MOD_GPR_MB)
2911         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
2912       if (pinfo2 & INSN2_MOD_GPR_MC)
2913         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
2914       if (pinfo2 & INSN2_MOD_GPR_MD)
2915         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
2916       if (pinfo2 & INSN2_MOD_GPR_ME)
2917         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
2918       if (pinfo2 & INSN2_MOD_GPR_MF)
2919         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
2920       if (pinfo2 & INSN2_MOD_GPR_MG)
2921         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
2922       if (pinfo2 & INSN2_MOD_GPR_MHI)
2923         {
2924           mask |= 1 << micromips_to_32_reg_h_map[EXTRACT_OPERAND (1, MH, *ip)];
2925           mask |= 1 << micromips_to_32_reg_i_map[EXTRACT_OPERAND (1, MI, *ip)];
2926         }
2927       if (pinfo2 & INSN2_MOD_GPR_MJ)
2928         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
2929       if (pinfo2 & INSN2_MOD_GPR_MM)
2930         mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
2931       if (pinfo2 & INSN2_MOD_GPR_MN)
2932         mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
2933       if (pinfo2 & INSN2_MOD_GPR_MP)
2934         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
2935       if (pinfo2 & INSN2_MOD_GPR_MQ)
2936         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
2937       if (pinfo2 & INSN2_MOD_SP)
2938         mask |= 1 << SP;
2939     }
2940   return mask;
2941 }
2942
2943 /* Return the mask of core registers that IP reads.  */
2944
2945 static unsigned int
2946 gpr_read_mask (const struct mips_cl_insn *ip)
2947 {
2948   unsigned long pinfo, pinfo2;
2949   unsigned int mask;
2950
2951   mask = gpr_mod_mask (ip);
2952   pinfo = ip->insn_mo->pinfo;
2953   pinfo2 = ip->insn_mo->pinfo2;
2954   if (mips_opts.mips16)
2955     {
2956       if (pinfo & MIPS16_INSN_READ_X)
2957         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
2958       if (pinfo & MIPS16_INSN_READ_Y)
2959         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
2960       if (pinfo & MIPS16_INSN_READ_T)
2961         mask |= 1 << TREG;
2962       if (pinfo & MIPS16_INSN_READ_SP)
2963         mask |= 1 << SP;
2964       if (pinfo & MIPS16_INSN_READ_31)
2965         mask |= 1 << RA;
2966       if (pinfo & MIPS16_INSN_READ_Z)
2967         mask |= 1 << (mips16_to_32_reg_map
2968                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
2969       if (pinfo & MIPS16_INSN_READ_GPR_X)
2970         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
2971     }
2972   else if (mips_opts.micromips)
2973     {
2974       if (pinfo & INSN_READ_GPR_T)
2975         mask |= 1 << EXTRACT_OPERAND (1, RT, *ip);
2976       if (pinfo & INSN_READ_GPR_S)
2977         mask |= 1 << EXTRACT_OPERAND (1, RS, *ip);
2978       if (pinfo2 & INSN2_READ_GPR_31)
2979         mask |= 1 << RA;
2980       if (pinfo2 & INSN2_READ_GP)
2981         mask |= 1 << GP;
2982     }
2983   else
2984     {
2985       if (pinfo2 & INSN2_READ_GPR_D)
2986         mask |= 1 << EXTRACT_OPERAND (0, RD, *ip);
2987       if (pinfo & INSN_READ_GPR_T)
2988         mask |= 1 << EXTRACT_OPERAND (0, RT, *ip);
2989       if (pinfo & INSN_READ_GPR_S)
2990         mask |= 1 << EXTRACT_OPERAND (0, RS, *ip);
2991       if (pinfo2 & INSN2_READ_GPR_Z)
2992         mask |= 1 << EXTRACT_OPERAND (0, RZ, *ip);
2993     }
2994   /* Don't include register 0.  */
2995   return mask & ~1;
2996 }
2997
2998 /* Return the mask of core registers that IP writes.  */
2999
3000 static unsigned int
3001 gpr_write_mask (const struct mips_cl_insn *ip)
3002 {
3003   unsigned long pinfo, pinfo2;
3004   unsigned int mask;
3005
3006   mask = gpr_mod_mask (ip);
3007   pinfo = ip->insn_mo->pinfo;
3008   pinfo2 = ip->insn_mo->pinfo2;
3009   if (mips_opts.mips16)
3010     {
3011       if (pinfo & MIPS16_INSN_WRITE_X)
3012         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3013       if (pinfo & MIPS16_INSN_WRITE_Y)
3014         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3015       if (pinfo & MIPS16_INSN_WRITE_Z)
3016         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3017       if (pinfo & MIPS16_INSN_WRITE_T)
3018         mask |= 1 << TREG;
3019       if (pinfo & MIPS16_INSN_WRITE_SP)
3020         mask |= 1 << SP;
3021       if (pinfo & MIPS16_INSN_WRITE_31)
3022         mask |= 1 << RA;
3023       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3024         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3025     }
3026   else if (mips_opts.micromips)
3027     {
3028       if (pinfo & INSN_WRITE_GPR_D)
3029         mask |= 1 << EXTRACT_OPERAND (1, RD, *ip);
3030       if (pinfo & INSN_WRITE_GPR_T)
3031         mask |= 1 << EXTRACT_OPERAND (1, RT, *ip);
3032       if (pinfo2 & INSN2_WRITE_GPR_S)
3033         mask |= 1 << EXTRACT_OPERAND (1, RS, *ip);
3034       if (pinfo & INSN_WRITE_GPR_31)
3035         mask |= 1 << RA;
3036     }
3037   else
3038     {
3039       if (pinfo & INSN_WRITE_GPR_D)
3040         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3041       if (pinfo & INSN_WRITE_GPR_T)
3042         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3043       if (pinfo & INSN_WRITE_GPR_31)
3044         mask |= 1 << RA;
3045       if (pinfo2 & INSN2_WRITE_GPR_Z)
3046         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3047     }
3048   /* Don't include register 0.  */
3049   return mask & ~1;
3050 }
3051
3052 /* Return the mask of floating-point registers that IP reads.  */
3053
3054 static unsigned int
3055 fpr_read_mask (const struct mips_cl_insn *ip)
3056 {
3057   unsigned long pinfo, pinfo2;
3058   unsigned int mask;
3059
3060   mask = 0;
3061   pinfo = ip->insn_mo->pinfo;
3062   pinfo2 = ip->insn_mo->pinfo2;
3063   if (mips_opts.micromips)
3064     {
3065       if (pinfo2 & INSN2_READ_FPR_D)
3066         mask |= 1 << EXTRACT_OPERAND (1, FD, *ip);
3067       if (pinfo & INSN_READ_FPR_S)
3068         mask |= 1 << EXTRACT_OPERAND (1, FS, *ip);
3069       if (pinfo & INSN_READ_FPR_T)
3070         mask |= 1 << EXTRACT_OPERAND (1, FT, *ip);
3071       if (pinfo & INSN_READ_FPR_R)
3072         mask |= 1 << EXTRACT_OPERAND (1, FR, *ip);
3073     }
3074   else if (!mips_opts.mips16)
3075     {
3076       if (pinfo & INSN_READ_FPR_S)
3077         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3078       if (pinfo & INSN_READ_FPR_T)
3079         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3080       if (pinfo & INSN_READ_FPR_R)
3081         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3082       if (pinfo2 & INSN2_READ_FPR_Z)
3083         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3084     }
3085   /* Conservatively treat all operands to an FP_D instruction are doubles.
3086      (This is overly pessimistic for things like cvt.d.s.)  */
3087   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3088     mask |= mask << 1;
3089   return mask;
3090 }
3091
3092 /* Return the mask of floating-point registers that IP writes.  */
3093
3094 static unsigned int
3095 fpr_write_mask (const struct mips_cl_insn *ip)
3096 {
3097   unsigned long pinfo, pinfo2;
3098   unsigned int mask;
3099
3100   mask = 0;
3101   pinfo = ip->insn_mo->pinfo;
3102   pinfo2 = ip->insn_mo->pinfo2;
3103   if (mips_opts.micromips)
3104     {
3105       if (pinfo2 & INSN_WRITE_FPR_D)
3106         mask |= 1 << EXTRACT_OPERAND (1, FD, *ip);
3107       if (pinfo & INSN_WRITE_FPR_S)
3108         mask |= 1 << EXTRACT_OPERAND (1, FS, *ip);
3109       if (pinfo & INSN_WRITE_FPR_T)
3110         mask |= 1 << EXTRACT_OPERAND (1, FT, *ip);
3111     }
3112   else if (!mips_opts.mips16)
3113     {
3114       if (pinfo & INSN_WRITE_FPR_D)
3115         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3116       if (pinfo & INSN_WRITE_FPR_S)
3117         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3118       if (pinfo & INSN_WRITE_FPR_T)
3119         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3120       if (pinfo2 & INSN2_WRITE_FPR_Z)
3121         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3122     }
3123   /* Conservatively treat all operands to an FP_D instruction are doubles.
3124      (This is overly pessimistic for things like cvt.s.d.)  */
3125   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3126     mask |= mask << 1;
3127   return mask;
3128 }
3129
3130 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3131    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3132    by VR4120 errata.  */
3133
3134 static unsigned int
3135 classify_vr4120_insn (const char *name)
3136 {
3137   if (strncmp (name, "macc", 4) == 0)
3138     return FIX_VR4120_MACC;
3139   if (strncmp (name, "dmacc", 5) == 0)
3140     return FIX_VR4120_DMACC;
3141   if (strncmp (name, "mult", 4) == 0)
3142     return FIX_VR4120_MULT;
3143   if (strncmp (name, "dmult", 5) == 0)
3144     return FIX_VR4120_DMULT;
3145   if (strstr (name, "div"))
3146     return FIX_VR4120_DIV;
3147   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3148     return FIX_VR4120_MTHILO;
3149   return NUM_FIX_VR4120_CLASSES;
3150 }
3151
3152 #define INSN_ERET  0x42000018
3153 #define INSN_DERET 0x4200001f
3154
3155 /* Return the number of instructions that must separate INSN1 and INSN2,
3156    where INSN1 is the earlier instruction.  Return the worst-case value
3157    for any INSN2 if INSN2 is null.  */
3158
3159 static unsigned int
3160 insns_between (const struct mips_cl_insn *insn1,
3161                const struct mips_cl_insn *insn2)
3162 {
3163   unsigned long pinfo1, pinfo2;
3164   unsigned int mask;
3165
3166   /* This function needs to know which pinfo flags are set for INSN2
3167      and which registers INSN2 uses.  The former is stored in PINFO2 and
3168      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3169      will have every flag set and INSN2_USES_GPR will always return true.  */
3170   pinfo1 = insn1->insn_mo->pinfo;
3171   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3172
3173 #define INSN2_USES_GPR(REG) \
3174   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3175
3176   /* For most targets, write-after-read dependencies on the HI and LO
3177      registers must be separated by at least two instructions.  */
3178   if (!hilo_interlocks)
3179     {
3180       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3181         return 2;
3182       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3183         return 2;
3184     }
3185
3186   /* If we're working around r7000 errata, there must be two instructions
3187      between an mfhi or mflo and any instruction that uses the result.  */
3188   if (mips_7000_hilo_fix
3189       && !mips_opts.micromips
3190       && MF_HILO_INSN (pinfo1)
3191       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3192     return 2;
3193
3194   /* If we're working around 24K errata, one instruction is required
3195      if an ERET or DERET is followed by a branch instruction.  */
3196   if (mips_fix_24k && !mips_opts.micromips)
3197     {
3198       if (insn1->insn_opcode == INSN_ERET
3199           || insn1->insn_opcode == INSN_DERET)
3200         {
3201           if (insn2 == NULL
3202               || insn2->insn_opcode == INSN_ERET
3203               || insn2->insn_opcode == INSN_DERET
3204               || (insn2->insn_mo->pinfo
3205                   & (INSN_UNCOND_BRANCH_DELAY
3206                      | INSN_COND_BRANCH_DELAY
3207                      | INSN_COND_BRANCH_LIKELY)) != 0)
3208             return 1;
3209         }
3210     }
3211
3212   /* If working around VR4120 errata, check for combinations that need
3213      a single intervening instruction.  */
3214   if (mips_fix_vr4120 && !mips_opts.micromips)
3215     {
3216       unsigned int class1, class2;
3217
3218       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3219       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3220         {
3221           if (insn2 == NULL)
3222             return 1;
3223           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3224           if (vr4120_conflicts[class1] & (1 << class2))
3225             return 1;
3226         }
3227     }
3228
3229   if (!HAVE_CODE_COMPRESSION)
3230     {
3231       /* Check for GPR or coprocessor load delays.  All such delays
3232          are on the RT register.  */
3233       /* Itbl support may require additional care here.  */
3234       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3235           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3236         {
3237           know (pinfo1 & INSN_WRITE_GPR_T);
3238           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3239             return 1;
3240         }
3241
3242       /* Check for generic coprocessor hazards.
3243
3244          This case is not handled very well.  There is no special
3245          knowledge of CP0 handling, and the coprocessors other than
3246          the floating point unit are not distinguished at all.  */
3247       /* Itbl support may require additional care here. FIXME!
3248          Need to modify this to include knowledge about
3249          user specified delays!  */
3250       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3251                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3252         {
3253           /* Handle cases where INSN1 writes to a known general coprocessor
3254              register.  There must be a one instruction delay before INSN2
3255              if INSN2 reads that register, otherwise no delay is needed.  */
3256           mask = fpr_write_mask (insn1);
3257           if (mask != 0)
3258             {
3259               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3260                 return 1;
3261             }
3262           else
3263             {
3264               /* Read-after-write dependencies on the control registers
3265                  require a two-instruction gap.  */
3266               if ((pinfo1 & INSN_WRITE_COND_CODE)
3267                   && (pinfo2 & INSN_READ_COND_CODE))
3268                 return 2;
3269
3270               /* We don't know exactly what INSN1 does.  If INSN2 is
3271                  also a coprocessor instruction, assume there must be
3272                  a one instruction gap.  */
3273               if (pinfo2 & INSN_COP)
3274                 return 1;
3275             }
3276         }
3277
3278       /* Check for read-after-write dependencies on the coprocessor
3279          control registers in cases where INSN1 does not need a general
3280          coprocessor delay.  This means that INSN1 is a floating point
3281          comparison instruction.  */
3282       /* Itbl support may require additional care here.  */
3283       else if (!cop_interlocks
3284                && (pinfo1 & INSN_WRITE_COND_CODE)
3285                && (pinfo2 & INSN_READ_COND_CODE))
3286         return 1;
3287     }
3288
3289 #undef INSN2_USES_GPR
3290
3291   return 0;
3292 }
3293
3294 /* Return the number of nops that would be needed to work around the
3295    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3296    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3297    that are contained within the first IGNORE instructions of HIST.  */
3298
3299 static int
3300 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3301                  const struct mips_cl_insn *insn)
3302 {
3303   int i, j;
3304   unsigned int mask;
3305
3306   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3307      are not affected by the errata.  */
3308   if (insn != 0
3309       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3310           || strcmp (insn->insn_mo->name, "mtlo") == 0
3311           || strcmp (insn->insn_mo->name, "mthi") == 0))
3312     return 0;
3313
3314   /* Search for the first MFLO or MFHI.  */
3315   for (i = 0; i < MAX_VR4130_NOPS; i++)
3316     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3317       {
3318         /* Extract the destination register.  */
3319         mask = gpr_write_mask (&hist[i]);
3320
3321         /* No nops are needed if INSN reads that register.  */
3322         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3323           return 0;
3324
3325         /* ...or if any of the intervening instructions do.  */
3326         for (j = 0; j < i; j++)
3327           if (gpr_read_mask (&hist[j]) & mask)
3328             return 0;
3329
3330         if (i >= ignore)
3331           return MAX_VR4130_NOPS - i;
3332       }
3333   return 0;
3334 }
3335
3336 #define BASE_REG_EQ(INSN1, INSN2)       \
3337   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3338       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3339
3340 /* Return the minimum alignment for this store instruction.  */
3341
3342 static int
3343 fix_24k_align_to (const struct mips_opcode *mo)
3344 {
3345   if (strcmp (mo->name, "sh") == 0)
3346     return 2;
3347
3348   if (strcmp (mo->name, "swc1") == 0
3349       || strcmp (mo->name, "swc2") == 0
3350       || strcmp (mo->name, "sw") == 0
3351       || strcmp (mo->name, "sc") == 0
3352       || strcmp (mo->name, "s.s") == 0)
3353     return 4;
3354
3355   if (strcmp (mo->name, "sdc1") == 0
3356       || strcmp (mo->name, "sdc2") == 0
3357       || strcmp (mo->name, "s.d") == 0)
3358     return 8;
3359
3360   /* sb, swl, swr */
3361   return 1;
3362 }
3363
3364 struct fix_24k_store_info
3365   {
3366     /* Immediate offset, if any, for this store instruction.  */
3367     short off;
3368     /* Alignment required by this store instruction.  */
3369     int align_to;
3370     /* True for register offsets.  */
3371     int register_offset;
3372   };
3373
3374 /* Comparison function used by qsort.  */
3375
3376 static int
3377 fix_24k_sort (const void *a, const void *b)
3378 {
3379   const struct fix_24k_store_info *pos1 = a;
3380   const struct fix_24k_store_info *pos2 = b;
3381
3382   return (pos1->off - pos2->off);
3383 }
3384
3385 /* INSN is a store instruction.  Try to record the store information
3386    in STINFO.  Return false if the information isn't known.  */
3387
3388 static bfd_boolean
3389 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3390                            const struct mips_cl_insn *insn)
3391 {
3392   /* The instruction must have a known offset.  */
3393   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3394     return FALSE;
3395
3396   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3397   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3398   return TRUE;
3399 }
3400
3401 /* Return the number of nops that would be needed to work around the 24k
3402    "lost data on stores during refill" errata if instruction INSN
3403    immediately followed the 2 instructions described by HIST.
3404    Ignore hazards that are contained within the first IGNORE
3405    instructions of HIST.
3406
3407    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3408    for the data cache refills and store data. The following describes
3409    the scenario where the store data could be lost.
3410
3411    * A data cache miss, due to either a load or a store, causing fill
3412      data to be supplied by the memory subsystem
3413    * The first three doublewords of fill data are returned and written
3414      into the cache
3415    * A sequence of four stores occurs in consecutive cycles around the
3416      final doubleword of the fill:
3417    * Store A
3418    * Store B
3419    * Store C
3420    * Zero, One or more instructions
3421    * Store D
3422
3423    The four stores A-D must be to different doublewords of the line that
3424    is being filled. The fourth instruction in the sequence above permits
3425    the fill of the final doubleword to be transferred from the FSB into
3426    the cache. In the sequence above, the stores may be either integer
3427    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
3428    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
3429    different doublewords on the line. If the floating point unit is
3430    running in 1:2 mode, it is not possible to create the sequence above
3431    using only floating point store instructions.
3432
3433    In this case, the cache line being filled is incorrectly marked
3434    invalid, thereby losing the data from any store to the line that
3435    occurs between the original miss and the completion of the five
3436    cycle sequence shown above.
3437
3438    The workarounds are:
3439
3440    * Run the data cache in write-through mode.
3441    * Insert a non-store instruction between
3442      Store A and Store B or Store B and Store C.  */
3443   
3444 static int
3445 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
3446               const struct mips_cl_insn *insn)
3447 {
3448   struct fix_24k_store_info pos[3];
3449   int align, i, base_offset;
3450
3451   if (ignore >= 2)
3452     return 0;
3453
3454   /* If the previous instruction wasn't a store, there's nothing to
3455      worry about.  */
3456   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3457     return 0;
3458
3459   /* If the instructions after the previous one are unknown, we have
3460      to assume the worst.  */
3461   if (!insn)
3462     return 1;
3463
3464   /* Check whether we are dealing with three consecutive stores.  */
3465   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
3466       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3467     return 0;
3468
3469   /* If we don't know the relationship between the store addresses,
3470      assume the worst.  */
3471   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
3472       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
3473     return 1;
3474
3475   if (!fix_24k_record_store_info (&pos[0], insn)
3476       || !fix_24k_record_store_info (&pos[1], &hist[0])
3477       || !fix_24k_record_store_info (&pos[2], &hist[1]))
3478     return 1;
3479
3480   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
3481
3482   /* Pick a value of ALIGN and X such that all offsets are adjusted by
3483      X bytes and such that the base register + X is known to be aligned
3484      to align bytes.  */
3485
3486   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
3487     align = 8;
3488   else
3489     {
3490       align = pos[0].align_to;
3491       base_offset = pos[0].off;
3492       for (i = 1; i < 3; i++)
3493         if (align < pos[i].align_to)
3494           {
3495             align = pos[i].align_to;
3496             base_offset = pos[i].off;
3497           }
3498       for (i = 0; i < 3; i++)
3499         pos[i].off -= base_offset;
3500     }
3501
3502   pos[0].off &= ~align + 1;
3503   pos[1].off &= ~align + 1;
3504   pos[2].off &= ~align + 1;
3505
3506   /* If any two stores write to the same chunk, they also write to the
3507      same doubleword.  The offsets are still sorted at this point.  */
3508   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
3509     return 0;
3510
3511   /* A range of at least 9 bytes is needed for the stores to be in
3512      non-overlapping doublewords.  */
3513   if (pos[2].off - pos[0].off <= 8)
3514     return 0;
3515
3516   if (pos[2].off - pos[1].off >= 24
3517       || pos[1].off - pos[0].off >= 24
3518       || pos[2].off - pos[0].off >= 32)
3519     return 0;
3520
3521   return 1;
3522 }
3523
3524 /* Return the number of nops that would be needed if instruction INSN
3525    immediately followed the MAX_NOPS instructions given by HIST,
3526    where HIST[0] is the most recent instruction.  Ignore hazards
3527    between INSN and the first IGNORE instructions in HIST.
3528
3529    If INSN is null, return the worse-case number of nops for any
3530    instruction.  */
3531
3532 static int
3533 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
3534                const struct mips_cl_insn *insn)
3535 {
3536   int i, nops, tmp_nops;
3537
3538   nops = 0;
3539   for (i = ignore; i < MAX_DELAY_NOPS; i++)
3540     {
3541       tmp_nops = insns_between (hist + i, insn) - i;
3542       if (tmp_nops > nops)
3543         nops = tmp_nops;
3544     }
3545
3546   if (mips_fix_vr4130 && !mips_opts.micromips)
3547     {
3548       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
3549       if (tmp_nops > nops)
3550         nops = tmp_nops;
3551     }
3552
3553   if (mips_fix_24k && !mips_opts.micromips)
3554     {
3555       tmp_nops = nops_for_24k (ignore, hist, insn);
3556       if (tmp_nops > nops)
3557         nops = tmp_nops;
3558     }
3559
3560   return nops;
3561 }
3562
3563 /* The variable arguments provide NUM_INSNS extra instructions that
3564    might be added to HIST.  Return the largest number of nops that
3565    would be needed after the extended sequence, ignoring hazards
3566    in the first IGNORE instructions.  */
3567
3568 static int
3569 nops_for_sequence (int num_insns, int ignore,
3570                    const struct mips_cl_insn *hist, ...)
3571 {
3572   va_list args;
3573   struct mips_cl_insn buffer[MAX_NOPS];
3574   struct mips_cl_insn *cursor;
3575   int nops;
3576
3577   va_start (args, hist);
3578   cursor = buffer + num_insns;
3579   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
3580   while (cursor > buffer)
3581     *--cursor = *va_arg (args, const struct mips_cl_insn *);
3582
3583   nops = nops_for_insn (ignore, buffer, NULL);
3584   va_end (args);
3585   return nops;
3586 }
3587
3588 /* Like nops_for_insn, but if INSN is a branch, take into account the
3589    worst-case delay for the branch target.  */
3590
3591 static int
3592 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
3593                          const struct mips_cl_insn *insn)
3594 {
3595   int nops, tmp_nops;
3596
3597   nops = nops_for_insn (ignore, hist, insn);
3598   if (insn->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3599                               | INSN_COND_BRANCH_DELAY
3600                               | INSN_COND_BRANCH_LIKELY))
3601     {
3602       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
3603                                     hist, insn, NOP_INSN);
3604       if (tmp_nops > nops)
3605         nops = tmp_nops;
3606     }
3607   else if (mips_opts.mips16
3608            && (insn->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3609                                        | MIPS16_INSN_COND_BRANCH)))
3610     {
3611       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
3612       if (tmp_nops > nops)
3613         nops = tmp_nops;
3614     }
3615   return nops;
3616 }
3617
3618 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
3619
3620 static void
3621 fix_loongson2f_nop (struct mips_cl_insn * ip)
3622 {
3623   gas_assert (!HAVE_CODE_COMPRESSION);
3624   if (strcmp (ip->insn_mo->name, "nop") == 0)
3625     ip->insn_opcode = LOONGSON2F_NOP_INSN;
3626 }
3627
3628 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
3629                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
3630
3631 static void
3632 fix_loongson2f_jump (struct mips_cl_insn * ip)
3633 {
3634   gas_assert (!HAVE_CODE_COMPRESSION);
3635   if (strcmp (ip->insn_mo->name, "j") == 0
3636       || strcmp (ip->insn_mo->name, "jr") == 0
3637       || strcmp (ip->insn_mo->name, "jalr") == 0)
3638     {
3639       int sreg;
3640       expressionS ep;
3641
3642       if (! mips_opts.at)
3643         return;
3644
3645       sreg = EXTRACT_OPERAND (0, RS, *ip);
3646       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
3647         return;
3648
3649       ep.X_op = O_constant;
3650       ep.X_add_number = 0xcfff0000;
3651       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
3652       ep.X_add_number = 0xffff;
3653       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
3654       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
3655     }
3656 }
3657
3658 static void
3659 fix_loongson2f (struct mips_cl_insn * ip)
3660 {
3661   if (mips_fix_loongson2f_nop)
3662     fix_loongson2f_nop (ip);
3663
3664   if (mips_fix_loongson2f_jump)
3665     fix_loongson2f_jump (ip);
3666 }
3667
3668 /* IP is a branch that has a delay slot, and we need to fill it
3669    automatically.   Return true if we can do that by swapping IP
3670    with the previous instruction.  */
3671
3672 static bfd_boolean
3673 can_swap_branch_p (struct mips_cl_insn *ip)
3674 {
3675   unsigned long pinfo, pinfo2, prev_pinfo;
3676   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
3677
3678   /* For microMIPS, disable reordering.  */
3679   if (mips_opts.micromips)
3680     return FALSE;
3681
3682   /* -O2 and above is required for this optimization.  */
3683   if (mips_optimize < 2)
3684     return FALSE;
3685
3686   /* If we have seen .set volatile or .set nomove, don't optimize.  */
3687   if (mips_opts.nomove)
3688     return FALSE;
3689
3690   /* We can't swap if the previous instruction's position is fixed.  */
3691   if (history[0].fixed_p)
3692     return FALSE;
3693
3694   /* If the previous previous insn was in a .set noreorder, we can't
3695      swap.  Actually, the MIPS assembler will swap in this situation.
3696      However, gcc configured -with-gnu-as will generate code like
3697
3698         .set    noreorder
3699         lw      $4,XXX
3700         .set    reorder
3701         INSN
3702         bne     $4,$0,foo
3703
3704      in which we can not swap the bne and INSN.  If gcc is not configured
3705      -with-gnu-as, it does not output the .set pseudo-ops.  */
3706   if (history[1].noreorder_p)
3707     return FALSE;
3708
3709   /* If the previous instruction had a fixup in mips16 mode, we can not
3710      swap.  This normally means that the previous instruction was a 4
3711      byte branch anyhow.  */
3712   if (mips_opts.mips16 && history[0].fixp[0])
3713     return FALSE;
3714
3715   /* If the branch is itself the target of a branch, we can not swap.
3716      We cheat on this; all we check for is whether there is a label on
3717      this instruction.  If there are any branches to anything other than
3718      a label, users must use .set noreorder.  */
3719   if (seg_info (now_seg)->label_list)
3720     return FALSE;
3721
3722   /* If the previous instruction is in a variant frag other than this
3723      branch's one, we cannot do the swap.  This does not apply to the
3724      mips16, which uses variant frags for different purposes.  */
3725   if (!HAVE_CODE_COMPRESSION
3726       && history[0].frag
3727       && history[0].frag->fr_type == rs_machine_dependent)
3728     return FALSE;
3729
3730   /* We do not swap with instructions that cannot architecturally
3731      be placed in a branch delay slot, such as SYNC or ERET.  We
3732      also refrain from swapping with a trap instruction, since it
3733      complicates trap handlers to have the trap instruction be in
3734      a delay slot.  */
3735   prev_pinfo = history[0].insn_mo->pinfo;
3736   if (prev_pinfo & INSN_NO_DELAY_SLOT)
3737     return FALSE;
3738
3739   /* Check for conflicts between the branch and the instructions
3740      before the candidate delay slot.  */
3741   if (nops_for_insn (0, history + 1, ip) > 0)
3742     return FALSE;
3743
3744   /* Check for conflicts between the swapped sequence and the
3745      target of the branch.  */
3746   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
3747     return FALSE;
3748
3749   /* If the branch reads a register that the previous
3750      instruction sets, we can not swap.  */
3751   gpr_read = gpr_read_mask (ip);
3752   prev_gpr_write = gpr_write_mask (&history[0]);
3753   if (gpr_read & prev_gpr_write)
3754     return FALSE;
3755
3756   /* If the branch writes a register that the previous
3757      instruction sets, we can not swap.  */
3758   gpr_write = gpr_write_mask (ip);
3759   if (gpr_write & prev_gpr_write)
3760     return FALSE;
3761
3762   /* If the branch writes a register that the previous
3763      instruction reads, we can not swap.  */
3764   prev_gpr_read = gpr_read_mask (&history[0]);
3765   if (gpr_write & prev_gpr_read)
3766     return FALSE;
3767
3768   /* If one instruction sets a condition code and the
3769      other one uses a condition code, we can not swap.  */
3770   pinfo = ip->insn_mo->pinfo;
3771   if ((pinfo & INSN_READ_COND_CODE)
3772       && (prev_pinfo & INSN_WRITE_COND_CODE))
3773     return FALSE;
3774   if ((pinfo & INSN_WRITE_COND_CODE)
3775       && (prev_pinfo & INSN_READ_COND_CODE))
3776     return FALSE;
3777
3778   /* If the previous instruction uses the PC, we can not swap.  */
3779   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
3780     return FALSE;
3781
3782   /* If the previous instruction has an incorrect size for a fixed
3783      branch delay slot in microMIPS mode, we cannot swap.  */
3784   if (mips_opts.micromips)
3785     {
3786       pinfo2 = ip->insn_mo->pinfo;
3787       if ((pinfo2 & INSN2_BRANCH_DELAY_16BIT)
3788           && insn_length (history) != 2)
3789         return FALSE;
3790
3791       if ((pinfo2 & INSN2_BRANCH_DELAY_32BIT)
3792           && insn_length (history) != 4)
3793         return FALSE;
3794     }
3795   return TRUE;
3796 }
3797
3798 /* Decide how we should add IP to the instruction stream.  */
3799
3800 static enum append_method
3801 get_append_method (struct mips_cl_insn *ip)
3802 {
3803   unsigned long pinfo;
3804
3805   /* The relaxed version of a macro sequence must be inherently
3806      hazard-free.  */
3807   if (mips_relax.sequence == 2)
3808     return APPEND_ADD;
3809
3810   /* We must not dabble with instructions in a ".set norerorder" block.  */
3811   if (mips_opts.noreorder)
3812     return APPEND_ADD;
3813
3814   /* Otherwise, it's our responsibility to fill branch delay slots.  */
3815   pinfo = ip->insn_mo->pinfo;
3816   if ((pinfo & INSN_UNCOND_BRANCH_DELAY)
3817       || (pinfo & INSN_COND_BRANCH_DELAY))
3818     {
3819       if (can_swap_branch_p (ip))
3820         return APPEND_SWAP;
3821
3822       if (mips_opts.mips16
3823           && ISA_SUPPORTS_MIPS16E
3824           && (pinfo & INSN_UNCOND_BRANCH_DELAY)
3825           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
3826         return APPEND_ADD_COMPACT;
3827
3828       return APPEND_ADD_WITH_NOP;
3829     }
3830
3831   /* We don't bother trying to track the target of branches, so there's
3832      nothing we can use to fill a branch-likely slot.  */
3833   if (pinfo & INSN_COND_BRANCH_LIKELY)
3834     return APPEND_ADD_WITH_NOP;
3835
3836   return APPEND_ADD;
3837 }
3838
3839 /* IP is a MIPS16 instruction whose opcode we have just changed.
3840    Point IP->insn_mo to the new opcode's definition.  */
3841
3842 static void
3843 find_altered_mips16_opcode (struct mips_cl_insn *ip)
3844 {
3845   const struct mips_opcode *mo, *end;
3846
3847   end = &mips16_opcodes[bfd_mips16_num_opcodes];
3848   for (mo = ip->insn_mo; mo < end; mo++)
3849     if ((ip->insn_opcode & mo->mask) == mo->match)
3850       {
3851         ip->insn_mo = mo;
3852         return;
3853       }
3854   abort ();
3855 }
3856
3857 /* For microMIPS macros, we need to generate a local number label
3858    as the target of branches.  */
3859 #define MICROMIPS_LABEL_CHAR            '\037'
3860 static unsigned long micromips_target_label;
3861 static char micromips_target_name[32];
3862
3863 static char *
3864 micromips_label_name (void)
3865 {
3866   char *p = micromips_target_name;
3867   char symbol_name_temporary[24];
3868   unsigned long l;
3869   int i;
3870
3871   if (*p)
3872     return p;
3873
3874   i = 0;
3875   l = micromips_target_label;
3876 #ifdef LOCAL_LABEL_PREFIX
3877   *p++ = LOCAL_LABEL_PREFIX;
3878 #endif
3879   *p++ = 'L';
3880   *p++ = MICROMIPS_LABEL_CHAR;
3881   do
3882     {
3883       symbol_name_temporary[i++] = l % 10 + '0';
3884       l /= 10;
3885     }
3886   while (l != 0);
3887   while (i > 0)
3888     *p++ = symbol_name_temporary[--i];
3889   *p = '\0';
3890
3891   return micromips_target_name;
3892 }
3893
3894 static void
3895 micromips_label_expr (expressionS *label_expr)
3896 {
3897   label_expr->X_op = O_symbol;
3898   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
3899   label_expr->X_add_number = 0;
3900 }
3901
3902 static void
3903 micromips_label_inc (void)
3904 {
3905   micromips_target_label++;
3906   *micromips_target_name = '\0';
3907 }
3908
3909 static void
3910 micromips_add_label (void)
3911 {
3912   symbolS *s;
3913
3914   s = colon (micromips_label_name ());
3915   micromips_label_inc ();
3916 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
3917   if (IS_ELF)
3918     S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
3919 #endif
3920 }
3921
3922 /* If assembling microMIPS code, then return the microMIPS reloc
3923    corresponding to the requested one if any.  Otherwise return
3924    the reloc unchanged.  */
3925
3926 static bfd_reloc_code_real_type
3927 micromips_map_reloc (bfd_reloc_code_real_type reloc)
3928 {
3929   static const bfd_reloc_code_real_type relocs[][2] =
3930     {
3931       /* Keep sorted incrementally by the left-hand key.  */
3932       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
3933       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
3934       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
3935       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
3936       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
3937       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
3938       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
3939       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
3940       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
3941       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
3942       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
3943       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
3944       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
3945       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
3946       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
3947       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
3948       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
3949       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
3950       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
3951       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
3952       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
3953       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
3954       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
3955       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
3956       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
3957       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
3958       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
3959     };
3960   bfd_reloc_code_real_type r;
3961   size_t i;
3962
3963   if (!mips_opts.micromips)
3964     return reloc;
3965   for (i = 0; i < ARRAY_SIZE (relocs); i++)
3966     {
3967       r = relocs[i][0];
3968       if (r > reloc)
3969         return reloc;
3970       if (r == reloc)
3971         return relocs[i][1];
3972     }
3973   return reloc;
3974 }
3975
3976 /* Output an instruction.  IP is the instruction information.
3977    ADDRESS_EXPR is an operand of the instruction to be used with
3978    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
3979    a macro expansion.  */
3980
3981 static void
3982 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
3983              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
3984 {
3985   unsigned long prev_pinfo, prev_pinfo2, pinfo, pinfo2;
3986   bfd_boolean relaxed_branch = FALSE;
3987   bfd_boolean relax32;
3988   enum append_method method;
3989
3990   if (mips_fix_loongson2f && !mips_opts.micromips)
3991     fix_loongson2f (ip);
3992
3993   mips_mark_labels ();
3994
3995   file_ase_mips16 |= mips_opts.mips16;
3996   file_ase_micromips |= mips_opts.micromips;
3997
3998   prev_pinfo = history[0].insn_mo->pinfo;
3999   prev_pinfo2 = history[0].insn_mo->pinfo2;
4000   pinfo = ip->insn_mo->pinfo;
4001   pinfo2 = ip->insn_mo->pinfo2;
4002
4003   if (mips_opts.micromips
4004       && !expansionp
4005       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
4006            && micromips_insn_length (ip->insn_mo) != 2)
4007           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
4008               && micromips_insn_length (ip->insn_mo) != 4)))
4009     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
4010              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
4011
4012   if (address_expr == NULL)
4013     ip->complete_p = 1;
4014   else if (*reloc_type <= BFD_RELOC_UNUSED
4015            && address_expr->X_op == O_constant)
4016     {
4017       unsigned int tmp;
4018
4019       ip->complete_p = 1;
4020       switch (*reloc_type)
4021         {
4022         case BFD_RELOC_32:
4023           ip->insn_opcode |= address_expr->X_add_number;
4024           break;
4025
4026         case BFD_RELOC_MIPS_HIGHEST:
4027           tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
4028           ip->insn_opcode |= tmp & 0xffff;
4029           break;
4030
4031         case BFD_RELOC_MIPS_HIGHER:
4032           tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
4033           ip->insn_opcode |= tmp & 0xffff;
4034           break;
4035
4036         case BFD_RELOC_HI16_S:
4037           tmp = (address_expr->X_add_number + 0x8000) >> 16;
4038           ip->insn_opcode |= tmp & 0xffff;
4039           break;
4040
4041         case BFD_RELOC_HI16:
4042           ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
4043           break;
4044
4045         case BFD_RELOC_UNUSED:
4046         case BFD_RELOC_LO16:
4047         case BFD_RELOC_MIPS_GOT_DISP:
4048           ip->insn_opcode |= address_expr->X_add_number & 0xffff;
4049           break;
4050
4051         case BFD_RELOC_MIPS_JMP:
4052           {
4053             int shift;
4054
4055             shift = mips_opts.micromips ? 1 : 2;
4056             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4057               as_bad (_("jump to misaligned address (0x%lx)"),
4058                       (unsigned long) address_expr->X_add_number);
4059             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4060                                 & 0x3ffffff);
4061             ip->complete_p = 0;
4062           }
4063           break;
4064
4065         case BFD_RELOC_MIPS16_JMP:
4066           if ((address_expr->X_add_number & 3) != 0)
4067             as_bad (_("jump to misaligned address (0x%lx)"),
4068                     (unsigned long) address_expr->X_add_number);
4069           ip->insn_opcode |=
4070             (((address_expr->X_add_number & 0x7c0000) << 3)
4071                | ((address_expr->X_add_number & 0xf800000) >> 7)
4072                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4073           ip->complete_p = 0;
4074           break;
4075
4076         case BFD_RELOC_16_PCREL_S2:
4077           {
4078             int shift;
4079
4080             shift = mips_opts.micromips ? 1 : 2;
4081             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4082               as_bad (_("branch to misaligned address (0x%lx)"),
4083                       (unsigned long) address_expr->X_add_number);
4084             if (!mips_relax_branch)
4085               {
4086                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4087                     & ~((1 << (shift + 16)) - 1))
4088                   as_bad (_("branch address range overflow (0x%lx)"),
4089                           (unsigned long) address_expr->X_add_number);
4090                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4091                                     & 0xffff);
4092               }
4093             ip->complete_p = 0;
4094           }
4095           break;
4096
4097         default:
4098           internalError ();
4099         }       
4100     }
4101
4102   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4103     {
4104       /* There are a lot of optimizations we could do that we don't.
4105          In particular, we do not, in general, reorder instructions.
4106          If you use gcc with optimization, it will reorder
4107          instructions and generally do much more optimization then we
4108          do here; repeating all that work in the assembler would only
4109          benefit hand written assembly code, and does not seem worth
4110          it.  */
4111       int nops = (mips_optimize == 0
4112                   ? nops_for_insn (0, history, NULL)
4113                   : nops_for_insn_or_target (0, history, ip));
4114       if (nops > 0)
4115         {
4116           fragS *old_frag;
4117           unsigned long old_frag_offset;
4118           int i;
4119
4120           old_frag = frag_now;
4121           old_frag_offset = frag_now_fix ();
4122
4123           for (i = 0; i < nops; i++)
4124             emit_nop ();
4125
4126           if (listing)
4127             {
4128               listing_prev_line ();
4129               /* We may be at the start of a variant frag.  In case we
4130                  are, make sure there is enough space for the frag
4131                  after the frags created by listing_prev_line.  The
4132                  argument to frag_grow here must be at least as large
4133                  as the argument to all other calls to frag_grow in
4134                  this file.  We don't have to worry about being in the
4135                  middle of a variant frag, because the variants insert
4136                  all needed nop instructions themselves.  */
4137               frag_grow (40);
4138             }
4139
4140           mips_move_labels ();
4141
4142 #ifndef NO_ECOFF_DEBUGGING
4143           if (ECOFF_DEBUGGING)
4144             ecoff_fix_loc (old_frag, old_frag_offset);
4145 #endif
4146         }
4147     }
4148   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4149     {
4150       int nops;
4151
4152       /* Work out how many nops in prev_nop_frag are needed by IP,
4153          ignoring hazards generated by the first prev_nop_frag_since
4154          instructions.  */
4155       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4156       gas_assert (nops <= prev_nop_frag_holds);
4157
4158       /* Enforce NOPS as a minimum.  */
4159       if (nops > prev_nop_frag_required)
4160         prev_nop_frag_required = nops;
4161
4162       if (prev_nop_frag_holds == prev_nop_frag_required)
4163         {
4164           /* Settle for the current number of nops.  Update the history
4165              accordingly (for the benefit of any future .set reorder code).  */
4166           prev_nop_frag = NULL;
4167           insert_into_history (prev_nop_frag_since,
4168                                prev_nop_frag_holds, NOP_INSN);
4169         }
4170       else
4171         {
4172           /* Allow this instruction to replace one of the nops that was
4173              tentatively added to prev_nop_frag.  */
4174           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4175           prev_nop_frag_holds--;
4176           prev_nop_frag_since++;
4177         }
4178     }
4179
4180   method = get_append_method (ip);
4181
4182 #ifdef OBJ_ELF
4183   /* The value passed to dwarf2_emit_insn is the distance between
4184      the beginning of the current instruction and the address that
4185      should be recorded in the debug tables.  This is normally the
4186      current address.
4187
4188      For MIPS16/microMIPS debug info we want to use ISA-encoded
4189      addresses, so we use -1 for an address higher by one than the
4190      current one.
4191
4192      If the instruction produced is a branch that we will swap with
4193      the preceding instruction, then we add the displacement by which
4194      the branch will be moved backwards.  This is more appropriate
4195      and for MIPS16/microMIPS code also prevents a debugger from placing
4196      a breakpoint in the middle of the branch (and corrupting code if
4197      software breakpoints are used).  */
4198   dwarf2_emit_insn ((HAVE_CODE_COMPRESSION ? -1 : 0)
4199                     + (method == APPEND_SWAP ? insn_length (history) : 0));
4200 #endif
4201
4202   relax32 = (mips_relax_branch
4203              /* Don't try branch relaxation within .set nomacro, or within
4204                 .set noat if we use $at for PIC computations.  If it turns
4205                 out that the branch was out-of-range, we'll get an error.  */
4206              && !mips_opts.warn_about_macros
4207              && (mips_opts.at || mips_pic == NO_PIC)
4208              /* Don't relax BPOSGE32/64 as they have no complementing
4209                 branches.  */
4210              && !(ip->insn_mo->membership & (INSN_DSP64 | INSN_DSP))
4211              /* Don't try 32-bit branch relaxation when users specify
4212                 16-bit/32-bit instructions.  */
4213              && !forced_insn_length);
4214
4215   if (!HAVE_CODE_COMPRESSION
4216       && address_expr
4217       && relax32
4218       && *reloc_type == BFD_RELOC_16_PCREL_S2
4219       && (pinfo & INSN_UNCOND_BRANCH_DELAY || pinfo & INSN_COND_BRANCH_DELAY
4220           || pinfo & INSN_COND_BRANCH_LIKELY))
4221     {
4222       relaxed_branch = TRUE;
4223       add_relaxed_insn (ip, (relaxed_branch_length
4224                              (NULL, NULL,
4225                               (pinfo & INSN_UNCOND_BRANCH_DELAY) ? -1
4226                               : (pinfo & INSN_COND_BRANCH_LIKELY) ? 1
4227                               : 0)), 4,
4228                         RELAX_BRANCH_ENCODE
4229                         (AT,
4230                          pinfo & INSN_UNCOND_BRANCH_DELAY,
4231                          pinfo & INSN_COND_BRANCH_LIKELY,
4232                          pinfo & INSN_WRITE_GPR_31,
4233                          0),
4234                         address_expr->X_add_symbol,
4235                         address_expr->X_add_number);
4236       *reloc_type = BFD_RELOC_UNUSED;
4237     }
4238   else if (mips_opts.micromips
4239            && address_expr
4240            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4241                || *reloc_type > BFD_RELOC_UNUSED)
4242            && (pinfo & INSN_UNCOND_BRANCH_DELAY
4243                || pinfo & INSN_COND_BRANCH_DELAY
4244                || (pinfo2 & ~INSN2_ALIAS) == INSN2_UNCOND_BRANCH
4245                || pinfo2 & INSN2_COND_BRANCH))
4246     {
4247       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4248       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4249       int uncond = (pinfo & INSN_UNCOND_BRANCH_DELAY
4250                     || pinfo2 & INSN2_UNCOND_BRANCH) ? -1 : 0;
4251       int compact = pinfo2 & (INSN2_COND_BRANCH | INSN2_UNCOND_BRANCH);
4252       int al = pinfo & INSN_WRITE_GPR_31;
4253       int length32;
4254
4255       gas_assert (address_expr != NULL);
4256       gas_assert (!mips_relax.sequence);
4257
4258       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4259       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4260                         RELAX_MICROMIPS_ENCODE (type, AT,
4261                                                 forced_insn_length == 2,
4262                                                 uncond, compact, al, relax32,
4263                                                 0, 0),
4264                         address_expr->X_add_symbol,
4265                         address_expr->X_add_number);
4266       *reloc_type = BFD_RELOC_UNUSED;
4267     }
4268   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4269     {
4270       /* We need to set up a variant frag.  */
4271       gas_assert (address_expr != NULL);
4272       add_relaxed_insn (ip, 4, 0,
4273                         RELAX_MIPS16_ENCODE
4274                         (*reloc_type - BFD_RELOC_UNUSED,
4275                          forced_insn_length == 2, forced_insn_length == 4,
4276                          prev_pinfo & INSN_UNCOND_BRANCH_DELAY,
4277                          history[0].mips16_absolute_jump_p),
4278                         make_expr_symbol (address_expr), 0);
4279     }
4280   else if (mips_opts.mips16
4281            && ! ip->use_extend
4282            && *reloc_type != BFD_RELOC_MIPS16_JMP)
4283     {
4284       if ((pinfo & INSN_UNCOND_BRANCH_DELAY) == 0)
4285         /* Make sure there is enough room to swap this instruction with
4286            a following jump instruction.  */
4287         frag_grow (6);
4288       add_fixed_insn (ip);
4289     }
4290   else
4291     {
4292       if (mips_opts.mips16
4293           && mips_opts.noreorder
4294           && (prev_pinfo & INSN_UNCOND_BRANCH_DELAY) != 0)
4295         as_warn (_("extended instruction in delay slot"));
4296
4297       if (mips_relax.sequence)
4298         {
4299           /* If we've reached the end of this frag, turn it into a variant
4300              frag and record the information for the instructions we've
4301              written so far.  */
4302           if (frag_room () < 4)
4303             relax_close_frag ();
4304           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4305         }
4306
4307       if (mips_relax.sequence != 2)
4308         {
4309           if (mips_macro_warning.first_insn_sizes[0] == 0)
4310             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4311           mips_macro_warning.sizes[0] += insn_length (ip);
4312           mips_macro_warning.insns[0]++;
4313         }
4314       if (mips_relax.sequence != 1)
4315         {
4316           if (mips_macro_warning.first_insn_sizes[1] == 0)
4317             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4318           mips_macro_warning.sizes[1] += insn_length (ip);
4319           mips_macro_warning.insns[1]++;
4320         }
4321
4322       if (mips_opts.mips16)
4323         {
4324           ip->fixed_p = 1;
4325           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4326         }
4327       add_fixed_insn (ip);
4328     }
4329
4330   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4331     {
4332       bfd_reloc_code_real_type final_type[3];
4333       reloc_howto_type *howto;
4334       int i;
4335
4336       /* Perform any necessary conversion to microMIPS relocations
4337          and find out how many relocations there actually are.  */
4338       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4339         final_type[i] = micromips_map_reloc (reloc_type[i]);
4340
4341       /* In a compound relocation, it is the final (outermost)
4342          operator that determines the relocated field.  */
4343       howto = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4344       if (howto == NULL)
4345         {
4346           /* To reproduce this failure try assembling gas/testsuites/
4347              gas/mips/mips16-intermix.s with a mips-ecoff targeted
4348              assembler.  */
4349           as_bad (_("Unsupported MIPS relocation number %d"),
4350                   final_type[i - 1]);
4351           howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16);
4352         }
4353           
4354       howto = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4355       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4356                                  bfd_get_reloc_size (howto),
4357                                  address_expr,
4358                                  howto->pc_relative, final_type[0]);
4359
4360       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4361       if (reloc_type[0] == BFD_RELOC_MIPS16_JMP
4362           && ip->fixp[0]->fx_addsy)
4363         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4364
4365       /* These relocations can have an addend that won't fit in
4366          4 octets for 64bit assembly.  */
4367       if (HAVE_64BIT_GPRS
4368           && ! howto->partial_inplace
4369           && (reloc_type[0] == BFD_RELOC_16
4370               || reloc_type[0] == BFD_RELOC_32
4371               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4372               || reloc_type[0] == BFD_RELOC_GPREL16
4373               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4374               || reloc_type[0] == BFD_RELOC_GPREL32
4375               || reloc_type[0] == BFD_RELOC_64
4376               || reloc_type[0] == BFD_RELOC_CTOR
4377               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4378               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4379               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4380               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4381               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4382               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4383               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4384               || hi16_reloc_p (reloc_type[0])
4385               || lo16_reloc_p (reloc_type[0])))
4386         ip->fixp[0]->fx_no_overflow = 1;
4387
4388       if (mips_relax.sequence)
4389         {
4390           if (mips_relax.first_fixup == 0)
4391             mips_relax.first_fixup = ip->fixp[0];
4392         }
4393       else if (reloc_needs_lo_p (*reloc_type))
4394         {
4395           struct mips_hi_fixup *hi_fixup;
4396
4397           /* Reuse the last entry if it already has a matching %lo.  */
4398           hi_fixup = mips_hi_fixup_list;
4399           if (hi_fixup == 0
4400               || !fixup_has_matching_lo_p (hi_fixup->fixp))
4401             {
4402               hi_fixup = ((struct mips_hi_fixup *)
4403                           xmalloc (sizeof (struct mips_hi_fixup)));
4404               hi_fixup->next = mips_hi_fixup_list;
4405               mips_hi_fixup_list = hi_fixup;
4406             }
4407           hi_fixup->fixp = ip->fixp[0];
4408           hi_fixup->seg = now_seg;
4409         }
4410
4411       /* Add fixups for the second and third relocations, if given.
4412          Note that the ABI allows the second relocation to be
4413          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
4414          moment we only use RSS_UNDEF, but we could add support
4415          for the others if it ever becomes necessary.  */
4416       for (i = 1; i < 3; i++)
4417         if (reloc_type[i] != BFD_RELOC_UNUSED)
4418           {
4419             ip->fixp[i] = fix_new (ip->frag, ip->where,
4420                                    ip->fixp[0]->fx_size, NULL, 0,
4421                                    FALSE, final_type[i]);
4422
4423             /* Use fx_tcbit to mark compound relocs.  */
4424             ip->fixp[0]->fx_tcbit = 1;
4425             ip->fixp[i]->fx_tcbit = 1;
4426           }
4427     }
4428   install_insn (ip);
4429
4430   /* Update the register mask information.  */
4431   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
4432   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
4433
4434   switch (method)
4435     {
4436     case APPEND_ADD:
4437       insert_into_history (0, 1, ip);
4438       break;
4439
4440     case APPEND_ADD_WITH_NOP:
4441       insert_into_history (0, 1, ip);
4442       if (mips_opts.micromips
4443           && (pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4444         {
4445           add_fixed_insn (&micromips_nop32_insn);
4446           insert_into_history (0, 1, &micromips_nop32_insn);
4447           if (mips_relax.sequence)
4448             mips_relax.sizes[mips_relax.sequence - 1] += 4;
4449         }
4450       else
4451         {
4452           emit_nop ();
4453           if (mips_relax.sequence)
4454             mips_relax.sizes[mips_relax.sequence - 1] += NOP_INSN_SIZE;
4455         }
4456       break;
4457
4458     case APPEND_ADD_COMPACT:
4459       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
4460       gas_assert (mips_opts.mips16);
4461       ip->insn_opcode |= 0x0080;
4462       find_altered_mips16_opcode (ip);
4463       install_insn (ip);
4464       insert_into_history (0, 1, ip);
4465       break;
4466
4467     case APPEND_SWAP:
4468       {
4469         struct mips_cl_insn delay = history[0];
4470         if (mips_opts.mips16)
4471           {
4472             know (delay.frag == ip->frag);
4473             move_insn (ip, delay.frag, delay.where);
4474             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
4475           }
4476         else if (mips_opts.micromips)
4477           {
4478             /* We don't reorder for micromips.  */
4479             abort ();
4480           }
4481         else if (relaxed_branch)
4482           {
4483             /* Add the delay slot instruction to the end of the
4484                current frag and shrink the fixed part of the
4485                original frag.  If the branch occupies the tail of
4486                the latter, move it backwards to cover the gap.  */
4487             delay.frag->fr_fix -= 4;
4488             if (delay.frag == ip->frag)
4489               move_insn (ip, ip->frag, ip->where - 4);
4490             add_fixed_insn (&delay);
4491           }
4492         else
4493           {
4494             move_insn (&delay, ip->frag, ip->where);
4495             move_insn (ip, history[0].frag, history[0].where);
4496           }
4497         history[0] = *ip;
4498         delay.fixed_p = 1;
4499         insert_into_history (0, 1, &delay);
4500       }
4501       break;
4502     }
4503
4504   /* If we have just completed an unconditional branch, clear the history.  */
4505   if ((history[1].insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY)
4506       || (mips_opts.mips16
4507           && (history[0].insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH)))
4508     mips_no_prev_insn ();
4509
4510   /* We need to emit a label at the end of branch-likely macros.  */
4511   if (emit_branch_likely_macro)
4512     {
4513       emit_branch_likely_macro = FALSE;
4514       micromips_add_label ();
4515     }
4516
4517   /* We just output an insn, so the next one doesn't have a label.  */
4518   mips_clear_insn_labels ();
4519 }
4520
4521 /* Forget that there was any previous instruction or label.  */
4522
4523 static void
4524 mips_no_prev_insn (void)
4525 {
4526   prev_nop_frag = NULL;
4527   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
4528   mips_clear_insn_labels ();
4529 }
4530
4531 /* This function must be called before we emit something other than
4532    instructions.  It is like mips_no_prev_insn except that it inserts
4533    any NOPS that might be needed by previous instructions.  */
4534
4535 void
4536 mips_emit_delays (void)
4537 {
4538   if (! mips_opts.noreorder)
4539     {
4540       int nops = nops_for_insn (0, history, NULL);
4541       if (nops > 0)
4542         {
4543           while (nops-- > 0)
4544             add_fixed_insn (NOP_INSN);
4545           mips_move_labels ();
4546         }
4547     }
4548   mips_no_prev_insn ();
4549 }
4550
4551 /* Start a (possibly nested) noreorder block.  */
4552
4553 static void
4554 start_noreorder (void)
4555 {
4556   if (mips_opts.noreorder == 0)
4557     {
4558       unsigned int i;
4559       int nops;
4560
4561       /* None of the instructions before the .set noreorder can be moved.  */
4562       for (i = 0; i < ARRAY_SIZE (history); i++)
4563         history[i].fixed_p = 1;
4564
4565       /* Insert any nops that might be needed between the .set noreorder
4566          block and the previous instructions.  We will later remove any
4567          nops that turn out not to be needed.  */
4568       nops = nops_for_insn (0, history, NULL);
4569       if (nops > 0)
4570         {
4571           if (mips_optimize != 0)
4572             {
4573               /* Record the frag which holds the nop instructions, so
4574                  that we can remove them if we don't need them.  */
4575               frag_grow (nops * NOP_INSN_SIZE);
4576               prev_nop_frag = frag_now;
4577               prev_nop_frag_holds = nops;
4578               prev_nop_frag_required = 0;
4579               prev_nop_frag_since = 0;
4580             }
4581
4582           for (; nops > 0; --nops)
4583             add_fixed_insn (NOP_INSN);
4584
4585           /* Move on to a new frag, so that it is safe to simply
4586              decrease the size of prev_nop_frag.  */
4587           frag_wane (frag_now);
4588           frag_new (0);
4589           mips_move_labels ();
4590         }
4591       mips_mark_labels ();
4592       mips_clear_insn_labels ();
4593     }
4594   mips_opts.noreorder++;
4595   mips_any_noreorder = 1;
4596 }
4597
4598 /* End a nested noreorder block.  */
4599
4600 static void
4601 end_noreorder (void)
4602 {
4603
4604   mips_opts.noreorder--;
4605   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
4606     {
4607       /* Commit to inserting prev_nop_frag_required nops and go back to
4608          handling nop insertion the .set reorder way.  */
4609       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
4610                                 * NOP_INSN_SIZE);
4611       insert_into_history (prev_nop_frag_since,
4612                            prev_nop_frag_required, NOP_INSN);
4613       prev_nop_frag = NULL;
4614     }
4615 }
4616
4617 /* Set up global variables for the start of a new macro.  */
4618
4619 static void
4620 macro_start (void)
4621 {
4622   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
4623   memset (&mips_macro_warning.first_insn_sizes, 0,
4624           sizeof (mips_macro_warning.first_insn_sizes));
4625   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
4626   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
4627                                      && (history[0].insn_mo->pinfo
4628                                          & (INSN_UNCOND_BRANCH_DELAY
4629                                             | INSN_COND_BRANCH_DELAY
4630                                             | INSN_COND_BRANCH_LIKELY)) != 0);
4631   switch (history[0].insn_mo->pinfo2
4632           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
4633     {
4634     case INSN2_BRANCH_DELAY_32BIT:
4635       mips_macro_warning.delay_slot_length = 4;
4636       break;
4637     case INSN2_BRANCH_DELAY_16BIT:
4638       mips_macro_warning.delay_slot_length = 2;
4639       break;
4640     default:
4641       mips_macro_warning.delay_slot_length = 0;
4642       break;
4643     }
4644   mips_macro_warning.first_frag = NULL;
4645 }
4646
4647 /* Given that a macro is longer than one instruction or of the wrong size,
4648    return the appropriate warning for it.  Return null if no warning is
4649    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
4650    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
4651    and RELAX_NOMACRO.  */
4652
4653 static const char *
4654 macro_warning (relax_substateT subtype)
4655 {
4656   if (subtype & RELAX_DELAY_SLOT)
4657     return _("Macro instruction expanded into multiple instructions"
4658              " in a branch delay slot");
4659   else if (subtype & RELAX_NOMACRO)
4660     return _("Macro instruction expanded into multiple instructions");
4661   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
4662                       | RELAX_DELAY_SLOT_SIZE_SECOND))
4663     return ((subtype & RELAX_DELAY_SLOT_16BIT)
4664             ? _("Macro instruction expanded into a wrong size instruction"
4665                 " in a 16-bit branch delay slot")
4666             : _("Macro instruction expanded into a wrong size instruction"
4667                 " in a 32-bit branch delay slot"));
4668   else
4669     return 0;
4670 }
4671
4672 /* Finish up a macro.  Emit warnings as appropriate.  */
4673
4674 static void
4675 macro_end (void)
4676 {
4677   /* Relaxation warning flags.  */
4678   relax_substateT subtype = 0;
4679
4680   /* Check delay slot size requirements.  */
4681   if (mips_macro_warning.delay_slot_length == 2)
4682     subtype |= RELAX_DELAY_SLOT_16BIT;
4683   if (mips_macro_warning.delay_slot_length != 0)
4684     {
4685       if (mips_macro_warning.delay_slot_length
4686           != mips_macro_warning.first_insn_sizes[0])
4687         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
4688       if (mips_macro_warning.delay_slot_length
4689           != mips_macro_warning.first_insn_sizes[1])
4690         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
4691     }
4692
4693   /* Check instruction count requirements.  */
4694   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
4695     {
4696       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
4697         subtype |= RELAX_SECOND_LONGER;
4698       if (mips_opts.warn_about_macros)
4699         subtype |= RELAX_NOMACRO;
4700       if (mips_macro_warning.delay_slot_p)
4701         subtype |= RELAX_DELAY_SLOT;
4702     }
4703
4704   /* If both alternatives fail to fill a delay slot correctly,
4705      emit the warning now.  */
4706   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
4707       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
4708     {
4709       relax_substateT s;
4710       const char *msg;
4711
4712       s = subtype & (RELAX_DELAY_SLOT_16BIT
4713                      | RELAX_DELAY_SLOT_SIZE_FIRST
4714                      | RELAX_DELAY_SLOT_SIZE_SECOND);
4715       msg = macro_warning (s);
4716       if (msg != NULL)
4717         as_warn ("%s", msg);
4718       subtype &= ~s;
4719     }
4720
4721   /* If both implementations are longer than 1 instruction, then emit the
4722      warning now.  */
4723   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
4724     {
4725       relax_substateT s;
4726       const char *msg;
4727
4728       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
4729       msg = macro_warning (s);
4730       if (msg != NULL)
4731         as_warn ("%s", msg);
4732       subtype &= ~s;
4733     }
4734
4735   /* If any flags still set, then one implementation might need a warning
4736      and the other either will need one of a different kind or none at all.
4737      Pass any remaining flags over to relaxation.  */
4738   if (mips_macro_warning.first_frag != NULL)
4739     mips_macro_warning.first_frag->fr_subtype |= subtype;
4740 }
4741
4742 /* Instruction operand formats used in macros that vary between
4743    standard MIPS and microMIPS code.  */
4744
4745 static const char * const brk_fmt[2] = { "c", "mF" };
4746 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
4747 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
4748 static const char * const lui_fmt[2] = { "t,u", "s,u" };
4749 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
4750 static const char * const mfhl_fmt[2] = { "d", "mj" };
4751 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
4752 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
4753
4754 #define BRK_FMT (brk_fmt[mips_opts.micromips])
4755 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
4756 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
4757 #define LUI_FMT (lui_fmt[mips_opts.micromips])
4758 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
4759 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips])
4760 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
4761 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
4762
4763 /* Read a macro's relocation codes from *ARGS and store them in *R.
4764    The first argument in *ARGS will be either the code for a single
4765    relocation or -1 followed by the three codes that make up a
4766    composite relocation.  */
4767
4768 static void
4769 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
4770 {
4771   int i, next;
4772
4773   next = va_arg (*args, int);
4774   if (next >= 0)
4775     r[0] = (bfd_reloc_code_real_type) next;
4776   else
4777     for (i = 0; i < 3; i++)
4778       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
4779 }
4780
4781 /* Build an instruction created by a macro expansion.  This is passed
4782    a pointer to the count of instructions created so far, an
4783    expression, the name of the instruction to build, an operand format
4784    string, and corresponding arguments.  */
4785
4786 static void
4787 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
4788 {
4789   const struct mips_opcode *mo = NULL;
4790   bfd_reloc_code_real_type r[3];
4791   const struct mips_opcode *amo;
4792   struct hash_control *hash;
4793   struct mips_cl_insn insn;
4794   va_list args;
4795
4796   va_start (args, fmt);
4797
4798   if (mips_opts.mips16)
4799     {
4800       mips16_macro_build (ep, name, fmt, &args);
4801       va_end (args);
4802       return;
4803     }
4804
4805   r[0] = BFD_RELOC_UNUSED;
4806   r[1] = BFD_RELOC_UNUSED;
4807   r[2] = BFD_RELOC_UNUSED;
4808   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
4809   amo = (struct mips_opcode *) hash_find (hash, name);
4810   gas_assert (amo);
4811   gas_assert (strcmp (name, amo->name) == 0);
4812
4813   do
4814     {
4815       /* Search until we get a match for NAME.  It is assumed here that
4816          macros will never generate MDMX, MIPS-3D, or MT instructions.
4817          We try to match an instruction that fulfils the branch delay
4818          slot instruction length requirement (if any) of the previous
4819          instruction.  While doing this we record the first instruction
4820          seen that matches all the other conditions and use it anyway
4821          if the requirement cannot be met; we will issue an appropriate
4822          warning later on.  */
4823       if (strcmp (fmt, amo->args) == 0
4824           && amo->pinfo != INSN_MACRO
4825           && is_opcode_valid (amo)
4826           && is_size_valid (amo))
4827         {
4828           if (is_delay_slot_valid (amo))
4829             {
4830               mo = amo;
4831               break;
4832             }
4833           else if (!mo)
4834             mo = amo;
4835         }
4836
4837       ++amo;
4838       gas_assert (amo->name);
4839     }
4840   while (strcmp (name, amo->name) == 0);
4841
4842   gas_assert (mo);
4843   create_insn (&insn, mo);
4844   for (;;)
4845     {
4846       switch (*fmt++)
4847         {
4848         case '\0':
4849           break;
4850
4851         case ',':
4852         case '(':
4853         case ')':
4854           continue;
4855
4856         case '+':
4857           switch (*fmt++)
4858             {
4859             case 'A':
4860             case 'E':
4861               INSERT_OPERAND (mips_opts.micromips,
4862                               EXTLSB, insn, va_arg (args, int));
4863               continue;
4864
4865             case 'B':
4866             case 'F':
4867               /* Note that in the macro case, these arguments are already
4868                  in MSB form.  (When handling the instruction in the
4869                  non-macro case, these arguments are sizes from which
4870                  MSB values must be calculated.)  */
4871               INSERT_OPERAND (mips_opts.micromips,
4872                               INSMSB, insn, va_arg (args, int));
4873               continue;
4874
4875             case 'C':
4876             case 'G':
4877             case 'H':
4878               /* Note that in the macro case, these arguments are already
4879                  in MSBD form.  (When handling the instruction in the
4880                  non-macro case, these arguments are sizes from which
4881                  MSBD values must be calculated.)  */
4882               INSERT_OPERAND (mips_opts.micromips,
4883                               EXTMSBD, insn, va_arg (args, int));
4884               continue;
4885
4886             case 'Q':
4887               gas_assert (!mips_opts.micromips);
4888               INSERT_OPERAND (0, SEQI, insn, va_arg (args, int));
4889               continue;
4890
4891             default:
4892               internalError ();
4893             }
4894           continue;
4895
4896         case '2':
4897           gas_assert (!mips_opts.micromips);
4898           INSERT_OPERAND (0, BP, insn, va_arg (args, int));
4899           continue;
4900
4901         case 'n':
4902           gas_assert (mips_opts.micromips);
4903         case 't':
4904         case 'w':
4905         case 'E':
4906           INSERT_OPERAND (mips_opts.micromips, RT, insn, va_arg (args, int));
4907           continue;
4908
4909         case 'c':
4910           gas_assert (!mips_opts.micromips);
4911           INSERT_OPERAND (0, CODE, insn, va_arg (args, int));
4912           continue;
4913
4914         case 'W':
4915           gas_assert (!mips_opts.micromips);
4916         case 'T':
4917           INSERT_OPERAND (mips_opts.micromips, FT, insn, va_arg (args, int));
4918           continue;
4919
4920         case 'G':
4921           if (mips_opts.micromips)
4922             INSERT_OPERAND (1, RS, insn, va_arg (args, int));
4923           else
4924             INSERT_OPERAND (0, RD, insn, va_arg (args, int));
4925           continue;
4926
4927         case 'K':
4928           gas_assert (!mips_opts.micromips);
4929         case 'd':
4930           INSERT_OPERAND (mips_opts.micromips, RD, insn, va_arg (args, int));
4931           continue;
4932
4933         case 'U':
4934           gas_assert (!mips_opts.micromips);
4935           {
4936             int tmp = va_arg (args, int);
4937
4938             INSERT_OPERAND (0, RT, insn, tmp);
4939             INSERT_OPERAND (0, RD, insn, tmp);
4940           }
4941           continue;
4942
4943         case 'V':
4944         case 'S':
4945           gas_assert (!mips_opts.micromips);
4946           INSERT_OPERAND (0, FS, insn, va_arg (args, int));
4947           continue;
4948
4949         case 'z':
4950           continue;
4951
4952         case '<':
4953           INSERT_OPERAND (mips_opts.micromips,
4954                           SHAMT, insn, va_arg (args, int));
4955           continue;
4956
4957         case 'D':
4958           gas_assert (!mips_opts.micromips);
4959           INSERT_OPERAND (0, FD, insn, va_arg (args, int));
4960           continue;
4961
4962         case 'B':
4963           gas_assert (!mips_opts.micromips);
4964           INSERT_OPERAND (0, CODE20, insn, va_arg (args, int));
4965           continue;
4966
4967         case 'J':
4968           gas_assert (!mips_opts.micromips);
4969           INSERT_OPERAND (0, CODE19, insn, va_arg (args, int));
4970           continue;
4971
4972         case 'q':
4973           gas_assert (!mips_opts.micromips);
4974           INSERT_OPERAND (0, CODE2, insn, va_arg (args, int));
4975           continue;
4976
4977         case 'b':
4978         case 's':
4979         case 'r':
4980         case 'v':
4981           INSERT_OPERAND (mips_opts.micromips, RS, insn, va_arg (args, int));
4982           continue;
4983
4984         case 'i':
4985         case 'j':
4986           macro_read_relocs (&args, r);
4987           gas_assert (*r == BFD_RELOC_GPREL16
4988                       || *r == BFD_RELOC_MIPS_HIGHER
4989                       || *r == BFD_RELOC_HI16_S
4990                       || *r == BFD_RELOC_LO16
4991                       || *r == BFD_RELOC_MIPS_GOT_OFST);
4992           continue;
4993
4994         case 'o':
4995           macro_read_relocs (&args, r);
4996           continue;
4997
4998         case 'u':
4999           macro_read_relocs (&args, r);
5000           gas_assert (ep != NULL
5001                       && (ep->X_op == O_constant
5002                           || (ep->X_op == O_symbol
5003                               && (*r == BFD_RELOC_MIPS_HIGHEST
5004                                   || *r == BFD_RELOC_HI16_S
5005                                   || *r == BFD_RELOC_HI16
5006                                   || *r == BFD_RELOC_GPREL16
5007                                   || *r == BFD_RELOC_MIPS_GOT_HI16
5008                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
5009           continue;
5010
5011         case 'p':
5012           gas_assert (ep != NULL);
5013
5014           /*
5015            * This allows macro() to pass an immediate expression for
5016            * creating short branches without creating a symbol.
5017            *
5018            * We don't allow branch relaxation for these branches, as
5019            * they should only appear in ".set nomacro" anyway.
5020            */
5021           if (ep->X_op == O_constant)
5022             {
5023               /* For microMIPS we always use relocations for branches.
5024                  So we should not resolve immediate values.  */
5025               gas_assert (!mips_opts.micromips);
5026
5027               if ((ep->X_add_number & 3) != 0)
5028                 as_bad (_("branch to misaligned address (0x%lx)"),
5029                         (unsigned long) ep->X_add_number);
5030               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5031                 as_bad (_("branch address range overflow (0x%lx)"),
5032                         (unsigned long) ep->X_add_number);
5033               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5034               ep = NULL;
5035             }
5036           else
5037             *r = BFD_RELOC_16_PCREL_S2;
5038           continue;
5039
5040         case 'a':
5041           gas_assert (ep != NULL);
5042           *r = BFD_RELOC_MIPS_JMP;
5043           continue;
5044
5045         case 'C':
5046           gas_assert (!mips_opts.micromips);
5047           INSERT_OPERAND (0, COPZ, insn, va_arg (args, unsigned long));
5048           continue;
5049
5050         case 'k':
5051           INSERT_OPERAND (mips_opts.micromips,
5052                           CACHE, insn, va_arg (args, unsigned long));
5053           continue;
5054
5055         case '|':
5056           gas_assert (mips_opts.micromips);
5057           INSERT_OPERAND (1, TRAP, insn, va_arg (args, int));
5058           continue;
5059
5060         case '.':
5061           gas_assert (mips_opts.micromips);
5062           INSERT_OPERAND (1, OFFSET10, insn, va_arg (args, int));
5063           continue;
5064
5065         case '~':
5066           gas_assert (mips_opts.micromips);
5067           INSERT_OPERAND (1, OFFSET12, insn, va_arg (args, unsigned long));
5068           continue;
5069
5070         case 'N':
5071           gas_assert (mips_opts.micromips);
5072           INSERT_OPERAND (1, BCC, insn, va_arg (args, int));
5073           continue;
5074
5075         case 'm':       /* Opcode extension character.  */
5076           gas_assert (mips_opts.micromips);
5077           switch (*fmt++)
5078             {
5079             case 'j':
5080               INSERT_OPERAND (1, MJ, insn, va_arg (args, int));
5081               break;
5082
5083             case 'p':
5084               INSERT_OPERAND (1, MP, insn, va_arg (args, int));
5085               break;
5086
5087             case 'F':
5088               INSERT_OPERAND (1, IMMF, insn, va_arg (args, int));
5089               break;
5090
5091             default:
5092               internalError ();
5093             }
5094           continue;
5095
5096         default:
5097           internalError ();
5098         }
5099       break;
5100     }
5101   va_end (args);
5102   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5103
5104   append_insn (&insn, ep, r, TRUE);
5105 }
5106
5107 static void
5108 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5109                     va_list *args)
5110 {
5111   struct mips_opcode *mo;
5112   struct mips_cl_insn insn;
5113   bfd_reloc_code_real_type r[3]
5114     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5115
5116   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5117   gas_assert (mo);
5118   gas_assert (strcmp (name, mo->name) == 0);
5119
5120   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5121     {
5122       ++mo;
5123       gas_assert (mo->name);
5124       gas_assert (strcmp (name, mo->name) == 0);
5125     }
5126
5127   create_insn (&insn, mo);
5128   for (;;)
5129     {
5130       int c;
5131
5132       c = *fmt++;
5133       switch (c)
5134         {
5135         case '\0':
5136           break;
5137
5138         case ',':
5139         case '(':
5140         case ')':
5141           continue;
5142
5143         case 'y':
5144         case 'w':
5145           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
5146           continue;
5147
5148         case 'x':
5149         case 'v':
5150           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
5151           continue;
5152
5153         case 'z':
5154           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
5155           continue;
5156
5157         case 'Z':
5158           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
5159           continue;
5160
5161         case '0':
5162         case 'S':
5163         case 'P':
5164         case 'R':
5165           continue;
5166
5167         case 'X':
5168           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
5169           continue;
5170
5171         case 'Y':
5172           {
5173             int regno;
5174
5175             regno = va_arg (*args, int);
5176             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
5177             MIPS16_INSERT_OPERAND (REG32R, insn, regno);
5178           }
5179           continue;
5180
5181         case '<':
5182         case '>':
5183         case '4':
5184         case '5':
5185         case 'H':
5186         case 'W':
5187         case 'D':
5188         case 'j':
5189         case '8':
5190         case 'V':
5191         case 'C':
5192         case 'U':
5193         case 'k':
5194         case 'K':
5195         case 'p':
5196         case 'q':
5197           {
5198             gas_assert (ep != NULL);
5199
5200             if (ep->X_op != O_constant)
5201               *r = (int) BFD_RELOC_UNUSED + c;
5202             else
5203               {
5204                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
5205                               FALSE, &insn.insn_opcode, &insn.use_extend,
5206                               &insn.extend);
5207                 ep = NULL;
5208                 *r = BFD_RELOC_UNUSED;
5209               }
5210           }
5211           continue;
5212
5213         case '6':
5214           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
5215           continue;
5216         }
5217
5218       break;
5219     }
5220
5221   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5222
5223   append_insn (&insn, ep, r, TRUE);
5224 }
5225
5226 /*
5227  * Sign-extend 32-bit mode constants that have bit 31 set and all
5228  * higher bits unset.
5229  */
5230 static void
5231 normalize_constant_expr (expressionS *ex)
5232 {
5233   if (ex->X_op == O_constant
5234       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5235     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5236                         - 0x80000000);
5237 }
5238
5239 /*
5240  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5241  * all higher bits unset.
5242  */
5243 static void
5244 normalize_address_expr (expressionS *ex)
5245 {
5246   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5247         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5248       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5249     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5250                         - 0x80000000);
5251 }
5252
5253 /*
5254  * Generate a "jalr" instruction with a relocation hint to the called
5255  * function.  This occurs in NewABI PIC code.
5256  */
5257 static void
5258 macro_build_jalr (expressionS *ep, int cprestore)
5259 {
5260   static const bfd_reloc_code_real_type jalr_relocs[2]
5261     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5262   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5263   const char *jalr;
5264   char *f = NULL;
5265
5266   if (MIPS_JALR_HINT_P (ep))
5267     {
5268       frag_grow (8);
5269       f = frag_more (0);
5270     }
5271   if (!mips_opts.micromips)
5272     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5273   else
5274     {
5275       jalr = mips_opts.noreorder && !cprestore ? "jalr" : "jalrs";
5276       if (MIPS_JALR_HINT_P (ep))
5277         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5278       else
5279         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5280     }
5281   if (MIPS_JALR_HINT_P (ep))
5282     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5283 }
5284
5285 /*
5286  * Generate a "lui" instruction.
5287  */
5288 static void
5289 macro_build_lui (expressionS *ep, int regnum)
5290 {
5291   gas_assert (! mips_opts.mips16);
5292
5293   if (ep->X_op != O_constant)
5294     {
5295       gas_assert (ep->X_op == O_symbol);
5296       /* _gp_disp is a special case, used from s_cpload.
5297          __gnu_local_gp is used if mips_no_shared.  */
5298       gas_assert (mips_pic == NO_PIC
5299               || (! HAVE_NEWABI
5300                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5301               || (! mips_in_shared
5302                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5303                              "__gnu_local_gp") == 0));
5304     }
5305
5306   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5307 }
5308
5309 /* Generate a sequence of instructions to do a load or store from a constant
5310    offset off of a base register (breg) into/from a target register (treg),
5311    using AT if necessary.  */
5312 static void
5313 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5314                               int treg, int breg, int dbl)
5315 {
5316   gas_assert (ep->X_op == O_constant);
5317
5318   /* Sign-extending 32-bit constants makes their handling easier.  */
5319   if (!dbl)
5320     normalize_constant_expr (ep);
5321
5322   /* Right now, this routine can only handle signed 32-bit constants.  */
5323   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5324     as_warn (_("operand overflow"));
5325
5326   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5327     {
5328       /* Signed 16-bit offset will fit in the op.  Easy!  */
5329       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5330     }
5331   else
5332     {
5333       /* 32-bit offset, need multiple instructions and AT, like:
5334            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5335            addu     $tempreg,$tempreg,$breg
5336            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5337          to handle the complete offset.  */
5338       macro_build_lui (ep, AT);
5339       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5340       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5341
5342       if (!mips_opts.at)
5343         as_bad (_("Macro used $at after \".set noat\""));
5344     }
5345 }
5346
5347 /*                      set_at()
5348  * Generates code to set the $at register to true (one)
5349  * if reg is less than the immediate expression.
5350  */
5351 static void
5352 set_at (int reg, int unsignedp)
5353 {
5354   if (imm_expr.X_op == O_constant
5355       && imm_expr.X_add_number >= -0x8000
5356       && imm_expr.X_add_number < 0x8000)
5357     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5358                  AT, reg, BFD_RELOC_LO16);
5359   else
5360     {
5361       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5362       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5363     }
5364 }
5365
5366 /* Warn if an expression is not a constant.  */
5367
5368 static void
5369 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5370 {
5371   if (ex->X_op == O_big)
5372     as_bad (_("unsupported large constant"));
5373   else if (ex->X_op != O_constant)
5374     as_bad (_("Instruction %s requires absolute expression"),
5375             ip->insn_mo->name);
5376
5377   if (HAVE_32BIT_GPRS)
5378     normalize_constant_expr (ex);
5379 }
5380
5381 /* Count the leading zeroes by performing a binary chop. This is a
5382    bulky bit of source, but performance is a LOT better for the
5383    majority of values than a simple loop to count the bits:
5384        for (lcnt = 0; (lcnt < 32); lcnt++)
5385          if ((v) & (1 << (31 - lcnt)))
5386            break;
5387   However it is not code size friendly, and the gain will drop a bit
5388   on certain cached systems.
5389 */
5390 #define COUNT_TOP_ZEROES(v)             \
5391   (((v) & ~0xffff) == 0                 \
5392    ? ((v) & ~0xff) == 0                 \
5393      ? ((v) & ~0xf) == 0                \
5394        ? ((v) & ~0x3) == 0              \
5395          ? ((v) & ~0x1) == 0            \
5396            ? !(v)                       \
5397              ? 32                       \
5398              : 31                       \
5399            : 30                         \
5400          : ((v) & ~0x7) == 0            \
5401            ? 29                         \
5402            : 28                         \
5403        : ((v) & ~0x3f) == 0             \
5404          ? ((v) & ~0x1f) == 0           \
5405            ? 27                         \
5406            : 26                         \
5407          : ((v) & ~0x7f) == 0           \
5408            ? 25                         \
5409            : 24                         \
5410      : ((v) & ~0xfff) == 0              \
5411        ? ((v) & ~0x3ff) == 0            \
5412          ? ((v) & ~0x1ff) == 0          \
5413            ? 23                         \
5414            : 22                         \
5415          : ((v) & ~0x7ff) == 0          \
5416            ? 21                         \
5417            : 20                         \
5418        : ((v) & ~0x3fff) == 0           \
5419          ? ((v) & ~0x1fff) == 0         \
5420            ? 19                         \
5421            : 18                         \
5422          : ((v) & ~0x7fff) == 0         \
5423            ? 17                         \
5424            : 16                         \
5425    : ((v) & ~0xffffff) == 0             \
5426      ? ((v) & ~0xfffff) == 0            \
5427        ? ((v) & ~0x3ffff) == 0          \
5428          ? ((v) & ~0x1ffff) == 0        \
5429            ? 15                         \
5430            : 14                         \
5431          : ((v) & ~0x7ffff) == 0        \
5432            ? 13                         \
5433            : 12                         \
5434        : ((v) & ~0x3fffff) == 0         \
5435          ? ((v) & ~0x1fffff) == 0       \
5436            ? 11                         \
5437            : 10                         \
5438          : ((v) & ~0x7fffff) == 0       \
5439            ? 9                          \
5440            : 8                          \
5441      : ((v) & ~0xfffffff) == 0          \
5442        ? ((v) & ~0x3ffffff) == 0        \
5443          ? ((v) & ~0x1ffffff) == 0      \
5444            ? 7                          \
5445            : 6                          \
5446          : ((v) & ~0x7ffffff) == 0      \
5447            ? 5                          \
5448            : 4                          \
5449        : ((v) & ~0x3fffffff) == 0       \
5450          ? ((v) & ~0x1fffffff) == 0     \
5451            ? 3                          \
5452            : 2                          \
5453          : ((v) & ~0x7fffffff) == 0     \
5454            ? 1                          \
5455            : 0)
5456
5457 /*                      load_register()
5458  *  This routine generates the least number of instructions necessary to load
5459  *  an absolute expression value into a register.
5460  */
5461 static void
5462 load_register (int reg, expressionS *ep, int dbl)
5463 {
5464   int freg;
5465   expressionS hi32, lo32;
5466
5467   if (ep->X_op != O_big)
5468     {
5469       gas_assert (ep->X_op == O_constant);
5470
5471       /* Sign-extending 32-bit constants makes their handling easier.  */
5472       if (!dbl)
5473         normalize_constant_expr (ep);
5474
5475       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
5476         {
5477           /* We can handle 16 bit signed values with an addiu to
5478              $zero.  No need to ever use daddiu here, since $zero and
5479              the result are always correct in 32 bit mode.  */
5480           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5481           return;
5482         }
5483       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
5484         {
5485           /* We can handle 16 bit unsigned values with an ori to
5486              $zero.  */
5487           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5488           return;
5489         }
5490       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
5491         {
5492           /* 32 bit values require an lui.  */
5493           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5494           if ((ep->X_add_number & 0xffff) != 0)
5495             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5496           return;
5497         }
5498     }
5499
5500   /* The value is larger than 32 bits.  */
5501
5502   if (!dbl || HAVE_32BIT_GPRS)
5503     {
5504       char value[32];
5505
5506       sprintf_vma (value, ep->X_add_number);
5507       as_bad (_("Number (0x%s) larger than 32 bits"), value);
5508       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5509       return;
5510     }
5511
5512   if (ep->X_op != O_big)
5513     {
5514       hi32 = *ep;
5515       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5516       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5517       hi32.X_add_number &= 0xffffffff;
5518       lo32 = *ep;
5519       lo32.X_add_number &= 0xffffffff;
5520     }
5521   else
5522     {
5523       gas_assert (ep->X_add_number > 2);
5524       if (ep->X_add_number == 3)
5525         generic_bignum[3] = 0;
5526       else if (ep->X_add_number > 4)
5527         as_bad (_("Number larger than 64 bits"));
5528       lo32.X_op = O_constant;
5529       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
5530       hi32.X_op = O_constant;
5531       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
5532     }
5533
5534   if (hi32.X_add_number == 0)
5535     freg = 0;
5536   else
5537     {
5538       int shift, bit;
5539       unsigned long hi, lo;
5540
5541       if (hi32.X_add_number == (offsetT) 0xffffffff)
5542         {
5543           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
5544             {
5545               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5546               return;
5547             }
5548           if (lo32.X_add_number & 0x80000000)
5549             {
5550               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5551               if (lo32.X_add_number & 0xffff)
5552                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5553               return;
5554             }
5555         }
5556
5557       /* Check for 16bit shifted constant.  We know that hi32 is
5558          non-zero, so start the mask on the first bit of the hi32
5559          value.  */
5560       shift = 17;
5561       do
5562         {
5563           unsigned long himask, lomask;
5564
5565           if (shift < 32)
5566             {
5567               himask = 0xffff >> (32 - shift);
5568               lomask = (0xffff << shift) & 0xffffffff;
5569             }
5570           else
5571             {
5572               himask = 0xffff << (shift - 32);
5573               lomask = 0;
5574             }
5575           if ((hi32.X_add_number & ~(offsetT) himask) == 0
5576               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
5577             {
5578               expressionS tmp;
5579
5580               tmp.X_op = O_constant;
5581               if (shift < 32)
5582                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
5583                                     | (lo32.X_add_number >> shift));
5584               else
5585                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
5586               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5587               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5588                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5589               return;
5590             }
5591           ++shift;
5592         }
5593       while (shift <= (64 - 16));
5594
5595       /* Find the bit number of the lowest one bit, and store the
5596          shifted value in hi/lo.  */
5597       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
5598       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
5599       if (lo != 0)
5600         {
5601           bit = 0;
5602           while ((lo & 1) == 0)
5603             {
5604               lo >>= 1;
5605               ++bit;
5606             }
5607           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
5608           hi >>= bit;
5609         }
5610       else
5611         {
5612           bit = 32;
5613           while ((hi & 1) == 0)
5614             {
5615               hi >>= 1;
5616               ++bit;
5617             }
5618           lo = hi;
5619           hi = 0;
5620         }
5621
5622       /* Optimize if the shifted value is a (power of 2) - 1.  */
5623       if ((hi == 0 && ((lo + 1) & lo) == 0)
5624           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
5625         {
5626           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
5627           if (shift != 0)
5628             {
5629               expressionS tmp;
5630
5631               /* This instruction will set the register to be all
5632                  ones.  */
5633               tmp.X_op = O_constant;
5634               tmp.X_add_number = (offsetT) -1;
5635               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5636               if (bit != 0)
5637                 {
5638                   bit += shift;
5639                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5640                                reg, reg, (bit >= 32) ? bit - 32 : bit);
5641                 }
5642               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
5643                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5644               return;
5645             }
5646         }
5647
5648       /* Sign extend hi32 before calling load_register, because we can
5649          generally get better code when we load a sign extended value.  */
5650       if ((hi32.X_add_number & 0x80000000) != 0)
5651         hi32.X_add_number |= ~(offsetT) 0xffffffff;
5652       load_register (reg, &hi32, 0);
5653       freg = reg;
5654     }
5655   if ((lo32.X_add_number & 0xffff0000) == 0)
5656     {
5657       if (freg != 0)
5658         {
5659           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
5660           freg = reg;
5661         }
5662     }
5663   else
5664     {
5665       expressionS mid16;
5666
5667       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
5668         {
5669           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5670           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
5671           return;
5672         }
5673
5674       if (freg != 0)
5675         {
5676           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
5677           freg = reg;
5678         }
5679       mid16 = lo32;
5680       mid16.X_add_number >>= 16;
5681       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5682       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5683       freg = reg;
5684     }
5685   if ((lo32.X_add_number & 0xffff) != 0)
5686     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5687 }
5688
5689 static inline void
5690 load_delay_nop (void)
5691 {
5692   if (!gpr_interlocks)
5693     macro_build (NULL, "nop", "");
5694 }
5695
5696 /* Load an address into a register.  */
5697
5698 static void
5699 load_address (int reg, expressionS *ep, int *used_at)
5700 {
5701   if (ep->X_op != O_constant
5702       && ep->X_op != O_symbol)
5703     {
5704       as_bad (_("expression too complex"));
5705       ep->X_op = O_constant;
5706     }
5707
5708   if (ep->X_op == O_constant)
5709     {
5710       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
5711       return;
5712     }
5713
5714   if (mips_pic == NO_PIC)
5715     {
5716       /* If this is a reference to a GP relative symbol, we want
5717            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
5718          Otherwise we want
5719            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
5720            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5721          If we have an addend, we always use the latter form.
5722
5723          With 64bit address space and a usable $at we want
5724            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5725            lui          $at,<sym>               (BFD_RELOC_HI16_S)
5726            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5727            daddiu       $at,<sym>               (BFD_RELOC_LO16)
5728            dsll32       $reg,0
5729            daddu        $reg,$reg,$at
5730
5731          If $at is already in use, we use a path which is suboptimal
5732          on superscalar processors.
5733            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5734            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5735            dsll         $reg,16
5736            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
5737            dsll         $reg,16
5738            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
5739
5740          For GP relative symbols in 64bit address space we can use
5741          the same sequence as in 32bit address space.  */
5742       if (HAVE_64BIT_SYMBOLS)
5743         {
5744           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5745               && !nopic_need_relax (ep->X_add_symbol, 1))
5746             {
5747               relax_start (ep->X_add_symbol);
5748               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5749                            mips_gp_register, BFD_RELOC_GPREL16);
5750               relax_switch ();
5751             }
5752
5753           if (*used_at == 0 && mips_opts.at)
5754             {
5755               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5756               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
5757               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5758                            BFD_RELOC_MIPS_HIGHER);
5759               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
5760               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
5761               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
5762               *used_at = 1;
5763             }
5764           else
5765             {
5766               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5767               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5768                            BFD_RELOC_MIPS_HIGHER);
5769               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5770               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
5771               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5772               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
5773             }
5774
5775           if (mips_relax.sequence)
5776             relax_end ();
5777         }
5778       else
5779         {
5780           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5781               && !nopic_need_relax (ep->X_add_symbol, 1))
5782             {
5783               relax_start (ep->X_add_symbol);
5784               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5785                            mips_gp_register, BFD_RELOC_GPREL16);
5786               relax_switch ();
5787             }
5788           macro_build_lui (ep, reg);
5789           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
5790                        reg, reg, BFD_RELOC_LO16);
5791           if (mips_relax.sequence)
5792             relax_end ();
5793         }
5794     }
5795   else if (!mips_big_got)
5796     {
5797       expressionS ex;
5798
5799       /* If this is a reference to an external symbol, we want
5800            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5801          Otherwise we want
5802            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5803            nop
5804            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5805          If there is a constant, it must be added in after.
5806
5807          If we have NewABI, we want
5808            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5809          unless we're referencing a global symbol with a non-zero
5810          offset, in which case cst must be added separately.  */
5811       if (HAVE_NEWABI)
5812         {
5813           if (ep->X_add_number)
5814             {
5815               ex.X_add_number = ep->X_add_number;
5816               ep->X_add_number = 0;
5817               relax_start (ep->X_add_symbol);
5818               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5819                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5820               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5821                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5822               ex.X_op = O_constant;
5823               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5824                            reg, reg, BFD_RELOC_LO16);
5825               ep->X_add_number = ex.X_add_number;
5826               relax_switch ();
5827             }
5828           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5829                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5830           if (mips_relax.sequence)
5831             relax_end ();
5832         }
5833       else
5834         {
5835           ex.X_add_number = ep->X_add_number;
5836           ep->X_add_number = 0;
5837           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5838                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5839           load_delay_nop ();
5840           relax_start (ep->X_add_symbol);
5841           relax_switch ();
5842           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5843                        BFD_RELOC_LO16);
5844           relax_end ();
5845
5846           if (ex.X_add_number != 0)
5847             {
5848               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5849                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5850               ex.X_op = O_constant;
5851               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5852                            reg, reg, BFD_RELOC_LO16);
5853             }
5854         }
5855     }
5856   else if (mips_big_got)
5857     {
5858       expressionS ex;
5859
5860       /* This is the large GOT case.  If this is a reference to an
5861          external symbol, we want
5862            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
5863            addu         $reg,$reg,$gp
5864            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
5865
5866          Otherwise, for a reference to a local symbol in old ABI, we want
5867            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5868            nop
5869            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5870          If there is a constant, it must be added in after.
5871
5872          In the NewABI, for local symbols, with or without offsets, we want:
5873            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
5874            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
5875       */
5876       if (HAVE_NEWABI)
5877         {
5878           ex.X_add_number = ep->X_add_number;
5879           ep->X_add_number = 0;
5880           relax_start (ep->X_add_symbol);
5881           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5882           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5883                        reg, reg, mips_gp_register);
5884           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5885                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5886           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5887             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5888           else if (ex.X_add_number)
5889             {
5890               ex.X_op = O_constant;
5891               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5892                            BFD_RELOC_LO16);
5893             }
5894
5895           ep->X_add_number = ex.X_add_number;
5896           relax_switch ();
5897           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5898                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
5899           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5900                        BFD_RELOC_MIPS_GOT_OFST);
5901           relax_end ();
5902         }
5903       else
5904         {
5905           ex.X_add_number = ep->X_add_number;
5906           ep->X_add_number = 0;
5907           relax_start (ep->X_add_symbol);
5908           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5909           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5910                        reg, reg, mips_gp_register);
5911           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5912                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5913           relax_switch ();
5914           if (reg_needs_delay (mips_gp_register))
5915             {
5916               /* We need a nop before loading from $gp.  This special
5917                  check is required because the lui which starts the main
5918                  instruction stream does not refer to $gp, and so will not
5919                  insert the nop which may be required.  */
5920               macro_build (NULL, "nop", "");
5921             }
5922           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5923                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5924           load_delay_nop ();
5925           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5926                        BFD_RELOC_LO16);
5927           relax_end ();
5928
5929           if (ex.X_add_number != 0)
5930             {
5931               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5932                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5933               ex.X_op = O_constant;
5934               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5935                            BFD_RELOC_LO16);
5936             }
5937         }
5938     }
5939   else
5940     abort ();
5941
5942   if (!mips_opts.at && *used_at == 1)
5943     as_bad (_("Macro used $at after \".set noat\""));
5944 }
5945
5946 /* Move the contents of register SOURCE into register DEST.  */
5947
5948 static void
5949 move_register (int dest, int source)
5950 {
5951   /* Prefer to use a 16-bit microMIPS instruction unless the previous
5952      instruction specifically requires a 32-bit one.  */
5953   if (mips_opts.micromips
5954       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5955     macro_build (NULL, "move", "mp,mj", dest, source );
5956   else
5957     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
5958                  dest, source, 0);
5959 }
5960
5961 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
5962    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
5963    The two alternatives are:
5964
5965    Global symbol                Local sybmol
5966    -------------                ------------
5967    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
5968    ...                          ...
5969    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
5970
5971    load_got_offset emits the first instruction and add_got_offset
5972    emits the second for a 16-bit offset or add_got_offset_hilo emits
5973    a sequence to add a 32-bit offset using a scratch register.  */
5974
5975 static void
5976 load_got_offset (int dest, expressionS *local)
5977 {
5978   expressionS global;
5979
5980   global = *local;
5981   global.X_add_number = 0;
5982
5983   relax_start (local->X_add_symbol);
5984   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5985                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5986   relax_switch ();
5987   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5988                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5989   relax_end ();
5990 }
5991
5992 static void
5993 add_got_offset (int dest, expressionS *local)
5994 {
5995   expressionS global;
5996
5997   global.X_op = O_constant;
5998   global.X_op_symbol = NULL;
5999   global.X_add_symbol = NULL;
6000   global.X_add_number = local->X_add_number;
6001
6002   relax_start (local->X_add_symbol);
6003   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
6004                dest, dest, BFD_RELOC_LO16);
6005   relax_switch ();
6006   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
6007   relax_end ();
6008 }
6009
6010 static void
6011 add_got_offset_hilo (int dest, expressionS *local, int tmp)
6012 {
6013   expressionS global;
6014   int hold_mips_optimize;
6015
6016   global.X_op = O_constant;
6017   global.X_op_symbol = NULL;
6018   global.X_add_symbol = NULL;
6019   global.X_add_number = local->X_add_number;
6020
6021   relax_start (local->X_add_symbol);
6022   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6023   relax_switch ();
6024   /* Set mips_optimize around the lui instruction to avoid
6025      inserting an unnecessary nop after the lw.  */
6026   hold_mips_optimize = mips_optimize;
6027   mips_optimize = 2;
6028   macro_build_lui (&global, tmp);
6029   mips_optimize = hold_mips_optimize;
6030   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6031   relax_end ();
6032
6033   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6034 }
6035
6036 /* Emit a sequence of instructions to emulate a branch likely operation.
6037    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6038    is its complementing branch with the original condition negated.
6039    CALL is set if the original branch specified the link operation.
6040    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6041
6042    Code like this is produced in the noreorder mode:
6043
6044         BRNEG   <args>, 1f
6045          nop
6046         b       <sym>
6047          delay slot (executed only if branch taken)
6048     1:
6049
6050    or, if CALL is set:
6051
6052         BRNEG   <args>, 1f
6053          nop
6054         bal     <sym>
6055          delay slot (executed only if branch taken)
6056     1:
6057
6058    In the reorder mode the delay slot would be filled with a nop anyway,
6059    so code produced is simply:
6060
6061         BR      <args>, <sym>
6062          nop
6063
6064    This function is used when producing code for the microMIPS ASE that
6065    does not implement branch likely instructions in hardware.  */
6066
6067 static void
6068 macro_build_branch_likely (const char *br, const char *brneg,
6069                            int call, expressionS *ep, const char *fmt,
6070                            unsigned int sreg, unsigned int treg)
6071 {
6072   int noreorder = mips_opts.noreorder;
6073   expressionS expr1;
6074
6075   gas_assert (mips_opts.micromips);
6076   start_noreorder ();
6077   if (noreorder)
6078     {
6079       micromips_label_expr (&expr1);
6080       macro_build (&expr1, brneg, fmt, sreg, treg);
6081       macro_build (NULL, "nop", "");
6082       macro_build (ep, call ? "bal" : "b", "p");
6083
6084       /* Set to true so that append_insn adds a label.  */
6085       emit_branch_likely_macro = TRUE;
6086     }
6087   else
6088     {
6089       macro_build (ep, br, fmt, sreg, treg);
6090       macro_build (NULL, "nop", "");
6091     }
6092   end_noreorder ();
6093 }
6094
6095 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6096    the condition code tested.  EP specifies the branch target.  */
6097
6098 static void
6099 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6100 {
6101   const int call = 0;
6102   const char *brneg;
6103   const char *br;
6104
6105   switch (type)
6106     {
6107     case M_BC1FL:
6108       br = "bc1f";
6109       brneg = "bc1t";
6110       break;
6111     case M_BC1TL:
6112       br = "bc1t";
6113       brneg = "bc1f";
6114       break;
6115     case M_BC2FL:
6116       br = "bc2f";
6117       brneg = "bc2t";
6118       break;
6119     case M_BC2TL:
6120       br = "bc2t";
6121       brneg = "bc2f";
6122       break;
6123     default:
6124       abort ();
6125     }
6126   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6127 }
6128
6129 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6130    the register tested.  EP specifies the branch target.  */
6131
6132 static void
6133 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6134 {
6135   const char *brneg = NULL;
6136   const char *br;
6137   int call = 0;
6138
6139   switch (type)
6140     {
6141     case M_BGEZ:
6142       br = "bgez";
6143       break;
6144     case M_BGEZL:
6145       br = mips_opts.micromips ? "bgez" : "bgezl";
6146       brneg = "bltz";
6147       break;
6148     case M_BGEZALL:
6149       gas_assert (mips_opts.micromips);
6150       br = "bgezals";
6151       brneg = "bltz";
6152       call = 1;
6153       break;
6154     case M_BGTZ:
6155       br = "bgtz";
6156       break;
6157     case M_BGTZL:
6158       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6159       brneg = "blez";
6160       break;
6161     case M_BLEZ:
6162       br = "blez";
6163       break;
6164     case M_BLEZL:
6165       br = mips_opts.micromips ? "blez" : "blezl";
6166       brneg = "bgtz";
6167       break;
6168     case M_BLTZ:
6169       br = "bltz";
6170       break;
6171     case M_BLTZL:
6172       br = mips_opts.micromips ? "bltz" : "bltzl";
6173       brneg = "bgez";
6174       break;
6175     case M_BLTZALL:
6176       gas_assert (mips_opts.micromips);
6177       br = "bltzals";
6178       brneg = "bgez";
6179       call = 1;
6180       break;
6181     default:
6182       abort ();
6183     }
6184   if (mips_opts.micromips && brneg)
6185     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6186   else
6187     macro_build (ep, br, "s,p", sreg);
6188 }
6189
6190 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6191    TREG as the registers tested.  EP specifies the branch target.  */
6192
6193 static void
6194 macro_build_branch_rsrt (int type, expressionS *ep,
6195                          unsigned int sreg, unsigned int treg)
6196 {
6197   const char *brneg = NULL;
6198   const int call = 0;
6199   const char *br;
6200
6201   switch (type)
6202     {
6203     case M_BEQ:
6204     case M_BEQ_I:
6205       br = "beq";
6206       break;
6207     case M_BEQL:
6208     case M_BEQL_I:
6209       br = mips_opts.micromips ? "beq" : "beql";
6210       brneg = "bne";
6211       break;
6212     case M_BNE:
6213     case M_BNE_I:
6214       br = "bne";
6215       break;
6216     case M_BNEL:
6217     case M_BNEL_I:
6218       br = mips_opts.micromips ? "bne" : "bnel";
6219       brneg = "beq";
6220       break;
6221     default:
6222       abort ();
6223     }
6224   if (mips_opts.micromips && brneg)
6225     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6226   else
6227     macro_build (ep, br, "s,t,p", sreg, treg);
6228 }
6229
6230 /*
6231  *                      Build macros
6232  *   This routine implements the seemingly endless macro or synthesized
6233  * instructions and addressing modes in the mips assembly language. Many
6234  * of these macros are simple and are similar to each other. These could
6235  * probably be handled by some kind of table or grammar approach instead of
6236  * this verbose method. Others are not simple macros but are more like
6237  * optimizing code generation.
6238  *   One interesting optimization is when several store macros appear
6239  * consecutively that would load AT with the upper half of the same address.
6240  * The ensuing load upper instructions are ommited. This implies some kind
6241  * of global optimization. We currently only optimize within a single macro.
6242  *   For many of the load and store macros if the address is specified as a
6243  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6244  * first load register 'at' with zero and use it as the base register. The
6245  * mips assembler simply uses register $zero. Just one tiny optimization
6246  * we're missing.
6247  */
6248 static void
6249 macro (struct mips_cl_insn *ip)
6250 {
6251   unsigned int treg, sreg, dreg, breg;
6252   unsigned int tempreg;
6253   int mask;
6254   int used_at = 0;
6255   expressionS label_expr;
6256   expressionS expr1;
6257   expressionS *ep;
6258   const char *s;
6259   const char *s2;
6260   const char *fmt;
6261   int likely = 0;
6262   int coproc = 0;
6263   int off12 = 0;
6264   int call = 0;
6265   int jals = 0;
6266   int dbl = 0;
6267   int imm = 0;
6268   int ust = 0;
6269   int lp = 0;
6270   int ab = 0;
6271   int off;
6272   offsetT maxnum;
6273   bfd_reloc_code_real_type r;
6274   int hold_mips_optimize;
6275
6276   gas_assert (! mips_opts.mips16);
6277
6278   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6279   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6280   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6281   mask = ip->insn_mo->mask;
6282
6283   label_expr.X_op = O_constant;
6284   label_expr.X_op_symbol = NULL;
6285   label_expr.X_add_symbol = NULL;
6286   label_expr.X_add_number = 0;
6287
6288   expr1.X_op = O_constant;
6289   expr1.X_op_symbol = NULL;
6290   expr1.X_add_symbol = NULL;
6291   expr1.X_add_number = 1;
6292
6293   switch (mask)
6294     {
6295     case M_DABS:
6296       dbl = 1;
6297     case M_ABS:
6298       /*    bgez    $a0,1f
6299             move    v0,$a0
6300             sub     v0,$zero,$a0
6301          1:
6302        */
6303
6304       start_noreorder ();
6305
6306       if (mips_opts.micromips)
6307         micromips_label_expr (&label_expr);
6308       else
6309         label_expr.X_add_number = 8;
6310       macro_build (&label_expr, "bgez", "s,p", sreg);
6311       if (dreg == sreg)
6312         macro_build (NULL, "nop", "");
6313       else
6314         move_register (dreg, sreg);
6315       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6316       if (mips_opts.micromips)
6317         micromips_add_label ();
6318
6319       end_noreorder ();
6320       break;
6321
6322     case M_ADD_I:
6323       s = "addi";
6324       s2 = "add";
6325       goto do_addi;
6326     case M_ADDU_I:
6327       s = "addiu";
6328       s2 = "addu";
6329       goto do_addi;
6330     case M_DADD_I:
6331       dbl = 1;
6332       s = "daddi";
6333       s2 = "dadd";
6334       if (!mips_opts.micromips)
6335         goto do_addi;
6336       if (imm_expr.X_op == O_constant
6337           && imm_expr.X_add_number >= -0x200
6338           && imm_expr.X_add_number < 0x200)
6339         {
6340           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
6341           break;
6342         }
6343       goto do_addi_i;
6344     case M_DADDU_I:
6345       dbl = 1;
6346       s = "daddiu";
6347       s2 = "daddu";
6348     do_addi:
6349       if (imm_expr.X_op == O_constant
6350           && imm_expr.X_add_number >= -0x8000
6351           && imm_expr.X_add_number < 0x8000)
6352         {
6353           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
6354           break;
6355         }
6356     do_addi_i:
6357       used_at = 1;
6358       load_register (AT, &imm_expr, dbl);
6359       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6360       break;
6361
6362     case M_AND_I:
6363       s = "andi";
6364       s2 = "and";
6365       goto do_bit;
6366     case M_OR_I:
6367       s = "ori";
6368       s2 = "or";
6369       goto do_bit;
6370     case M_NOR_I:
6371       s = "";
6372       s2 = "nor";
6373       goto do_bit;
6374     case M_XOR_I:
6375       s = "xori";
6376       s2 = "xor";
6377     do_bit:
6378       if (imm_expr.X_op == O_constant
6379           && imm_expr.X_add_number >= 0
6380           && imm_expr.X_add_number < 0x10000)
6381         {
6382           if (mask != M_NOR_I)
6383             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
6384           else
6385             {
6386               macro_build (&imm_expr, "ori", "t,r,i",
6387                            treg, sreg, BFD_RELOC_LO16);
6388               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
6389             }
6390           break;
6391         }
6392
6393       used_at = 1;
6394       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6395       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6396       break;
6397
6398     case M_BALIGN:
6399       switch (imm_expr.X_add_number)
6400         {
6401         case 0:
6402           macro_build (NULL, "nop", "");
6403           break;
6404         case 2:
6405           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
6406           break;
6407         default:
6408           macro_build (NULL, "balign", "t,s,2", treg, sreg,
6409                        (int) imm_expr.X_add_number);
6410           break;
6411         }
6412       break;
6413
6414     case M_BC1FL:
6415     case M_BC1TL:
6416     case M_BC2FL:
6417     case M_BC2TL:
6418       gas_assert (mips_opts.micromips);
6419       macro_build_branch_ccl (mask, &offset_expr,
6420                               EXTRACT_OPERAND (1, BCC, *ip));
6421       break;
6422
6423     case M_BEQ_I:
6424     case M_BEQL_I:
6425     case M_BNE_I:
6426     case M_BNEL_I:
6427       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6428         treg = 0;
6429       else
6430         {
6431           treg = AT;
6432           used_at = 1;
6433           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
6434         }
6435       /* Fall through.  */
6436     case M_BEQL:
6437     case M_BNEL:
6438       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
6439       break;
6440
6441     case M_BGEL:
6442       likely = 1;
6443     case M_BGE:
6444       if (treg == 0)
6445         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
6446       else if (sreg == 0)
6447         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
6448       else
6449         {
6450           used_at = 1;
6451           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6452           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6453                                    &offset_expr, AT, ZERO);
6454         }
6455       break;
6456
6457     case M_BGEZL:
6458     case M_BGEZALL:
6459     case M_BGTZL:
6460     case M_BLEZL:
6461     case M_BLTZL:
6462     case M_BLTZALL:
6463       macro_build_branch_rs (mask, &offset_expr, sreg);
6464       break;
6465
6466     case M_BGTL_I:
6467       likely = 1;
6468     case M_BGT_I:
6469       /* Check for > max integer.  */
6470       maxnum = 0x7fffffff;
6471       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6472         {
6473           maxnum <<= 16;
6474           maxnum |= 0xffff;
6475           maxnum <<= 16;
6476           maxnum |= 0xffff;
6477         }
6478       if (imm_expr.X_op == O_constant
6479           && imm_expr.X_add_number >= maxnum
6480           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6481         {
6482         do_false:
6483           /* Result is always false.  */
6484           if (! likely)
6485             macro_build (NULL, "nop", "");
6486           else
6487             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
6488           break;
6489         }
6490       if (imm_expr.X_op != O_constant)
6491         as_bad (_("Unsupported large constant"));
6492       ++imm_expr.X_add_number;
6493       /* FALLTHROUGH */
6494     case M_BGE_I:
6495     case M_BGEL_I:
6496       if (mask == M_BGEL_I)
6497         likely = 1;
6498       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6499         {
6500           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
6501                                  &offset_expr, sreg);
6502           break;
6503         }
6504       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6505         {
6506           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
6507                                  &offset_expr, sreg);
6508           break;
6509         }
6510       maxnum = 0x7fffffff;
6511       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6512         {
6513           maxnum <<= 16;
6514           maxnum |= 0xffff;
6515           maxnum <<= 16;
6516           maxnum |= 0xffff;
6517         }
6518       maxnum = - maxnum - 1;
6519       if (imm_expr.X_op == O_constant
6520           && imm_expr.X_add_number <= maxnum
6521           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6522         {
6523         do_true:
6524           /* result is always true */
6525           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
6526           macro_build (&offset_expr, "b", "p");
6527           break;
6528         }
6529       used_at = 1;
6530       set_at (sreg, 0);
6531       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6532                                &offset_expr, AT, ZERO);
6533       break;
6534
6535     case M_BGEUL:
6536       likely = 1;
6537     case M_BGEU:
6538       if (treg == 0)
6539         goto do_true;
6540       else if (sreg == 0)
6541         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6542                                  &offset_expr, ZERO, treg);
6543       else
6544         {
6545           used_at = 1;
6546           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6547           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6548                                    &offset_expr, AT, ZERO);
6549         }
6550       break;
6551
6552     case M_BGTUL_I:
6553       likely = 1;
6554     case M_BGTU_I:
6555       if (sreg == 0
6556           || (HAVE_32BIT_GPRS
6557               && imm_expr.X_op == O_constant
6558               && imm_expr.X_add_number == -1))
6559         goto do_false;
6560       if (imm_expr.X_op != O_constant)
6561         as_bad (_("Unsupported large constant"));
6562       ++imm_expr.X_add_number;
6563       /* FALLTHROUGH */
6564     case M_BGEU_I:
6565     case M_BGEUL_I:
6566       if (mask == M_BGEUL_I)
6567         likely = 1;
6568       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6569         goto do_true;
6570       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6571         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6572                                  &offset_expr, sreg, ZERO);
6573       else
6574         {
6575           used_at = 1;
6576           set_at (sreg, 1);
6577           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6578                                    &offset_expr, AT, ZERO);
6579         }
6580       break;
6581
6582     case M_BGTL:
6583       likely = 1;
6584     case M_BGT:
6585       if (treg == 0)
6586         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
6587       else if (sreg == 0)
6588         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
6589       else
6590         {
6591           used_at = 1;
6592           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6593           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6594                                    &offset_expr, AT, ZERO);
6595         }
6596       break;
6597
6598     case M_BGTUL:
6599       likely = 1;
6600     case M_BGTU:
6601       if (treg == 0)
6602         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6603                                  &offset_expr, sreg, ZERO);
6604       else if (sreg == 0)
6605         goto do_false;
6606       else
6607         {
6608           used_at = 1;
6609           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6610           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6611                                    &offset_expr, AT, ZERO);
6612         }
6613       break;
6614
6615     case M_BLEL:
6616       likely = 1;
6617     case M_BLE:
6618       if (treg == 0)
6619         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6620       else if (sreg == 0)
6621         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
6622       else
6623         {
6624           used_at = 1;
6625           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6626           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6627                                    &offset_expr, AT, ZERO);
6628         }
6629       break;
6630
6631     case M_BLEL_I:
6632       likely = 1;
6633     case M_BLE_I:
6634       maxnum = 0x7fffffff;
6635       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6636         {
6637           maxnum <<= 16;
6638           maxnum |= 0xffff;
6639           maxnum <<= 16;
6640           maxnum |= 0xffff;
6641         }
6642       if (imm_expr.X_op == O_constant
6643           && imm_expr.X_add_number >= maxnum
6644           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6645         goto do_true;
6646       if (imm_expr.X_op != O_constant)
6647         as_bad (_("Unsupported large constant"));
6648       ++imm_expr.X_add_number;
6649       /* FALLTHROUGH */
6650     case M_BLT_I:
6651     case M_BLTL_I:
6652       if (mask == M_BLTL_I)
6653         likely = 1;
6654       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6655         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6656       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6657         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6658       else
6659         {
6660           used_at = 1;
6661           set_at (sreg, 0);
6662           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6663                                    &offset_expr, AT, ZERO);
6664         }
6665       break;
6666
6667     case M_BLEUL:
6668       likely = 1;
6669     case M_BLEU:
6670       if (treg == 0)
6671         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6672                                  &offset_expr, sreg, ZERO);
6673       else if (sreg == 0)
6674         goto do_true;
6675       else
6676         {
6677           used_at = 1;
6678           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6679           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6680                                    &offset_expr, AT, ZERO);
6681         }
6682       break;
6683
6684     case M_BLEUL_I:
6685       likely = 1;
6686     case M_BLEU_I:
6687       if (sreg == 0
6688           || (HAVE_32BIT_GPRS
6689               && imm_expr.X_op == O_constant
6690               && imm_expr.X_add_number == -1))
6691         goto do_true;
6692       if (imm_expr.X_op != O_constant)
6693         as_bad (_("Unsupported large constant"));
6694       ++imm_expr.X_add_number;
6695       /* FALLTHROUGH */
6696     case M_BLTU_I:
6697     case M_BLTUL_I:
6698       if (mask == M_BLTUL_I)
6699         likely = 1;
6700       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6701         goto do_false;
6702       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6703         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6704                                  &offset_expr, sreg, ZERO);
6705       else
6706         {
6707           used_at = 1;
6708           set_at (sreg, 1);
6709           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6710                                    &offset_expr, AT, ZERO);
6711         }
6712       break;
6713
6714     case M_BLTL:
6715       likely = 1;
6716     case M_BLT:
6717       if (treg == 0)
6718         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6719       else if (sreg == 0)
6720         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
6721       else
6722         {
6723           used_at = 1;
6724           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6725           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6726                                    &offset_expr, AT, ZERO);
6727         }
6728       break;
6729
6730     case M_BLTUL:
6731       likely = 1;
6732     case M_BLTU:
6733       if (treg == 0)
6734         goto do_false;
6735       else if (sreg == 0)
6736         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6737                                  &offset_expr, ZERO, treg);
6738       else
6739         {
6740           used_at = 1;
6741           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6742           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6743                                    &offset_expr, AT, ZERO);
6744         }
6745       break;
6746
6747     case M_DEXT:
6748       {
6749         /* Use unsigned arithmetic.  */
6750         addressT pos;
6751         addressT size;
6752
6753         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6754           {
6755             as_bad (_("Unsupported large constant"));
6756             pos = size = 1;
6757           }
6758         else
6759           {
6760             pos = imm_expr.X_add_number;
6761             size = imm2_expr.X_add_number;
6762           }
6763
6764         if (pos > 63)
6765           {
6766             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6767             pos = 1;
6768           }
6769         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6770           {
6771             as_bad (_("Improper extract size (%lu, position %lu)"),
6772                     (unsigned long) size, (unsigned long) pos);
6773             size = 1;
6774           }
6775
6776         if (size <= 32 && pos < 32)
6777           {
6778             s = "dext";
6779             fmt = "t,r,+A,+C";
6780           }
6781         else if (size <= 32)
6782           {
6783             s = "dextu";
6784             fmt = "t,r,+E,+H";
6785           }
6786         else
6787           {
6788             s = "dextm";
6789             fmt = "t,r,+A,+G";
6790           }
6791         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6792                      (int) (size - 1));
6793       }
6794       break;
6795
6796     case M_DINS:
6797       {
6798         /* Use unsigned arithmetic.  */
6799         addressT pos;
6800         addressT size;
6801
6802         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6803           {
6804             as_bad (_("Unsupported large constant"));
6805             pos = size = 1;
6806           }
6807         else
6808           {
6809             pos = imm_expr.X_add_number;
6810             size = imm2_expr.X_add_number;
6811           }
6812
6813         if (pos > 63)
6814           {
6815             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6816             pos = 1;
6817           }
6818         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6819           {
6820             as_bad (_("Improper insert size (%lu, position %lu)"),
6821                     (unsigned long) size, (unsigned long) pos);
6822             size = 1;
6823           }
6824
6825         if (pos < 32 && (pos + size - 1) < 32)
6826           {
6827             s = "dins";
6828             fmt = "t,r,+A,+B";
6829           }
6830         else if (pos >= 32)
6831           {
6832             s = "dinsu";
6833             fmt = "t,r,+E,+F";
6834           }
6835         else
6836           {
6837             s = "dinsm";
6838             fmt = "t,r,+A,+F";
6839           }
6840         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6841                      (int) (pos + size - 1));
6842       }
6843       break;
6844
6845     case M_DDIV_3:
6846       dbl = 1;
6847     case M_DIV_3:
6848       s = "mflo";
6849       goto do_div3;
6850     case M_DREM_3:
6851       dbl = 1;
6852     case M_REM_3:
6853       s = "mfhi";
6854     do_div3:
6855       if (treg == 0)
6856         {
6857           as_warn (_("Divide by zero."));
6858           if (mips_trap)
6859             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6860           else
6861             macro_build (NULL, "break", BRK_FMT, 7);
6862           break;
6863         }
6864
6865       start_noreorder ();
6866       if (mips_trap)
6867         {
6868           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
6869           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6870         }
6871       else
6872         {
6873           if (mips_opts.micromips)
6874             micromips_label_expr (&label_expr);
6875           else
6876             label_expr.X_add_number = 8;
6877           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
6878           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6879           macro_build (NULL, "break", BRK_FMT, 7);
6880           if (mips_opts.micromips)
6881             micromips_add_label ();
6882         }
6883       expr1.X_add_number = -1;
6884       used_at = 1;
6885       load_register (AT, &expr1, dbl);
6886       if (mips_opts.micromips)
6887         micromips_label_expr (&label_expr);
6888       else
6889         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
6890       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
6891       if (dbl)
6892         {
6893           expr1.X_add_number = 1;
6894           load_register (AT, &expr1, dbl);
6895           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
6896         }
6897       else
6898         {
6899           expr1.X_add_number = 0x80000000;
6900           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
6901         }
6902       if (mips_trap)
6903         {
6904           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
6905           /* We want to close the noreorder block as soon as possible, so
6906              that later insns are available for delay slot filling.  */
6907           end_noreorder ();
6908         }
6909       else
6910         {
6911           if (mips_opts.micromips)
6912             micromips_label_expr (&label_expr);
6913           else
6914             label_expr.X_add_number = 8;
6915           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
6916           macro_build (NULL, "nop", "");
6917
6918           /* We want to close the noreorder block as soon as possible, so
6919              that later insns are available for delay slot filling.  */
6920           end_noreorder ();
6921
6922           macro_build (NULL, "break", BRK_FMT, 6);
6923         }
6924       if (mips_opts.micromips)
6925         micromips_add_label ();
6926       macro_build (NULL, s, MFHL_FMT, dreg);
6927       break;
6928
6929     case M_DIV_3I:
6930       s = "div";
6931       s2 = "mflo";
6932       goto do_divi;
6933     case M_DIVU_3I:
6934       s = "divu";
6935       s2 = "mflo";
6936       goto do_divi;
6937     case M_REM_3I:
6938       s = "div";
6939       s2 = "mfhi";
6940       goto do_divi;
6941     case M_REMU_3I:
6942       s = "divu";
6943       s2 = "mfhi";
6944       goto do_divi;
6945     case M_DDIV_3I:
6946       dbl = 1;
6947       s = "ddiv";
6948       s2 = "mflo";
6949       goto do_divi;
6950     case M_DDIVU_3I:
6951       dbl = 1;
6952       s = "ddivu";
6953       s2 = "mflo";
6954       goto do_divi;
6955     case M_DREM_3I:
6956       dbl = 1;
6957       s = "ddiv";
6958       s2 = "mfhi";
6959       goto do_divi;
6960     case M_DREMU_3I:
6961       dbl = 1;
6962       s = "ddivu";
6963       s2 = "mfhi";
6964     do_divi:
6965       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6966         {
6967           as_warn (_("Divide by zero."));
6968           if (mips_trap)
6969             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6970           else
6971             macro_build (NULL, "break", BRK_FMT, 7);
6972           break;
6973         }
6974       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6975         {
6976           if (strcmp (s2, "mflo") == 0)
6977             move_register (dreg, sreg);
6978           else
6979             move_register (dreg, ZERO);
6980           break;
6981         }
6982       if (imm_expr.X_op == O_constant
6983           && imm_expr.X_add_number == -1
6984           && s[strlen (s) - 1] != 'u')
6985         {
6986           if (strcmp (s2, "mflo") == 0)
6987             {
6988               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
6989             }
6990           else
6991             move_register (dreg, ZERO);
6992           break;
6993         }
6994
6995       used_at = 1;
6996       load_register (AT, &imm_expr, dbl);
6997       macro_build (NULL, s, "z,s,t", sreg, AT);
6998       macro_build (NULL, s2, MFHL_FMT, dreg);
6999       break;
7000
7001     case M_DIVU_3:
7002       s = "divu";
7003       s2 = "mflo";
7004       goto do_divu3;
7005     case M_REMU_3:
7006       s = "divu";
7007       s2 = "mfhi";
7008       goto do_divu3;
7009     case M_DDIVU_3:
7010       s = "ddivu";
7011       s2 = "mflo";
7012       goto do_divu3;
7013     case M_DREMU_3:
7014       s = "ddivu";
7015       s2 = "mfhi";
7016     do_divu3:
7017       start_noreorder ();
7018       if (mips_trap)
7019         {
7020           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7021           macro_build (NULL, s, "z,s,t", sreg, treg);
7022           /* We want to close the noreorder block as soon as possible, so
7023              that later insns are available for delay slot filling.  */
7024           end_noreorder ();
7025         }
7026       else
7027         {
7028           if (mips_opts.micromips)
7029             micromips_label_expr (&label_expr);
7030           else
7031             label_expr.X_add_number = 8;
7032           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7033           macro_build (NULL, s, "z,s,t", sreg, treg);
7034
7035           /* We want to close the noreorder block as soon as possible, so
7036              that later insns are available for delay slot filling.  */
7037           end_noreorder ();
7038           macro_build (NULL, "break", BRK_FMT, 7);
7039           if (mips_opts.micromips)
7040             micromips_add_label ();
7041         }
7042       macro_build (NULL, s2, MFHL_FMT, dreg);
7043       break;
7044
7045     case M_DLCA_AB:
7046       dbl = 1;
7047     case M_LCA_AB:
7048       call = 1;
7049       goto do_la;
7050     case M_DLA_AB:
7051       dbl = 1;
7052     case M_LA_AB:
7053     do_la:
7054       /* Load the address of a symbol into a register.  If breg is not
7055          zero, we then add a base register to it.  */
7056
7057       if (dbl && HAVE_32BIT_GPRS)
7058         as_warn (_("dla used to load 32-bit register"));
7059
7060       if (!dbl && HAVE_64BIT_OBJECTS)
7061         as_warn (_("la used to load 64-bit address"));
7062
7063       if (offset_expr.X_op == O_constant
7064           && offset_expr.X_add_number >= -0x8000
7065           && offset_expr.X_add_number < 0x8000)
7066         {
7067           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
7068                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
7069           break;
7070         }
7071
7072       if (mips_opts.at && (treg == breg))
7073         {
7074           tempreg = AT;
7075           used_at = 1;
7076         }
7077       else
7078         {
7079           tempreg = treg;
7080         }
7081
7082       if (offset_expr.X_op != O_symbol
7083           && offset_expr.X_op != O_constant)
7084         {
7085           as_bad (_("Expression too complex"));
7086           offset_expr.X_op = O_constant;
7087         }
7088
7089       if (offset_expr.X_op == O_constant)
7090         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7091       else if (mips_pic == NO_PIC)
7092         {
7093           /* If this is a reference to a GP relative symbol, we want
7094                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7095              Otherwise we want
7096                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7097                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7098              If we have a constant, we need two instructions anyhow,
7099              so we may as well always use the latter form.
7100
7101              With 64bit address space and a usable $at we want
7102                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7103                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7104                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7105                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7106                dsll32   $tempreg,0
7107                daddu    $tempreg,$tempreg,$at
7108
7109              If $at is already in use, we use a path which is suboptimal
7110              on superscalar processors.
7111                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7112                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7113                dsll     $tempreg,16
7114                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7115                dsll     $tempreg,16
7116                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7117
7118              For GP relative symbols in 64bit address space we can use
7119              the same sequence as in 32bit address space.  */
7120           if (HAVE_64BIT_SYMBOLS)
7121             {
7122               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7123                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7124                 {
7125                   relax_start (offset_expr.X_add_symbol);
7126                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7127                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7128                   relax_switch ();
7129                 }
7130
7131               if (used_at == 0 && mips_opts.at)
7132                 {
7133                   macro_build (&offset_expr, "lui", LUI_FMT,
7134                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7135                   macro_build (&offset_expr, "lui", LUI_FMT,
7136                                AT, BFD_RELOC_HI16_S);
7137                   macro_build (&offset_expr, "daddiu", "t,r,j",
7138                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7139                   macro_build (&offset_expr, "daddiu", "t,r,j",
7140                                AT, AT, BFD_RELOC_LO16);
7141                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7142                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7143                   used_at = 1;
7144                 }
7145               else
7146                 {
7147                   macro_build (&offset_expr, "lui", LUI_FMT,
7148                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7149                   macro_build (&offset_expr, "daddiu", "t,r,j",
7150                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7151                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7152                   macro_build (&offset_expr, "daddiu", "t,r,j",
7153                                tempreg, tempreg, BFD_RELOC_HI16_S);
7154                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7155                   macro_build (&offset_expr, "daddiu", "t,r,j",
7156                                tempreg, tempreg, BFD_RELOC_LO16);
7157                 }
7158
7159               if (mips_relax.sequence)
7160                 relax_end ();
7161             }
7162           else
7163             {
7164               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7165                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7166                 {
7167                   relax_start (offset_expr.X_add_symbol);
7168                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7169                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7170                   relax_switch ();
7171                 }
7172               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7173                 as_bad (_("Offset too large"));
7174               macro_build_lui (&offset_expr, tempreg);
7175               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7176                            tempreg, tempreg, BFD_RELOC_LO16);
7177               if (mips_relax.sequence)
7178                 relax_end ();
7179             }
7180         }
7181       else if (!mips_big_got && !HAVE_NEWABI)
7182         {
7183           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7184
7185           /* If this is a reference to an external symbol, and there
7186              is no constant, we want
7187                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7188              or for lca or if tempreg is PIC_CALL_REG
7189                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7190              For a local symbol, we want
7191                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7192                nop
7193                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7194
7195              If we have a small constant, and this is a reference to
7196              an external symbol, we want
7197                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7198                nop
7199                addiu    $tempreg,$tempreg,<constant>
7200              For a local symbol, we want the same instruction
7201              sequence, but we output a BFD_RELOC_LO16 reloc on the
7202              addiu instruction.
7203
7204              If we have a large constant, and this is a reference to
7205              an external symbol, we want
7206                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7207                lui      $at,<hiconstant>
7208                addiu    $at,$at,<loconstant>
7209                addu     $tempreg,$tempreg,$at
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
7215           if (offset_expr.X_add_number == 0)
7216             {
7217               if (mips_pic == SVR4_PIC
7218                   && breg == 0
7219                   && (call || tempreg == PIC_CALL_REG))
7220                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7221
7222               relax_start (offset_expr.X_add_symbol);
7223               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7224                            lw_reloc_type, mips_gp_register);
7225               if (breg != 0)
7226                 {
7227                   /* We're going to put in an addu instruction using
7228                      tempreg, so we may as well insert the nop right
7229                      now.  */
7230                   load_delay_nop ();
7231                 }
7232               relax_switch ();
7233               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7234                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7235               load_delay_nop ();
7236               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7237                            tempreg, tempreg, BFD_RELOC_LO16);
7238               relax_end ();
7239               /* FIXME: If breg == 0, and the next instruction uses
7240                  $tempreg, then if this variant case is used an extra
7241                  nop will be generated.  */
7242             }
7243           else if (offset_expr.X_add_number >= -0x8000
7244                    && offset_expr.X_add_number < 0x8000)
7245             {
7246               load_got_offset (tempreg, &offset_expr);
7247               load_delay_nop ();
7248               add_got_offset (tempreg, &offset_expr);
7249             }
7250           else
7251             {
7252               expr1.X_add_number = offset_expr.X_add_number;
7253               offset_expr.X_add_number =
7254                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
7255               load_got_offset (tempreg, &offset_expr);
7256               offset_expr.X_add_number = expr1.X_add_number;
7257               /* If we are going to add in a base register, and the
7258                  target register and the base register are the same,
7259                  then we are using AT as a temporary register.  Since
7260                  we want to load the constant into AT, we add our
7261                  current AT (from the global offset table) and the
7262                  register into the register now, and pretend we were
7263                  not using a base register.  */
7264               if (breg == treg)
7265                 {
7266                   load_delay_nop ();
7267                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7268                                treg, AT, breg);
7269                   breg = 0;
7270                   tempreg = treg;
7271                 }
7272               add_got_offset_hilo (tempreg, &offset_expr, AT);
7273               used_at = 1;
7274             }
7275         }
7276       else if (!mips_big_got && HAVE_NEWABI)
7277         {
7278           int add_breg_early = 0;
7279
7280           /* If this is a reference to an external, and there is no
7281              constant, or local symbol (*), with or without a
7282              constant, we want
7283                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7284              or for lca or if tempreg is PIC_CALL_REG
7285                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7286
7287              If we have a small constant, and this is a reference to
7288              an external symbol, we want
7289                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7290                addiu    $tempreg,$tempreg,<constant>
7291
7292              If we have a large constant, and this is a reference to
7293              an external symbol, we want
7294                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7295                lui      $at,<hiconstant>
7296                addiu    $at,$at,<loconstant>
7297                addu     $tempreg,$tempreg,$at
7298
7299              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7300              local symbols, even though it introduces an additional
7301              instruction.  */
7302
7303           if (offset_expr.X_add_number)
7304             {
7305               expr1.X_add_number = offset_expr.X_add_number;
7306               offset_expr.X_add_number = 0;
7307
7308               relax_start (offset_expr.X_add_symbol);
7309               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7310                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7311
7312               if (expr1.X_add_number >= -0x8000
7313                   && expr1.X_add_number < 0x8000)
7314                 {
7315                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7316                                tempreg, tempreg, BFD_RELOC_LO16);
7317                 }
7318               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7319                 {
7320                   /* If we are going to add in a base register, and the
7321                      target register and the base register are the same,
7322                      then we are using AT as a temporary register.  Since
7323                      we want to load the constant into AT, we add our
7324                      current AT (from the global offset table) and the
7325                      register into the register now, and pretend we were
7326                      not using a base register.  */
7327                   if (breg != treg)
7328                     dreg = tempreg;
7329                   else
7330                     {
7331                       gas_assert (tempreg == AT);
7332                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7333                                    treg, AT, breg);
7334                       dreg = treg;
7335                       add_breg_early = 1;
7336                     }
7337
7338                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7339                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7340                                dreg, dreg, AT);
7341
7342                   used_at = 1;
7343                 }
7344               else
7345                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7346
7347               relax_switch ();
7348               offset_expr.X_add_number = expr1.X_add_number;
7349
7350               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7351                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7352               if (add_breg_early)
7353                 {
7354                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7355                                treg, tempreg, breg);
7356                   breg = 0;
7357                   tempreg = treg;
7358                 }
7359               relax_end ();
7360             }
7361           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7362             {
7363               relax_start (offset_expr.X_add_symbol);
7364               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7365                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7366               relax_switch ();
7367               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7368                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7369               relax_end ();
7370             }
7371           else
7372             {
7373               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7374                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7375             }
7376         }
7377       else if (mips_big_got && !HAVE_NEWABI)
7378         {
7379           int gpdelay;
7380           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7381           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7382           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7383
7384           /* This is the large GOT case.  If this is a reference to an
7385              external symbol, and there is no constant, we want
7386                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7387                addu     $tempreg,$tempreg,$gp
7388                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7389              or for lca or if tempreg is PIC_CALL_REG
7390                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7391                addu     $tempreg,$tempreg,$gp
7392                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7393              For a local symbol, we want
7394                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7395                nop
7396                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7397
7398              If we have a small constant, and this is a reference to
7399              an external symbol, we want
7400                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7401                addu     $tempreg,$tempreg,$gp
7402                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7403                nop
7404                addiu    $tempreg,$tempreg,<constant>
7405              For a local symbol, we want
7406                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7407                nop
7408                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
7409
7410              If we have a large constant, and this is a reference to
7411              an external symbol, we want
7412                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7413                addu     $tempreg,$tempreg,$gp
7414                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7415                lui      $at,<hiconstant>
7416                addiu    $at,$at,<loconstant>
7417                addu     $tempreg,$tempreg,$at
7418              For a local symbol, we want
7419                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7420                lui      $at,<hiconstant>
7421                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
7422                addu     $tempreg,$tempreg,$at
7423           */
7424
7425           expr1.X_add_number = offset_expr.X_add_number;
7426           offset_expr.X_add_number = 0;
7427           relax_start (offset_expr.X_add_symbol);
7428           gpdelay = reg_needs_delay (mips_gp_register);
7429           if (expr1.X_add_number == 0 && breg == 0
7430               && (call || tempreg == PIC_CALL_REG))
7431             {
7432               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7433               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7434             }
7435           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7436           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7437                        tempreg, tempreg, mips_gp_register);
7438           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7439                        tempreg, lw_reloc_type, tempreg);
7440           if (expr1.X_add_number == 0)
7441             {
7442               if (breg != 0)
7443                 {
7444                   /* We're going to put in an addu instruction using
7445                      tempreg, so we may as well insert the nop right
7446                      now.  */
7447                   load_delay_nop ();
7448                 }
7449             }
7450           else if (expr1.X_add_number >= -0x8000
7451                    && expr1.X_add_number < 0x8000)
7452             {
7453               load_delay_nop ();
7454               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7455                            tempreg, tempreg, BFD_RELOC_LO16);
7456             }
7457           else
7458             {
7459               /* If we are going to add in a base register, and the
7460                  target register and the base register are the same,
7461                  then we are using AT as a temporary register.  Since
7462                  we want to load the constant into AT, we add our
7463                  current AT (from the global offset table) and the
7464                  register into the register now, and pretend we were
7465                  not using a base register.  */
7466               if (breg != treg)
7467                 dreg = tempreg;
7468               else
7469                 {
7470                   gas_assert (tempreg == AT);
7471                   load_delay_nop ();
7472                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7473                                treg, AT, breg);
7474                   dreg = treg;
7475                 }
7476
7477               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7478               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7479
7480               used_at = 1;
7481             }
7482           offset_expr.X_add_number =
7483             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
7484           relax_switch ();
7485
7486           if (gpdelay)
7487             {
7488               /* This is needed because this instruction uses $gp, but
7489                  the first instruction on the main stream does not.  */
7490               macro_build (NULL, "nop", "");
7491             }
7492
7493           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7494                        local_reloc_type, mips_gp_register);
7495           if (expr1.X_add_number >= -0x8000
7496               && expr1.X_add_number < 0x8000)
7497             {
7498               load_delay_nop ();
7499               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7500                            tempreg, tempreg, BFD_RELOC_LO16);
7501               /* FIXME: If add_number is 0, and there was no base
7502                  register, the external symbol case ended with a load,
7503                  so if the symbol turns out to not be external, and
7504                  the next instruction uses tempreg, an unnecessary nop
7505                  will be inserted.  */
7506             }
7507           else
7508             {
7509               if (breg == treg)
7510                 {
7511                   /* We must add in the base register now, as in the
7512                      external symbol case.  */
7513                   gas_assert (tempreg == AT);
7514                   load_delay_nop ();
7515                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7516                                treg, AT, breg);
7517                   tempreg = treg;
7518                   /* We set breg to 0 because we have arranged to add
7519                      it in in both cases.  */
7520                   breg = 0;
7521                 }
7522
7523               macro_build_lui (&expr1, AT);
7524               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7525                            AT, AT, BFD_RELOC_LO16);
7526               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7527                            tempreg, tempreg, AT);
7528               used_at = 1;
7529             }
7530           relax_end ();
7531         }
7532       else if (mips_big_got && HAVE_NEWABI)
7533         {
7534           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7535           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7536           int add_breg_early = 0;
7537
7538           /* This is the large GOT case.  If this is a reference to an
7539              external symbol, and there is no constant, we want
7540                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7541                add      $tempreg,$tempreg,$gp
7542                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7543              or for lca or if tempreg is PIC_CALL_REG
7544                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7545                add      $tempreg,$tempreg,$gp
7546                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7547
7548              If we have a small constant, and this is a reference to
7549              an external symbol, 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                addi     $tempreg,$tempreg,<constant>
7554
7555              If we have a large constant, and this is a reference to
7556              an external symbol, we want
7557                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7558                addu     $tempreg,$tempreg,$gp
7559                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7560                lui      $at,<hiconstant>
7561                addi     $at,$at,<loconstant>
7562                add      $tempreg,$tempreg,$at
7563
7564              If we have NewABI, and we know it's a local symbol, we want
7565                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7566                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7567              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
7568
7569           relax_start (offset_expr.X_add_symbol);
7570
7571           expr1.X_add_number = offset_expr.X_add_number;
7572           offset_expr.X_add_number = 0;
7573
7574           if (expr1.X_add_number == 0 && breg == 0
7575               && (call || tempreg == PIC_CALL_REG))
7576             {
7577               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7578               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7579             }
7580           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7581           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7582                        tempreg, tempreg, mips_gp_register);
7583           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7584                        tempreg, lw_reloc_type, tempreg);
7585
7586           if (expr1.X_add_number == 0)
7587             ;
7588           else if (expr1.X_add_number >= -0x8000
7589                    && expr1.X_add_number < 0x8000)
7590             {
7591               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7592                            tempreg, tempreg, BFD_RELOC_LO16);
7593             }
7594           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7595             {
7596               /* If we are going to add in a base register, and the
7597                  target register and the base register are the same,
7598                  then we are using AT as a temporary register.  Since
7599                  we want to load the constant into AT, we add our
7600                  current AT (from the global offset table) and the
7601                  register into the register now, and pretend we were
7602                  not using a base register.  */
7603               if (breg != treg)
7604                 dreg = tempreg;
7605               else
7606                 {
7607                   gas_assert (tempreg == AT);
7608                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7609                                treg, AT, breg);
7610                   dreg = treg;
7611                   add_breg_early = 1;
7612                 }
7613
7614               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7615               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7616
7617               used_at = 1;
7618             }
7619           else
7620             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7621
7622           relax_switch ();
7623           offset_expr.X_add_number = expr1.X_add_number;
7624           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7625                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7626           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
7627                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
7628           if (add_breg_early)
7629             {
7630               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7631                            treg, tempreg, breg);
7632               breg = 0;
7633               tempreg = treg;
7634             }
7635           relax_end ();
7636         }
7637       else
7638         abort ();
7639
7640       if (breg != 0)
7641         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
7642       break;
7643
7644     case M_MSGSND:
7645       gas_assert (!mips_opts.micromips);
7646       {
7647         unsigned long temp = (treg << 16) | (0x01);
7648         macro_build (NULL, "c2", "C", temp);
7649       }
7650       break;
7651
7652     case M_MSGLD:
7653       gas_assert (!mips_opts.micromips);
7654       {
7655         unsigned long temp = (0x02);
7656         macro_build (NULL, "c2", "C", temp);
7657       }
7658       break;
7659
7660     case M_MSGLD_T:
7661       gas_assert (!mips_opts.micromips);
7662       {
7663         unsigned long temp = (treg << 16) | (0x02);
7664         macro_build (NULL, "c2", "C", temp);
7665       }
7666       break;
7667
7668     case M_MSGWAIT:
7669       gas_assert (!mips_opts.micromips);
7670       macro_build (NULL, "c2", "C", 3);
7671       break;
7672
7673     case M_MSGWAIT_T:
7674       gas_assert (!mips_opts.micromips);
7675       {
7676         unsigned long temp = (treg << 16) | 0x03;
7677         macro_build (NULL, "c2", "C", temp);
7678       }
7679       break;
7680
7681     case M_J_A:
7682       /* The j instruction may not be used in PIC code, since it
7683          requires an absolute address.  We convert it to a b
7684          instruction.  */
7685       if (mips_pic == NO_PIC)
7686         macro_build (&offset_expr, "j", "a");
7687       else
7688         macro_build (&offset_expr, "b", "p");
7689       break;
7690
7691       /* The jal instructions must be handled as macros because when
7692          generating PIC code they expand to multi-instruction
7693          sequences.  Normally they are simple instructions.  */
7694     case M_JALS_1:
7695       dreg = RA;
7696       /* Fall through.  */
7697     case M_JALS_2:
7698       gas_assert (mips_opts.micromips);
7699       jals = 1;
7700       goto jal;
7701     case M_JAL_1:
7702       dreg = RA;
7703       /* Fall through.  */
7704     case M_JAL_2:
7705     jal:
7706       if (mips_pic == NO_PIC)
7707         {
7708           s = jals ? "jalrs" : "jalr";
7709           if (mips_opts.micromips && dreg == RA)
7710             macro_build (NULL, s, "mj", sreg);
7711           else
7712             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7713         }
7714       else
7715         {
7716           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
7717                            && mips_cprestore_offset >= 0);
7718
7719           if (sreg != PIC_CALL_REG)
7720             as_warn (_("MIPS PIC call to register other than $25"));
7721
7722           s = (mips_opts.micromips && (!mips_opts.noreorder || cprestore)
7723                ? "jalrs" : "jalr");
7724           if (mips_opts.micromips && dreg == RA)
7725             macro_build (NULL, s, "mj", sreg);
7726           else
7727             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7728           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
7729             {
7730               if (mips_cprestore_offset < 0)
7731                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7732               else
7733                 {
7734                   if (!mips_frame_reg_valid)
7735                     {
7736                       as_warn (_("No .frame pseudo-op used in PIC code"));
7737                       /* Quiet this warning.  */
7738                       mips_frame_reg_valid = 1;
7739                     }
7740                   if (!mips_cprestore_valid)
7741                     {
7742                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7743                       /* Quiet this warning.  */
7744                       mips_cprestore_valid = 1;
7745                     }
7746                   if (mips_opts.noreorder)
7747                     macro_build (NULL, "nop", "");
7748                   expr1.X_add_number = mips_cprestore_offset;
7749                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7750                                                 mips_gp_register,
7751                                                 mips_frame_reg,
7752                                                 HAVE_64BIT_ADDRESSES);
7753                 }
7754             }
7755         }
7756
7757       break;
7758
7759     case M_JALS_A:
7760       gas_assert (mips_opts.micromips);
7761       jals = 1;
7762       /* Fall through.  */
7763     case M_JAL_A:
7764       if (mips_pic == NO_PIC)
7765         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
7766       else if (mips_pic == SVR4_PIC)
7767         {
7768           /* If this is a reference to an external symbol, and we are
7769              using a small GOT, we want
7770                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
7771                nop
7772                jalr     $ra,$25
7773                nop
7774                lw       $gp,cprestore($sp)
7775              The cprestore value is set using the .cprestore
7776              pseudo-op.  If we are using a big GOT, we want
7777                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
7778                addu     $25,$25,$gp
7779                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
7780                nop
7781                jalr     $ra,$25
7782                nop
7783                lw       $gp,cprestore($sp)
7784              If the symbol is not external, we want
7785                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7786                nop
7787                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
7788                jalr     $ra,$25
7789                nop
7790                lw $gp,cprestore($sp)
7791
7792              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
7793              sequences above, minus nops, unless the symbol is local,
7794              which enables us to use GOT_PAGE/GOT_OFST (big got) or
7795              GOT_DISP.  */
7796           if (HAVE_NEWABI)
7797             {
7798               if (!mips_big_got)
7799                 {
7800                   relax_start (offset_expr.X_add_symbol);
7801                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7802                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7803                                mips_gp_register);
7804                   relax_switch ();
7805                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7806                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
7807                                mips_gp_register);
7808                   relax_end ();
7809                 }
7810               else
7811                 {
7812                   relax_start (offset_expr.X_add_symbol);
7813                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7814                                BFD_RELOC_MIPS_CALL_HI16);
7815                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7816                                PIC_CALL_REG, mips_gp_register);
7817                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7818                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7819                                PIC_CALL_REG);
7820                   relax_switch ();
7821                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7822                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
7823                                mips_gp_register);
7824                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7825                                PIC_CALL_REG, PIC_CALL_REG,
7826                                BFD_RELOC_MIPS_GOT_OFST);
7827                   relax_end ();
7828                 }
7829
7830               macro_build_jalr (&offset_expr, 0);
7831             }
7832           else
7833             {
7834               relax_start (offset_expr.X_add_symbol);
7835               if (!mips_big_got)
7836                 {
7837                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7838                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7839                                mips_gp_register);
7840                   load_delay_nop ();
7841                   relax_switch ();
7842                 }
7843               else
7844                 {
7845                   int gpdelay;
7846
7847                   gpdelay = reg_needs_delay (mips_gp_register);
7848                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7849                                BFD_RELOC_MIPS_CALL_HI16);
7850                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7851                                PIC_CALL_REG, mips_gp_register);
7852                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7853                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7854                                PIC_CALL_REG);
7855                   load_delay_nop ();
7856                   relax_switch ();
7857                   if (gpdelay)
7858                     macro_build (NULL, "nop", "");
7859                 }
7860               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7861                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
7862                            mips_gp_register);
7863               load_delay_nop ();
7864               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7865                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
7866               relax_end ();
7867               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
7868
7869               if (mips_cprestore_offset < 0)
7870                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7871               else
7872                 {
7873                   if (!mips_frame_reg_valid)
7874                     {
7875                       as_warn (_("No .frame pseudo-op used in PIC code"));
7876                       /* Quiet this warning.  */
7877                       mips_frame_reg_valid = 1;
7878                     }
7879                   if (!mips_cprestore_valid)
7880                     {
7881                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7882                       /* Quiet this warning.  */
7883                       mips_cprestore_valid = 1;
7884                     }
7885                   if (mips_opts.noreorder)
7886                     macro_build (NULL, "nop", "");
7887                   expr1.X_add_number = mips_cprestore_offset;
7888                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7889                                                 mips_gp_register,
7890                                                 mips_frame_reg,
7891                                                 HAVE_64BIT_ADDRESSES);
7892                 }
7893             }
7894         }
7895       else if (mips_pic == VXWORKS_PIC)
7896         as_bad (_("Non-PIC jump used in PIC library"));
7897       else
7898         abort ();
7899
7900       break;
7901
7902     case M_LB_AB:
7903       ab = 1;
7904       s = "lb";
7905       fmt = "t,o(b)";
7906       goto ld;
7907     case M_LBU_AB:
7908       ab = 1;
7909       s = "lbu";
7910       fmt = "t,o(b)";
7911       goto ld;
7912     case M_LH_AB:
7913       ab = 1;
7914       s = "lh";
7915       fmt = "t,o(b)";
7916       goto ld;
7917     case M_LHU_AB:
7918       ab = 1;
7919       s = "lhu";
7920       fmt = "t,o(b)";
7921       goto ld;
7922     case M_LW_AB:
7923       ab = 1;
7924       s = "lw";
7925       fmt = "t,o(b)";
7926       goto ld;
7927     case M_LWC0_AB:
7928       ab = 1;
7929       gas_assert (!mips_opts.micromips);
7930       s = "lwc0";
7931       fmt = "E,o(b)";
7932       /* Itbl support may require additional care here.  */
7933       coproc = 1;
7934       goto ld_st;
7935     case M_LWC1_AB:
7936       ab = 1;
7937       s = "lwc1";
7938       fmt = "T,o(b)";
7939       /* Itbl support may require additional care here.  */
7940       coproc = 1;
7941       goto ld_st;
7942     case M_LWC2_AB:
7943       ab = 1;
7944     case M_LWC2_OB:
7945       s = "lwc2";
7946       fmt = COP12_FMT;
7947       off12 = mips_opts.micromips;
7948       /* Itbl support may require additional care here.  */
7949       coproc = 1;
7950       goto ld_st;
7951     case M_LWC3_AB:
7952       ab = 1;
7953       gas_assert (!mips_opts.micromips);
7954       s = "lwc3";
7955       fmt = "E,o(b)";
7956       /* Itbl support may require additional care here.  */
7957       coproc = 1;
7958       goto ld_st;
7959     case M_LWL_AB:
7960       ab = 1;
7961     case M_LWL_OB:
7962       s = "lwl";
7963       fmt = MEM12_FMT;
7964       off12 = mips_opts.micromips;
7965       goto ld_st;
7966     case M_LWR_AB:
7967       ab = 1;
7968     case M_LWR_OB:
7969       s = "lwr";
7970       fmt = MEM12_FMT;
7971       off12 = mips_opts.micromips;
7972       goto ld_st;
7973     case M_LDC1_AB:
7974       ab = 1;
7975       s = "ldc1";
7976       fmt = "T,o(b)";
7977       /* Itbl support may require additional care here.  */
7978       coproc = 1;
7979       goto ld_st;
7980     case M_LDC2_AB:
7981       ab = 1;
7982     case M_LDC2_OB:
7983       s = "ldc2";
7984       fmt = COP12_FMT;
7985       off12 = mips_opts.micromips;
7986       /* Itbl support may require additional care here.  */
7987       coproc = 1;
7988       goto ld_st;
7989     case M_LDC3_AB:
7990       ab = 1;
7991       s = "ldc3";
7992       fmt = "E,o(b)";
7993       /* Itbl support may require additional care here.  */
7994       coproc = 1;
7995       goto ld_st;
7996     case M_LDL_AB:
7997       ab = 1;
7998     case M_LDL_OB:
7999       s = "ldl";
8000       fmt = MEM12_FMT;
8001       off12 = mips_opts.micromips;
8002       goto ld_st;
8003     case M_LDR_AB:
8004       ab = 1;
8005     case M_LDR_OB:
8006       s = "ldr";
8007       fmt = MEM12_FMT;
8008       off12 = mips_opts.micromips;
8009       goto ld_st;
8010     case M_LL_AB:
8011       ab = 1;
8012     case M_LL_OB:
8013       s = "ll";
8014       fmt = MEM12_FMT;
8015       off12 = mips_opts.micromips;
8016       goto ld;
8017     case M_LLD_AB:
8018       ab = 1;
8019     case M_LLD_OB:
8020       s = "lld";
8021       fmt = MEM12_FMT;
8022       off12 = mips_opts.micromips;
8023       goto ld;
8024     case M_LWU_AB:
8025       ab = 1;
8026     case M_LWU_OB:
8027       s = "lwu";
8028       fmt = MEM12_FMT;
8029       off12 = mips_opts.micromips;
8030       goto ld;
8031     case M_LWP_AB:
8032       ab = 1;
8033     case M_LWP_OB:
8034       gas_assert (mips_opts.micromips);
8035       s = "lwp";
8036       fmt = "t,~(b)";
8037       off12 = 1;
8038       lp = 1;
8039       goto ld;
8040     case M_LDP_AB:
8041       ab = 1;
8042     case M_LDP_OB:
8043       gas_assert (mips_opts.micromips);
8044       s = "ldp";
8045       fmt = "t,~(b)";
8046       off12 = 1;
8047       lp = 1;
8048       goto ld;
8049     case M_LWM_AB:
8050       ab = 1;
8051     case M_LWM_OB:
8052       gas_assert (mips_opts.micromips);
8053       s = "lwm";
8054       fmt = "n,~(b)";
8055       off12 = 1;
8056       goto ld_st;
8057     case M_LDM_AB:
8058       ab = 1;
8059     case M_LDM_OB:
8060       gas_assert (mips_opts.micromips);
8061       s = "ldm";
8062       fmt = "n,~(b)";
8063       off12 = 1;
8064       goto ld_st;
8065
8066     ld:
8067       if (breg == treg + lp)
8068         goto ld_st;
8069       else
8070         tempreg = treg + lp;
8071       goto ld_noat;
8072
8073     case M_SB_AB:
8074       ab = 1;
8075       s = "sb";
8076       fmt = "t,o(b)";
8077       goto ld_st;
8078     case M_SH_AB:
8079       ab = 1;
8080       s = "sh";
8081       fmt = "t,o(b)";
8082       goto ld_st;
8083     case M_SW_AB:
8084       ab = 1;
8085       s = "sw";
8086       fmt = "t,o(b)";
8087       goto ld_st;
8088     case M_SWC0_AB:
8089       ab = 1;
8090       gas_assert (!mips_opts.micromips);
8091       s = "swc0";
8092       fmt = "E,o(b)";
8093       /* Itbl support may require additional care here.  */
8094       coproc = 1;
8095       goto ld_st;
8096     case M_SWC1_AB:
8097       ab = 1;
8098       s = "swc1";
8099       fmt = "T,o(b)";
8100       /* Itbl support may require additional care here.  */
8101       coproc = 1;
8102       goto ld_st;
8103     case M_SWC2_AB:
8104       ab = 1;
8105     case M_SWC2_OB:
8106       s = "swc2";
8107       fmt = COP12_FMT;
8108       off12 = mips_opts.micromips;
8109       /* Itbl support may require additional care here.  */
8110       coproc = 1;
8111       goto ld_st;
8112     case M_SWC3_AB:
8113       ab = 1;
8114       gas_assert (!mips_opts.micromips);
8115       s = "swc3";
8116       fmt = "E,o(b)";
8117       /* Itbl support may require additional care here.  */
8118       coproc = 1;
8119       goto ld_st;
8120     case M_SWL_AB:
8121       ab = 1;
8122     case M_SWL_OB:
8123       s = "swl";
8124       fmt = MEM12_FMT;
8125       off12 = mips_opts.micromips;
8126       goto ld_st;
8127     case M_SWR_AB:
8128       ab = 1;
8129     case M_SWR_OB:
8130       s = "swr";
8131       fmt = MEM12_FMT;
8132       off12 = mips_opts.micromips;
8133       goto ld_st;
8134     case M_SC_AB:
8135       ab = 1;
8136     case M_SC_OB:
8137       s = "sc";
8138       fmt = MEM12_FMT;
8139       off12 = mips_opts.micromips;
8140       goto ld_st;
8141     case M_SCD_AB:
8142       ab = 1;
8143     case M_SCD_OB:
8144       s = "scd";
8145       fmt = MEM12_FMT;
8146       off12 = mips_opts.micromips;
8147       goto ld_st;
8148     case M_CACHE_AB:
8149       ab = 1;
8150     case M_CACHE_OB:
8151       s = "cache";
8152       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8153       off12 = mips_opts.micromips;
8154       goto ld_st;
8155     case M_PREF_AB:
8156       ab = 1;
8157     case M_PREF_OB:
8158       s = "pref";
8159       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8160       off12 = mips_opts.micromips;
8161       goto ld_st;
8162     case M_SDC1_AB:
8163       ab = 1;
8164       s = "sdc1";
8165       fmt = "T,o(b)";
8166       coproc = 1;
8167       /* Itbl support may require additional care here.  */
8168       goto ld_st;
8169     case M_SDC2_AB:
8170       ab = 1;
8171     case M_SDC2_OB:
8172       s = "sdc2";
8173       fmt = COP12_FMT;
8174       off12 = mips_opts.micromips;
8175       /* Itbl support may require additional care here.  */
8176       coproc = 1;
8177       goto ld_st;
8178     case M_SDC3_AB:
8179       ab = 1;
8180       gas_assert (!mips_opts.micromips);
8181       s = "sdc3";
8182       fmt = "E,o(b)";
8183       /* Itbl support may require additional care here.  */
8184       coproc = 1;
8185       goto ld_st;
8186     case M_SDL_AB:
8187       ab = 1;
8188     case M_SDL_OB:
8189       s = "sdl";
8190       fmt = MEM12_FMT;
8191       off12 = mips_opts.micromips;
8192       goto ld_st;
8193     case M_SDR_AB:
8194       ab = 1;
8195     case M_SDR_OB:
8196       s = "sdr";
8197       fmt = MEM12_FMT;
8198       off12 = mips_opts.micromips;
8199       goto ld_st;
8200     case M_SWP_AB:
8201       ab = 1;
8202     case M_SWP_OB:
8203       gas_assert (mips_opts.micromips);
8204       s = "swp";
8205       fmt = "t,~(b)";
8206       off12 = 1;
8207       goto ld_st;
8208     case M_SDP_AB:
8209       ab = 1;
8210     case M_SDP_OB:
8211       gas_assert (mips_opts.micromips);
8212       s = "sdp";
8213       fmt = "t,~(b)";
8214       off12 = 1;
8215       goto ld_st;
8216     case M_SWM_AB:
8217       ab = 1;
8218     case M_SWM_OB:
8219       gas_assert (mips_opts.micromips);
8220       s = "swm";
8221       fmt = "n,~(b)";
8222       off12 = 1;
8223       goto ld_st;
8224     case M_SDM_AB:
8225       ab = 1;
8226     case M_SDM_OB:
8227       gas_assert (mips_opts.micromips);
8228       s = "sdm";
8229       fmt = "n,~(b)";
8230       off12 = 1;
8231
8232     ld_st:
8233       tempreg = AT;
8234       used_at = 1;
8235     ld_noat:
8236       if (coproc
8237           && NO_ISA_COP (mips_opts.arch)
8238           && (ip->insn_mo->pinfo2 & (INSN2_M_FP_S | INSN2_M_FP_D)) == 0)
8239         {
8240           as_bad (_("Opcode not supported on this processor: %s"),
8241                   mips_cpu_info_from_arch (mips_opts.arch)->name);
8242           break;
8243         }
8244
8245       if (offset_expr.X_op != O_constant
8246           && offset_expr.X_op != O_symbol)
8247         {
8248           as_bad (_("Expression too complex"));
8249           offset_expr.X_op = O_constant;
8250         }
8251
8252       if (HAVE_32BIT_ADDRESSES
8253           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8254         {
8255           char value [32];
8256
8257           sprintf_vma (value, offset_expr.X_add_number);
8258           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8259         }
8260
8261       /* A constant expression in PIC code can be handled just as it
8262          is in non PIC code.  */
8263       if (offset_expr.X_op == O_constant)
8264         {
8265           int hipart = 0;
8266
8267           expr1.X_add_number = offset_expr.X_add_number;
8268           normalize_address_expr (&expr1);
8269           if (!off12 && !IS_SEXT_16BIT_NUM (expr1.X_add_number))
8270             {
8271               expr1.X_add_number = ((expr1.X_add_number + 0x8000)
8272                                     & ~(bfd_vma) 0xffff);
8273               hipart = 1;
8274             }
8275           else if (off12 && !IS_SEXT_12BIT_NUM (expr1.X_add_number))
8276             {
8277               expr1.X_add_number = ((expr1.X_add_number + 0x800)
8278                                     & ~(bfd_vma) 0xfff);
8279               hipart = 1;
8280             }
8281           if (hipart)
8282             {
8283               load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8284               if (breg != 0)
8285                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8286                              tempreg, tempreg, breg);
8287               breg = tempreg;
8288             }
8289           if (!off12)
8290             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, breg);
8291           else
8292             macro_build (NULL, s, fmt,
8293                          treg, (unsigned long) offset_expr.X_add_number, breg);
8294         }
8295       else if (off12)
8296         {
8297           /* A 12-bit offset field is too narrow to be used for a low-part
8298              relocation, so load the whole address into the auxillary
8299              register.  In the case of "A(b)" addresses, we first load
8300              absolute address "A" into the register and then add base
8301              register "b".  In the case of "o(b)" addresses, we simply
8302              need to add 16-bit offset "o" to base register "b", and
8303              offset_reloc already contains the relocations associated
8304              with "o".  */
8305           if (ab)
8306             {
8307               load_address (tempreg, &offset_expr, &used_at);
8308               if (breg != 0)
8309                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8310                              tempreg, tempreg, breg);
8311             }
8312           else
8313             macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8314                          tempreg, breg, -1,
8315                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8316           expr1.X_add_number = 0;
8317           macro_build (NULL, s, fmt,
8318                        treg, (unsigned long) expr1.X_add_number, tempreg);
8319         }
8320       else if (mips_pic == NO_PIC)
8321         {
8322           /* If this is a reference to a GP relative symbol, and there
8323              is no base register, we want
8324                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8325              Otherwise, if there is no base register, we want
8326                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8327                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8328              If we have a constant, we need two instructions anyhow,
8329              so we always use the latter form.
8330
8331              If we have a base register, and this is a reference to a
8332              GP relative symbol, we want
8333                addu     $tempreg,$breg,$gp
8334                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
8335              Otherwise we want
8336                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8337                addu     $tempreg,$tempreg,$breg
8338                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8339              With a constant we always use the latter case.
8340
8341              With 64bit address space and no base register and $at usable,
8342              we want
8343                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8344                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8345                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8346                dsll32   $tempreg,0
8347                daddu    $tempreg,$at
8348                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8349              If we have a base register, we want
8350                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8351                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8352                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8353                daddu    $at,$breg
8354                dsll32   $tempreg,0
8355                daddu    $tempreg,$at
8356                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8357
8358              Without $at we can't generate the optimal path for superscalar
8359              processors here since this would require two temporary registers.
8360                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8361                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8362                dsll     $tempreg,16
8363                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8364                dsll     $tempreg,16
8365                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8366              If we have a base register, we want
8367                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8368                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8369                dsll     $tempreg,16
8370                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8371                dsll     $tempreg,16
8372                daddu    $tempreg,$tempreg,$breg
8373                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8374
8375              For GP relative symbols in 64bit address space we can use
8376              the same sequence as in 32bit address space.  */
8377           if (HAVE_64BIT_SYMBOLS)
8378             {
8379               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8380                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8381                 {
8382                   relax_start (offset_expr.X_add_symbol);
8383                   if (breg == 0)
8384                     {
8385                       macro_build (&offset_expr, s, fmt, treg,
8386                                    BFD_RELOC_GPREL16, mips_gp_register);
8387                     }
8388                   else
8389                     {
8390                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8391                                    tempreg, breg, mips_gp_register);
8392                       macro_build (&offset_expr, s, fmt, treg,
8393                                    BFD_RELOC_GPREL16, tempreg);
8394                     }
8395                   relax_switch ();
8396                 }
8397
8398               if (used_at == 0 && mips_opts.at)
8399                 {
8400                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8401                                BFD_RELOC_MIPS_HIGHEST);
8402                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
8403                                BFD_RELOC_HI16_S);
8404                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8405                                tempreg, BFD_RELOC_MIPS_HIGHER);
8406                   if (breg != 0)
8407                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
8408                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8409                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8410                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
8411                                tempreg);
8412                   used_at = 1;
8413                 }
8414               else
8415                 {
8416                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8417                                BFD_RELOC_MIPS_HIGHEST);
8418                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8419                                tempreg, BFD_RELOC_MIPS_HIGHER);
8420                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8421                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8422                                tempreg, BFD_RELOC_HI16_S);
8423                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8424                   if (breg != 0)
8425                     macro_build (NULL, "daddu", "d,v,t",
8426                                  tempreg, tempreg, breg);
8427                   macro_build (&offset_expr, s, fmt, treg,
8428                                BFD_RELOC_LO16, tempreg);
8429                 }
8430
8431               if (mips_relax.sequence)
8432                 relax_end ();
8433               break;
8434             }
8435
8436           if (breg == 0)
8437             {
8438               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8439                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8440                 {
8441                   relax_start (offset_expr.X_add_symbol);
8442                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
8443                                mips_gp_register);
8444                   relax_switch ();
8445                 }
8446               macro_build_lui (&offset_expr, tempreg);
8447               macro_build (&offset_expr, s, fmt, treg,
8448                            BFD_RELOC_LO16, tempreg);
8449               if (mips_relax.sequence)
8450                 relax_end ();
8451             }
8452           else
8453             {
8454               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8455                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8456                 {
8457                   relax_start (offset_expr.X_add_symbol);
8458                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8459                                tempreg, breg, mips_gp_register);
8460                   macro_build (&offset_expr, s, fmt, treg,
8461                                BFD_RELOC_GPREL16, tempreg);
8462                   relax_switch ();
8463                 }
8464               macro_build_lui (&offset_expr, tempreg);
8465               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8466                            tempreg, tempreg, breg);
8467               macro_build (&offset_expr, s, fmt, treg,
8468                            BFD_RELOC_LO16, tempreg);
8469               if (mips_relax.sequence)
8470                 relax_end ();
8471             }
8472         }
8473       else if (!mips_big_got)
8474         {
8475           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8476
8477           /* If this is a reference to an external symbol, we want
8478                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8479                nop
8480                <op>     $treg,0($tempreg)
8481              Otherwise we want
8482                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8483                nop
8484                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8485                <op>     $treg,0($tempreg)
8486
8487              For NewABI, we want
8488                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8489                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
8490
8491              If there is a base register, we add it to $tempreg before
8492              the <op>.  If there is a constant, we stick it in the
8493              <op> instruction.  We don't handle constants larger than
8494              16 bits, because we have no way to load the upper 16 bits
8495              (actually, we could handle them for the subset of cases
8496              in which we are not using $at).  */
8497           gas_assert (offset_expr.X_op == O_symbol);
8498           if (HAVE_NEWABI)
8499             {
8500               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8501                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8502               if (breg != 0)
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_MIPS_GOT_OFST, tempreg);
8507               break;
8508             }
8509           expr1.X_add_number = offset_expr.X_add_number;
8510           offset_expr.X_add_number = 0;
8511           if (expr1.X_add_number < -0x8000
8512               || expr1.X_add_number >= 0x8000)
8513             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8514           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8515                        lw_reloc_type, mips_gp_register);
8516           load_delay_nop ();
8517           relax_start (offset_expr.X_add_symbol);
8518           relax_switch ();
8519           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8520                        tempreg, BFD_RELOC_LO16);
8521           relax_end ();
8522           if (breg != 0)
8523             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8524                          tempreg, tempreg, breg);
8525           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8526         }
8527       else if (mips_big_got && !HAVE_NEWABI)
8528         {
8529           int gpdelay;
8530
8531           /* If this is a reference to an external symbol, we want
8532                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8533                addu     $tempreg,$tempreg,$gp
8534                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8535                <op>     $treg,0($tempreg)
8536              Otherwise we want
8537                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8538                nop
8539                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8540                <op>     $treg,0($tempreg)
8541              If there is a base register, we add it to $tempreg before
8542              the <op>.  If there is a constant, we stick it in the
8543              <op> instruction.  We don't handle constants larger than
8544              16 bits, because we have no way to load the upper 16 bits
8545              (actually, we could handle them for the subset of cases
8546              in which we are not using $at).  */
8547           gas_assert (offset_expr.X_op == O_symbol);
8548           expr1.X_add_number = offset_expr.X_add_number;
8549           offset_expr.X_add_number = 0;
8550           if (expr1.X_add_number < -0x8000
8551               || expr1.X_add_number >= 0x8000)
8552             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8553           gpdelay = reg_needs_delay (mips_gp_register);
8554           relax_start (offset_expr.X_add_symbol);
8555           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8556                        BFD_RELOC_MIPS_GOT_HI16);
8557           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
8558                        mips_gp_register);
8559           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8560                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
8561           relax_switch ();
8562           if (gpdelay)
8563             macro_build (NULL, "nop", "");
8564           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8565                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8566           load_delay_nop ();
8567           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8568                        tempreg, BFD_RELOC_LO16);
8569           relax_end ();
8570
8571           if (breg != 0)
8572             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8573                          tempreg, tempreg, breg);
8574           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8575         }
8576       else if (mips_big_got && HAVE_NEWABI)
8577         {
8578           /* If this is a reference to an external symbol, we want
8579                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8580                add      $tempreg,$tempreg,$gp
8581                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8582                <op>     $treg,<ofst>($tempreg)
8583              Otherwise, for local symbols, we want:
8584                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8585                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
8586           gas_assert (offset_expr.X_op == O_symbol);
8587           expr1.X_add_number = offset_expr.X_add_number;
8588           offset_expr.X_add_number = 0;
8589           if (expr1.X_add_number < -0x8000
8590               || expr1.X_add_number >= 0x8000)
8591             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
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           if (breg != 0)
8600             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8601                          tempreg, tempreg, breg);
8602           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8603
8604           relax_switch ();
8605           offset_expr.X_add_number = expr1.X_add_number;
8606           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8607                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8608           if (breg != 0)
8609             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8610                          tempreg, tempreg, breg);
8611           macro_build (&offset_expr, s, fmt, treg,
8612                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
8613           relax_end ();
8614         }
8615       else
8616         abort ();
8617
8618       break;
8619
8620     case M_LI:
8621     case M_LI_S:
8622       load_register (treg, &imm_expr, 0);
8623       break;
8624
8625     case M_DLI:
8626       load_register (treg, &imm_expr, 1);
8627       break;
8628
8629     case M_LI_SS:
8630       if (imm_expr.X_op == O_constant)
8631         {
8632           used_at = 1;
8633           load_register (AT, &imm_expr, 0);
8634           macro_build (NULL, "mtc1", "t,G", AT, treg);
8635           break;
8636         }
8637       else
8638         {
8639           gas_assert (offset_expr.X_op == O_symbol
8640                       && strcmp (segment_name (S_GET_SEGMENT
8641                                                (offset_expr.X_add_symbol)),
8642                                  ".lit4") == 0
8643                       && offset_expr.X_add_number == 0);
8644           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
8645                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8646           break;
8647         }
8648
8649     case M_LI_D:
8650       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
8651          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
8652          order 32 bits of the value and the low order 32 bits are either
8653          zero or in OFFSET_EXPR.  */
8654       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8655         {
8656           if (HAVE_64BIT_GPRS)
8657             load_register (treg, &imm_expr, 1);
8658           else
8659             {
8660               int hreg, lreg;
8661
8662               if (target_big_endian)
8663                 {
8664                   hreg = treg;
8665                   lreg = treg + 1;
8666                 }
8667               else
8668                 {
8669                   hreg = treg + 1;
8670                   lreg = treg;
8671                 }
8672
8673               if (hreg <= 31)
8674                 load_register (hreg, &imm_expr, 0);
8675               if (lreg <= 31)
8676                 {
8677                   if (offset_expr.X_op == O_absent)
8678                     move_register (lreg, 0);
8679                   else
8680                     {
8681                       gas_assert (offset_expr.X_op == O_constant);
8682                       load_register (lreg, &offset_expr, 0);
8683                     }
8684                 }
8685             }
8686           break;
8687         }
8688
8689       /* We know that sym is in the .rdata section.  First we get the
8690          upper 16 bits of the address.  */
8691       if (mips_pic == NO_PIC)
8692         {
8693           macro_build_lui (&offset_expr, AT);
8694           used_at = 1;
8695         }
8696       else
8697         {
8698           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8699                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8700           used_at = 1;
8701         }
8702
8703       /* Now we load the register(s).  */
8704       if (HAVE_64BIT_GPRS)
8705         {
8706           used_at = 1;
8707           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8708         }
8709       else
8710         {
8711           used_at = 1;
8712           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8713           if (treg != RA)
8714             {
8715               /* FIXME: How in the world do we deal with the possible
8716                  overflow here?  */
8717               offset_expr.X_add_number += 4;
8718               macro_build (&offset_expr, "lw", "t,o(b)",
8719                            treg + 1, BFD_RELOC_LO16, AT);
8720             }
8721         }
8722       break;
8723
8724     case M_LI_DD:
8725       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
8726          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
8727          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
8728          the value and the low order 32 bits are either zero or in
8729          OFFSET_EXPR.  */
8730       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8731         {
8732           used_at = 1;
8733           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
8734           if (HAVE_64BIT_FPRS)
8735             {
8736               gas_assert (HAVE_64BIT_GPRS);
8737               macro_build (NULL, "dmtc1", "t,S", AT, treg);
8738             }
8739           else
8740             {
8741               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
8742               if (offset_expr.X_op == O_absent)
8743                 macro_build (NULL, "mtc1", "t,G", 0, treg);
8744               else
8745                 {
8746                   gas_assert (offset_expr.X_op == O_constant);
8747                   load_register (AT, &offset_expr, 0);
8748                   macro_build (NULL, "mtc1", "t,G", AT, treg);
8749                 }
8750             }
8751           break;
8752         }
8753
8754       gas_assert (offset_expr.X_op == O_symbol
8755                   && offset_expr.X_add_number == 0);
8756       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
8757       if (strcmp (s, ".lit8") == 0)
8758         {
8759           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8760             {
8761               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
8762                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8763               break;
8764             }
8765           breg = mips_gp_register;
8766           r = BFD_RELOC_MIPS_LITERAL;
8767           goto dob;
8768         }
8769       else
8770         {
8771           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
8772           used_at = 1;
8773           if (mips_pic != NO_PIC)
8774             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8775                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
8776           else
8777             {
8778               /* FIXME: This won't work for a 64 bit address.  */
8779               macro_build_lui (&offset_expr, AT);
8780             }
8781
8782           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8783             {
8784               macro_build (&offset_expr, "ldc1", "T,o(b)",
8785                            treg, BFD_RELOC_LO16, AT);
8786               break;
8787             }
8788           breg = AT;
8789           r = BFD_RELOC_LO16;
8790           goto dob;
8791         }
8792
8793     case M_L_DOB:
8794       /* Even on a big endian machine $fn comes before $fn+1.  We have
8795          to adjust when loading from memory.  */
8796       r = BFD_RELOC_LO16;
8797     dob:
8798       gas_assert (!mips_opts.micromips);
8799       gas_assert (mips_opts.isa == ISA_MIPS1);
8800       macro_build (&offset_expr, "lwc1", "T,o(b)",
8801                    target_big_endian ? treg + 1 : treg, r, breg);
8802       /* FIXME: A possible overflow which I don't know how to deal
8803          with.  */
8804       offset_expr.X_add_number += 4;
8805       macro_build (&offset_expr, "lwc1", "T,o(b)",
8806                    target_big_endian ? treg : treg + 1, r, breg);
8807       break;
8808
8809     case M_S_DOB:
8810       gas_assert (!mips_opts.micromips);
8811       gas_assert (mips_opts.isa == ISA_MIPS1);
8812       /* Even on a big endian machine $fn comes before $fn+1.  We have
8813          to adjust when storing to memory.  */
8814       macro_build (&offset_expr, "swc1", "T,o(b)",
8815                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
8816       offset_expr.X_add_number += 4;
8817       macro_build (&offset_expr, "swc1", "T,o(b)",
8818                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
8819       break;
8820
8821     case M_L_DAB:
8822       gas_assert (!mips_opts.micromips);
8823       /*
8824        * The MIPS assembler seems to check for X_add_number not
8825        * being double aligned and generating:
8826        *        lui     at,%hi(foo+1)
8827        *        addu    at,at,v1
8828        *        addiu   at,at,%lo(foo+1)
8829        *        lwc1    f2,0(at)
8830        *        lwc1    f3,4(at)
8831        * But, the resulting address is the same after relocation so why
8832        * generate the extra instruction?
8833        */
8834       /* Itbl support may require additional care here.  */
8835       coproc = 1;
8836       fmt = "T,o(b)";
8837       if (mips_opts.isa != ISA_MIPS1)
8838         {
8839           s = "ldc1";
8840           goto ld_st;
8841         }
8842       s = "lwc1";
8843       goto ldd_std;
8844
8845     case M_S_DAB:
8846       gas_assert (!mips_opts.micromips);
8847       /* Itbl support may require additional care here.  */
8848       coproc = 1;
8849       fmt = "T,o(b)";
8850       if (mips_opts.isa != ISA_MIPS1)
8851         {
8852           s = "sdc1";
8853           goto ld_st;
8854         }
8855       s = "swc1";
8856       goto ldd_std;
8857
8858     case M_LD_AB:
8859       fmt = "t,o(b)";
8860       if (HAVE_64BIT_GPRS)
8861         {
8862           s = "ld";
8863           goto ld;
8864         }
8865       s = "lw";
8866       goto ldd_std;
8867
8868     case M_SD_AB:
8869       fmt = "t,o(b)";
8870       if (HAVE_64BIT_GPRS)
8871         {
8872           s = "sd";
8873           goto ld_st;
8874         }
8875       s = "sw";
8876
8877     ldd_std:
8878       if (offset_expr.X_op != O_symbol
8879           && offset_expr.X_op != O_constant)
8880         {
8881           as_bad (_("Expression too complex"));
8882           offset_expr.X_op = O_constant;
8883         }
8884
8885       if (HAVE_32BIT_ADDRESSES
8886           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8887         {
8888           char value [32];
8889
8890           sprintf_vma (value, offset_expr.X_add_number);
8891           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8892         }
8893
8894       /* Even on a big endian machine $fn comes before $fn+1.  We have
8895          to adjust when loading from memory.  We set coproc if we must
8896          load $fn+1 first.  */
8897       /* Itbl support may require additional care here.  */
8898       if (!target_big_endian)
8899         coproc = 0;
8900
8901       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
8902         {
8903           /* If this is a reference to a GP relative symbol, we want
8904                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8905                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
8906              If we have a base register, we use this
8907                addu     $at,$breg,$gp
8908                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
8909                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
8910              If this is not a GP relative symbol, we want
8911                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8912                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
8913                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
8914              If there is a base register, we add it to $at after the
8915              lui instruction.  If there is a constant, we always use
8916              the last case.  */
8917           if (offset_expr.X_op == O_symbol
8918               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8919               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8920             {
8921               relax_start (offset_expr.X_add_symbol);
8922               if (breg == 0)
8923                 {
8924                   tempreg = mips_gp_register;
8925                 }
8926               else
8927                 {
8928                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8929                                AT, breg, mips_gp_register);
8930                   tempreg = AT;
8931                   used_at = 1;
8932                 }
8933
8934               /* Itbl support may require additional care here.  */
8935               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8936                            BFD_RELOC_GPREL16, tempreg);
8937               offset_expr.X_add_number += 4;
8938
8939               /* Set mips_optimize to 2 to avoid inserting an
8940                  undesired nop.  */
8941               hold_mips_optimize = mips_optimize;
8942               mips_optimize = 2;
8943               /* Itbl support may require additional care here.  */
8944               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8945                            BFD_RELOC_GPREL16, tempreg);
8946               mips_optimize = hold_mips_optimize;
8947
8948               relax_switch ();
8949
8950               offset_expr.X_add_number -= 4;
8951             }
8952           used_at = 1;
8953           macro_build_lui (&offset_expr, AT);
8954           if (breg != 0)
8955             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
8956           /* Itbl support may require additional care here.  */
8957           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8958                        BFD_RELOC_LO16, AT);
8959           /* FIXME: How do we handle overflow here?  */
8960           offset_expr.X_add_number += 4;
8961           /* Itbl support may require additional care here.  */
8962           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8963                        BFD_RELOC_LO16, AT);
8964           if (mips_relax.sequence)
8965             relax_end ();
8966         }
8967       else if (!mips_big_got)
8968         {
8969           /* If this is a reference to an external symbol, we want
8970                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8971                nop
8972                <op>     $treg,0($at)
8973                <op>     $treg+1,4($at)
8974              Otherwise we want
8975                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8976                nop
8977                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
8978                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
8979              If there is a base register we add it to $at before the
8980              lwc1 instructions.  If there is a constant we include it
8981              in the lwc1 instructions.  */
8982           used_at = 1;
8983           expr1.X_add_number = offset_expr.X_add_number;
8984           if (expr1.X_add_number < -0x8000
8985               || expr1.X_add_number >= 0x8000 - 4)
8986             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8987           load_got_offset (AT, &offset_expr);
8988           load_delay_nop ();
8989           if (breg != 0)
8990             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
8991
8992           /* Set mips_optimize to 2 to avoid inserting an undesired
8993              nop.  */
8994           hold_mips_optimize = mips_optimize;
8995           mips_optimize = 2;
8996
8997           /* Itbl support may require additional care here.  */
8998           relax_start (offset_expr.X_add_symbol);
8999           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9000                        BFD_RELOC_LO16, AT);
9001           expr1.X_add_number += 4;
9002           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9003                        BFD_RELOC_LO16, AT);
9004           relax_switch ();
9005           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9006                        BFD_RELOC_LO16, AT);
9007           offset_expr.X_add_number += 4;
9008           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9009                        BFD_RELOC_LO16, AT);
9010           relax_end ();
9011
9012           mips_optimize = hold_mips_optimize;
9013         }
9014       else if (mips_big_got)
9015         {
9016           int gpdelay;
9017
9018           /* If this is a reference to an external symbol, we want
9019                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9020                addu     $at,$at,$gp
9021                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9022                nop
9023                <op>     $treg,0($at)
9024                <op>     $treg+1,4($at)
9025              Otherwise we want
9026                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9027                nop
9028                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9029                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9030              If there is a base register we add it to $at before the
9031              lwc1 instructions.  If there is a constant we include it
9032              in the lwc1 instructions.  */
9033           used_at = 1;
9034           expr1.X_add_number = offset_expr.X_add_number;
9035           offset_expr.X_add_number = 0;
9036           if (expr1.X_add_number < -0x8000
9037               || expr1.X_add_number >= 0x8000 - 4)
9038             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9039           gpdelay = reg_needs_delay (mips_gp_register);
9040           relax_start (offset_expr.X_add_symbol);
9041           macro_build (&offset_expr, "lui", LUI_FMT,
9042                        AT, BFD_RELOC_MIPS_GOT_HI16);
9043           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9044                        AT, AT, mips_gp_register);
9045           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9046                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9047           load_delay_nop ();
9048           if (breg != 0)
9049             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9050           /* Itbl support may require additional care here.  */
9051           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9052                        BFD_RELOC_LO16, AT);
9053           expr1.X_add_number += 4;
9054
9055           /* Set mips_optimize to 2 to avoid inserting an undesired
9056              nop.  */
9057           hold_mips_optimize = mips_optimize;
9058           mips_optimize = 2;
9059           /* Itbl support may require additional care here.  */
9060           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9061                        BFD_RELOC_LO16, AT);
9062           mips_optimize = hold_mips_optimize;
9063           expr1.X_add_number -= 4;
9064
9065           relax_switch ();
9066           offset_expr.X_add_number = expr1.X_add_number;
9067           if (gpdelay)
9068             macro_build (NULL, "nop", "");
9069           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9070                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9071           load_delay_nop ();
9072           if (breg != 0)
9073             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9074           /* Itbl support may require additional care here.  */
9075           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9076                        BFD_RELOC_LO16, AT);
9077           offset_expr.X_add_number += 4;
9078
9079           /* Set mips_optimize to 2 to avoid inserting an undesired
9080              nop.  */
9081           hold_mips_optimize = mips_optimize;
9082           mips_optimize = 2;
9083           /* Itbl support may require additional care here.  */
9084           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9085                        BFD_RELOC_LO16, AT);
9086           mips_optimize = hold_mips_optimize;
9087           relax_end ();
9088         }
9089       else
9090         abort ();
9091
9092       break;
9093
9094     case M_LD_OB:
9095       s = HAVE_64BIT_GPRS ? "ld" : "lw";
9096       goto sd_ob;
9097     case M_SD_OB:
9098       s = HAVE_64BIT_GPRS ? "sd" : "sw";
9099     sd_ob:
9100       macro_build (&offset_expr, s, "t,o(b)", treg,
9101                    -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9102                    breg);
9103       if (!HAVE_64BIT_GPRS)
9104         {
9105           offset_expr.X_add_number += 4;
9106           macro_build (&offset_expr, s, "t,o(b)", treg + 1,
9107                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9108                        breg);
9109         }
9110       break;
9111
9112    /* New code added to support COPZ instructions.
9113       This code builds table entries out of the macros in mip_opcodes.
9114       R4000 uses interlocks to handle coproc delays.
9115       Other chips (like the R3000) require nops to be inserted for delays.
9116
9117       FIXME: Currently, we require that the user handle delays.
9118       In order to fill delay slots for non-interlocked chips,
9119       we must have a way to specify delays based on the coprocessor.
9120       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9121       What are the side-effects of the cop instruction?
9122       What cache support might we have and what are its effects?
9123       Both coprocessor & memory require delays. how long???
9124       What registers are read/set/modified?
9125
9126       If an itbl is provided to interpret cop instructions,
9127       this knowledge can be encoded in the itbl spec.  */
9128
9129     case M_COP0:
9130       s = "c0";
9131       goto copz;
9132     case M_COP1:
9133       s = "c1";
9134       goto copz;
9135     case M_COP2:
9136       s = "c2";
9137       goto copz;
9138     case M_COP3:
9139       s = "c3";
9140     copz:
9141       gas_assert (!mips_opts.micromips);
9142       if (NO_ISA_COP (mips_opts.arch)
9143           && (ip->insn_mo->pinfo2 & INSN2_M_FP_S) == 0)
9144         {
9145           as_bad (_("opcode not supported on this processor: %s"),
9146                   mips_cpu_info_from_arch (mips_opts.arch)->name);
9147           break;
9148         }
9149
9150       /* For now we just do C (same as Cz).  The parameter will be
9151          stored in insn_opcode by mips_ip.  */
9152       macro_build (NULL, s, "C", ip->insn_opcode);
9153       break;
9154
9155     case M_MOVE:
9156       move_register (dreg, sreg);
9157       break;
9158
9159     case M_DMUL:
9160       dbl = 1;
9161     case M_MUL:
9162       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9163       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9164       break;
9165
9166     case M_DMUL_I:
9167       dbl = 1;
9168     case M_MUL_I:
9169       /* The MIPS assembler some times generates shifts and adds.  I'm
9170          not trying to be that fancy. GCC should do this for us
9171          anyway.  */
9172       used_at = 1;
9173       load_register (AT, &imm_expr, dbl);
9174       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9175       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9176       break;
9177
9178     case M_DMULO_I:
9179       dbl = 1;
9180     case M_MULO_I:
9181       imm = 1;
9182       goto do_mulo;
9183
9184     case M_DMULO:
9185       dbl = 1;
9186     case M_MULO:
9187     do_mulo:
9188       start_noreorder ();
9189       used_at = 1;
9190       if (imm)
9191         load_register (AT, &imm_expr, dbl);
9192       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9193       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9194       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9195       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9196       if (mips_trap)
9197         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9198       else
9199         {
9200           if (mips_opts.micromips)
9201             micromips_label_expr (&label_expr);
9202           else
9203             label_expr.X_add_number = 8;
9204           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9205           macro_build (NULL, "nop", "");
9206           macro_build (NULL, "break", BRK_FMT, 6);
9207           if (mips_opts.micromips)
9208             micromips_add_label ();
9209         }
9210       end_noreorder ();
9211       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9212       break;
9213
9214     case M_DMULOU_I:
9215       dbl = 1;
9216     case M_MULOU_I:
9217       imm = 1;
9218       goto do_mulou;
9219
9220     case M_DMULOU:
9221       dbl = 1;
9222     case M_MULOU:
9223     do_mulou:
9224       start_noreorder ();
9225       used_at = 1;
9226       if (imm)
9227         load_register (AT, &imm_expr, dbl);
9228       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9229                    sreg, imm ? AT : treg);
9230       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9231       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9232       if (mips_trap)
9233         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9234       else
9235         {
9236           if (mips_opts.micromips)
9237             micromips_label_expr (&label_expr);
9238           else
9239             label_expr.X_add_number = 8;
9240           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9241           macro_build (NULL, "nop", "");
9242           macro_build (NULL, "break", BRK_FMT, 6);
9243           if (mips_opts.micromips)
9244             micromips_add_label ();
9245         }
9246       end_noreorder ();
9247       break;
9248
9249     case M_DROL:
9250       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9251         {
9252           if (dreg == sreg)
9253             {
9254               tempreg = AT;
9255               used_at = 1;
9256             }
9257           else
9258             {
9259               tempreg = dreg;
9260             }
9261           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9262           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9263           break;
9264         }
9265       used_at = 1;
9266       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9267       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9268       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9269       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9270       break;
9271
9272     case M_ROL:
9273       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9274         {
9275           if (dreg == sreg)
9276             {
9277               tempreg = AT;
9278               used_at = 1;
9279             }
9280           else
9281             {
9282               tempreg = dreg;
9283             }
9284           macro_build (NULL, "negu", "d,w", tempreg, treg);
9285           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
9286           break;
9287         }
9288       used_at = 1;
9289       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9290       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
9291       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
9292       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9293       break;
9294
9295     case M_DROL_I:
9296       {
9297         unsigned int rot;
9298         char *l;
9299         char *rr;
9300
9301         if (imm_expr.X_op != O_constant)
9302           as_bad (_("Improper rotate count"));
9303         rot = imm_expr.X_add_number & 0x3f;
9304         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9305           {
9306             rot = (64 - rot) & 0x3f;
9307             if (rot >= 32)
9308               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9309             else
9310               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9311             break;
9312           }
9313         if (rot == 0)
9314           {
9315             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9316             break;
9317           }
9318         l = (rot < 0x20) ? "dsll" : "dsll32";
9319         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
9320         rot &= 0x1f;
9321         used_at = 1;
9322         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
9323         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9324         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9325       }
9326       break;
9327
9328     case M_ROL_I:
9329       {
9330         unsigned int rot;
9331
9332         if (imm_expr.X_op != O_constant)
9333           as_bad (_("Improper rotate count"));
9334         rot = imm_expr.X_add_number & 0x1f;
9335         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9336           {
9337             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
9338             break;
9339           }
9340         if (rot == 0)
9341           {
9342             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9343             break;
9344           }
9345         used_at = 1;
9346         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
9347         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9348         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9349       }
9350       break;
9351
9352     case M_DROR:
9353       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9354         {
9355           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
9356           break;
9357         }
9358       used_at = 1;
9359       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9360       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
9361       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
9362       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9363       break;
9364
9365     case M_ROR:
9366       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9367         {
9368           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
9369           break;
9370         }
9371       used_at = 1;
9372       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9373       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
9374       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
9375       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9376       break;
9377
9378     case M_DROR_I:
9379       {
9380         unsigned int rot;
9381         char *l;
9382         char *rr;
9383
9384         if (imm_expr.X_op != O_constant)
9385           as_bad (_("Improper rotate count"));
9386         rot = imm_expr.X_add_number & 0x3f;
9387         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9388           {
9389             if (rot >= 32)
9390               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9391             else
9392               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9393             break;
9394           }
9395         if (rot == 0)
9396           {
9397             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9398             break;
9399           }
9400         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
9401         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
9402         rot &= 0x1f;
9403         used_at = 1;
9404         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
9405         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9406         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9407       }
9408       break;
9409
9410     case M_ROR_I:
9411       {
9412         unsigned int rot;
9413
9414         if (imm_expr.X_op != O_constant)
9415           as_bad (_("Improper rotate count"));
9416         rot = imm_expr.X_add_number & 0x1f;
9417         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9418           {
9419             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
9420             break;
9421           }
9422         if (rot == 0)
9423           {
9424             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9425             break;
9426           }
9427         used_at = 1;
9428         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
9429         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9430         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9431       }
9432       break;
9433
9434     case M_SEQ:
9435       if (sreg == 0)
9436         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
9437       else if (treg == 0)
9438         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9439       else
9440         {
9441           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9442           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9443         }
9444       break;
9445
9446     case M_SEQ_I:
9447       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9448         {
9449           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9450           break;
9451         }
9452       if (sreg == 0)
9453         {
9454           as_warn (_("Instruction %s: result is always false"),
9455                    ip->insn_mo->name);
9456           move_register (dreg, 0);
9457           break;
9458         }
9459       if (CPU_HAS_SEQ (mips_opts.arch)
9460           && -512 <= imm_expr.X_add_number
9461           && imm_expr.X_add_number < 512)
9462         {
9463           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
9464                        (int) imm_expr.X_add_number);
9465           break;
9466         }
9467       if (imm_expr.X_op == O_constant
9468           && imm_expr.X_add_number >= 0
9469           && imm_expr.X_add_number < 0x10000)
9470         {
9471           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9472         }
9473       else if (imm_expr.X_op == O_constant
9474                && imm_expr.X_add_number > -0x8000
9475                && imm_expr.X_add_number < 0)
9476         {
9477           imm_expr.X_add_number = -imm_expr.X_add_number;
9478           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9479                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9480         }
9481       else if (CPU_HAS_SEQ (mips_opts.arch))
9482         {
9483           used_at = 1;
9484           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9485           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
9486           break;
9487         }
9488       else
9489         {
9490           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9491           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9492           used_at = 1;
9493         }
9494       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9495       break;
9496
9497     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
9498       s = "slt";
9499       goto sge;
9500     case M_SGEU:
9501       s = "sltu";
9502     sge:
9503       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
9504       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9505       break;
9506
9507     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
9508     case M_SGEU_I:
9509       if (imm_expr.X_op == O_constant
9510           && imm_expr.X_add_number >= -0x8000
9511           && imm_expr.X_add_number < 0x8000)
9512         {
9513           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
9514                        dreg, sreg, BFD_RELOC_LO16);
9515         }
9516       else
9517         {
9518           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9519           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
9520                        dreg, sreg, AT);
9521           used_at = 1;
9522         }
9523       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9524       break;
9525
9526     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
9527       s = "slt";
9528       goto sgt;
9529     case M_SGTU:
9530       s = "sltu";
9531     sgt:
9532       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9533       break;
9534
9535     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
9536       s = "slt";
9537       goto sgti;
9538     case M_SGTU_I:
9539       s = "sltu";
9540     sgti:
9541       used_at = 1;
9542       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9543       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9544       break;
9545
9546     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
9547       s = "slt";
9548       goto sle;
9549     case M_SLEU:
9550       s = "sltu";
9551     sle:
9552       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9553       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9554       break;
9555
9556     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
9557       s = "slt";
9558       goto slei;
9559     case M_SLEU_I:
9560       s = "sltu";
9561     slei:
9562       used_at = 1;
9563       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9564       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9565       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9566       break;
9567
9568     case M_SLT_I:
9569       if (imm_expr.X_op == O_constant
9570           && imm_expr.X_add_number >= -0x8000
9571           && imm_expr.X_add_number < 0x8000)
9572         {
9573           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9574           break;
9575         }
9576       used_at = 1;
9577       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9578       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
9579       break;
9580
9581     case M_SLTU_I:
9582       if (imm_expr.X_op == O_constant
9583           && imm_expr.X_add_number >= -0x8000
9584           && imm_expr.X_add_number < 0x8000)
9585         {
9586           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
9587                        BFD_RELOC_LO16);
9588           break;
9589         }
9590       used_at = 1;
9591       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9592       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
9593       break;
9594
9595     case M_SNE:
9596       if (sreg == 0)
9597         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
9598       else if (treg == 0)
9599         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9600       else
9601         {
9602           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9603           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9604         }
9605       break;
9606
9607     case M_SNE_I:
9608       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9609         {
9610           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9611           break;
9612         }
9613       if (sreg == 0)
9614         {
9615           as_warn (_("Instruction %s: result is always true"),
9616                    ip->insn_mo->name);
9617           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
9618                        dreg, 0, BFD_RELOC_LO16);
9619           break;
9620         }
9621       if (CPU_HAS_SEQ (mips_opts.arch)
9622           && -512 <= imm_expr.X_add_number
9623           && imm_expr.X_add_number < 512)
9624         {
9625           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
9626                        (int) imm_expr.X_add_number);
9627           break;
9628         }
9629       if (imm_expr.X_op == O_constant
9630           && imm_expr.X_add_number >= 0
9631           && imm_expr.X_add_number < 0x10000)
9632         {
9633           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9634         }
9635       else if (imm_expr.X_op == O_constant
9636                && imm_expr.X_add_number > -0x8000
9637                && imm_expr.X_add_number < 0)
9638         {
9639           imm_expr.X_add_number = -imm_expr.X_add_number;
9640           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9641                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9642         }
9643       else if (CPU_HAS_SEQ (mips_opts.arch))
9644         {
9645           used_at = 1;
9646           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9647           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
9648           break;
9649         }
9650       else
9651         {
9652           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9653           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9654           used_at = 1;
9655         }
9656       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9657       break;
9658
9659     case M_SUB_I:
9660       s = "addi";
9661       s2 = "sub";
9662       goto do_subi;
9663     case M_SUBU_I:
9664       s = "addiu";
9665       s2 = "subu";
9666       goto do_subi;
9667     case M_DSUB_I:
9668       dbl = 1;
9669       s = "daddi";
9670       s2 = "dsub";
9671       if (!mips_opts.micromips)
9672         goto do_subi;
9673       if (imm_expr.X_op == O_constant
9674           && imm_expr.X_add_number > -0x200
9675           && imm_expr.X_add_number <= 0x200)
9676         {
9677           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
9678           break;
9679         }
9680       goto do_subi_i;
9681     case M_DSUBU_I:
9682       dbl = 1;
9683       s = "daddiu";
9684       s2 = "dsubu";
9685     do_subi:
9686       if (imm_expr.X_op == O_constant
9687           && imm_expr.X_add_number > -0x8000
9688           && imm_expr.X_add_number <= 0x8000)
9689         {
9690           imm_expr.X_add_number = -imm_expr.X_add_number;
9691           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9692           break;
9693         }
9694     do_subi_i:
9695       used_at = 1;
9696       load_register (AT, &imm_expr, dbl);
9697       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
9698       break;
9699
9700     case M_TEQ_I:
9701       s = "teq";
9702       goto trap;
9703     case M_TGE_I:
9704       s = "tge";
9705       goto trap;
9706     case M_TGEU_I:
9707       s = "tgeu";
9708       goto trap;
9709     case M_TLT_I:
9710       s = "tlt";
9711       goto trap;
9712     case M_TLTU_I:
9713       s = "tltu";
9714       goto trap;
9715     case M_TNE_I:
9716       s = "tne";
9717     trap:
9718       used_at = 1;
9719       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9720       macro_build (NULL, s, "s,t", sreg, AT);
9721       break;
9722
9723     case M_TRUNCWS:
9724     case M_TRUNCWD:
9725       gas_assert (!mips_opts.micromips);
9726       gas_assert (mips_opts.isa == ISA_MIPS1);
9727       used_at = 1;
9728       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
9729       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
9730
9731       /*
9732        * Is the double cfc1 instruction a bug in the mips assembler;
9733        * or is there a reason for it?
9734        */
9735       start_noreorder ();
9736       macro_build (NULL, "cfc1", "t,G", treg, RA);
9737       macro_build (NULL, "cfc1", "t,G", treg, RA);
9738       macro_build (NULL, "nop", "");
9739       expr1.X_add_number = 3;
9740       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
9741       expr1.X_add_number = 2;
9742       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
9743       macro_build (NULL, "ctc1", "t,G", AT, RA);
9744       macro_build (NULL, "nop", "");
9745       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
9746                    dreg, sreg);
9747       macro_build (NULL, "ctc1", "t,G", treg, RA);
9748       macro_build (NULL, "nop", "");
9749       end_noreorder ();
9750       break;
9751
9752     case M_ULH_A:
9753       ab = 1;
9754     case M_ULH:
9755       s = "lb";
9756       s2 = "lbu";
9757       off = 1;
9758       goto uld_st;
9759     case M_ULHU_A:
9760       ab = 1;
9761     case M_ULHU:
9762       s = "lbu";
9763       s2 = "lbu";
9764       off = 1;
9765       goto uld_st;
9766     case M_ULW_A:
9767       ab = 1;
9768     case M_ULW:
9769       s = "lwl";
9770       s2 = "lwr";
9771       off12 = mips_opts.micromips;
9772       off = 3;
9773       goto uld_st;
9774     case M_ULD_A:
9775       ab = 1;
9776     case M_ULD:
9777       s = "ldl";
9778       s2 = "ldr";
9779       off12 = mips_opts.micromips;
9780       off = 7;
9781       goto uld_st;
9782     case M_USH_A:
9783       ab = 1;
9784     case M_USH:
9785       s = "sb";
9786       s2 = "sb";
9787       off = 1;
9788       ust = 1;
9789       goto uld_st;
9790     case M_USW_A:
9791       ab = 1;
9792     case M_USW:
9793       s = "swl";
9794       s2 = "swr";
9795       off12 = mips_opts.micromips;
9796       off = 3;
9797       ust = 1;
9798       goto uld_st;
9799     case M_USD_A:
9800       ab = 1;
9801     case M_USD:
9802       s = "sdl";
9803       s2 = "sdr";
9804       off12 = mips_opts.micromips;
9805       off = 7;
9806       ust = 1;
9807
9808     uld_st:
9809       if (!ab && offset_expr.X_add_number >= 0x8000 - off)
9810         as_bad (_("Operand overflow"));
9811
9812       ep = &offset_expr;
9813       expr1.X_add_number = 0;
9814       if (ab)
9815         {
9816           used_at = 1;
9817           tempreg = AT;
9818           load_address (tempreg, ep, &used_at);
9819           if (breg != 0)
9820             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9821                          tempreg, tempreg, breg);
9822           breg = tempreg;
9823           tempreg = treg;
9824           ep = &expr1;
9825         }
9826       else if (off12
9827                && (offset_expr.X_op != O_constant
9828                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number)
9829                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number + off)))
9830         {
9831           used_at = 1;
9832           tempreg = AT;
9833           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg,
9834                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9835           breg = tempreg;
9836           tempreg = treg;
9837           ep = &expr1;
9838         }
9839       else if (!ust && treg == breg)
9840         {
9841           used_at = 1;
9842           tempreg = AT;
9843         }
9844       else
9845         tempreg = treg;
9846
9847       if (off == 1)
9848         goto ulh_sh;
9849
9850       if (!target_big_endian)
9851         ep->X_add_number += off;
9852       if (!off12)
9853         macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9854       else
9855         macro_build (NULL, s, "t,~(b)",
9856                      tempreg, (unsigned long) ep->X_add_number, breg);
9857
9858       if (!target_big_endian)
9859         ep->X_add_number -= off;
9860       else
9861         ep->X_add_number += off;
9862       if (!off12)
9863         macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9864       else
9865         macro_build (NULL, s2, "t,~(b)",
9866                      tempreg, (unsigned long) ep->X_add_number, breg);
9867
9868       /* If necessary, move the result in tempreg to the final destination.  */
9869       if (!ust && treg != tempreg)
9870         {
9871           /* Protect second load's delay slot.  */
9872           load_delay_nop ();
9873           move_register (treg, tempreg);
9874         }
9875       break;
9876
9877     ulh_sh:
9878       used_at = 1;
9879       if (target_big_endian == ust)
9880         ep->X_add_number += off;
9881       tempreg = ust || ab ? treg : AT;
9882       macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9883
9884       /* For halfword transfers we need a temporary register to shuffle
9885          bytes.  Unfortunately for M_USH_A we have none available before
9886          the next store as AT holds the base address.  We deal with this
9887          case by clobbering TREG and then restoring it as with ULH.  */
9888       tempreg = ust == ab ? treg : AT;
9889       if (ust)
9890         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
9891
9892       if (target_big_endian == ust)
9893         ep->X_add_number -= off;
9894       else
9895         ep->X_add_number += off;
9896       macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9897
9898       /* For M_USH_A re-retrieve the LSB.  */
9899       if (ust && ab)
9900         {
9901           if (target_big_endian)
9902             ep->X_add_number += off;
9903           else
9904             ep->X_add_number -= off;
9905           macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
9906         }
9907       /* For ULH and M_USH_A OR the LSB in.  */
9908       if (!ust || ab)
9909         {
9910           tempreg = !ab ? AT : treg;
9911           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
9912           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
9913         }
9914       break;
9915
9916     default:
9917       /* FIXME: Check if this is one of the itbl macros, since they
9918          are added dynamically.  */
9919       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
9920       break;
9921     }
9922   if (!mips_opts.at && used_at)
9923     as_bad (_("Macro used $at after \".set noat\""));
9924 }
9925
9926 /* Implement macros in mips16 mode.  */
9927
9928 static void
9929 mips16_macro (struct mips_cl_insn *ip)
9930 {
9931   int mask;
9932   int xreg, yreg, zreg, tmp;
9933   expressionS expr1;
9934   int dbl;
9935   const char *s, *s2, *s3;
9936
9937   mask = ip->insn_mo->mask;
9938
9939   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
9940   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
9941   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
9942
9943   expr1.X_op = O_constant;
9944   expr1.X_op_symbol = NULL;
9945   expr1.X_add_symbol = NULL;
9946   expr1.X_add_number = 1;
9947
9948   dbl = 0;
9949
9950   switch (mask)
9951     {
9952     default:
9953       internalError ();
9954
9955     case M_DDIV_3:
9956       dbl = 1;
9957     case M_DIV_3:
9958       s = "mflo";
9959       goto do_div3;
9960     case M_DREM_3:
9961       dbl = 1;
9962     case M_REM_3:
9963       s = "mfhi";
9964     do_div3:
9965       start_noreorder ();
9966       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
9967       expr1.X_add_number = 2;
9968       macro_build (&expr1, "bnez", "x,p", yreg);
9969       macro_build (NULL, "break", "6", 7);
9970
9971       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
9972          since that causes an overflow.  We should do that as well,
9973          but I don't see how to do the comparisons without a temporary
9974          register.  */
9975       end_noreorder ();
9976       macro_build (NULL, s, "x", zreg);
9977       break;
9978
9979     case M_DIVU_3:
9980       s = "divu";
9981       s2 = "mflo";
9982       goto do_divu3;
9983     case M_REMU_3:
9984       s = "divu";
9985       s2 = "mfhi";
9986       goto do_divu3;
9987     case M_DDIVU_3:
9988       s = "ddivu";
9989       s2 = "mflo";
9990       goto do_divu3;
9991     case M_DREMU_3:
9992       s = "ddivu";
9993       s2 = "mfhi";
9994     do_divu3:
9995       start_noreorder ();
9996       macro_build (NULL, s, "0,x,y", xreg, yreg);
9997       expr1.X_add_number = 2;
9998       macro_build (&expr1, "bnez", "x,p", yreg);
9999       macro_build (NULL, "break", "6", 7);
10000       end_noreorder ();
10001       macro_build (NULL, s2, "x", zreg);
10002       break;
10003
10004     case M_DMUL:
10005       dbl = 1;
10006     case M_MUL:
10007       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
10008       macro_build (NULL, "mflo", "x", zreg);
10009       break;
10010
10011     case M_DSUBU_I:
10012       dbl = 1;
10013       goto do_subu;
10014     case M_SUBU_I:
10015     do_subu:
10016       if (imm_expr.X_op != O_constant)
10017         as_bad (_("Unsupported large constant"));
10018       imm_expr.X_add_number = -imm_expr.X_add_number;
10019       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10020       break;
10021
10022     case M_SUBU_I_2:
10023       if (imm_expr.X_op != O_constant)
10024         as_bad (_("Unsupported large constant"));
10025       imm_expr.X_add_number = -imm_expr.X_add_number;
10026       macro_build (&imm_expr, "addiu", "x,k", xreg);
10027       break;
10028
10029     case M_DSUBU_I_2:
10030       if (imm_expr.X_op != O_constant)
10031         as_bad (_("Unsupported large constant"));
10032       imm_expr.X_add_number = -imm_expr.X_add_number;
10033       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10034       break;
10035
10036     case M_BEQ:
10037       s = "cmp";
10038       s2 = "bteqz";
10039       goto do_branch;
10040     case M_BNE:
10041       s = "cmp";
10042       s2 = "btnez";
10043       goto do_branch;
10044     case M_BLT:
10045       s = "slt";
10046       s2 = "btnez";
10047       goto do_branch;
10048     case M_BLTU:
10049       s = "sltu";
10050       s2 = "btnez";
10051       goto do_branch;
10052     case M_BLE:
10053       s = "slt";
10054       s2 = "bteqz";
10055       goto do_reverse_branch;
10056     case M_BLEU:
10057       s = "sltu";
10058       s2 = "bteqz";
10059       goto do_reverse_branch;
10060     case M_BGE:
10061       s = "slt";
10062       s2 = "bteqz";
10063       goto do_branch;
10064     case M_BGEU:
10065       s = "sltu";
10066       s2 = "bteqz";
10067       goto do_branch;
10068     case M_BGT:
10069       s = "slt";
10070       s2 = "btnez";
10071       goto do_reverse_branch;
10072     case M_BGTU:
10073       s = "sltu";
10074       s2 = "btnez";
10075
10076     do_reverse_branch:
10077       tmp = xreg;
10078       xreg = yreg;
10079       yreg = tmp;
10080
10081     do_branch:
10082       macro_build (NULL, s, "x,y", xreg, yreg);
10083       macro_build (&offset_expr, s2, "p");
10084       break;
10085
10086     case M_BEQ_I:
10087       s = "cmpi";
10088       s2 = "bteqz";
10089       s3 = "x,U";
10090       goto do_branch_i;
10091     case M_BNE_I:
10092       s = "cmpi";
10093       s2 = "btnez";
10094       s3 = "x,U";
10095       goto do_branch_i;
10096     case M_BLT_I:
10097       s = "slti";
10098       s2 = "btnez";
10099       s3 = "x,8";
10100       goto do_branch_i;
10101     case M_BLTU_I:
10102       s = "sltiu";
10103       s2 = "btnez";
10104       s3 = "x,8";
10105       goto do_branch_i;
10106     case M_BLE_I:
10107       s = "slti";
10108       s2 = "btnez";
10109       s3 = "x,8";
10110       goto do_addone_branch_i;
10111     case M_BLEU_I:
10112       s = "sltiu";
10113       s2 = "btnez";
10114       s3 = "x,8";
10115       goto do_addone_branch_i;
10116     case M_BGE_I:
10117       s = "slti";
10118       s2 = "bteqz";
10119       s3 = "x,8";
10120       goto do_branch_i;
10121     case M_BGEU_I:
10122       s = "sltiu";
10123       s2 = "bteqz";
10124       s3 = "x,8";
10125       goto do_branch_i;
10126     case M_BGT_I:
10127       s = "slti";
10128       s2 = "bteqz";
10129       s3 = "x,8";
10130       goto do_addone_branch_i;
10131     case M_BGTU_I:
10132       s = "sltiu";
10133       s2 = "bteqz";
10134       s3 = "x,8";
10135
10136     do_addone_branch_i:
10137       if (imm_expr.X_op != O_constant)
10138         as_bad (_("Unsupported large constant"));
10139       ++imm_expr.X_add_number;
10140
10141     do_branch_i:
10142       macro_build (&imm_expr, s, s3, xreg);
10143       macro_build (&offset_expr, s2, "p");
10144       break;
10145
10146     case M_ABS:
10147       expr1.X_add_number = 0;
10148       macro_build (&expr1, "slti", "x,8", yreg);
10149       if (xreg != yreg)
10150         move_register (xreg, yreg);
10151       expr1.X_add_number = 2;
10152       macro_build (&expr1, "bteqz", "p");
10153       macro_build (NULL, "neg", "x,w", xreg, xreg);
10154     }
10155 }
10156
10157 /* For consistency checking, verify that all bits are specified either
10158    by the match/mask part of the instruction definition, or by the
10159    operand list.  */
10160 static int
10161 validate_mips_insn (const struct mips_opcode *opc)
10162 {
10163   const char *p = opc->args;
10164   char c;
10165   unsigned long used_bits = opc->mask;
10166
10167   if ((used_bits & opc->match) != opc->match)
10168     {
10169       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
10170               opc->name, opc->args);
10171       return 0;
10172     }
10173 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
10174   while (*p)
10175     switch (c = *p++)
10176       {
10177       case ',': break;
10178       case '(': break;
10179       case ')': break;
10180       case '+':
10181         switch (c = *p++)
10182           {
10183           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
10184           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
10185           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
10186           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
10187           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10188           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10189           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10190           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
10191                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10192           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10193           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10194           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10195           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10196           case 'I': break;
10197           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
10198           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
10199                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10200           case 'x': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10201           case 'X': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10202           case 'p': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10203           case 'P': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10204           case 'Q': USE_BITS (OP_MASK_SEQI,     OP_SH_SEQI);    break;
10205           case 's': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10206           case 'S': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10207           case 'z': USE_BITS (OP_MASK_RZ,       OP_SH_RZ);      break;
10208           case 'Z': USE_BITS (OP_MASK_FZ,       OP_SH_FZ);      break;
10209           case 'a': USE_BITS (OP_MASK_OFFSET_A, OP_SH_OFFSET_A); break;
10210           case 'b': USE_BITS (OP_MASK_OFFSET_B, OP_SH_OFFSET_B); break;
10211           case 'c': USE_BITS (OP_MASK_OFFSET_C, OP_SH_OFFSET_C); break;
10212
10213           default:
10214             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
10215                     c, opc->name, opc->args);
10216             return 0;
10217           }
10218         break;
10219       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10220       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10221       case 'A': break;
10222       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
10223       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
10224       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10225       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10226       case 'F': break;
10227       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10228       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
10229       case 'I': break;
10230       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
10231       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10232       case 'L': break;
10233       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
10234       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
10235       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
10236       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
10237                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10238       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
10239       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10240       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10241       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10242       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10243       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10244       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10245       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10246       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
10247       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10248       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
10249       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10250       case 'f': break;
10251       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
10252       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10253       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10254       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
10255       case 'l': break;
10256       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10257       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10258       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
10259       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10260       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10261       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10262       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10263       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10264       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10265       case 'x': break;
10266       case 'z': break;
10267       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
10268       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
10269                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10270       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
10271       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
10272       case '[': break;
10273       case ']': break;
10274       case '1': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10275       case '2': USE_BITS (OP_MASK_BP,           OP_SH_BP);      break;
10276       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
10277       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
10278       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
10279       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10280       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
10281       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
10282       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
10283       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
10284       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
10285       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
10286       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
10287       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
10288       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
10289       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
10290       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
10291       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10292       default:
10293         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
10294                 c, opc->name, opc->args);
10295         return 0;
10296       }
10297 #undef USE_BITS
10298   if (used_bits != 0xffffffff)
10299     {
10300       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
10301               ~used_bits & 0xffffffff, opc->name, opc->args);
10302       return 0;
10303     }
10304   return 1;
10305 }
10306
10307 /* For consistency checking, verify that the length implied matches the
10308    major opcode and that all bits are specified either by the match/mask
10309    part of the instruction definition, or by the operand list.  */
10310
10311 static int
10312 validate_micromips_insn (const struct mips_opcode *opc)
10313 {
10314   unsigned long match = opc->match;
10315   unsigned long mask = opc->mask;
10316   const char *p = opc->args;
10317   unsigned long insn_bits;
10318   unsigned long used_bits;
10319   unsigned long major;
10320   unsigned int length;
10321   char e;
10322   char c;
10323
10324   if ((mask & match) != match)
10325     {
10326       as_bad (_("Internal error: bad microMIPS opcode (mask error): %s %s"),
10327               opc->name, opc->args);
10328       return 0;
10329     }
10330   length = micromips_insn_length (opc);
10331   if (length != 2 && length != 4)
10332     {
10333       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
10334                 "%s %s"), length, opc->name, opc->args);
10335       return 0;
10336     }
10337   major = match >> (10 + 8 * (length - 2));
10338   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
10339       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
10340     {
10341       as_bad (_("Internal error: bad microMIPS opcode "
10342                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
10343       return 0;
10344     }
10345
10346   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
10347   insn_bits = 1 << 4 * length;
10348   insn_bits <<= 4 * length;
10349   insn_bits -= 1;
10350   used_bits = mask;
10351 #define USE_BITS(field) \
10352   (used_bits |= MICROMIPSOP_MASK_##field << MICROMIPSOP_SH_##field)
10353   while (*p)
10354     switch (c = *p++)
10355       {
10356       case ',': break;
10357       case '(': break;
10358       case ')': break;
10359       case '+':
10360         e = c;
10361         switch (c = *p++)
10362           {
10363           case 'A': USE_BITS (EXTLSB);  break;
10364           case 'B': USE_BITS (INSMSB);  break;
10365           case 'C': USE_BITS (EXTMSBD); break;
10366           case 'D': USE_BITS (RS);      USE_BITS (SEL); break;
10367           case 'E': USE_BITS (EXTLSB);  break;
10368           case 'F': USE_BITS (INSMSB);  break;
10369           case 'G': USE_BITS (EXTMSBD); break;
10370           case 'H': USE_BITS (EXTMSBD); break;
10371           default:
10372             as_bad (_("Internal error: bad mips opcode "
10373                       "(unknown extension operand type `%c%c'): %s %s"),
10374                     e, c, opc->name, opc->args);
10375             return 0;
10376           }
10377         break;
10378       case 'm':
10379         e = c;
10380         switch (c = *p++)
10381           {
10382           case 'A': USE_BITS (IMMA);    break;
10383           case 'B': USE_BITS (IMMB);    break;
10384           case 'C': USE_BITS (IMMC);    break;
10385           case 'D': USE_BITS (IMMD);    break;
10386           case 'E': USE_BITS (IMME);    break;
10387           case 'F': USE_BITS (IMMF);    break;
10388           case 'G': USE_BITS (IMMG);    break;
10389           case 'H': USE_BITS (IMMH);    break;
10390           case 'I': USE_BITS (IMMI);    break;
10391           case 'J': USE_BITS (IMMJ);    break;
10392           case 'L': USE_BITS (IMML);    break;
10393           case 'M': USE_BITS (IMMM);    break;
10394           case 'N': USE_BITS (IMMN);    break;
10395           case 'O': USE_BITS (IMMO);    break;
10396           case 'P': USE_BITS (IMMP);    break;
10397           case 'Q': USE_BITS (IMMQ);    break;
10398           case 'U': USE_BITS (IMMU);    break;
10399           case 'W': USE_BITS (IMMW);    break;
10400           case 'X': USE_BITS (IMMX);    break;
10401           case 'Y': USE_BITS (IMMY);    break;
10402           case 'Z': break;
10403           case 'a': break;
10404           case 'b': USE_BITS (MB);      break;
10405           case 'c': USE_BITS (MC);      break;
10406           case 'd': USE_BITS (MD);      break;
10407           case 'e': USE_BITS (ME);      break;
10408           case 'f': USE_BITS (MF);      break;
10409           case 'g': USE_BITS (MG);      break;
10410           case 'h': USE_BITS (MH);      break;
10411           case 'i': USE_BITS (MI);      break;
10412           case 'j': USE_BITS (MJ);      break;
10413           case 'l': USE_BITS (ML);      break;
10414           case 'm': USE_BITS (MM);      break;
10415           case 'n': USE_BITS (MN);      break;
10416           case 'p': USE_BITS (MP);      break;
10417           case 'q': USE_BITS (MQ);      break;
10418           case 'r': break;
10419           case 's': break;
10420           case 't': break;
10421           case 'x': break;
10422           case 'y': break;
10423           case 'z': break;
10424           default:
10425             as_bad (_("Internal error: bad mips opcode "
10426                       "(unknown extension operand type `%c%c'): %s %s"),
10427                     e, c, opc->name, opc->args);
10428             return 0;
10429           }
10430         break;
10431       case '.': USE_BITS (OFFSET10);    break;
10432       case '1': USE_BITS (STYPE);       break;
10433       case '<': USE_BITS (SHAMT);       break;
10434       case '>': USE_BITS (SHAMT);       break;
10435       case 'B': USE_BITS (CODE10);      break;
10436       case 'C': USE_BITS (COPZ);        break;
10437       case 'D': USE_BITS (FD);          break;
10438       case 'E': USE_BITS (RT);          break;
10439       case 'G': USE_BITS (RS);          break;
10440       case 'H': USE_BITS (SEL); break;
10441       case 'K': USE_BITS (RS);          break;
10442       case 'M': USE_BITS (CCC);         break;
10443       case 'N': USE_BITS (BCC);         break;
10444       case 'R': USE_BITS (FR);          break;
10445       case 'S': USE_BITS (FS);          break;
10446       case 'T': USE_BITS (FT);          break;
10447       case 'V': USE_BITS (FS);          break;
10448       case 'a': USE_BITS (TARGET);      break;
10449       case 'b': USE_BITS (RS);          break;
10450       case 'c': USE_BITS (CODE);        break;
10451       case 'd': USE_BITS (RD);          break;
10452       case 'h': USE_BITS (PREFX);       break;
10453       case 'i': USE_BITS (IMMEDIATE);   break;
10454       case 'j': USE_BITS (DELTA);       break;
10455       case 'k': USE_BITS (CACHE);       break;
10456       case 'n': USE_BITS (RT);          break;
10457       case 'o': USE_BITS (DELTA);       break;
10458       case 'p': USE_BITS (DELTA);       break;
10459       case 'q': USE_BITS (CODE2);       break;
10460       case 'r': USE_BITS (RS);          break;
10461       case 's': USE_BITS (RS);          break;
10462       case 't': USE_BITS (RT);          break;
10463       case 'u': USE_BITS (IMMEDIATE);   break;
10464       case 'v': USE_BITS (RS);          break;
10465       case 'w': USE_BITS (RT);          break;
10466       case 'y': USE_BITS (RS3);         break;
10467       case 'z': break;
10468       case '|': USE_BITS (TRAP);        break;
10469       case '~': USE_BITS (OFFSET12);    break;
10470       default:
10471         as_bad (_("Internal error: bad microMIPS opcode "
10472                   "(unknown operand type `%c'): %s %s"),
10473                 c, opc->name, opc->args);
10474         return 0;
10475       }
10476 #undef USE_BITS
10477   if (used_bits != insn_bits)
10478     {
10479       if (~used_bits & insn_bits)
10480         as_bad (_("Internal error: bad microMIPS opcode "
10481                   "(bits 0x%lx undefined): %s %s"),
10482                 ~used_bits & insn_bits, opc->name, opc->args);
10483       if (used_bits & ~insn_bits)
10484         as_bad (_("Internal error: bad microMIPS opcode "
10485                   "(bits 0x%lx defined): %s %s"),
10486                 used_bits & ~insn_bits, opc->name, opc->args);
10487       return 0;
10488     }
10489   return 1;
10490 }
10491
10492 /* UDI immediates.  */
10493 struct mips_immed {
10494   char          type;
10495   unsigned int  shift;
10496   unsigned long mask;
10497   const char *  desc;
10498 };
10499
10500 static const struct mips_immed mips_immed[] = {
10501   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
10502   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
10503   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
10504   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
10505   { 0,0,0,0 }
10506 };
10507
10508 /* Check whether an odd floating-point register is allowed.  */
10509 static int
10510 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
10511 {
10512   const char *s = insn->name;
10513
10514   if (insn->pinfo == INSN_MACRO)
10515     /* Let a macro pass, we'll catch it later when it is expanded.  */
10516     return 1;
10517
10518   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa))
10519     {
10520       /* Allow odd registers for single-precision ops.  */
10521       switch (insn->pinfo & (FP_S | FP_D))
10522         {
10523         case FP_S:
10524         case 0:
10525           return 1;     /* both single precision - ok */
10526         case FP_D:
10527           return 0;     /* both double precision - fail */
10528         default:
10529           break;
10530         }
10531
10532       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
10533       s = strchr (insn->name, '.');
10534       if (argnum == 2)
10535         s = s != NULL ? strchr (s + 1, '.') : NULL;
10536       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
10537     } 
10538
10539   /* Single-precision coprocessor loads and moves are OK too.  */
10540   if ((insn->pinfo & FP_S)
10541       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
10542                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
10543     return 1;
10544
10545   return 0;
10546 }
10547
10548 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
10549    taking bits from BIT up.  */
10550 static int
10551 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
10552 {
10553   return (ep->X_op == O_constant
10554           && (ep->X_add_number & ((1 << bit) - 1)) == 0
10555           && ep->X_add_number >= min << bit
10556           && ep->X_add_number < max << bit);
10557 }
10558
10559 /* This routine assembles an instruction into its binary format.  As a
10560    side effect, it sets one of the global variables imm_reloc or
10561    offset_reloc to the type of relocation to do if one of the operands
10562    is an address expression.  */
10563
10564 static void
10565 mips_ip (char *str, struct mips_cl_insn *ip)
10566 {
10567   bfd_boolean wrong_delay_slot_insns = FALSE;
10568   bfd_boolean need_delay_slot_ok = TRUE;
10569   struct mips_opcode *firstinsn = NULL;
10570   const struct mips_opcode *past;
10571   struct hash_control *hash;
10572   char *s;
10573   const char *args;
10574   char c = 0;
10575   struct mips_opcode *insn;
10576   char *argsStart;
10577   unsigned int regno;
10578   unsigned int lastregno;
10579   unsigned int destregno = 0;
10580   unsigned int lastpos = 0;
10581   unsigned int limlo, limhi;
10582   char *s_reset;
10583   offsetT min_range, max_range;
10584   long opend;
10585   char *name;
10586   int argnum;
10587   unsigned int rtype;
10588   char *dot;
10589   long end;
10590
10591   insn_error = NULL;
10592
10593   if (mips_opts.micromips)
10594     {
10595       hash = micromips_op_hash;
10596       past = &micromips_opcodes[bfd_micromips_num_opcodes];
10597     }
10598   else
10599     {
10600       hash = op_hash;
10601       past = &mips_opcodes[NUMOPCODES];
10602     }
10603   forced_insn_length = 0;
10604   insn = NULL;
10605
10606   /* We first try to match an instruction up to a space or to the end.  */
10607   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
10608     continue;
10609
10610   /* Make a copy of the instruction so that we can fiddle with it.  */
10611   name = alloca (end + 1);
10612   memcpy (name, str, end);
10613   name[end] = '\0';
10614
10615   for (;;)
10616     {
10617       insn = (struct mips_opcode *) hash_find (hash, name);
10618
10619       if (insn != NULL || !mips_opts.micromips)
10620         break;
10621       if (forced_insn_length)
10622         break;
10623
10624       /* See if there's an instruction size override suffix,
10625          either `16' or `32', at the end of the mnemonic proper,
10626          that defines the operation, i.e. before the first `.'
10627          character if any.  Strip it and retry.  */
10628       dot = strchr (name, '.');
10629       opend = dot != NULL ? dot - name : end;
10630       if (opend < 3)
10631         break;
10632       if (name[opend - 2] == '1' && name[opend - 1] == '6')
10633         forced_insn_length = 2;
10634       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
10635         forced_insn_length = 4;
10636       else
10637         break;
10638       memcpy (name + opend - 2, name + opend, end - opend + 1);
10639     }
10640   if (insn == NULL)
10641     {
10642       insn_error = _("Unrecognized opcode");
10643       return;
10644     }
10645
10646   /* For microMIPS instructions placed in a fixed-length branch delay slot
10647      we make up to two passes over the relevant fragment of the opcode
10648      table.  First we try instructions that meet the delay slot's length
10649      requirement.  If none matched, then we retry with the remaining ones
10650      and if one matches, then we use it and then issue an appropriate
10651      warning later on.  */
10652   argsStart = s = str + end;
10653   for (;;)
10654     {
10655       bfd_boolean delay_slot_ok;
10656       bfd_boolean size_ok;
10657       bfd_boolean ok;
10658
10659       gas_assert (strcmp (insn->name, name) == 0);
10660
10661       ok = is_opcode_valid (insn);
10662       size_ok = is_size_valid (insn);
10663       delay_slot_ok = is_delay_slot_valid (insn);
10664       if (!delay_slot_ok && !wrong_delay_slot_insns)
10665         {
10666           firstinsn = insn;
10667           wrong_delay_slot_insns = TRUE;
10668         }
10669       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
10670         {
10671           static char buf[256];
10672
10673           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
10674             {
10675               ++insn;
10676               continue;
10677             }
10678           if (wrong_delay_slot_insns && need_delay_slot_ok)
10679             {
10680               gas_assert (firstinsn);
10681               need_delay_slot_ok = FALSE;
10682               past = insn + 1;
10683               insn = firstinsn;
10684               continue;
10685             }
10686
10687           if (insn_error)
10688             return;
10689
10690           if (!ok)
10691             sprintf (buf, _("opcode not supported on this processor: %s (%s)"),
10692                      mips_cpu_info_from_arch (mips_opts.arch)->name,
10693                      mips_cpu_info_from_isa (mips_opts.isa)->name);
10694           else
10695             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
10696                      8 * forced_insn_length);
10697           insn_error = buf;
10698
10699           return;
10700         }
10701
10702       create_insn (ip, insn);
10703       insn_error = NULL;
10704       argnum = 1;
10705       lastregno = 0xffffffff;
10706       for (args = insn->args;; ++args)
10707         {
10708           int is_mdmx;
10709
10710           s += strspn (s, " \t");
10711           is_mdmx = 0;
10712           switch (*args)
10713             {
10714             case '\0':          /* end of args */
10715               if (*s == '\0')
10716                 return;
10717               break;
10718
10719             case '2': /* DSP 2-bit unsigned immediate in bit 11.  */
10720               gas_assert (!mips_opts.micromips);
10721               my_getExpression (&imm_expr, s);
10722               check_absolute_expr (ip, &imm_expr);
10723               if ((unsigned long) imm_expr.X_add_number != 1
10724                   && (unsigned long) imm_expr.X_add_number != 3)
10725                 {
10726                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
10727                           (unsigned long) imm_expr.X_add_number);
10728                 }
10729               INSERT_OPERAND (0, BP, *ip, imm_expr.X_add_number);
10730               imm_expr.X_op = O_absent;
10731               s = expr_end;
10732               continue;
10733
10734             case '3': /* DSP 3-bit unsigned immediate in bit 21.  */
10735               gas_assert (!mips_opts.micromips);
10736               my_getExpression (&imm_expr, s);
10737               check_absolute_expr (ip, &imm_expr);
10738               if (imm_expr.X_add_number & ~OP_MASK_SA3)
10739                 {
10740                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10741                           OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
10742                 }
10743               INSERT_OPERAND (0, SA3, *ip, imm_expr.X_add_number);
10744               imm_expr.X_op = O_absent;
10745               s = expr_end;
10746               continue;
10747
10748             case '4': /* DSP 4-bit unsigned immediate in bit 21.  */
10749               gas_assert (!mips_opts.micromips);
10750               my_getExpression (&imm_expr, s);
10751               check_absolute_expr (ip, &imm_expr);
10752               if (imm_expr.X_add_number & ~OP_MASK_SA4)
10753                 {
10754                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10755                           OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
10756                 }
10757               INSERT_OPERAND (0, SA4, *ip, imm_expr.X_add_number);
10758               imm_expr.X_op = O_absent;
10759               s = expr_end;
10760               continue;
10761
10762             case '5': /* DSP 8-bit unsigned immediate in bit 16.  */
10763               gas_assert (!mips_opts.micromips);
10764               my_getExpression (&imm_expr, s);
10765               check_absolute_expr (ip, &imm_expr);
10766               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
10767                 {
10768                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10769                           OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
10770                 }
10771               INSERT_OPERAND (0, IMM8, *ip, imm_expr.X_add_number);
10772               imm_expr.X_op = O_absent;
10773               s = expr_end;
10774               continue;
10775
10776             case '6': /* DSP 5-bit unsigned immediate in bit 21.  */
10777               gas_assert (!mips_opts.micromips);
10778               my_getExpression (&imm_expr, s);
10779               check_absolute_expr (ip, &imm_expr);
10780               if (imm_expr.X_add_number & ~OP_MASK_RS)
10781                 {
10782                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10783                           OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
10784                 }
10785               INSERT_OPERAND (0, RS, *ip, imm_expr.X_add_number);
10786               imm_expr.X_op = O_absent;
10787               s = expr_end;
10788               continue;
10789
10790             case '7': /* Four DSP accumulators in bits 11,12.  */
10791               gas_assert (!mips_opts.micromips);
10792               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10793                   s[3] >= '0' && s[3] <= '3')
10794                 {
10795                   regno = s[3] - '0';
10796                   s += 4;
10797                   INSERT_OPERAND (0, DSPACC, *ip, regno);
10798                   continue;
10799                 }
10800               else
10801                 as_bad (_("Invalid dsp acc register"));
10802               break;
10803
10804             case '8': /* DSP 6-bit unsigned immediate in bit 11.  */
10805               gas_assert (!mips_opts.micromips);
10806               my_getExpression (&imm_expr, s);
10807               check_absolute_expr (ip, &imm_expr);
10808               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
10809                 {
10810                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10811                           OP_MASK_WRDSP,
10812                           (unsigned long) imm_expr.X_add_number);
10813                 }
10814               INSERT_OPERAND (0, WRDSP, *ip, imm_expr.X_add_number);
10815               imm_expr.X_op = O_absent;
10816               s = expr_end;
10817               continue;
10818
10819             case '9': /* Four DSP accumulators in bits 21,22.  */
10820               gas_assert (!mips_opts.micromips);
10821               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10822                   s[3] >= '0' && s[3] <= '3')
10823                 {
10824                   regno = s[3] - '0';
10825                   s += 4;
10826                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
10827                   continue;
10828                 }
10829               else
10830                 as_bad (_("Invalid dsp acc register"));
10831               break;
10832
10833             case '0': /* DSP 6-bit signed immediate in bit 20.  */
10834               gas_assert (!mips_opts.micromips);
10835               my_getExpression (&imm_expr, s);
10836               check_absolute_expr (ip, &imm_expr);
10837               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
10838               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
10839               if (imm_expr.X_add_number < min_range ||
10840                   imm_expr.X_add_number > max_range)
10841                 {
10842                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10843                           (long) min_range, (long) max_range,
10844                           (long) imm_expr.X_add_number);
10845                 }
10846               INSERT_OPERAND (0, DSPSFT, *ip, imm_expr.X_add_number);
10847               imm_expr.X_op = O_absent;
10848               s = expr_end;
10849               continue;
10850
10851             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
10852               gas_assert (!mips_opts.micromips);
10853               my_getExpression (&imm_expr, s);
10854               check_absolute_expr (ip, &imm_expr);
10855               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
10856                 {
10857                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10858                           OP_MASK_RDDSP,
10859                           (unsigned long) imm_expr.X_add_number);
10860                 }
10861               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
10862               imm_expr.X_op = O_absent;
10863               s = expr_end;
10864               continue;
10865
10866             case ':': /* DSP 7-bit signed immediate in bit 19.  */
10867               gas_assert (!mips_opts.micromips);
10868               my_getExpression (&imm_expr, s);
10869               check_absolute_expr (ip, &imm_expr);
10870               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
10871               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
10872               if (imm_expr.X_add_number < min_range ||
10873                   imm_expr.X_add_number > max_range)
10874                 {
10875                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10876                           (long) min_range, (long) max_range,
10877                           (long) imm_expr.X_add_number);
10878                 }
10879               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
10880               imm_expr.X_op = O_absent;
10881               s = expr_end;
10882               continue;
10883
10884             case '@': /* DSP 10-bit signed immediate in bit 16.  */
10885               gas_assert (!mips_opts.micromips);
10886               my_getExpression (&imm_expr, s);
10887               check_absolute_expr (ip, &imm_expr);
10888               min_range = -((OP_MASK_IMM10 + 1) >> 1);
10889               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
10890               if (imm_expr.X_add_number < min_range ||
10891                   imm_expr.X_add_number > max_range)
10892                 {
10893                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10894                           (long) min_range, (long) max_range,
10895                           (long) imm_expr.X_add_number);
10896                 }
10897               INSERT_OPERAND (0, IMM10, *ip, imm_expr.X_add_number);
10898               imm_expr.X_op = O_absent;
10899               s = expr_end;
10900               continue;
10901
10902             case '!': /* MT usermode flag bit.  */
10903               gas_assert (!mips_opts.micromips);
10904               my_getExpression (&imm_expr, s);
10905               check_absolute_expr (ip, &imm_expr);
10906               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
10907                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
10908                         (unsigned long) imm_expr.X_add_number);
10909               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
10910               imm_expr.X_op = O_absent;
10911               s = expr_end;
10912               continue;
10913
10914             case '$': /* MT load high flag bit.  */
10915               gas_assert (!mips_opts.micromips);
10916               my_getExpression (&imm_expr, s);
10917               check_absolute_expr (ip, &imm_expr);
10918               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
10919                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
10920                         (unsigned long) imm_expr.X_add_number);
10921               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
10922               imm_expr.X_op = O_absent;
10923               s = expr_end;
10924               continue;
10925
10926             case '*': /* Four DSP accumulators in bits 18,19.  */
10927               gas_assert (!mips_opts.micromips);
10928               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10929                   s[3] >= '0' && s[3] <= '3')
10930                 {
10931                   regno = s[3] - '0';
10932                   s += 4;
10933                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
10934                   continue;
10935                 }
10936               else
10937                 as_bad (_("Invalid dsp/smartmips acc register"));
10938               break;
10939
10940             case '&': /* Four DSP accumulators in bits 13,14.  */
10941               gas_assert (!mips_opts.micromips);
10942               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10943                   s[3] >= '0' && s[3] <= '3')
10944                 {
10945                   regno = s[3] - '0';
10946                   s += 4;
10947                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
10948                   continue;
10949                 }
10950               else
10951                 as_bad (_("Invalid dsp/smartmips acc register"));
10952               break;
10953
10954             case ',':
10955               ++argnum;
10956               if (*s++ == *args)
10957                 continue;
10958               s--;
10959               switch (*++args)
10960                 {
10961                 case 'r':
10962                 case 'v':
10963                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
10964                   continue;
10965
10966                 case 'w':
10967                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
10968                   continue;
10969
10970                 case 'W':
10971                   gas_assert (!mips_opts.micromips);
10972                   INSERT_OPERAND (0, FT, *ip, lastregno);
10973                   continue;
10974
10975                 case 'V':
10976                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
10977                   continue;
10978                 }
10979               break;
10980
10981             case '(':
10982               /* Handle optional base register.
10983                  Either the base register is omitted or
10984                  we must have a left paren.  */
10985               /* This is dependent on the next operand specifier
10986                  is a base register specification.  */
10987               gas_assert (args[1] == 'b'
10988                           || (mips_opts.micromips
10989                               && args[1] == 'm'
10990                               && (args[2] == 'l' || args[2] == 'n'
10991                                   || args[2] == 's' || args[2] == 'a')));
10992               if (*s == '\0' && args[1] == 'b')
10993                 return;
10994               /* Fall through.  */
10995
10996             case ')':           /* These must match exactly.  */
10997               if (*s++ == *args)
10998                 continue;
10999               break;
11000
11001             case '[':           /* These must match exactly.  */
11002             case ']':
11003               gas_assert (!mips_opts.micromips);
11004               if (*s++ == *args)
11005                 continue;
11006               break;
11007
11008             case '+':           /* Opcode extension character.  */
11009               switch (*++args)
11010                 {
11011                 case '1':       /* UDI immediates.  */
11012                 case '2':
11013                 case '3':
11014                 case '4':
11015                   gas_assert (!mips_opts.micromips);
11016                   {
11017                     const struct mips_immed *imm = mips_immed;
11018
11019                     while (imm->type && imm->type != *args)
11020                       ++imm;
11021                     if (! imm->type)
11022                       internalError ();
11023                     my_getExpression (&imm_expr, s);
11024                     check_absolute_expr (ip, &imm_expr);
11025                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11026                       {
11027                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11028                                  imm->desc ? imm->desc : ip->insn_mo->name,
11029                                  (unsigned long) imm_expr.X_add_number,
11030                                  (unsigned long) imm_expr.X_add_number);
11031                         imm_expr.X_add_number &= imm->mask;
11032                       }
11033                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11034                                         << imm->shift);
11035                     imm_expr.X_op = O_absent;
11036                     s = expr_end;
11037                   }
11038                   continue;
11039
11040                 case 'A':               /* ins/ext position, becomes LSB.  */
11041                   limlo = 0;
11042                   limhi = 31;
11043                   goto do_lsb;
11044                 case 'E':
11045                   limlo = 32;
11046                   limhi = 63;
11047                   goto do_lsb;
11048                 do_lsb:
11049                   my_getExpression (&imm_expr, s);
11050                   check_absolute_expr (ip, &imm_expr);
11051                   if ((unsigned long) imm_expr.X_add_number < limlo
11052                       || (unsigned long) imm_expr.X_add_number > limhi)
11053                     {
11054                       as_bad (_("Improper position (%lu)"),
11055                               (unsigned long) imm_expr.X_add_number);
11056                       imm_expr.X_add_number = limlo;
11057                     }
11058                   lastpos = imm_expr.X_add_number;
11059                   INSERT_OPERAND (mips_opts.micromips,
11060                                   EXTLSB, *ip, imm_expr.X_add_number);
11061                   imm_expr.X_op = O_absent;
11062                   s = expr_end;
11063                   continue;
11064
11065                 case 'B':               /* ins size, becomes MSB.  */
11066                   limlo = 1;
11067                   limhi = 32;
11068                   goto do_msb;
11069                 case 'F':
11070                   limlo = 33;
11071                   limhi = 64;
11072                   goto do_msb;
11073                 do_msb:
11074                   my_getExpression (&imm_expr, s);
11075                   check_absolute_expr (ip, &imm_expr);
11076                   /* Check for negative input so that small negative numbers
11077                      will not succeed incorrectly.  The checks against
11078                      (pos+size) transitively check "size" itself,
11079                      assuming that "pos" is reasonable.  */
11080                   if ((long) imm_expr.X_add_number < 0
11081                       || ((unsigned long) imm_expr.X_add_number
11082                           + lastpos) < limlo
11083                       || ((unsigned long) imm_expr.X_add_number
11084                           + lastpos) > limhi)
11085                     {
11086                       as_bad (_("Improper insert size (%lu, position %lu)"),
11087                               (unsigned long) imm_expr.X_add_number,
11088                               (unsigned long) lastpos);
11089                       imm_expr.X_add_number = limlo - lastpos;
11090                     }
11091                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11092                                   lastpos + imm_expr.X_add_number - 1);
11093                   imm_expr.X_op = O_absent;
11094                   s = expr_end;
11095                   continue;
11096
11097                 case 'C':               /* ext size, becomes MSBD.  */
11098                   limlo = 1;
11099                   limhi = 32;
11100                   goto do_msbd;
11101                 case 'G':
11102                   limlo = 33;
11103                   limhi = 64;
11104                   goto do_msbd;
11105                 case 'H':
11106                   limlo = 33;
11107                   limhi = 64;
11108                   goto do_msbd;
11109                 do_msbd:
11110                   my_getExpression (&imm_expr, s);
11111                   check_absolute_expr (ip, &imm_expr);
11112                   /* Check for negative input so that small negative numbers
11113                      will not succeed incorrectly.  The checks against
11114                      (pos+size) transitively check "size" itself,
11115                      assuming that "pos" is reasonable.  */
11116                   if ((long) imm_expr.X_add_number < 0
11117                       || ((unsigned long) imm_expr.X_add_number
11118                           + lastpos) < limlo
11119                       || ((unsigned long) imm_expr.X_add_number
11120                           + lastpos) > limhi)
11121                     {
11122                       as_bad (_("Improper extract size (%lu, position %lu)"),
11123                               (unsigned long) imm_expr.X_add_number,
11124                               (unsigned long) lastpos);
11125                       imm_expr.X_add_number = limlo - lastpos;
11126                     }
11127                   INSERT_OPERAND (mips_opts.micromips,
11128                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11129                   imm_expr.X_op = O_absent;
11130                   s = expr_end;
11131                   continue;
11132
11133                 case 'D':
11134                   /* +D is for disassembly only; never match.  */
11135                   break;
11136
11137                 case 'I':
11138                   /* "+I" is like "I", except that imm2_expr is used.  */
11139                   my_getExpression (&imm2_expr, s);
11140                   if (imm2_expr.X_op != O_big
11141                       && imm2_expr.X_op != O_constant)
11142                   insn_error = _("absolute expression required");
11143                   if (HAVE_32BIT_GPRS)
11144                     normalize_constant_expr (&imm2_expr);
11145                   s = expr_end;
11146                   continue;
11147
11148                 case 'T': /* Coprocessor register.  */
11149                   gas_assert (!mips_opts.micromips);
11150                   /* +T is for disassembly only; never match.  */
11151                   break;
11152
11153                 case 't': /* Coprocessor register number.  */
11154                   gas_assert (!mips_opts.micromips);
11155                   if (s[0] == '$' && ISDIGIT (s[1]))
11156                     {
11157                       ++s;
11158                       regno = 0;
11159                       do
11160                         {
11161                           regno *= 10;
11162                           regno += *s - '0';
11163                           ++s;
11164                         }
11165                       while (ISDIGIT (*s));
11166                       if (regno > 31)
11167                         as_bad (_("Invalid register number (%d)"), regno);
11168                       else
11169                         {
11170                           INSERT_OPERAND (0, RT, *ip, regno);
11171                           continue;
11172                         }
11173                     }
11174                   else
11175                     as_bad (_("Invalid coprocessor 0 register number"));
11176                   break;
11177
11178                 case 'x':
11179                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11180                      is not in the valid range.  */
11181                   gas_assert (!mips_opts.micromips);
11182                   my_getExpression (&imm_expr, s);
11183                   check_absolute_expr (ip, &imm_expr);
11184                   if ((unsigned) imm_expr.X_add_number > 31)
11185                     {
11186                       as_bad (_("Improper bit index (%lu)"),
11187                               (unsigned long) imm_expr.X_add_number);
11188                       imm_expr.X_add_number = 0;
11189                     }
11190                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11191                   imm_expr.X_op = O_absent;
11192                   s = expr_end;
11193                   continue;
11194
11195                 case 'X':
11196                   /* bbit[01] bit index when bbit is used but we generate
11197                      bbit[01]32 because the index is over 32.  Move to the
11198                      next candidate if index is not in the valid range.  */
11199                   gas_assert (!mips_opts.micromips);
11200                   my_getExpression (&imm_expr, s);
11201                   check_absolute_expr (ip, &imm_expr);
11202                   if ((unsigned) imm_expr.X_add_number < 32
11203                       || (unsigned) imm_expr.X_add_number > 63)
11204                     break;
11205                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11206                   imm_expr.X_op = O_absent;
11207                   s = expr_end;
11208                   continue;
11209
11210                 case 'p':
11211                   /* cins, cins32, exts and exts32 position field.  Give error
11212                      if it's not in the valid range.  */
11213                   gas_assert (!mips_opts.micromips);
11214                   my_getExpression (&imm_expr, s);
11215                   check_absolute_expr (ip, &imm_expr);
11216                   if ((unsigned) imm_expr.X_add_number > 31)
11217                     {
11218                       as_bad (_("Improper position (%lu)"),
11219                               (unsigned long) imm_expr.X_add_number);
11220                       imm_expr.X_add_number = 0;
11221                     }
11222                   /* Make the pos explicit to simplify +S.  */
11223                   lastpos = imm_expr.X_add_number + 32;
11224                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
11225                   imm_expr.X_op = O_absent;
11226                   s = expr_end;
11227                   continue;
11228
11229                 case 'P':
11230                   /* cins, cins32, exts and exts32 position field.  Move to
11231                      the next candidate if it's not in the valid range.  */
11232                   gas_assert (!mips_opts.micromips);
11233                   my_getExpression (&imm_expr, s);
11234                   check_absolute_expr (ip, &imm_expr);
11235                   if ((unsigned) imm_expr.X_add_number < 32
11236                       || (unsigned) imm_expr.X_add_number > 63)
11237                     break;
11238                   lastpos = imm_expr.X_add_number;
11239                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
11240                   imm_expr.X_op = O_absent;
11241                   s = expr_end;
11242                   continue;
11243
11244                 case 's':
11245                   /* cins and exts length-minus-one field.  */
11246                   gas_assert (!mips_opts.micromips);
11247                   my_getExpression (&imm_expr, s);
11248                   check_absolute_expr (ip, &imm_expr);
11249                   if ((unsigned long) imm_expr.X_add_number > 31)
11250                     {
11251                       as_bad (_("Improper size (%lu)"),
11252                               (unsigned long) imm_expr.X_add_number);
11253                       imm_expr.X_add_number = 0;
11254                     }
11255                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11256                   imm_expr.X_op = O_absent;
11257                   s = expr_end;
11258                   continue;
11259
11260                 case 'S':
11261                   /* cins32/exts32 and cins/exts aliasing cint32/exts32
11262                      length-minus-one field.  */
11263                   gas_assert (!mips_opts.micromips);
11264                   my_getExpression (&imm_expr, s);
11265                   check_absolute_expr (ip, &imm_expr);
11266                   if ((long) imm_expr.X_add_number < 0
11267                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
11268                     {
11269                       as_bad (_("Improper size (%lu)"),
11270                               (unsigned long) imm_expr.X_add_number);
11271                       imm_expr.X_add_number = 0;
11272                     }
11273                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11274                   imm_expr.X_op = O_absent;
11275                   s = expr_end;
11276                   continue;
11277
11278                 case 'Q':
11279                   /* seqi/snei immediate field.  */
11280                   gas_assert (!mips_opts.micromips);
11281                   my_getExpression (&imm_expr, s);
11282                   check_absolute_expr (ip, &imm_expr);
11283                   if ((long) imm_expr.X_add_number < -512
11284                       || (long) imm_expr.X_add_number >= 512)
11285                     {
11286                       as_bad (_("Improper immediate (%ld)"),
11287                                (long) imm_expr.X_add_number);
11288                       imm_expr.X_add_number = 0;
11289                     }
11290                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
11291                   imm_expr.X_op = O_absent;
11292                   s = expr_end;
11293                   continue;
11294
11295                 case 'a': /* 8-bit signed offset in bit 6 */
11296                   gas_assert (!mips_opts.micromips);
11297                   my_getExpression (&imm_expr, s);
11298                   check_absolute_expr (ip, &imm_expr);
11299                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
11300                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
11301                   if (imm_expr.X_add_number < min_range
11302                       || imm_expr.X_add_number > max_range)
11303                     {
11304                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11305                               (long) min_range, (long) max_range,
11306                               (long) imm_expr.X_add_number);
11307                     }
11308                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
11309                   imm_expr.X_op = O_absent;
11310                   s = expr_end;
11311                   continue;
11312
11313                 case 'b': /* 8-bit signed offset in bit 3 */
11314                   gas_assert (!mips_opts.micromips);
11315                   my_getExpression (&imm_expr, s);
11316                   check_absolute_expr (ip, &imm_expr);
11317                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
11318                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
11319                   if (imm_expr.X_add_number < min_range
11320                       || imm_expr.X_add_number > max_range)
11321                     {
11322                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11323                               (long) min_range, (long) max_range,
11324                               (long) imm_expr.X_add_number);
11325                     }
11326                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
11327                   imm_expr.X_op = O_absent;
11328                   s = expr_end;
11329                   continue;
11330
11331                 case 'c': /* 9-bit signed offset in bit 6 */
11332                   gas_assert (!mips_opts.micromips);
11333                   my_getExpression (&imm_expr, s);
11334                   check_absolute_expr (ip, &imm_expr);
11335                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
11336                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
11337                   /* We check the offset range before adjusted.  */
11338                   min_range <<= 4;
11339                   max_range <<= 4;
11340                   if (imm_expr.X_add_number < min_range
11341                       || imm_expr.X_add_number > max_range)
11342                     {
11343                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11344                               (long) min_range, (long) max_range,
11345                               (long) imm_expr.X_add_number);
11346                     }
11347                   if (imm_expr.X_add_number & 0xf)
11348                     {
11349                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
11350                               (long) imm_expr.X_add_number);
11351                     }
11352                   /* Right shift 4 bits to adjust the offset operand.  */
11353                   INSERT_OPERAND (0, OFFSET_C, *ip,
11354                                   imm_expr.X_add_number >> 4);
11355                   imm_expr.X_op = O_absent;
11356                   s = expr_end;
11357                   continue;
11358
11359                 case 'z':
11360                   gas_assert (!mips_opts.micromips);
11361                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
11362                     break;
11363                   if (regno == AT && mips_opts.at)
11364                     {
11365                       if (mips_opts.at == ATREG)
11366                         as_warn (_("used $at without \".set noat\""));
11367                       else
11368                         as_warn (_("used $%u with \".set at=$%u\""),
11369                                  regno, mips_opts.at);
11370                     }
11371                   INSERT_OPERAND (0, RZ, *ip, regno);
11372                   continue;
11373
11374                 case 'Z':
11375                   gas_assert (!mips_opts.micromips);
11376                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
11377                     break;
11378                   INSERT_OPERAND (0, FZ, *ip, regno);
11379                   continue;
11380
11381                 default:
11382                   as_bad (_("Internal error: bad %s opcode "
11383                             "(unknown extension operand type `+%c'): %s %s"),
11384                           mips_opts.micromips ? "microMIPS" : "MIPS",
11385                           *args, insn->name, insn->args);
11386                   /* Further processing is fruitless.  */
11387                   return;
11388                 }
11389               break;
11390
11391             case '.':           /* 10-bit offset.  */
11392             case '~':           /* 12-bit offset.  */
11393               gas_assert (mips_opts.micromips);
11394               {
11395                 int shift = *args == '.' ? 9 : 11;
11396                 size_t i;
11397
11398                 /* Check whether there is only a single bracketed expression
11399                    left.  If so, it must be the base register and the
11400                    constant must be zero.  */
11401                 if (*s == '(' && strchr (s + 1, '(') == 0)
11402                   continue;
11403
11404                 /* If this value won't fit into the offset, then go find
11405                    a macro that will generate a 16- or 32-bit offset code
11406                    pattern.  */
11407                 i = my_getSmallExpression (&imm_expr, imm_reloc, s);
11408                 if ((i == 0 && (imm_expr.X_op != O_constant
11409                                 || imm_expr.X_add_number >= 1 << shift
11410                                 || imm_expr.X_add_number < -1 << shift))
11411                     || i > 0)
11412                   {
11413                     imm_expr.X_op = O_absent;
11414                     break;
11415                   }
11416                 if (shift == 9)
11417                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
11418                 else
11419                   INSERT_OPERAND (1, OFFSET12, *ip, imm_expr.X_add_number);
11420                 imm_expr.X_op = O_absent;
11421                 s = expr_end;
11422               }
11423               continue;
11424
11425             case '<':           /* must be at least one digit */
11426               /*
11427                * According to the manual, if the shift amount is greater
11428                * than 31 or less than 0, then the shift amount should be
11429                * mod 32.  In reality the mips assembler issues an error.
11430                * We issue a warning and mask out all but the low 5 bits.
11431                */
11432               my_getExpression (&imm_expr, s);
11433               check_absolute_expr (ip, &imm_expr);
11434               if ((unsigned long) imm_expr.X_add_number > 31)
11435                 as_warn (_("Improper shift amount (%lu)"),
11436                          (unsigned long) imm_expr.X_add_number);
11437               INSERT_OPERAND (mips_opts.micromips,
11438                               SHAMT, *ip, imm_expr.X_add_number);
11439               imm_expr.X_op = O_absent;
11440               s = expr_end;
11441               continue;
11442
11443             case '>':           /* shift amount minus 32 */
11444               my_getExpression (&imm_expr, s);
11445               check_absolute_expr (ip, &imm_expr);
11446               if ((unsigned long) imm_expr.X_add_number < 32
11447                   || (unsigned long) imm_expr.X_add_number > 63)
11448                 break;
11449               INSERT_OPERAND (mips_opts.micromips,
11450                               SHAMT, *ip, imm_expr.X_add_number - 32);
11451               imm_expr.X_op = O_absent;
11452               s = expr_end;
11453               continue;
11454
11455             case 'k':           /* CACHE code.  */
11456             case 'h':           /* PREFX code.  */
11457             case '1':           /* SYNC type.  */
11458               my_getExpression (&imm_expr, s);
11459               check_absolute_expr (ip, &imm_expr);
11460               if ((unsigned long) imm_expr.X_add_number > 31)
11461                 as_warn (_("Invalid value for `%s' (%lu)"),
11462                          ip->insn_mo->name,
11463                          (unsigned long) imm_expr.X_add_number);
11464               switch (*args)
11465                 {
11466                 case 'k':
11467                   if (mips_fix_cn63xxp1
11468                       && !mips_opts.micromips
11469                       && strcmp ("pref", insn->name) == 0)
11470                     switch (imm_expr.X_add_number)
11471                       {
11472                       case 5:
11473                       case 25:
11474                       case 26:
11475                       case 27:
11476                       case 28:
11477                       case 29:
11478                       case 30:
11479                       case 31:  /* These are ok.  */
11480                         break;
11481
11482                       default:  /* The rest must be changed to 28.  */
11483                         imm_expr.X_add_number = 28;
11484                         break;
11485                       }
11486                   INSERT_OPERAND (mips_opts.micromips,
11487                                   CACHE, *ip, imm_expr.X_add_number);
11488                   break;
11489                 case 'h':
11490                   INSERT_OPERAND (mips_opts.micromips,
11491                                   PREFX, *ip, imm_expr.X_add_number);
11492                   break;
11493                 case '1':
11494                   INSERT_OPERAND (mips_opts.micromips,
11495                                   STYPE, *ip, imm_expr.X_add_number);
11496                   break;
11497                 }
11498               imm_expr.X_op = O_absent;
11499               s = expr_end;
11500               continue;
11501
11502             case 'c':           /* BREAK code.  */
11503               {
11504                 unsigned long mask = (mips_opts.micromips
11505                                       ? MICROMIPSOP_MASK_CODE
11506                                       : OP_MASK_CODE);
11507
11508                 my_getExpression (&imm_expr, s);
11509                 check_absolute_expr (ip, &imm_expr);
11510                 if ((unsigned long) imm_expr.X_add_number > mask)
11511                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11512                            ip->insn_mo->name,
11513                            mask, (unsigned long) imm_expr.X_add_number);
11514                 INSERT_OPERAND (mips_opts.micromips,
11515                                 CODE, *ip, imm_expr.X_add_number);
11516                 imm_expr.X_op = O_absent;
11517                 s = expr_end;
11518               }
11519               continue;
11520
11521             case 'q':           /* Lower BREAK code.  */
11522               {
11523                 unsigned long mask = (mips_opts.micromips
11524                                       ? MICROMIPSOP_MASK_CODE2
11525                                       : OP_MASK_CODE2);
11526
11527                 my_getExpression (&imm_expr, s);
11528                 check_absolute_expr (ip, &imm_expr);
11529                 if ((unsigned long) imm_expr.X_add_number > mask)
11530                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
11531                            ip->insn_mo->name,
11532                            mask, (unsigned long) imm_expr.X_add_number);
11533                 INSERT_OPERAND (mips_opts.micromips,
11534                                 CODE2, *ip, imm_expr.X_add_number);
11535                 imm_expr.X_op = O_absent;
11536                 s = expr_end;
11537               }
11538               continue;
11539
11540             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
11541               {
11542                 unsigned long mask = (mips_opts.micromips
11543                                       ? MICROMIPSOP_MASK_CODE10
11544                                       : OP_MASK_CODE20);
11545
11546                 my_getExpression (&imm_expr, s);
11547                 check_absolute_expr (ip, &imm_expr);
11548                 if ((unsigned long) imm_expr.X_add_number > mask)
11549                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11550                            ip->insn_mo->name,
11551                            mask, (unsigned long) imm_expr.X_add_number);
11552                 if (mips_opts.micromips)
11553                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
11554                 else
11555                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
11556                 imm_expr.X_op = O_absent;
11557                 s = expr_end;
11558               }
11559               continue;
11560
11561             case 'C':           /* 25- or 23-bit coprocessor code.  */
11562               {
11563                 unsigned long mask = (mips_opts.micromips
11564                                       ? MICROMIPSOP_MASK_COPZ
11565                                       : OP_MASK_COPZ);
11566
11567                 my_getExpression (&imm_expr, s);
11568                 check_absolute_expr (ip, &imm_expr);
11569                 if ((unsigned long) imm_expr.X_add_number > mask)
11570                   as_warn (_("Coproccesor code > %u bits (%lu)"),
11571                            mips_opts.micromips ? 23U : 25U,
11572                            (unsigned long) imm_expr.X_add_number);
11573                 INSERT_OPERAND (mips_opts.micromips,
11574                                 COPZ, *ip, imm_expr.X_add_number);
11575                 imm_expr.X_op = O_absent;
11576                 s = expr_end;
11577               }
11578               continue;
11579
11580             case 'J':           /* 19-bit WAIT code.  */
11581               gas_assert (!mips_opts.micromips);
11582               my_getExpression (&imm_expr, s);
11583               check_absolute_expr (ip, &imm_expr);
11584               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
11585                 {
11586                   as_warn (_("Illegal 19-bit code (%lu)"),
11587                            (unsigned long) imm_expr.X_add_number);
11588                   imm_expr.X_add_number &= OP_MASK_CODE19;
11589                 }
11590               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
11591               imm_expr.X_op = O_absent;
11592               s = expr_end;
11593               continue;
11594
11595             case 'P':           /* Performance register.  */
11596               gas_assert (!mips_opts.micromips);
11597               my_getExpression (&imm_expr, s);
11598               check_absolute_expr (ip, &imm_expr);
11599               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
11600                 as_warn (_("Invalid performance register (%lu)"),
11601                          (unsigned long) imm_expr.X_add_number);
11602               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
11603               imm_expr.X_op = O_absent;
11604               s = expr_end;
11605               continue;
11606
11607             case 'G':           /* Coprocessor destination register.  */
11608               {
11609                 unsigned long opcode = ip->insn_opcode;
11610                 unsigned long mask;
11611                 unsigned int types;
11612                 int cop0;
11613
11614                 if (mips_opts.micromips)
11615                   {
11616                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
11617                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
11618                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
11619                     opcode &= mask;
11620                     switch (opcode)
11621                       {
11622                       case 0x000000fc:                          /* mfc0  */
11623                       case 0x000002fc:                          /* mtc0  */
11624                       case 0x580000fc:                          /* dmfc0 */
11625                       case 0x580002fc:                          /* dmtc0 */
11626                         cop0 = 1;
11627                         break;
11628                       default:
11629                         cop0 = 0;
11630                         break;
11631                       }
11632                   }
11633                 else
11634                   {
11635                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
11636                     cop0 = opcode == OP_OP_COP0;
11637                   }
11638                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
11639                 ok = reg_lookup (&s, types, &regno);
11640                 if (mips_opts.micromips)
11641                   INSERT_OPERAND (1, RS, *ip, regno);
11642                 else
11643                   INSERT_OPERAND (0, RD, *ip, regno);
11644                 if (ok)
11645                   {
11646                     lastregno = regno;
11647                     continue;
11648                   }
11649               }
11650               break;
11651
11652             case 'y':           /* ALNV.PS source register.  */
11653               gas_assert (mips_opts.micromips);
11654               goto do_reg;
11655             case 'x':           /* Ignore register name.  */
11656             case 'U':           /* Destination register (CLO/CLZ).  */
11657             case 'g':           /* Coprocessor destination register.  */
11658               gas_assert (!mips_opts.micromips);
11659             case 'b':           /* Base register.  */
11660             case 'd':           /* Destination register.  */
11661             case 's':           /* Source register.  */
11662             case 't':           /* Target register.  */
11663             case 'r':           /* Both target and source.  */
11664             case 'v':           /* Both dest and source.  */
11665             case 'w':           /* Both dest and target.  */
11666             case 'E':           /* Coprocessor target register.  */
11667             case 'K':           /* RDHWR destination register.  */
11668             case 'z':           /* Must be zero register.  */
11669             do_reg:
11670               s_reset = s;
11671               if (*args == 'E' || *args == 'K')
11672                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
11673               else
11674                 {
11675                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
11676                   if (regno == AT && mips_opts.at)
11677                     {
11678                       if (mips_opts.at == ATREG)
11679                         as_warn (_("Used $at without \".set noat\""));
11680                       else
11681                         as_warn (_("Used $%u with \".set at=$%u\""),
11682                                  regno, mips_opts.at);
11683                     }
11684                 }
11685               if (ok)
11686                 {
11687                   c = *args;
11688                   if (*s == ' ')
11689                     ++s;
11690                   if (args[1] != *s)
11691                     {
11692                       if (c == 'r' || c == 'v' || c == 'w')
11693                         {
11694                           regno = lastregno;
11695                           s = s_reset;
11696                           ++args;
11697                         }
11698                     }
11699                   /* 'z' only matches $0.  */
11700                   if (c == 'z' && regno != 0)
11701                     break;
11702
11703                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
11704                     {
11705                       if (regno == lastregno)
11706                         {
11707                           insn_error
11708                             = _("Source and destination must be different");
11709                           continue;
11710                         }
11711                       if (regno == 31 && lastregno == 0xffffffff)
11712                         {
11713                           insn_error
11714                             = _("A destination register must be supplied");
11715                           continue;
11716                         }
11717                     }
11718                   /* Now that we have assembled one operand, we use the args
11719                      string to figure out where it goes in the instruction.  */
11720                   switch (c)
11721                     {
11722                     case 'r':
11723                     case 's':
11724                     case 'v':
11725                     case 'b':
11726                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
11727                       break;
11728
11729                     case 'K':
11730                       if (mips_opts.micromips)
11731                         INSERT_OPERAND (1, RS, *ip, regno);
11732                       else
11733                         INSERT_OPERAND (0, RD, *ip, regno);
11734                       break;
11735
11736                     case 'd':
11737                     case 'g':
11738                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
11739                       break;
11740
11741                     case 'U':
11742                       gas_assert (!mips_opts.micromips);
11743                       INSERT_OPERAND (0, RD, *ip, regno);
11744                       INSERT_OPERAND (0, RT, *ip, regno);
11745                       break;
11746
11747                     case 'w':
11748                     case 't':
11749                     case 'E':
11750                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
11751                       break;
11752
11753                     case 'y':
11754                       gas_assert (mips_opts.micromips);
11755                       INSERT_OPERAND (1, RS3, *ip, regno);
11756                       break;
11757
11758                     case 'x':
11759                       /* This case exists because on the r3000 trunc
11760                          expands into a macro which requires a gp
11761                          register.  On the r6000 or r4000 it is
11762                          assembled into a single instruction which
11763                          ignores the register.  Thus the insn version
11764                          is MIPS_ISA2 and uses 'x', and the macro
11765                          version is MIPS_ISA1 and uses 't'.  */
11766                       break;
11767
11768                     case 'z':
11769                       /* This case is for the div instruction, which
11770                          acts differently if the destination argument
11771                          is $0.  This only matches $0, and is checked
11772                          outside the switch.  */
11773                       break;
11774                     }
11775                   lastregno = regno;
11776                   continue;
11777                 }
11778               switch (*args++)
11779                 {
11780                 case 'r':
11781                 case 'v':
11782                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11783                   continue;
11784
11785                 case 'w':
11786                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11787                   continue;
11788                 }
11789               break;
11790
11791             case 'O':           /* MDMX alignment immediate constant.  */
11792               gas_assert (!mips_opts.micromips);
11793               my_getExpression (&imm_expr, s);
11794               check_absolute_expr (ip, &imm_expr);
11795               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
11796                 as_warn (_("Improper align amount (%ld), using low bits"),
11797                          (long) imm_expr.X_add_number);
11798               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
11799               imm_expr.X_op = O_absent;
11800               s = expr_end;
11801               continue;
11802
11803             case 'Q':           /* MDMX vector, element sel, or const.  */
11804               if (s[0] != '$')
11805                 {
11806                   /* MDMX Immediate.  */
11807                   gas_assert (!mips_opts.micromips);
11808                   my_getExpression (&imm_expr, s);
11809                   check_absolute_expr (ip, &imm_expr);
11810                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
11811                     as_warn (_("Invalid MDMX Immediate (%ld)"),
11812                              (long) imm_expr.X_add_number);
11813                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
11814                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11815                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
11816                   else
11817                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
11818                   imm_expr.X_op = O_absent;
11819                   s = expr_end;
11820                   continue;
11821                 }
11822               /* Not MDMX Immediate.  Fall through.  */
11823             case 'X':           /* MDMX destination register.  */
11824             case 'Y':           /* MDMX source register.  */
11825             case 'Z':           /* MDMX target register.  */
11826               is_mdmx = 1;
11827             case 'W':
11828               gas_assert (!mips_opts.micromips);
11829             case 'D':           /* Floating point destination register.  */
11830             case 'S':           /* Floating point source register.  */
11831             case 'T':           /* Floating point target register.  */
11832             case 'R':           /* Floating point source register.  */
11833             case 'V':
11834               rtype = RTYPE_FPU;
11835               if (is_mdmx
11836                   || (mips_opts.ase_mdmx
11837                       && (ip->insn_mo->pinfo & FP_D)
11838                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
11839                                                 | INSN_COPROC_MEMORY_DELAY
11840                                                 | INSN_LOAD_COPROC_DELAY
11841                                                 | INSN_LOAD_MEMORY_DELAY
11842                                                 | INSN_STORE_MEMORY))))
11843                 rtype |= RTYPE_VEC;
11844               s_reset = s;
11845               if (reg_lookup (&s, rtype, &regno))
11846                 {
11847                   if ((regno & 1) != 0
11848                       && HAVE_32BIT_FPRS
11849                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
11850                     as_warn (_("Float register should be even, was %d"),
11851                              regno);
11852
11853                   c = *args;
11854                   if (*s == ' ')
11855                     ++s;
11856                   if (args[1] != *s)
11857                     {
11858                       if (c == 'V' || c == 'W')
11859                         {
11860                           regno = lastregno;
11861                           s = s_reset;
11862                           ++args;
11863                         }
11864                     }
11865                   switch (c)
11866                     {
11867                     case 'D':
11868                     case 'X':
11869                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
11870                       break;
11871
11872                     case 'V':
11873                     case 'S':
11874                     case 'Y':
11875                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
11876                       break;
11877
11878                     case 'Q':
11879                       /* This is like 'Z', but also needs to fix the MDMX
11880                          vector/scalar select bits.  Note that the
11881                          scalar immediate case is handled above.  */
11882                       if (*s == '[')
11883                         {
11884                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
11885                           int max_el = (is_qh ? 3 : 7);
11886                           s++;
11887                           my_getExpression(&imm_expr, s);
11888                           check_absolute_expr (ip, &imm_expr);
11889                           s = expr_end;
11890                           if (imm_expr.X_add_number > max_el)
11891                             as_bad (_("Bad element selector %ld"),
11892                                     (long) imm_expr.X_add_number);
11893                           imm_expr.X_add_number &= max_el;
11894                           ip->insn_opcode |= (imm_expr.X_add_number
11895                                               << (OP_SH_VSEL +
11896                                                   (is_qh ? 2 : 1)));
11897                           imm_expr.X_op = O_absent;
11898                           if (*s != ']')
11899                             as_warn (_("Expecting ']' found '%s'"), s);
11900                           else
11901                             s++;
11902                         }
11903                       else
11904                         {
11905                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11906                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
11907                                                 << OP_SH_VSEL);
11908                           else
11909                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
11910                                                 OP_SH_VSEL);
11911                         }
11912                       /* Fall through.  */
11913                     case 'W':
11914                     case 'T':
11915                     case 'Z':
11916                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
11917                       break;
11918
11919                     case 'R':
11920                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
11921                       break;
11922                     }
11923                   lastregno = regno;
11924                   continue;
11925                 }
11926
11927               switch (*args++)
11928                 {
11929                 case 'V':
11930                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11931                   continue;
11932
11933                 case 'W':
11934                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
11935                   continue;
11936                 }
11937               break;
11938
11939             case 'I':
11940               my_getExpression (&imm_expr, s);
11941               if (imm_expr.X_op != O_big
11942                   && imm_expr.X_op != O_constant)
11943                 insn_error = _("absolute expression required");
11944               if (HAVE_32BIT_GPRS)
11945                 normalize_constant_expr (&imm_expr);
11946               s = expr_end;
11947               continue;
11948
11949             case 'A':
11950               my_getExpression (&offset_expr, s);
11951               normalize_address_expr (&offset_expr);
11952               *imm_reloc = BFD_RELOC_32;
11953               s = expr_end;
11954               continue;
11955
11956             case 'F':
11957             case 'L':
11958             case 'f':
11959             case 'l':
11960               {
11961                 int f64;
11962                 int using_gprs;
11963                 char *save_in;
11964                 char *err;
11965                 unsigned char temp[8];
11966                 int len;
11967                 unsigned int length;
11968                 segT seg;
11969                 subsegT subseg;
11970                 char *p;
11971
11972                 /* These only appear as the last operand in an
11973                    instruction, and every instruction that accepts
11974                    them in any variant accepts them in all variants.
11975                    This means we don't have to worry about backing out
11976                    any changes if the instruction does not match.
11977
11978                    The difference between them is the size of the
11979                    floating point constant and where it goes.  For 'F'
11980                    and 'L' the constant is 64 bits; for 'f' and 'l' it
11981                    is 32 bits.  Where the constant is placed is based
11982                    on how the MIPS assembler does things:
11983                     F -- .rdata
11984                     L -- .lit8
11985                     f -- immediate value
11986                     l -- .lit4
11987
11988                     The .lit4 and .lit8 sections are only used if
11989                     permitted by the -G argument.
11990
11991                     The code below needs to know whether the target register
11992                     is 32 or 64 bits wide.  It relies on the fact 'f' and
11993                     'F' are used with GPR-based instructions and 'l' and
11994                     'L' are used with FPR-based instructions.  */
11995
11996                 f64 = *args == 'F' || *args == 'L';
11997                 using_gprs = *args == 'F' || *args == 'f';
11998
11999                 save_in = input_line_pointer;
12000                 input_line_pointer = s;
12001                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12002                 length = len;
12003                 s = input_line_pointer;
12004                 input_line_pointer = save_in;
12005                 if (err != NULL && *err != '\0')
12006                   {
12007                     as_bad (_("Bad floating point constant: %s"), err);
12008                     memset (temp, '\0', sizeof temp);
12009                     length = f64 ? 8 : 4;
12010                   }
12011
12012                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12013
12014                 if (*args == 'f'
12015                     || (*args == 'l'
12016                         && (g_switch_value < 4
12017                             || (temp[0] == 0 && temp[1] == 0)
12018                             || (temp[2] == 0 && temp[3] == 0))))
12019                   {
12020                     imm_expr.X_op = O_constant;
12021                     if (!target_big_endian)
12022                       imm_expr.X_add_number = bfd_getl32 (temp);
12023                     else
12024                       imm_expr.X_add_number = bfd_getb32 (temp);
12025                   }
12026                 else if (length > 4
12027                          && !mips_disable_float_construction
12028                          /* Constants can only be constructed in GPRs and
12029                             copied to FPRs if the GPRs are at least as wide
12030                             as the FPRs.  Force the constant into memory if
12031                             we are using 64-bit FPRs but the GPRs are only
12032                             32 bits wide.  */
12033                          && (using_gprs
12034                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12035                          && ((temp[0] == 0 && temp[1] == 0)
12036                              || (temp[2] == 0 && temp[3] == 0))
12037                          && ((temp[4] == 0 && temp[5] == 0)
12038                              || (temp[6] == 0 && temp[7] == 0)))
12039                   {
12040                     /* The value is simple enough to load with a couple of
12041                        instructions.  If using 32-bit registers, set
12042                        imm_expr to the high order 32 bits and offset_expr to
12043                        the low order 32 bits.  Otherwise, set imm_expr to
12044                        the entire 64 bit constant.  */
12045                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12046                       {
12047                         imm_expr.X_op = O_constant;
12048                         offset_expr.X_op = O_constant;
12049                         if (!target_big_endian)
12050                           {
12051                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12052                             offset_expr.X_add_number = bfd_getl32 (temp);
12053                           }
12054                         else
12055                           {
12056                             imm_expr.X_add_number = bfd_getb32 (temp);
12057                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12058                           }
12059                         if (offset_expr.X_add_number == 0)
12060                           offset_expr.X_op = O_absent;
12061                       }
12062                     else if (sizeof (imm_expr.X_add_number) > 4)
12063                       {
12064                         imm_expr.X_op = O_constant;
12065                         if (!target_big_endian)
12066                           imm_expr.X_add_number = bfd_getl64 (temp);
12067                         else
12068                           imm_expr.X_add_number = bfd_getb64 (temp);
12069                       }
12070                     else
12071                       {
12072                         imm_expr.X_op = O_big;
12073                         imm_expr.X_add_number = 4;
12074                         if (!target_big_endian)
12075                           {
12076                             generic_bignum[0] = bfd_getl16 (temp);
12077                             generic_bignum[1] = bfd_getl16 (temp + 2);
12078                             generic_bignum[2] = bfd_getl16 (temp + 4);
12079                             generic_bignum[3] = bfd_getl16 (temp + 6);
12080                           }
12081                         else
12082                           {
12083                             generic_bignum[0] = bfd_getb16 (temp + 6);
12084                             generic_bignum[1] = bfd_getb16 (temp + 4);
12085                             generic_bignum[2] = bfd_getb16 (temp + 2);
12086                             generic_bignum[3] = bfd_getb16 (temp);
12087                           }
12088                       }
12089                   }
12090                 else
12091                   {
12092                     const char *newname;
12093                     segT new_seg;
12094
12095                     /* Switch to the right section.  */
12096                     seg = now_seg;
12097                     subseg = now_subseg;
12098                     switch (*args)
12099                       {
12100                       default: /* unused default case avoids warnings.  */
12101                       case 'L':
12102                         newname = RDATA_SECTION_NAME;
12103                         if (g_switch_value >= 8)
12104                           newname = ".lit8";
12105                         break;
12106                       case 'F':
12107                         newname = RDATA_SECTION_NAME;
12108                         break;
12109                       case 'l':
12110                         gas_assert (g_switch_value >= 4);
12111                         newname = ".lit4";
12112                         break;
12113                       }
12114                     new_seg = subseg_new (newname, (subsegT) 0);
12115                     if (IS_ELF)
12116                       bfd_set_section_flags (stdoutput, new_seg,
12117                                              (SEC_ALLOC
12118                                               | SEC_LOAD
12119                                               | SEC_READONLY
12120                                               | SEC_DATA));
12121                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12122                     if (IS_ELF && strncmp (TARGET_OS, "elf", 3) != 0)
12123                       record_alignment (new_seg, 4);
12124                     else
12125                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12126                     if (seg == now_seg)
12127                       as_bad (_("Can't use floating point insn in this section"));
12128
12129                     /* Set the argument to the current address in the
12130                        section.  */
12131                     offset_expr.X_op = O_symbol;
12132                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12133                     offset_expr.X_add_number = 0;
12134
12135                     /* Put the floating point number into the section.  */
12136                     p = frag_more ((int) length);
12137                     memcpy (p, temp, length);
12138
12139                     /* Switch back to the original section.  */
12140                     subseg_set (seg, subseg);
12141                   }
12142               }
12143               continue;
12144
12145             case 'i':           /* 16-bit unsigned immediate.  */
12146             case 'j':           /* 16-bit signed immediate.  */
12147               *imm_reloc = BFD_RELOC_LO16;
12148               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
12149                 {
12150                   int more;
12151                   offsetT minval, maxval;
12152
12153                   more = (insn + 1 < past
12154                           && strcmp (insn->name, insn[1].name) == 0);
12155
12156                   /* If the expression was written as an unsigned number,
12157                      only treat it as signed if there are no more
12158                      alternatives.  */
12159                   if (more
12160                       && *args == 'j'
12161                       && sizeof (imm_expr.X_add_number) <= 4
12162                       && imm_expr.X_op == O_constant
12163                       && imm_expr.X_add_number < 0
12164                       && imm_expr.X_unsigned
12165                       && HAVE_64BIT_GPRS)
12166                     break;
12167
12168                   /* For compatibility with older assemblers, we accept
12169                      0x8000-0xffff as signed 16-bit numbers when only
12170                      signed numbers are allowed.  */
12171                   if (*args == 'i')
12172                     minval = 0, maxval = 0xffff;
12173                   else if (more)
12174                     minval = -0x8000, maxval = 0x7fff;
12175                   else
12176                     minval = -0x8000, maxval = 0xffff;
12177
12178                   if (imm_expr.X_op != O_constant
12179                       || imm_expr.X_add_number < minval
12180                       || imm_expr.X_add_number > maxval)
12181                     {
12182                       if (more)
12183                         break;
12184                       if (imm_expr.X_op == O_constant
12185                           || imm_expr.X_op == O_big)
12186                         as_bad (_("Expression out of range"));
12187                     }
12188                 }
12189               s = expr_end;
12190               continue;
12191
12192             case 'o':           /* 16-bit offset.  */
12193               offset_reloc[0] = BFD_RELOC_LO16;
12194               offset_reloc[1] = BFD_RELOC_UNUSED;
12195               offset_reloc[2] = BFD_RELOC_UNUSED;
12196
12197               /* Check whether there is only a single bracketed expression
12198                  left.  If so, it must be the base register and the
12199                  constant must be zero.  */
12200               if (*s == '(' && strchr (s + 1, '(') == 0)
12201                 {
12202                   offset_expr.X_op = O_constant;
12203                   offset_expr.X_add_number = 0;
12204                   continue;
12205                 }
12206
12207               /* If this value won't fit into a 16 bit offset, then go
12208                  find a macro that will generate the 32 bit offset
12209                  code pattern.  */
12210               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12211                   && (offset_expr.X_op != O_constant
12212                       || offset_expr.X_add_number >= 0x8000
12213                       || offset_expr.X_add_number < -0x8000))
12214                 break;
12215
12216               s = expr_end;
12217               continue;
12218
12219             case 'p':           /* PC-relative offset.  */
12220               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12221               my_getExpression (&offset_expr, s);
12222               s = expr_end;
12223               continue;
12224
12225             case 'u':           /* Upper 16 bits.  */
12226               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
12227                   && imm_expr.X_op == O_constant
12228                   && (imm_expr.X_add_number < 0
12229                       || imm_expr.X_add_number >= 0x10000))
12230                 as_bad (_("lui expression (%lu) not in range 0..65535"),
12231                         (unsigned long) imm_expr.X_add_number);
12232               s = expr_end;
12233               continue;
12234
12235             case 'a':           /* 26-bit address.  */
12236               *offset_reloc = BFD_RELOC_MIPS_JMP;
12237               my_getExpression (&offset_expr, s);
12238               s = expr_end;
12239               continue;
12240
12241             case 'N':           /* 3-bit branch condition code.  */
12242             case 'M':           /* 3-bit compare condition code.  */
12243               rtype = RTYPE_CCC;
12244               if (ip->insn_mo->pinfo & (FP_D | FP_S))
12245                 rtype |= RTYPE_FCC;
12246               if (!reg_lookup (&s, rtype, &regno))
12247                 break;
12248               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
12249                    || strcmp (str + strlen (str) - 5, "any2f") == 0
12250                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
12251                   && (regno & 1) != 0)
12252                 as_warn (_("Condition code register should be even for %s, "
12253                            "was %d"),
12254                          str, regno);
12255               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
12256                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
12257                   && (regno & 3) != 0)
12258                 as_warn (_("Condition code register should be 0 or 4 for %s, "
12259                            "was %d"),
12260                          str, regno);
12261               if (*args == 'N')
12262                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
12263               else
12264                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
12265               continue;
12266
12267             case 'H':
12268               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
12269                 s += 2;
12270               if (ISDIGIT (*s))
12271                 {
12272                   c = 0;
12273                   do
12274                     {
12275                       c *= 10;
12276                       c += *s - '0';
12277                       ++s;
12278                     }
12279                   while (ISDIGIT (*s));
12280                 }
12281               else
12282                 c = 8; /* Invalid sel value.  */
12283
12284               if (c > 7)
12285                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
12286               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
12287               continue;
12288
12289             case 'e':
12290               gas_assert (!mips_opts.micromips);
12291               /* Must be at least one digit.  */
12292               my_getExpression (&imm_expr, s);
12293               check_absolute_expr (ip, &imm_expr);
12294
12295               if ((unsigned long) imm_expr.X_add_number
12296                   > (unsigned long) OP_MASK_VECBYTE)
12297                 {
12298                   as_bad (_("bad byte vector index (%ld)"),
12299                            (long) imm_expr.X_add_number);
12300                   imm_expr.X_add_number = 0;
12301                 }
12302
12303               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
12304               imm_expr.X_op = O_absent;
12305               s = expr_end;
12306               continue;
12307
12308             case '%':
12309               gas_assert (!mips_opts.micromips);
12310               my_getExpression (&imm_expr, s);
12311               check_absolute_expr (ip, &imm_expr);
12312
12313               if ((unsigned long) imm_expr.X_add_number
12314                   > (unsigned long) OP_MASK_VECALIGN)
12315                 {
12316                   as_bad (_("bad byte vector index (%ld)"),
12317                            (long) imm_expr.X_add_number);
12318                   imm_expr.X_add_number = 0;
12319                 }
12320
12321               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
12322               imm_expr.X_op = O_absent;
12323               s = expr_end;
12324               continue;
12325
12326             case 'm':           /* Opcode extension character.  */
12327               gas_assert (mips_opts.micromips);
12328               c = *++args;
12329               switch (c)
12330                 {
12331                 case 'r':
12332                   if (strncmp (s, "$pc", 3) == 0)
12333                     {
12334                       s += 3;
12335                       continue;
12336                     }
12337                   break;
12338
12339                 case 'a':
12340                 case 'b':
12341                 case 'c':
12342                 case 'd':
12343                 case 'e':
12344                 case 'f':
12345                 case 'g':
12346                 case 'h':
12347                 case 'i':
12348                 case 'j':
12349                 case 'l':
12350                 case 'm':
12351                 case 'n':
12352                 case 'p':
12353                 case 'q':
12354                 case 's':
12355                 case 't':
12356                 case 'x':
12357                 case 'y':
12358                 case 'z':
12359                   s_reset = s;
12360                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12361                   if (regno == AT && mips_opts.at)
12362                     {
12363                       if (mips_opts.at == ATREG)
12364                         as_warn (_("Used $at without \".set noat\""));
12365                       else
12366                         as_warn (_("Used $%u with \".set at=$%u\""),
12367                                  regno, mips_opts.at);
12368                     }
12369                   if (!ok)
12370                     {
12371                       if (c == 'c')
12372                         {
12373                           gas_assert (args[1] == ',');
12374                           regno = lastregno;
12375                           ++args;
12376                         }
12377                       else if (c == 't')
12378                         {
12379                           gas_assert (args[1] == ',');
12380                           ++args;
12381                           continue;                     /* Nothing to do.  */
12382                         }
12383                       else
12384                         break;
12385                     }
12386
12387                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
12388                     {
12389                       if (regno == lastregno)
12390                         {
12391                           insn_error
12392                             = _("Source and destination must be different");
12393                           continue;
12394                         }
12395                       if (regno == 31 && lastregno == 0xffffffff)
12396                         {
12397                           insn_error
12398                             = _("A destination register must be supplied");
12399                           continue;
12400                         }
12401                     }
12402
12403                   if (*s == ' ')
12404                     ++s;
12405                   if (args[1] != *s)
12406                     {
12407                       if (c == 'e')
12408                         {
12409                           gas_assert (args[1] == ',');
12410                           regno = lastregno;
12411                           s = s_reset;
12412                           ++args;
12413                         }
12414                       else if (c == 't')
12415                         {
12416                           gas_assert (args[1] == ',');
12417                           s = s_reset;
12418                           ++args;
12419                           continue;                     /* Nothing to do.  */
12420                         }
12421                     }
12422
12423                   /* Make sure regno is the same as lastregno.  */
12424                   if (c == 't' && regno != lastregno)
12425                     break;
12426
12427                   /* Make sure regno is the same as destregno.  */
12428                   if (c == 'x' && regno != destregno)
12429                     break;
12430
12431                   /* We need to save regno, before regno maps to the
12432                      microMIPS register encoding.  */
12433                   lastregno = regno;
12434
12435                   if (c == 'f')
12436                     destregno = regno;
12437
12438                   switch (c)
12439                     {
12440                       case 'a':
12441                         if (regno != GP)
12442                           regno = ILLEGAL_REG;
12443                         break;
12444
12445                       case 'b':
12446                         regno = mips32_to_micromips_reg_b_map[regno];
12447                         break;
12448
12449                       case 'c':
12450                         regno = mips32_to_micromips_reg_c_map[regno];
12451                         break;
12452
12453                       case 'd':
12454                         regno = mips32_to_micromips_reg_d_map[regno];
12455                         break;
12456
12457                       case 'e':
12458                         regno = mips32_to_micromips_reg_e_map[regno];
12459                         break;
12460
12461                       case 'f':
12462                         regno = mips32_to_micromips_reg_f_map[regno];
12463                         break;
12464
12465                       case 'g':
12466                         regno = mips32_to_micromips_reg_g_map[regno];
12467                         break;
12468
12469                       case 'h':
12470                         regno = mips32_to_micromips_reg_h_map[regno];
12471                         break;
12472
12473                       case 'i':
12474                         switch (EXTRACT_OPERAND (1, MI, *ip))
12475                           {
12476                             case 4:
12477                               if (regno == 21)
12478                                 regno = 3;
12479                               else if (regno == 22)
12480                                 regno = 4;
12481                               else if (regno == 5)
12482                                 regno = 5;
12483                               else if (regno == 6)
12484                                 regno = 6;
12485                               else if (regno == 7)
12486                                 regno = 7;
12487                               else
12488                                 regno = ILLEGAL_REG;
12489                               break;
12490
12491                             case 5:
12492                               if (regno == 6)
12493                                 regno = 0;
12494                               else if (regno == 7)
12495                                 regno = 1;
12496                               else
12497                                 regno = ILLEGAL_REG;
12498                               break;
12499
12500                             case 6:
12501                               if (regno == 7)
12502                                 regno = 2;
12503                               else
12504                                 regno = ILLEGAL_REG;
12505                               break;
12506
12507                             default:
12508                               regno = ILLEGAL_REG;
12509                               break;
12510                           }
12511                         break;
12512
12513                       case 'l':
12514                         regno = mips32_to_micromips_reg_l_map[regno];
12515                         break;
12516
12517                       case 'm':
12518                         regno = mips32_to_micromips_reg_m_map[regno];
12519                         break;
12520
12521                       case 'n':
12522                         regno = mips32_to_micromips_reg_n_map[regno];
12523                         break;
12524
12525                       case 'q':
12526                         regno = mips32_to_micromips_reg_q_map[regno];
12527                         break;
12528
12529                       case 's':
12530                         if (regno != SP)
12531                           regno = ILLEGAL_REG;
12532                         break;
12533
12534                       case 'y':
12535                         if (regno != 31)
12536                           regno = ILLEGAL_REG;
12537                         break;
12538
12539                       case 'z':
12540                         if (regno != ZERO)
12541                           regno = ILLEGAL_REG;
12542                         break;
12543
12544                       case 'j': /* Do nothing.  */
12545                       case 'p':
12546                       case 't':
12547                       case 'x':
12548                         break;
12549
12550                       default:
12551                         internalError ();
12552                     }
12553
12554                   if (regno == ILLEGAL_REG)
12555                     break;
12556
12557                   switch (c)
12558                     {
12559                       case 'b':
12560                         INSERT_OPERAND (1, MB, *ip, regno);
12561                         break;
12562
12563                       case 'c':
12564                         INSERT_OPERAND (1, MC, *ip, regno);
12565                         break;
12566
12567                       case 'd':
12568                         INSERT_OPERAND (1, MD, *ip, regno);
12569                         break;
12570
12571                       case 'e':
12572                         INSERT_OPERAND (1, ME, *ip, regno);
12573                         break;
12574
12575                       case 'f':
12576                         INSERT_OPERAND (1, MF, *ip, regno);
12577                         break;
12578
12579                       case 'g':
12580                         INSERT_OPERAND (1, MG, *ip, regno);
12581                         break;
12582
12583                       case 'h':
12584                         INSERT_OPERAND (1, MH, *ip, regno);
12585                         break;
12586
12587                       case 'i':
12588                         INSERT_OPERAND (1, MI, *ip, regno);
12589                         break;
12590
12591                       case 'j':
12592                         INSERT_OPERAND (1, MJ, *ip, regno);
12593                         break;
12594
12595                       case 'l':
12596                         INSERT_OPERAND (1, ML, *ip, regno);
12597                         break;
12598
12599                       case 'm':
12600                         INSERT_OPERAND (1, MM, *ip, regno);
12601                         break;
12602
12603                       case 'n':
12604                         INSERT_OPERAND (1, MN, *ip, regno);
12605                         break;
12606
12607                       case 'p':
12608                         INSERT_OPERAND (1, MP, *ip, regno);
12609                         break;
12610
12611                       case 'q':
12612                         INSERT_OPERAND (1, MQ, *ip, regno);
12613                         break;
12614
12615                       case 'a': /* Do nothing.  */
12616                       case 's': /* Do nothing.  */
12617                       case 't': /* Do nothing.  */
12618                       case 'x': /* Do nothing.  */
12619                       case 'y': /* Do nothing.  */
12620                       case 'z': /* Do nothing.  */
12621                         break;
12622
12623                       default:
12624                         internalError ();
12625                     }
12626                   continue;
12627
12628                 case 'A':
12629                   {
12630                     bfd_reloc_code_real_type r[3];
12631                     expressionS ep;
12632                     int imm;
12633
12634                     /* Check whether there is only a single bracketed
12635                        expression left.  If so, it must be the base register
12636                        and the constant must be zero.  */
12637                     if (*s == '(' && strchr (s + 1, '(') == 0)
12638                       {
12639                         INSERT_OPERAND (1, IMMA, *ip, 0);
12640                         continue;
12641                       }
12642
12643                     if (my_getSmallExpression (&ep, r, s) > 0
12644                         || !expr_const_in_range (&ep, -64, 64, 2))
12645                       break;
12646
12647                     imm = ep.X_add_number >> 2;
12648                     INSERT_OPERAND (1, IMMA, *ip, imm);
12649                   }
12650                   s = expr_end;
12651                   continue;
12652
12653                 case 'B':
12654                   {
12655                     bfd_reloc_code_real_type r[3];
12656                     expressionS ep;
12657                     int imm;
12658
12659                     if (my_getSmallExpression (&ep, r, s) > 0
12660                         || ep.X_op != O_constant)
12661                       break;
12662
12663                     for (imm = 0; imm < 8; imm++)
12664                       if (micromips_imm_b_map[imm] == ep.X_add_number)
12665                         break;
12666                     if (imm >= 8)
12667                       break;
12668
12669                     INSERT_OPERAND (1, IMMB, *ip, imm);
12670                   }
12671                   s = expr_end;
12672                   continue;
12673
12674                 case 'C':
12675                   {
12676                     bfd_reloc_code_real_type r[3];
12677                     expressionS ep;
12678                     int imm;
12679
12680                     if (my_getSmallExpression (&ep, r, s) > 0
12681                         || ep.X_op != O_constant)
12682                       break;
12683
12684                     for (imm = 0; imm < 16; imm++)
12685                       if (micromips_imm_c_map[imm] == ep.X_add_number)
12686                         break;
12687                     if (imm >= 16)
12688                       break;
12689
12690                     INSERT_OPERAND (1, IMMC, *ip, imm);
12691                   }
12692                   s = expr_end;
12693                   continue;
12694
12695                 case 'D':       /* pc relative offset */
12696                 case 'E':       /* pc relative offset */
12697                   my_getExpression (&offset_expr, s);
12698                   if (offset_expr.X_op == O_register)
12699                     break;
12700
12701                   *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12702                   s = expr_end;
12703                   continue;
12704
12705                 case 'F':
12706                   {
12707                     bfd_reloc_code_real_type r[3];
12708                     expressionS ep;
12709                     int imm;
12710
12711                     if (my_getSmallExpression (&ep, r, s) > 0
12712                         || !expr_const_in_range (&ep, 0, 16, 0))
12713                       break;
12714
12715                     imm = ep.X_add_number;
12716                     INSERT_OPERAND (1, IMMF, *ip, imm);
12717                   }
12718                   s = expr_end;
12719                   continue;
12720
12721                 case 'G':
12722                   {
12723                     bfd_reloc_code_real_type r[3];
12724                     expressionS ep;
12725                     int imm;
12726
12727                     /* Check whether there is only a single bracketed
12728                        expression left.  If so, it must be the base register
12729                        and the constant must be zero.  */
12730                     if (*s == '(' && strchr (s + 1, '(') == 0)
12731                       {
12732                         INSERT_OPERAND (1, IMMG, *ip, 0);
12733                         continue;
12734                       }
12735
12736                     if (my_getSmallExpression (&ep, r, s) > 0
12737                         || !expr_const_in_range (&ep, -1, 15, 0))
12738                       break;
12739
12740                     imm = ep.X_add_number & 15;
12741                     INSERT_OPERAND (1, IMMG, *ip, imm);
12742                   }
12743                   s = expr_end;
12744                   continue;
12745
12746                 case 'H':
12747                   {
12748                     bfd_reloc_code_real_type r[3];
12749                     expressionS ep;
12750                     int imm;
12751
12752                     /* Check whether there is only a single bracketed
12753                        expression left.  If so, it must be the base register
12754                        and the constant must be zero.  */
12755                     if (*s == '(' && strchr (s + 1, '(') == 0)
12756                       {
12757                         INSERT_OPERAND (1, IMMH, *ip, 0);
12758                         continue;
12759                       }
12760
12761                     if (my_getSmallExpression (&ep, r, s) > 0
12762                         || !expr_const_in_range (&ep, 0, 16, 1))
12763                       break;
12764
12765                     imm = ep.X_add_number >> 1;
12766                     INSERT_OPERAND (1, IMMH, *ip, imm);
12767                   }
12768                   s = expr_end;
12769                   continue;
12770
12771                 case 'I':
12772                   {
12773                     bfd_reloc_code_real_type r[3];
12774                     expressionS ep;
12775                     int imm;
12776
12777                     if (my_getSmallExpression (&ep, r, s) > 0
12778                         || !expr_const_in_range (&ep, -1, 127, 0))
12779                       break;
12780
12781                     imm = ep.X_add_number & 127;
12782                     INSERT_OPERAND (1, IMMI, *ip, imm);
12783                   }
12784                   s = expr_end;
12785                   continue;
12786
12787                 case 'J':
12788                   {
12789                     bfd_reloc_code_real_type r[3];
12790                     expressionS ep;
12791                     int imm;
12792
12793                     /* Check whether there is only a single bracketed
12794                        expression left.  If so, it must be the base register
12795                        and the constant must be zero.  */
12796                     if (*s == '(' && strchr (s + 1, '(') == 0)
12797                       {
12798                         INSERT_OPERAND (1, IMMJ, *ip, 0);
12799                         continue;
12800                       }
12801
12802                     if (my_getSmallExpression (&ep, r, s) > 0
12803                         || !expr_const_in_range (&ep, 0, 16, 2))
12804                       break;
12805
12806                     imm = ep.X_add_number >> 2;
12807                     INSERT_OPERAND (1, IMMJ, *ip, imm);
12808                   }
12809                   s = expr_end;
12810                   continue;
12811
12812                 case 'L':
12813                   {
12814                     bfd_reloc_code_real_type r[3];
12815                     expressionS ep;
12816                     int imm;
12817
12818                     /* Check whether there is only a single bracketed
12819                        expression left.  If so, it must be the base register
12820                        and the constant must be zero.  */
12821                     if (*s == '(' && strchr (s + 1, '(') == 0)
12822                       {
12823                         INSERT_OPERAND (1, IMML, *ip, 0);
12824                         continue;
12825                       }
12826
12827                     if (my_getSmallExpression (&ep, r, s) > 0
12828                         || !expr_const_in_range (&ep, 0, 16, 0))
12829                       break;
12830
12831                     imm = ep.X_add_number;
12832                     INSERT_OPERAND (1, IMML, *ip, imm);
12833                   }
12834                   s = expr_end;
12835                   continue;
12836
12837                 case 'M':
12838                   {
12839                     bfd_reloc_code_real_type r[3];
12840                     expressionS ep;
12841                     int imm;
12842
12843                     if (my_getSmallExpression (&ep, r, s) > 0
12844                         || !expr_const_in_range (&ep, 1, 9, 0))
12845                       break;
12846
12847                     imm = ep.X_add_number & 7;
12848                     INSERT_OPERAND (1, IMMM, *ip, imm);
12849                   }
12850                   s = expr_end;
12851                   continue;
12852
12853                 case 'N':       /* Register list for lwm and swm.  */
12854                   {
12855                     /* A comma-separated list of registers and/or
12856                        dash-separated contiguous ranges including
12857                        both ra and a set of one or more registers
12858                        starting at s0 up to s3 which have to be
12859                        consecutive, e.g.:
12860
12861                        s0, ra
12862                        s0, s1, ra, s2, s3
12863                        s0-s2, ra
12864
12865                        and any permutations of these.  */
12866                     unsigned int reglist;
12867                     int imm;
12868
12869                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
12870                       break;
12871
12872                     if ((reglist & 0xfff1ffff) != 0x80010000)
12873                       break;
12874
12875                     reglist = (reglist >> 17) & 7;
12876                     reglist += 1;
12877                     if ((reglist & -reglist) != reglist)
12878                       break;
12879
12880                     imm = ffs (reglist) - 1;
12881                     INSERT_OPERAND (1, IMMN, *ip, imm);
12882                   }
12883                   continue;
12884
12885                 case 'O':       /* sdbbp 4-bit code.  */
12886                   {
12887                     bfd_reloc_code_real_type r[3];
12888                     expressionS ep;
12889                     int imm;
12890
12891                     if (my_getSmallExpression (&ep, r, s) > 0
12892                         || !expr_const_in_range (&ep, 0, 16, 0))
12893                       break;
12894
12895                     imm = ep.X_add_number;
12896                     INSERT_OPERAND (1, IMMO, *ip, imm);
12897                   }
12898                   s = expr_end;
12899                   continue;
12900
12901                 case 'P':
12902                   {
12903                     bfd_reloc_code_real_type r[3];
12904                     expressionS ep;
12905                     int imm;
12906
12907                     if (my_getSmallExpression (&ep, r, s) > 0
12908                         || !expr_const_in_range (&ep, 0, 32, 2))
12909                       break;
12910
12911                     imm = ep.X_add_number >> 2;
12912                     INSERT_OPERAND (1, IMMP, *ip, imm);
12913                   }
12914                   s = expr_end;
12915                   continue;
12916
12917                 case 'Q':
12918                   {
12919                     bfd_reloc_code_real_type r[3];
12920                     expressionS ep;
12921                     int imm;
12922
12923                     if (my_getSmallExpression (&ep, r, s) > 0
12924                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
12925                       break;
12926
12927                     imm = ep.X_add_number >> 2;
12928                     INSERT_OPERAND (1, IMMQ, *ip, imm);
12929                   }
12930                   s = expr_end;
12931                   continue;
12932
12933                 case 'U':
12934                   {
12935                     bfd_reloc_code_real_type r[3];
12936                     expressionS ep;
12937                     int imm;
12938
12939                     /* Check whether there is only a single bracketed
12940                        expression left.  If so, it must be the base register
12941                        and the constant must be zero.  */
12942                     if (*s == '(' && strchr (s + 1, '(') == 0)
12943                       {
12944                         INSERT_OPERAND (1, IMMU, *ip, 0);
12945                         continue;
12946                       }
12947
12948                     if (my_getSmallExpression (&ep, r, s) > 0
12949                         || !expr_const_in_range (&ep, 0, 32, 2))
12950                       break;
12951
12952                     imm = ep.X_add_number >> 2;
12953                     INSERT_OPERAND (1, IMMU, *ip, imm);
12954                   }
12955                   s = expr_end;
12956                   continue;
12957
12958                 case 'W':
12959                   {
12960                     bfd_reloc_code_real_type r[3];
12961                     expressionS ep;
12962                     int imm;
12963
12964                     if (my_getSmallExpression (&ep, r, s) > 0
12965                         || !expr_const_in_range (&ep, 0, 64, 2))
12966                       break;
12967
12968                     imm = ep.X_add_number >> 2;
12969                     INSERT_OPERAND (1, IMMW, *ip, imm);
12970                   }
12971                   s = expr_end;
12972                   continue;
12973
12974                 case 'X':
12975                   {
12976                     bfd_reloc_code_real_type r[3];
12977                     expressionS ep;
12978                     int imm;
12979
12980                     if (my_getSmallExpression (&ep, r, s) > 0
12981                         || !expr_const_in_range (&ep, -8, 8, 0))
12982                       break;
12983
12984                     imm = ep.X_add_number;
12985                     INSERT_OPERAND (1, IMMX, *ip, imm);
12986                   }
12987                   s = expr_end;
12988                   continue;
12989
12990                 case 'Y':
12991                   {
12992                     bfd_reloc_code_real_type r[3];
12993                     expressionS ep;
12994                     int imm;
12995
12996                     if (my_getSmallExpression (&ep, r, s) > 0
12997                         || expr_const_in_range (&ep, -2, 2, 2)
12998                         || !expr_const_in_range (&ep, -258, 258, 2))
12999                       break;
13000
13001                     imm = ep.X_add_number >> 2;
13002                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
13003                     INSERT_OPERAND (1, IMMY, *ip, imm);
13004                   }
13005                   s = expr_end;
13006                   continue;
13007
13008                 case 'Z':
13009                   {
13010                     bfd_reloc_code_real_type r[3];
13011                     expressionS ep;
13012
13013                     if (my_getSmallExpression (&ep, r, s) > 0
13014                         || !expr_const_in_range (&ep, 0, 1, 0))
13015                       break;
13016                   }
13017                   s = expr_end;
13018                   continue;
13019
13020                 default:
13021                   as_bad (_("Internal error: bad microMIPS opcode "
13022                             "(unknown extension operand type `m%c'): %s %s"),
13023                           *args, insn->name, insn->args);
13024                   /* Further processing is fruitless.  */
13025                   return;
13026                 }
13027               break;
13028
13029             case 'n':           /* Register list for 32-bit lwm and swm.  */
13030               gas_assert (mips_opts.micromips);
13031               {
13032                 /* A comma-separated list of registers and/or
13033                    dash-separated contiguous ranges including
13034                    at least one of ra and a set of one or more
13035                    registers starting at s0 up to s7 and then
13036                    s8 which have to be consecutive, e.g.:
13037
13038                    ra
13039                    s0
13040                    ra, s0, s1, s2
13041                    s0-s8
13042                    s0-s5, ra
13043
13044                    and any permutations of these.  */
13045                 unsigned int reglist;
13046                 int imm;
13047                 int ra;
13048
13049                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13050                   break;
13051
13052                 if ((reglist & 0x3f00ffff) != 0)
13053                   break;
13054
13055                 ra = (reglist >> 27) & 0x10;
13056                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13057                 reglist += 1;
13058                 if ((reglist & -reglist) != reglist)
13059                   break;
13060
13061                 imm = (ffs (reglist) - 1) | ra;
13062                 INSERT_OPERAND (1, RT, *ip, imm);
13063                 imm_expr.X_op = O_absent;
13064               }
13065               continue;
13066
13067             case '|':           /* 4-bit trap code.  */
13068               gas_assert (mips_opts.micromips);
13069               my_getExpression (&imm_expr, s);
13070               check_absolute_expr (ip, &imm_expr);
13071               if ((unsigned long) imm_expr.X_add_number
13072                   > MICROMIPSOP_MASK_TRAP)
13073                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13074                         (unsigned long) imm_expr.X_add_number,
13075                         ip->insn_mo->name);
13076               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13077               imm_expr.X_op = O_absent;
13078               s = expr_end;
13079               continue;
13080
13081             default:
13082               as_bad (_("Bad char = '%c'\n"), *args);
13083               internalError ();
13084             }
13085           break;
13086         }
13087       /* Args don't match.  */
13088       s = argsStart;
13089       insn_error = _("Illegal operands");
13090       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13091         {
13092           ++insn;
13093           continue;
13094         }
13095       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13096         {
13097           gas_assert (firstinsn);
13098           need_delay_slot_ok = FALSE;
13099           past = insn + 1;
13100           insn = firstinsn;
13101           continue;
13102         }
13103       return;
13104     }
13105 }
13106
13107 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13108
13109 /* This routine assembles an instruction into its binary format when
13110    assembling for the mips16.  As a side effect, it sets one of the
13111    global variables imm_reloc or offset_reloc to the type of relocation
13112    to do if one of the operands is an address expression.  It also sets
13113    forced_insn_length to the resulting instruction size in bytes if the
13114    user explicitly requested a small or extended instruction.  */
13115
13116 static void
13117 mips16_ip (char *str, struct mips_cl_insn *ip)
13118 {
13119   char *s;
13120   const char *args;
13121   struct mips_opcode *insn;
13122   char *argsstart;
13123   unsigned int regno;
13124   unsigned int lastregno = 0;
13125   char *s_reset;
13126   size_t i;
13127
13128   insn_error = NULL;
13129
13130   forced_insn_length = 0;
13131
13132   for (s = str; ISLOWER (*s); ++s)
13133     ;
13134   switch (*s)
13135     {
13136     case '\0':
13137       break;
13138
13139     case ' ':
13140       *s++ = '\0';
13141       break;
13142
13143     case '.':
13144       if (s[1] == 't' && s[2] == ' ')
13145         {
13146           *s = '\0';
13147           forced_insn_length = 2;
13148           s += 3;
13149           break;
13150         }
13151       else if (s[1] == 'e' && s[2] == ' ')
13152         {
13153           *s = '\0';
13154           forced_insn_length = 4;
13155           s += 3;
13156           break;
13157         }
13158       /* Fall through.  */
13159     default:
13160       insn_error = _("unknown opcode");
13161       return;
13162     }
13163
13164   if (mips_opts.noautoextend && !forced_insn_length)
13165     forced_insn_length = 2;
13166
13167   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
13168     {
13169       insn_error = _("unrecognized opcode");
13170       return;
13171     }
13172
13173   argsstart = s;
13174   for (;;)
13175     {
13176       bfd_boolean ok;
13177
13178       gas_assert (strcmp (insn->name, str) == 0);
13179
13180       ok = is_opcode_valid_16 (insn);
13181       if (! ok)
13182         {
13183           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13184               && strcmp (insn->name, insn[1].name) == 0)
13185             {
13186               ++insn;
13187               continue;
13188             }
13189           else
13190             {
13191               if (!insn_error)
13192                 {
13193                   static char buf[100];
13194                   sprintf (buf,
13195                            _("opcode not supported on this processor: %s (%s)"),
13196                            mips_cpu_info_from_arch (mips_opts.arch)->name,
13197                            mips_cpu_info_from_isa (mips_opts.isa)->name);
13198                   insn_error = buf;
13199                 }
13200               return;
13201             }
13202         }
13203
13204       create_insn (ip, insn);
13205       imm_expr.X_op = O_absent;
13206       imm_reloc[0] = BFD_RELOC_UNUSED;
13207       imm_reloc[1] = BFD_RELOC_UNUSED;
13208       imm_reloc[2] = BFD_RELOC_UNUSED;
13209       imm2_expr.X_op = O_absent;
13210       offset_expr.X_op = O_absent;
13211       offset_reloc[0] = BFD_RELOC_UNUSED;
13212       offset_reloc[1] = BFD_RELOC_UNUSED;
13213       offset_reloc[2] = BFD_RELOC_UNUSED;
13214       for (args = insn->args; 1; ++args)
13215         {
13216           int c;
13217
13218           if (*s == ' ')
13219             ++s;
13220
13221           /* In this switch statement we call break if we did not find
13222              a match, continue if we did find a match, or return if we
13223              are done.  */
13224
13225           c = *args;
13226           switch (c)
13227             {
13228             case '\0':
13229               if (*s == '\0')
13230                 {
13231                   /* Stuff the immediate value in now, if we can.  */
13232                   if (imm_expr.X_op == O_constant
13233                       && *imm_reloc > BFD_RELOC_UNUSED
13234                       && *imm_reloc != BFD_RELOC_MIPS16_GOT16
13235                       && *imm_reloc != BFD_RELOC_MIPS16_CALL16
13236                       && insn->pinfo != INSN_MACRO)
13237                     {
13238                       valueT tmp;
13239
13240                       switch (*offset_reloc)
13241                         {
13242                           case BFD_RELOC_MIPS16_HI16_S:
13243                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
13244                             break;
13245
13246                           case BFD_RELOC_MIPS16_HI16:
13247                             tmp = imm_expr.X_add_number >> 16;
13248                             break;
13249
13250                           case BFD_RELOC_MIPS16_LO16:
13251                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
13252                                   - 0x8000;
13253                             break;
13254
13255                           case BFD_RELOC_UNUSED:
13256                             tmp = imm_expr.X_add_number;
13257                             break;
13258
13259                           default:
13260                             internalError ();
13261                         }
13262                       *offset_reloc = BFD_RELOC_UNUSED;
13263
13264                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
13265                                     tmp, TRUE, forced_insn_length == 2,
13266                                     forced_insn_length == 4, &ip->insn_opcode,
13267                                     &ip->use_extend, &ip->extend);
13268                       imm_expr.X_op = O_absent;
13269                       *imm_reloc = BFD_RELOC_UNUSED;
13270                     }
13271
13272                   return;
13273                 }
13274               break;
13275
13276             case ',':
13277               if (*s++ == c)
13278                 continue;
13279               s--;
13280               switch (*++args)
13281                 {
13282                 case 'v':
13283                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13284                   continue;
13285                 case 'w':
13286                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13287                   continue;
13288                 }
13289               break;
13290
13291             case '(':
13292             case ')':
13293               if (*s++ == c)
13294                 continue;
13295               break;
13296
13297             case 'v':
13298             case 'w':
13299               if (s[0] != '$')
13300                 {
13301                   if (c == 'v')
13302                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13303                   else
13304                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13305                   ++args;
13306                   continue;
13307                 }
13308               /* Fall through.  */
13309             case 'x':
13310             case 'y':
13311             case 'z':
13312             case 'Z':
13313             case '0':
13314             case 'S':
13315             case 'R':
13316             case 'X':
13317             case 'Y':
13318               s_reset = s;
13319               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
13320                 {
13321                   if (c == 'v' || c == 'w')
13322                     {
13323                       if (c == 'v')
13324                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13325                       else
13326                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13327                       ++args;
13328                       continue;
13329                     }
13330                   break;
13331                 }
13332
13333               if (*s == ' ')
13334                 ++s;
13335               if (args[1] != *s)
13336                 {
13337                   if (c == 'v' || c == 'w')
13338                     {
13339                       regno = mips16_to_32_reg_map[lastregno];
13340                       s = s_reset;
13341                       ++args;
13342                     }
13343                 }
13344
13345               switch (c)
13346                 {
13347                 case 'x':
13348                 case 'y':
13349                 case 'z':
13350                 case 'v':
13351                 case 'w':
13352                 case 'Z':
13353                   regno = mips32_to_16_reg_map[regno];
13354                   break;
13355
13356                 case '0':
13357                   if (regno != 0)
13358                     regno = ILLEGAL_REG;
13359                   break;
13360
13361                 case 'S':
13362                   if (regno != SP)
13363                     regno = ILLEGAL_REG;
13364                   break;
13365
13366                 case 'R':
13367                   if (regno != RA)
13368                     regno = ILLEGAL_REG;
13369                   break;
13370
13371                 case 'X':
13372                 case 'Y':
13373                   if (regno == AT && mips_opts.at)
13374                     {
13375                       if (mips_opts.at == ATREG)
13376                         as_warn (_("used $at without \".set noat\""));
13377                       else
13378                         as_warn (_("used $%u with \".set at=$%u\""),
13379                                  regno, mips_opts.at);
13380                     }
13381                   break;
13382
13383                 default:
13384                   internalError ();
13385                 }
13386
13387               if (regno == ILLEGAL_REG)
13388                 break;
13389
13390               switch (c)
13391                 {
13392                 case 'x':
13393                 case 'v':
13394                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
13395                   break;
13396                 case 'y':
13397                 case 'w':
13398                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
13399                   break;
13400                 case 'z':
13401                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
13402                   break;
13403                 case 'Z':
13404                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
13405                 case '0':
13406                 case 'S':
13407                 case 'R':
13408                   break;
13409                 case 'X':
13410                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
13411                   break;
13412                 case 'Y':
13413                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
13414                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
13415                   break;
13416                 default:
13417                   internalError ();
13418                 }
13419
13420               lastregno = regno;
13421               continue;
13422
13423             case 'P':
13424               if (strncmp (s, "$pc", 3) == 0)
13425                 {
13426                   s += 3;
13427                   continue;
13428                 }
13429               break;
13430
13431             case '5':
13432             case 'H':
13433             case 'W':
13434             case 'D':
13435             case 'j':
13436             case 'V':
13437             case 'C':
13438             case 'U':
13439             case 'k':
13440             case 'K':
13441               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
13442               if (i > 0)
13443                 {
13444                   if (imm_expr.X_op != O_constant)
13445                     {
13446                       forced_insn_length = 4;
13447                       ip->use_extend = TRUE;
13448                       ip->extend = 0;
13449                     }
13450                   else
13451                     {
13452                       /* We need to relax this instruction.  */
13453                       *offset_reloc = *imm_reloc;
13454                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13455                     }
13456                   s = expr_end;
13457                   continue;
13458                 }
13459               *imm_reloc = BFD_RELOC_UNUSED;
13460               /* Fall through.  */
13461             case '<':
13462             case '>':
13463             case '[':
13464             case ']':
13465             case '4':
13466             case '8':
13467               my_getExpression (&imm_expr, s);
13468               if (imm_expr.X_op == O_register)
13469                 {
13470                   /* What we thought was an expression turned out to
13471                      be a register.  */
13472
13473                   if (s[0] == '(' && args[1] == '(')
13474                     {
13475                       /* It looks like the expression was omitted
13476                          before a register indirection, which means
13477                          that the expression is implicitly zero.  We
13478                          still set up imm_expr, so that we handle
13479                          explicit extensions correctly.  */
13480                       imm_expr.X_op = O_constant;
13481                       imm_expr.X_add_number = 0;
13482                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13483                       continue;
13484                     }
13485
13486                   break;
13487                 }
13488
13489               /* We need to relax this instruction.  */
13490               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13491               s = expr_end;
13492               continue;
13493
13494             case 'p':
13495             case 'q':
13496             case 'A':
13497             case 'B':
13498             case 'E':
13499               /* We use offset_reloc rather than imm_reloc for the PC
13500                  relative operands.  This lets macros with both
13501                  immediate and address operands work correctly.  */
13502               my_getExpression (&offset_expr, s);
13503
13504               if (offset_expr.X_op == O_register)
13505                 break;
13506
13507               /* We need to relax this instruction.  */
13508               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13509               s = expr_end;
13510               continue;
13511
13512             case '6':           /* break code */
13513               my_getExpression (&imm_expr, s);
13514               check_absolute_expr (ip, &imm_expr);
13515               if ((unsigned long) imm_expr.X_add_number > 63)
13516                 as_warn (_("Invalid value for `%s' (%lu)"),
13517                          ip->insn_mo->name,
13518                          (unsigned long) imm_expr.X_add_number);
13519               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
13520               imm_expr.X_op = O_absent;
13521               s = expr_end;
13522               continue;
13523
13524             case 'a':           /* 26 bit address */
13525               my_getExpression (&offset_expr, s);
13526               s = expr_end;
13527               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13528               ip->insn_opcode <<= 16;
13529               continue;
13530
13531             case 'l':           /* register list for entry macro */
13532             case 'L':           /* register list for exit macro */
13533               {
13534                 int mask;
13535
13536                 if (c == 'l')
13537                   mask = 0;
13538                 else
13539                   mask = 7 << 3;
13540                 while (*s != '\0')
13541                   {
13542                     unsigned int freg, reg1, reg2;
13543
13544                     while (*s == ' ' || *s == ',')
13545                       ++s;
13546                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13547                       freg = 0;
13548                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
13549                       freg = 1;
13550                     else
13551                       {
13552                         as_bad (_("can't parse register list"));
13553                         break;
13554                       }
13555                     if (*s == ' ')
13556                       ++s;
13557                     if (*s != '-')
13558                       reg2 = reg1;
13559                     else
13560                       {
13561                         ++s;
13562                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
13563                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
13564                           {
13565                             as_bad (_("invalid register list"));
13566                             break;
13567                           }
13568                       }
13569                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
13570                       {
13571                         mask &= ~ (7 << 3);
13572                         mask |= 5 << 3;
13573                       }
13574                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
13575                       {
13576                         mask &= ~ (7 << 3);
13577                         mask |= 6 << 3;
13578                       }
13579                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
13580                       mask |= (reg2 - 3) << 3;
13581                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
13582                       mask |= (reg2 - 15) << 1;
13583                     else if (reg1 == RA && reg2 == RA)
13584                       mask |= 1;
13585                     else
13586                       {
13587                         as_bad (_("invalid register list"));
13588                         break;
13589                       }
13590                   }
13591                 /* The mask is filled in in the opcode table for the
13592                    benefit of the disassembler.  We remove it before
13593                    applying the actual mask.  */
13594                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
13595                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
13596               }
13597             continue;
13598
13599             case 'm':           /* Register list for save insn.  */
13600             case 'M':           /* Register list for restore insn.  */
13601               {
13602                 int opcode = 0;
13603                 int framesz = 0, seen_framesz = 0;
13604                 int nargs = 0, statics = 0, sregs = 0;
13605
13606                 while (*s != '\0')
13607                   {
13608                     unsigned int reg1, reg2;
13609
13610                     SKIP_SPACE_TABS (s);
13611                     while (*s == ',')
13612                       ++s;
13613                     SKIP_SPACE_TABS (s);
13614
13615                     my_getExpression (&imm_expr, s);
13616                     if (imm_expr.X_op == O_constant)
13617                       {
13618                         /* Handle the frame size.  */
13619                         if (seen_framesz)
13620                           {
13621                             as_bad (_("more than one frame size in list"));
13622                             break;
13623                           }
13624                         seen_framesz = 1;
13625                         framesz = imm_expr.X_add_number;
13626                         imm_expr.X_op = O_absent;
13627                         s = expr_end;
13628                         continue;
13629                       }
13630
13631                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13632                       {
13633                         as_bad (_("can't parse register list"));
13634                         break;
13635                       }
13636
13637                     while (*s == ' ')
13638                       ++s;
13639
13640                     if (*s != '-')
13641                       reg2 = reg1;
13642                     else
13643                       {
13644                         ++s;
13645                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
13646                             || reg2 < reg1)
13647                           {
13648                             as_bad (_("can't parse register list"));
13649                             break;
13650                           }
13651                       }
13652
13653                     while (reg1 <= reg2)
13654                       {
13655                         if (reg1 >= 4 && reg1 <= 7)
13656                           {
13657                             if (!seen_framesz)
13658                                 /* args $a0-$a3 */
13659                                 nargs |= 1 << (reg1 - 4);
13660                             else
13661                                 /* statics $a0-$a3 */
13662                                 statics |= 1 << (reg1 - 4);
13663                           }
13664                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
13665                           {
13666                             /* $s0-$s8 */
13667                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
13668                           }
13669                         else if (reg1 == 31)
13670                           {
13671                             /* Add $ra to insn.  */
13672                             opcode |= 0x40;
13673                           }
13674                         else
13675                           {
13676                             as_bad (_("unexpected register in list"));
13677                             break;
13678                           }
13679                         if (++reg1 == 24)
13680                           reg1 = 30;
13681                       }
13682                   }
13683
13684                 /* Encode args/statics combination.  */
13685                 if (nargs & statics)
13686                   as_bad (_("arg/static registers overlap"));
13687                 else if (nargs == 0xf)
13688                   /* All $a0-$a3 are args.  */
13689                   opcode |= MIPS16_ALL_ARGS << 16;
13690                 else if (statics == 0xf)
13691                   /* All $a0-$a3 are statics.  */
13692                   opcode |= MIPS16_ALL_STATICS << 16;
13693                 else 
13694                   {
13695                     int narg = 0, nstat = 0;
13696
13697                     /* Count arg registers.  */
13698                     while (nargs & 0x1)
13699                       {
13700                         nargs >>= 1;
13701                         narg++;
13702                       }
13703                     if (nargs != 0)
13704                       as_bad (_("invalid arg register list"));
13705
13706                     /* Count static registers.  */
13707                     while (statics & 0x8)
13708                       {
13709                         statics = (statics << 1) & 0xf;
13710                         nstat++;
13711                       }
13712                     if (statics != 0) 
13713                       as_bad (_("invalid static register list"));
13714
13715                     /* Encode args/statics.  */
13716                     opcode |= ((narg << 2) | nstat) << 16;
13717                   }
13718
13719                 /* Encode $s0/$s1.  */
13720                 if (sregs & (1 << 0))           /* $s0 */
13721                   opcode |= 0x20;
13722                 if (sregs & (1 << 1))           /* $s1 */
13723                   opcode |= 0x10;
13724                 sregs >>= 2;
13725
13726                 if (sregs != 0)
13727                   {
13728                     /* Count regs $s2-$s8.  */
13729                     int nsreg = 0;
13730                     while (sregs & 1)
13731                       {
13732                         sregs >>= 1;
13733                         nsreg++;
13734                       }
13735                     if (sregs != 0)
13736                       as_bad (_("invalid static register list"));
13737                     /* Encode $s2-$s8. */
13738                     opcode |= nsreg << 24;
13739                   }
13740
13741                 /* Encode frame size.  */
13742                 if (!seen_framesz)
13743                   as_bad (_("missing frame size"));
13744                 else if ((framesz & 7) != 0 || framesz < 0
13745                          || framesz > 0xff * 8)
13746                   as_bad (_("invalid frame size"));
13747                 else if (framesz != 128 || (opcode >> 16) != 0)
13748                   {
13749                     framesz /= 8;
13750                     opcode |= (((framesz & 0xf0) << 16)
13751                              | (framesz & 0x0f));
13752                   }
13753
13754                 /* Finally build the instruction.  */
13755                 if ((opcode >> 16) != 0 || framesz == 0)
13756                   {
13757                     ip->use_extend = TRUE;
13758                     ip->extend = opcode >> 16;
13759                   }
13760                 ip->insn_opcode |= opcode & 0x7f;
13761               }
13762             continue;
13763
13764             case 'e':           /* extend code */
13765               my_getExpression (&imm_expr, s);
13766               check_absolute_expr (ip, &imm_expr);
13767               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
13768                 {
13769                   as_warn (_("Invalid value for `%s' (%lu)"),
13770                            ip->insn_mo->name,
13771                            (unsigned long) imm_expr.X_add_number);
13772                   imm_expr.X_add_number &= 0x7ff;
13773                 }
13774               ip->insn_opcode |= imm_expr.X_add_number;
13775               imm_expr.X_op = O_absent;
13776               s = expr_end;
13777               continue;
13778
13779             default:
13780               internalError ();
13781             }
13782           break;
13783         }
13784
13785       /* Args don't match.  */
13786       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
13787           strcmp (insn->name, insn[1].name) == 0)
13788         {
13789           ++insn;
13790           s = argsstart;
13791           continue;
13792         }
13793
13794       insn_error = _("illegal operands");
13795
13796       return;
13797     }
13798 }
13799
13800 /* This structure holds information we know about a mips16 immediate
13801    argument type.  */
13802
13803 struct mips16_immed_operand
13804 {
13805   /* The type code used in the argument string in the opcode table.  */
13806   int type;
13807   /* The number of bits in the short form of the opcode.  */
13808   int nbits;
13809   /* The number of bits in the extended form of the opcode.  */
13810   int extbits;
13811   /* The amount by which the short form is shifted when it is used;
13812      for example, the sw instruction has a shift count of 2.  */
13813   int shift;
13814   /* The amount by which the short form is shifted when it is stored
13815      into the instruction code.  */
13816   int op_shift;
13817   /* Non-zero if the short form is unsigned.  */
13818   int unsp;
13819   /* Non-zero if the extended form is unsigned.  */
13820   int extu;
13821   /* Non-zero if the value is PC relative.  */
13822   int pcrel;
13823 };
13824
13825 /* The mips16 immediate operand types.  */
13826
13827 static const struct mips16_immed_operand mips16_immed_operands[] =
13828 {
13829   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13830   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13831   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13832   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13833   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
13834   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
13835   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
13836   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
13837   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
13838   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
13839   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
13840   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
13841   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
13842   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
13843   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
13844   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
13845   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13846   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13847   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
13848   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
13849   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
13850 };
13851
13852 #define MIPS16_NUM_IMMED \
13853   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
13854
13855 /* Handle a mips16 instruction with an immediate value.  This or's the
13856    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
13857    whether an extended value is needed; if one is needed, it sets
13858    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
13859    If SMALL is true, an unextended opcode was explicitly requested.
13860    If EXT is true, an extended opcode was explicitly requested.  If
13861    WARN is true, warn if EXT does not match reality.  */
13862
13863 static void
13864 mips16_immed (char *file, unsigned int line, int type, offsetT val,
13865               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
13866               unsigned long *insn, bfd_boolean *use_extend,
13867               unsigned short *extend)
13868 {
13869   const struct mips16_immed_operand *op;
13870   int mintiny, maxtiny;
13871   bfd_boolean needext;
13872
13873   op = mips16_immed_operands;
13874   while (op->type != type)
13875     {
13876       ++op;
13877       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
13878     }
13879
13880   if (op->unsp)
13881     {
13882       if (type == '<' || type == '>' || type == '[' || type == ']')
13883         {
13884           mintiny = 1;
13885           maxtiny = 1 << op->nbits;
13886         }
13887       else
13888         {
13889           mintiny = 0;
13890           maxtiny = (1 << op->nbits) - 1;
13891         }
13892     }
13893   else
13894     {
13895       mintiny = - (1 << (op->nbits - 1));
13896       maxtiny = (1 << (op->nbits - 1)) - 1;
13897     }
13898
13899   /* Branch offsets have an implicit 0 in the lowest bit.  */
13900   if (type == 'p' || type == 'q')
13901     val /= 2;
13902
13903   if ((val & ((1 << op->shift) - 1)) != 0
13904       || val < (mintiny << op->shift)
13905       || val > (maxtiny << op->shift))
13906     needext = TRUE;
13907   else
13908     needext = FALSE;
13909
13910   if (warn && ext && ! needext)
13911     as_warn_where (file, line,
13912                    _("extended operand requested but not required"));
13913   if (small && needext)
13914     as_bad_where (file, line, _("invalid unextended operand value"));
13915
13916   if (small || (! ext && ! needext))
13917     {
13918       int insnval;
13919
13920       *use_extend = FALSE;
13921       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
13922       insnval <<= op->op_shift;
13923       *insn |= insnval;
13924     }
13925   else
13926     {
13927       long minext, maxext;
13928       int extval;
13929
13930       if (op->extu)
13931         {
13932           minext = 0;
13933           maxext = (1 << op->extbits) - 1;
13934         }
13935       else
13936         {
13937           minext = - (1 << (op->extbits - 1));
13938           maxext = (1 << (op->extbits - 1)) - 1;
13939         }
13940       if (val < minext || val > maxext)
13941         as_bad_where (file, line,
13942                       _("operand value out of range for instruction"));
13943
13944       *use_extend = TRUE;
13945       if (op->extbits == 16)
13946         {
13947           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13948           val &= 0x1f;
13949         }
13950       else if (op->extbits == 15)
13951         {
13952           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13953           val &= 0xf;
13954         }
13955       else
13956         {
13957           extval = ((val & 0x1f) << 6) | (val & 0x20);
13958           val = 0;
13959         }
13960
13961       *extend = (unsigned short) extval;
13962       *insn |= val;
13963     }
13964 }
13965 \f
13966 struct percent_op_match
13967 {
13968   const char *str;
13969   bfd_reloc_code_real_type reloc;
13970 };
13971
13972 static const struct percent_op_match mips_percent_op[] =
13973 {
13974   {"%lo", BFD_RELOC_LO16},
13975 #ifdef OBJ_ELF
13976   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13977   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13978   {"%call16", BFD_RELOC_MIPS_CALL16},
13979   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13980   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13981   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13982   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13983   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13984   {"%got", BFD_RELOC_MIPS_GOT16},
13985   {"%gp_rel", BFD_RELOC_GPREL16},
13986   {"%half", BFD_RELOC_16},
13987   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13988   {"%higher", BFD_RELOC_MIPS_HIGHER},
13989   {"%neg", BFD_RELOC_MIPS_SUB},
13990   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13991   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13992   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13993   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13994   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13995   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13996   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13997 #endif
13998   {"%hi", BFD_RELOC_HI16_S}
13999 };
14000
14001 static const struct percent_op_match mips16_percent_op[] =
14002 {
14003   {"%lo", BFD_RELOC_MIPS16_LO16},
14004   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14005   {"%got", BFD_RELOC_MIPS16_GOT16},
14006   {"%call16", BFD_RELOC_MIPS16_CALL16},
14007   {"%hi", BFD_RELOC_MIPS16_HI16_S}
14008 };
14009
14010
14011 /* Return true if *STR points to a relocation operator.  When returning true,
14012    move *STR over the operator and store its relocation code in *RELOC.
14013    Leave both *STR and *RELOC alone when returning false.  */
14014
14015 static bfd_boolean
14016 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14017 {
14018   const struct percent_op_match *percent_op;
14019   size_t limit, i;
14020
14021   if (mips_opts.mips16)
14022     {
14023       percent_op = mips16_percent_op;
14024       limit = ARRAY_SIZE (mips16_percent_op);
14025     }
14026   else
14027     {
14028       percent_op = mips_percent_op;
14029       limit = ARRAY_SIZE (mips_percent_op);
14030     }
14031
14032   for (i = 0; i < limit; i++)
14033     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14034       {
14035         int len = strlen (percent_op[i].str);
14036
14037         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14038           continue;
14039
14040         *str += strlen (percent_op[i].str);
14041         *reloc = percent_op[i].reloc;
14042
14043         /* Check whether the output BFD supports this relocation.
14044            If not, issue an error and fall back on something safe.  */
14045         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14046           {
14047             as_bad (_("relocation %s isn't supported by the current ABI"),
14048                     percent_op[i].str);
14049             *reloc = BFD_RELOC_UNUSED;
14050           }
14051         return TRUE;
14052       }
14053   return FALSE;
14054 }
14055
14056
14057 /* Parse string STR as a 16-bit relocatable operand.  Store the
14058    expression in *EP and the relocations in the array starting
14059    at RELOC.  Return the number of relocation operators used.
14060
14061    On exit, EXPR_END points to the first character after the expression.  */
14062
14063 static size_t
14064 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14065                        char *str)
14066 {
14067   bfd_reloc_code_real_type reversed_reloc[3];
14068   size_t reloc_index, i;
14069   int crux_depth, str_depth;
14070   char *crux;
14071
14072   /* Search for the start of the main expression, recoding relocations
14073      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14074      of the main expression and with CRUX_DEPTH containing the number
14075      of open brackets at that point.  */
14076   reloc_index = -1;
14077   str_depth = 0;
14078   do
14079     {
14080       reloc_index++;
14081       crux = str;
14082       crux_depth = str_depth;
14083
14084       /* Skip over whitespace and brackets, keeping count of the number
14085          of brackets.  */
14086       while (*str == ' ' || *str == '\t' || *str == '(')
14087         if (*str++ == '(')
14088           str_depth++;
14089     }
14090   while (*str == '%'
14091          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14092          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14093
14094   my_getExpression (ep, crux);
14095   str = expr_end;
14096
14097   /* Match every open bracket.  */
14098   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14099     if (*str++ == ')')
14100       crux_depth--;
14101
14102   if (crux_depth > 0)
14103     as_bad (_("unclosed '('"));
14104
14105   expr_end = str;
14106
14107   if (reloc_index != 0)
14108     {
14109       prev_reloc_op_frag = frag_now;
14110       for (i = 0; i < reloc_index; i++)
14111         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14112     }
14113
14114   return reloc_index;
14115 }
14116
14117 static void
14118 my_getExpression (expressionS *ep, char *str)
14119 {
14120   char *save_in;
14121
14122   save_in = input_line_pointer;
14123   input_line_pointer = str;
14124   expression (ep);
14125   expr_end = input_line_pointer;
14126   input_line_pointer = save_in;
14127 }
14128
14129 char *
14130 md_atof (int type, char *litP, int *sizeP)
14131 {
14132   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14133 }
14134
14135 void
14136 md_number_to_chars (char *buf, valueT val, int n)
14137 {
14138   if (target_big_endian)
14139     number_to_chars_bigendian (buf, val, n);
14140   else
14141     number_to_chars_littleendian (buf, val, n);
14142 }
14143 \f
14144 #ifdef OBJ_ELF
14145 static int support_64bit_objects(void)
14146 {
14147   const char **list, **l;
14148   int yes;
14149
14150   list = bfd_target_list ();
14151   for (l = list; *l != NULL; l++)
14152     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14153         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14154       break;
14155   yes = (*l != NULL);
14156   free (list);
14157   return yes;
14158 }
14159 #endif /* OBJ_ELF */
14160
14161 const char *md_shortopts = "O::g::G:";
14162
14163 enum options
14164   {
14165     OPTION_MARCH = OPTION_MD_BASE,
14166     OPTION_MTUNE,
14167     OPTION_MIPS1,
14168     OPTION_MIPS2,
14169     OPTION_MIPS3,
14170     OPTION_MIPS4,
14171     OPTION_MIPS5,
14172     OPTION_MIPS32,
14173     OPTION_MIPS64,
14174     OPTION_MIPS32R2,
14175     OPTION_MIPS64R2,
14176     OPTION_MIPS16,
14177     OPTION_NO_MIPS16,
14178     OPTION_MIPS3D,
14179     OPTION_NO_MIPS3D,
14180     OPTION_MDMX,
14181     OPTION_NO_MDMX,
14182     OPTION_DSP,
14183     OPTION_NO_DSP,
14184     OPTION_MT,
14185     OPTION_NO_MT,
14186     OPTION_SMARTMIPS,
14187     OPTION_NO_SMARTMIPS,
14188     OPTION_DSPR2,
14189     OPTION_NO_DSPR2,
14190     OPTION_MICROMIPS,
14191     OPTION_NO_MICROMIPS,
14192     OPTION_COMPAT_ARCH_BASE,
14193     OPTION_M4650,
14194     OPTION_NO_M4650,
14195     OPTION_M4010,
14196     OPTION_NO_M4010,
14197     OPTION_M4100,
14198     OPTION_NO_M4100,
14199     OPTION_M3900,
14200     OPTION_NO_M3900,
14201     OPTION_M7000_HILO_FIX,
14202     OPTION_MNO_7000_HILO_FIX, 
14203     OPTION_FIX_24K,
14204     OPTION_NO_FIX_24K,
14205     OPTION_FIX_LOONGSON2F_JUMP,
14206     OPTION_NO_FIX_LOONGSON2F_JUMP,
14207     OPTION_FIX_LOONGSON2F_NOP,
14208     OPTION_NO_FIX_LOONGSON2F_NOP,
14209     OPTION_FIX_VR4120,
14210     OPTION_NO_FIX_VR4120,
14211     OPTION_FIX_VR4130,
14212     OPTION_NO_FIX_VR4130,
14213     OPTION_FIX_CN63XXP1,
14214     OPTION_NO_FIX_CN63XXP1,
14215     OPTION_TRAP,
14216     OPTION_BREAK,
14217     OPTION_EB,
14218     OPTION_EL,
14219     OPTION_FP32,
14220     OPTION_GP32,
14221     OPTION_CONSTRUCT_FLOATS,
14222     OPTION_NO_CONSTRUCT_FLOATS,
14223     OPTION_FP64,
14224     OPTION_GP64,
14225     OPTION_RELAX_BRANCH,
14226     OPTION_NO_RELAX_BRANCH,
14227     OPTION_MSHARED,
14228     OPTION_MNO_SHARED,
14229     OPTION_MSYM32,
14230     OPTION_MNO_SYM32,
14231     OPTION_SOFT_FLOAT,
14232     OPTION_HARD_FLOAT,
14233     OPTION_SINGLE_FLOAT,
14234     OPTION_DOUBLE_FLOAT,
14235     OPTION_32,
14236 #ifdef OBJ_ELF
14237     OPTION_CALL_SHARED,
14238     OPTION_CALL_NONPIC,
14239     OPTION_NON_SHARED,
14240     OPTION_XGOT,
14241     OPTION_MABI,
14242     OPTION_N32,
14243     OPTION_64,
14244     OPTION_MDEBUG,
14245     OPTION_NO_MDEBUG,
14246     OPTION_PDR,
14247     OPTION_NO_PDR,
14248     OPTION_MVXWORKS_PIC,
14249 #endif /* OBJ_ELF */
14250     OPTION_END_OF_ENUM    
14251   };
14252   
14253 struct option md_longopts[] =
14254 {
14255   /* Options which specify architecture.  */
14256   {"march", required_argument, NULL, OPTION_MARCH},
14257   {"mtune", required_argument, NULL, OPTION_MTUNE},
14258   {"mips0", no_argument, NULL, OPTION_MIPS1},
14259   {"mips1", no_argument, NULL, OPTION_MIPS1},
14260   {"mips2", no_argument, NULL, OPTION_MIPS2},
14261   {"mips3", no_argument, NULL, OPTION_MIPS3},
14262   {"mips4", no_argument, NULL, OPTION_MIPS4},
14263   {"mips5", no_argument, NULL, OPTION_MIPS5},
14264   {"mips32", no_argument, NULL, OPTION_MIPS32},
14265   {"mips64", no_argument, NULL, OPTION_MIPS64},
14266   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
14267   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
14268
14269   /* Options which specify Application Specific Extensions (ASEs).  */
14270   {"mips16", no_argument, NULL, OPTION_MIPS16},
14271   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
14272   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
14273   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
14274   {"mdmx", no_argument, NULL, OPTION_MDMX},
14275   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
14276   {"mdsp", no_argument, NULL, OPTION_DSP},
14277   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
14278   {"mmt", no_argument, NULL, OPTION_MT},
14279   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
14280   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
14281   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
14282   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
14283   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
14284   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
14285   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
14286
14287   /* Old-style architecture options.  Don't add more of these.  */
14288   {"m4650", no_argument, NULL, OPTION_M4650},
14289   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
14290   {"m4010", no_argument, NULL, OPTION_M4010},
14291   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
14292   {"m4100", no_argument, NULL, OPTION_M4100},
14293   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
14294   {"m3900", no_argument, NULL, OPTION_M3900},
14295   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
14296
14297   /* Options which enable bug fixes.  */
14298   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
14299   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14300   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14301   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
14302   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
14303   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
14304   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
14305   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
14306   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
14307   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
14308   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
14309   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
14310   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
14311   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
14312   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
14313
14314   /* Miscellaneous options.  */
14315   {"trap", no_argument, NULL, OPTION_TRAP},
14316   {"no-break", no_argument, NULL, OPTION_TRAP},
14317   {"break", no_argument, NULL, OPTION_BREAK},
14318   {"no-trap", no_argument, NULL, OPTION_BREAK},
14319   {"EB", no_argument, NULL, OPTION_EB},
14320   {"EL", no_argument, NULL, OPTION_EL},
14321   {"mfp32", no_argument, NULL, OPTION_FP32},
14322   {"mgp32", no_argument, NULL, OPTION_GP32},
14323   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
14324   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
14325   {"mfp64", no_argument, NULL, OPTION_FP64},
14326   {"mgp64", no_argument, NULL, OPTION_GP64},
14327   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
14328   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
14329   {"mshared", no_argument, NULL, OPTION_MSHARED},
14330   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
14331   {"msym32", no_argument, NULL, OPTION_MSYM32},
14332   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
14333   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
14334   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
14335   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
14336   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
14337
14338   /* Strictly speaking this next option is ELF specific,
14339      but we allow it for other ports as well in order to
14340      make testing easier.  */
14341   {"32",          no_argument, NULL, OPTION_32},
14342   
14343   /* ELF-specific options.  */
14344 #ifdef OBJ_ELF
14345   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
14346   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
14347   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
14348   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
14349   {"xgot",        no_argument, NULL, OPTION_XGOT},
14350   {"mabi", required_argument, NULL, OPTION_MABI},
14351   {"n32",         no_argument, NULL, OPTION_N32},
14352   {"64",          no_argument, NULL, OPTION_64},
14353   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
14354   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
14355   {"mpdr", no_argument, NULL, OPTION_PDR},
14356   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
14357   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
14358 #endif /* OBJ_ELF */
14359
14360   {NULL, no_argument, NULL, 0}
14361 };
14362 size_t md_longopts_size = sizeof (md_longopts);
14363
14364 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14365    NEW_VALUE.  Warn if another value was already specified.  Note:
14366    we have to defer parsing the -march and -mtune arguments in order
14367    to handle 'from-abi' correctly, since the ABI might be specified
14368    in a later argument.  */
14369
14370 static void
14371 mips_set_option_string (const char **string_ptr, const char *new_value)
14372 {
14373   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14374     as_warn (_("A different %s was already specified, is now %s"),
14375              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14376              new_value);
14377
14378   *string_ptr = new_value;
14379 }
14380
14381 int
14382 md_parse_option (int c, char *arg)
14383 {
14384   switch (c)
14385     {
14386     case OPTION_CONSTRUCT_FLOATS:
14387       mips_disable_float_construction = 0;
14388       break;
14389
14390     case OPTION_NO_CONSTRUCT_FLOATS:
14391       mips_disable_float_construction = 1;
14392       break;
14393
14394     case OPTION_TRAP:
14395       mips_trap = 1;
14396       break;
14397
14398     case OPTION_BREAK:
14399       mips_trap = 0;
14400       break;
14401
14402     case OPTION_EB:
14403       target_big_endian = 1;
14404       break;
14405
14406     case OPTION_EL:
14407       target_big_endian = 0;
14408       break;
14409
14410     case 'O':
14411       if (arg == NULL)
14412         mips_optimize = 1;
14413       else if (arg[0] == '0')
14414         mips_optimize = 0;
14415       else if (arg[0] == '1')
14416         mips_optimize = 1;
14417       else
14418         mips_optimize = 2;
14419       break;
14420
14421     case 'g':
14422       if (arg == NULL)
14423         mips_debug = 2;
14424       else
14425         mips_debug = atoi (arg);
14426       break;
14427
14428     case OPTION_MIPS1:
14429       file_mips_isa = ISA_MIPS1;
14430       break;
14431
14432     case OPTION_MIPS2:
14433       file_mips_isa = ISA_MIPS2;
14434       break;
14435
14436     case OPTION_MIPS3:
14437       file_mips_isa = ISA_MIPS3;
14438       break;
14439
14440     case OPTION_MIPS4:
14441       file_mips_isa = ISA_MIPS4;
14442       break;
14443
14444     case OPTION_MIPS5:
14445       file_mips_isa = ISA_MIPS5;
14446       break;
14447
14448     case OPTION_MIPS32:
14449       file_mips_isa = ISA_MIPS32;
14450       break;
14451
14452     case OPTION_MIPS32R2:
14453       file_mips_isa = ISA_MIPS32R2;
14454       break;
14455
14456     case OPTION_MIPS64R2:
14457       file_mips_isa = ISA_MIPS64R2;
14458       break;
14459
14460     case OPTION_MIPS64:
14461       file_mips_isa = ISA_MIPS64;
14462       break;
14463
14464     case OPTION_MTUNE:
14465       mips_set_option_string (&mips_tune_string, arg);
14466       break;
14467
14468     case OPTION_MARCH:
14469       mips_set_option_string (&mips_arch_string, arg);
14470       break;
14471
14472     case OPTION_M4650:
14473       mips_set_option_string (&mips_arch_string, "4650");
14474       mips_set_option_string (&mips_tune_string, "4650");
14475       break;
14476
14477     case OPTION_NO_M4650:
14478       break;
14479
14480     case OPTION_M4010:
14481       mips_set_option_string (&mips_arch_string, "4010");
14482       mips_set_option_string (&mips_tune_string, "4010");
14483       break;
14484
14485     case OPTION_NO_M4010:
14486       break;
14487
14488     case OPTION_M4100:
14489       mips_set_option_string (&mips_arch_string, "4100");
14490       mips_set_option_string (&mips_tune_string, "4100");
14491       break;
14492
14493     case OPTION_NO_M4100:
14494       break;
14495
14496     case OPTION_M3900:
14497       mips_set_option_string (&mips_arch_string, "3900");
14498       mips_set_option_string (&mips_tune_string, "3900");
14499       break;
14500
14501     case OPTION_NO_M3900:
14502       break;
14503
14504     case OPTION_MDMX:
14505       mips_opts.ase_mdmx = 1;
14506       break;
14507
14508     case OPTION_NO_MDMX:
14509       mips_opts.ase_mdmx = 0;
14510       break;
14511
14512     case OPTION_DSP:
14513       mips_opts.ase_dsp = 1;
14514       mips_opts.ase_dspr2 = 0;
14515       break;
14516
14517     case OPTION_NO_DSP:
14518       mips_opts.ase_dsp = 0;
14519       mips_opts.ase_dspr2 = 0;
14520       break;
14521
14522     case OPTION_DSPR2:
14523       mips_opts.ase_dspr2 = 1;
14524       mips_opts.ase_dsp = 1;
14525       break;
14526
14527     case OPTION_NO_DSPR2:
14528       mips_opts.ase_dspr2 = 0;
14529       mips_opts.ase_dsp = 0;
14530       break;
14531
14532     case OPTION_MT:
14533       mips_opts.ase_mt = 1;
14534       break;
14535
14536     case OPTION_NO_MT:
14537       mips_opts.ase_mt = 0;
14538       break;
14539
14540     case OPTION_MICROMIPS:
14541       if (mips_opts.mips16 == 1)
14542         {
14543           as_bad (_("-mmicromips cannot be used with -mips16"));
14544           return 0;
14545         }
14546       mips_opts.micromips = 1;
14547       mips_no_prev_insn ();
14548       break;
14549
14550     case OPTION_NO_MICROMIPS:
14551       mips_opts.micromips = 0;
14552       mips_no_prev_insn ();
14553       break;
14554
14555     case OPTION_MIPS16:
14556       if (mips_opts.micromips == 1)
14557         {
14558           as_bad (_("-mips16 cannot be used with -micromips"));
14559           return 0;
14560         }
14561       mips_opts.mips16 = 1;
14562       mips_no_prev_insn ();
14563       break;
14564
14565     case OPTION_NO_MIPS16:
14566       mips_opts.mips16 = 0;
14567       mips_no_prev_insn ();
14568       break;
14569
14570     case OPTION_MIPS3D:
14571       mips_opts.ase_mips3d = 1;
14572       break;
14573
14574     case OPTION_NO_MIPS3D:
14575       mips_opts.ase_mips3d = 0;
14576       break;
14577
14578     case OPTION_SMARTMIPS:
14579       mips_opts.ase_smartmips = 1;
14580       break;
14581
14582     case OPTION_NO_SMARTMIPS:
14583       mips_opts.ase_smartmips = 0;
14584       break;
14585
14586     case OPTION_FIX_24K:
14587       mips_fix_24k = 1;
14588       break;
14589
14590     case OPTION_NO_FIX_24K:
14591       mips_fix_24k = 0;
14592       break;
14593
14594     case OPTION_FIX_LOONGSON2F_JUMP:
14595       mips_fix_loongson2f_jump = TRUE;
14596       break;
14597
14598     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14599       mips_fix_loongson2f_jump = FALSE;
14600       break;
14601
14602     case OPTION_FIX_LOONGSON2F_NOP:
14603       mips_fix_loongson2f_nop = TRUE;
14604       break;
14605
14606     case OPTION_NO_FIX_LOONGSON2F_NOP:
14607       mips_fix_loongson2f_nop = FALSE;
14608       break;
14609
14610     case OPTION_FIX_VR4120:
14611       mips_fix_vr4120 = 1;
14612       break;
14613
14614     case OPTION_NO_FIX_VR4120:
14615       mips_fix_vr4120 = 0;
14616       break;
14617
14618     case OPTION_FIX_VR4130:
14619       mips_fix_vr4130 = 1;
14620       break;
14621
14622     case OPTION_NO_FIX_VR4130:
14623       mips_fix_vr4130 = 0;
14624       break;
14625
14626     case OPTION_FIX_CN63XXP1:
14627       mips_fix_cn63xxp1 = TRUE;
14628       break;
14629
14630     case OPTION_NO_FIX_CN63XXP1:
14631       mips_fix_cn63xxp1 = FALSE;
14632       break;
14633
14634     case OPTION_RELAX_BRANCH:
14635       mips_relax_branch = 1;
14636       break;
14637
14638     case OPTION_NO_RELAX_BRANCH:
14639       mips_relax_branch = 0;
14640       break;
14641
14642     case OPTION_MSHARED:
14643       mips_in_shared = TRUE;
14644       break;
14645
14646     case OPTION_MNO_SHARED:
14647       mips_in_shared = FALSE;
14648       break;
14649
14650     case OPTION_MSYM32:
14651       mips_opts.sym32 = TRUE;
14652       break;
14653
14654     case OPTION_MNO_SYM32:
14655       mips_opts.sym32 = FALSE;
14656       break;
14657
14658 #ifdef OBJ_ELF
14659       /* When generating ELF code, we permit -KPIC and -call_shared to
14660          select SVR4_PIC, and -non_shared to select no PIC.  This is
14661          intended to be compatible with Irix 5.  */
14662     case OPTION_CALL_SHARED:
14663       if (!IS_ELF)
14664         {
14665           as_bad (_("-call_shared is supported only for ELF format"));
14666           return 0;
14667         }
14668       mips_pic = SVR4_PIC;
14669       mips_abicalls = TRUE;
14670       break;
14671
14672     case OPTION_CALL_NONPIC:
14673       if (!IS_ELF)
14674         {
14675           as_bad (_("-call_nonpic is supported only for ELF format"));
14676           return 0;
14677         }
14678       mips_pic = NO_PIC;
14679       mips_abicalls = TRUE;
14680       break;
14681
14682     case OPTION_NON_SHARED:
14683       if (!IS_ELF)
14684         {
14685           as_bad (_("-non_shared is supported only for ELF format"));
14686           return 0;
14687         }
14688       mips_pic = NO_PIC;
14689       mips_abicalls = FALSE;
14690       break;
14691
14692       /* The -xgot option tells the assembler to use 32 bit offsets
14693          when accessing the got in SVR4_PIC mode.  It is for Irix
14694          compatibility.  */
14695     case OPTION_XGOT:
14696       mips_big_got = 1;
14697       break;
14698 #endif /* OBJ_ELF */
14699
14700     case 'G':
14701       g_switch_value = atoi (arg);
14702       g_switch_seen = 1;
14703       break;
14704
14705       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14706          and -mabi=64.  */
14707     case OPTION_32:
14708       if (IS_ELF)
14709         mips_abi = O32_ABI;
14710       /* We silently ignore -32 for non-ELF targets.  This greatly
14711          simplifies the construction of the MIPS GAS test cases.  */
14712       break;
14713
14714 #ifdef OBJ_ELF
14715     case OPTION_N32:
14716       if (!IS_ELF)
14717         {
14718           as_bad (_("-n32 is supported for ELF format only"));
14719           return 0;
14720         }
14721       mips_abi = N32_ABI;
14722       break;
14723
14724     case OPTION_64:
14725       if (!IS_ELF)
14726         {
14727           as_bad (_("-64 is supported for ELF format only"));
14728           return 0;
14729         }
14730       mips_abi = N64_ABI;
14731       if (!support_64bit_objects())
14732         as_fatal (_("No compiled in support for 64 bit object file format"));
14733       break;
14734 #endif /* OBJ_ELF */
14735
14736     case OPTION_GP32:
14737       file_mips_gp32 = 1;
14738       break;
14739
14740     case OPTION_GP64:
14741       file_mips_gp32 = 0;
14742       break;
14743
14744     case OPTION_FP32:
14745       file_mips_fp32 = 1;
14746       break;
14747
14748     case OPTION_FP64:
14749       file_mips_fp32 = 0;
14750       break;
14751
14752     case OPTION_SINGLE_FLOAT:
14753       file_mips_single_float = 1;
14754       break;
14755
14756     case OPTION_DOUBLE_FLOAT:
14757       file_mips_single_float = 0;
14758       break;
14759
14760     case OPTION_SOFT_FLOAT:
14761       file_mips_soft_float = 1;
14762       break;
14763
14764     case OPTION_HARD_FLOAT:
14765       file_mips_soft_float = 0;
14766       break;
14767
14768 #ifdef OBJ_ELF
14769     case OPTION_MABI:
14770       if (!IS_ELF)
14771         {
14772           as_bad (_("-mabi is supported for ELF format only"));
14773           return 0;
14774         }
14775       if (strcmp (arg, "32") == 0)
14776         mips_abi = O32_ABI;
14777       else if (strcmp (arg, "o64") == 0)
14778         mips_abi = O64_ABI;
14779       else if (strcmp (arg, "n32") == 0)
14780         mips_abi = N32_ABI;
14781       else if (strcmp (arg, "64") == 0)
14782         {
14783           mips_abi = N64_ABI;
14784           if (! support_64bit_objects())
14785             as_fatal (_("No compiled in support for 64 bit object file "
14786                         "format"));
14787         }
14788       else if (strcmp (arg, "eabi") == 0)
14789         mips_abi = EABI_ABI;
14790       else
14791         {
14792           as_fatal (_("invalid abi -mabi=%s"), arg);
14793           return 0;
14794         }
14795       break;
14796 #endif /* OBJ_ELF */
14797
14798     case OPTION_M7000_HILO_FIX:
14799       mips_7000_hilo_fix = TRUE;
14800       break;
14801
14802     case OPTION_MNO_7000_HILO_FIX:
14803       mips_7000_hilo_fix = FALSE;
14804       break;
14805
14806 #ifdef OBJ_ELF
14807     case OPTION_MDEBUG:
14808       mips_flag_mdebug = TRUE;
14809       break;
14810
14811     case OPTION_NO_MDEBUG:
14812       mips_flag_mdebug = FALSE;
14813       break;
14814
14815     case OPTION_PDR:
14816       mips_flag_pdr = TRUE;
14817       break;
14818
14819     case OPTION_NO_PDR:
14820       mips_flag_pdr = FALSE;
14821       break;
14822
14823     case OPTION_MVXWORKS_PIC:
14824       mips_pic = VXWORKS_PIC;
14825       break;
14826 #endif /* OBJ_ELF */
14827
14828     default:
14829       return 0;
14830     }
14831
14832     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14833
14834   return 1;
14835 }
14836 \f
14837 /* Set up globals to generate code for the ISA or processor
14838    described by INFO.  */
14839
14840 static void
14841 mips_set_architecture (const struct mips_cpu_info *info)
14842 {
14843   if (info != 0)
14844     {
14845       file_mips_arch = info->cpu;
14846       mips_opts.arch = info->cpu;
14847       mips_opts.isa = info->isa;
14848     }
14849 }
14850
14851
14852 /* Likewise for tuning.  */
14853
14854 static void
14855 mips_set_tune (const struct mips_cpu_info *info)
14856 {
14857   if (info != 0)
14858     mips_tune = info->cpu;
14859 }
14860
14861
14862 void
14863 mips_after_parse_args (void)
14864 {
14865   const struct mips_cpu_info *arch_info = 0;
14866   const struct mips_cpu_info *tune_info = 0;
14867
14868   /* GP relative stuff not working for PE */
14869   if (strncmp (TARGET_OS, "pe", 2) == 0)
14870     {
14871       if (g_switch_seen && g_switch_value != 0)
14872         as_bad (_("-G not supported in this configuration."));
14873       g_switch_value = 0;
14874     }
14875
14876   if (mips_abi == NO_ABI)
14877     mips_abi = MIPS_DEFAULT_ABI;
14878
14879   /* The following code determines the architecture and register size.
14880      Similar code was added to GCC 3.3 (see override_options() in
14881      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14882      as much as possible.  */
14883
14884   if (mips_arch_string != 0)
14885     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14886
14887   if (file_mips_isa != ISA_UNKNOWN)
14888     {
14889       /* Handle -mipsN.  At this point, file_mips_isa contains the
14890          ISA level specified by -mipsN, while arch_info->isa contains
14891          the -march selection (if any).  */
14892       if (arch_info != 0)
14893         {
14894           /* -march takes precedence over -mipsN, since it is more descriptive.
14895              There's no harm in specifying both as long as the ISA levels
14896              are the same.  */
14897           if (file_mips_isa != arch_info->isa)
14898             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
14899                     mips_cpu_info_from_isa (file_mips_isa)->name,
14900                     mips_cpu_info_from_isa (arch_info->isa)->name);
14901         }
14902       else
14903         arch_info = mips_cpu_info_from_isa (file_mips_isa);
14904     }
14905
14906   if (arch_info == 0)
14907     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14908
14909   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14910     as_bad (_("-march=%s is not compatible with the selected ABI"),
14911             arch_info->name);
14912
14913   mips_set_architecture (arch_info);
14914
14915   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
14916   if (mips_tune_string != 0)
14917     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14918
14919   if (tune_info == 0)
14920     mips_set_tune (arch_info);
14921   else
14922     mips_set_tune (tune_info);
14923
14924   if (file_mips_gp32 >= 0)
14925     {
14926       /* The user specified the size of the integer registers.  Make sure
14927          it agrees with the ABI and ISA.  */
14928       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
14929         as_bad (_("-mgp64 used with a 32-bit processor"));
14930       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
14931         as_bad (_("-mgp32 used with a 64-bit ABI"));
14932       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
14933         as_bad (_("-mgp64 used with a 32-bit ABI"));
14934     }
14935   else
14936     {
14937       /* Infer the integer register size from the ABI and processor.
14938          Restrict ourselves to 32-bit registers if that's all the
14939          processor has, or if the ABI cannot handle 64-bit registers.  */
14940       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
14941                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
14942     }
14943
14944   switch (file_mips_fp32)
14945     {
14946     default:
14947     case -1:
14948       /* No user specified float register size.
14949          ??? GAS treats single-float processors as though they had 64-bit
14950          float registers (although it complains when double-precision
14951          instructions are used).  As things stand, saying they have 32-bit
14952          registers would lead to spurious "register must be even" messages.
14953          So here we assume float registers are never smaller than the
14954          integer ones.  */
14955       if (file_mips_gp32 == 0)
14956         /* 64-bit integer registers implies 64-bit float registers.  */
14957         file_mips_fp32 = 0;
14958       else if ((mips_opts.ase_mips3d > 0 || mips_opts.ase_mdmx > 0)
14959                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
14960         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
14961         file_mips_fp32 = 0;
14962       else
14963         /* 32-bit float registers.  */
14964         file_mips_fp32 = 1;
14965       break;
14966
14967     /* The user specified the size of the float registers.  Check if it
14968        agrees with the ABI and ISA.  */
14969     case 0:
14970       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14971         as_bad (_("-mfp64 used with a 32-bit fpu"));
14972       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
14973                && !ISA_HAS_MXHC1 (mips_opts.isa))
14974         as_warn (_("-mfp64 used with a 32-bit ABI"));
14975       break;
14976     case 1:
14977       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14978         as_warn (_("-mfp32 used with a 64-bit ABI"));
14979       break;
14980     }
14981
14982   /* End of GCC-shared inference code.  */
14983
14984   /* This flag is set when we have a 64-bit capable CPU but use only
14985      32-bit wide registers.  Note that EABI does not use it.  */
14986   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14987       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14988           || mips_abi == O32_ABI))
14989     mips_32bitmode = 1;
14990
14991   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14992     as_bad (_("trap exception not supported at ISA 1"));
14993
14994   /* If the selected architecture includes support for ASEs, enable
14995      generation of code for them.  */
14996   if (mips_opts.mips16 == -1)
14997     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14998   if (mips_opts.micromips == -1)
14999     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15000   if (mips_opts.ase_mips3d == -1)
15001     mips_opts.ase_mips3d = ((arch_info->flags & MIPS_CPU_ASE_MIPS3D)
15002                             && file_mips_fp32 == 0) ? 1 : 0;
15003   if (mips_opts.ase_mips3d && file_mips_fp32 == 1)
15004     as_bad (_("-mfp32 used with -mips3d"));
15005
15006   if (mips_opts.ase_mdmx == -1)
15007     mips_opts.ase_mdmx = ((arch_info->flags & MIPS_CPU_ASE_MDMX)
15008                           && file_mips_fp32 == 0) ? 1 : 0;
15009   if (mips_opts.ase_mdmx && file_mips_fp32 == 1)
15010     as_bad (_("-mfp32 used with -mdmx"));
15011
15012   if (mips_opts.ase_smartmips == -1)
15013     mips_opts.ase_smartmips = (arch_info->flags & MIPS_CPU_ASE_SMARTMIPS) ? 1 : 0;
15014   if (mips_opts.ase_smartmips && !ISA_SUPPORTS_SMARTMIPS)
15015     as_warn (_("%s ISA does not support SmartMIPS"), 
15016              mips_cpu_info_from_isa (mips_opts.isa)->name);
15017
15018   if (mips_opts.ase_dsp == -1)
15019     mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15020   if (mips_opts.ase_dsp && !ISA_SUPPORTS_DSP_ASE)
15021     as_warn (_("%s ISA does not support DSP ASE"), 
15022              mips_cpu_info_from_isa (mips_opts.isa)->name);
15023
15024   if (mips_opts.ase_dspr2 == -1)
15025     {
15026       mips_opts.ase_dspr2 = (arch_info->flags & MIPS_CPU_ASE_DSPR2) ? 1 : 0;
15027       mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15028     }
15029   if (mips_opts.ase_dspr2 && !ISA_SUPPORTS_DSPR2_ASE)
15030     as_warn (_("%s ISA does not support DSP R2 ASE"),
15031              mips_cpu_info_from_isa (mips_opts.isa)->name);
15032
15033   if (mips_opts.ase_mt == -1)
15034     mips_opts.ase_mt = (arch_info->flags & MIPS_CPU_ASE_MT) ? 1 : 0;
15035   if (mips_opts.ase_mt && !ISA_SUPPORTS_MT_ASE)
15036     as_warn (_("%s ISA does not support MT ASE"),
15037              mips_cpu_info_from_isa (mips_opts.isa)->name);
15038
15039   file_mips_isa = mips_opts.isa;
15040   file_ase_mips3d = mips_opts.ase_mips3d;
15041   file_ase_mdmx = mips_opts.ase_mdmx;
15042   file_ase_smartmips = mips_opts.ase_smartmips;
15043   file_ase_dsp = mips_opts.ase_dsp;
15044   file_ase_dspr2 = mips_opts.ase_dspr2;
15045   file_ase_mt = mips_opts.ase_mt;
15046   mips_opts.gp32 = file_mips_gp32;
15047   mips_opts.fp32 = file_mips_fp32;
15048   mips_opts.soft_float = file_mips_soft_float;
15049   mips_opts.single_float = file_mips_single_float;
15050
15051   if (mips_flag_mdebug < 0)
15052     {
15053 #ifdef OBJ_MAYBE_ECOFF
15054       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
15055         mips_flag_mdebug = 1;
15056       else
15057 #endif /* OBJ_MAYBE_ECOFF */
15058         mips_flag_mdebug = 0;
15059     }
15060 }
15061 \f
15062 void
15063 mips_init_after_args (void)
15064 {
15065   /* initialize opcodes */
15066   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15067   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15068 }
15069
15070 long
15071 md_pcrel_from (fixS *fixP)
15072 {
15073   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15074   switch (fixP->fx_r_type)
15075     {
15076     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15077     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15078       /* Return the address of the delay slot.  */
15079       return addr + 2;
15080
15081     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15082     case BFD_RELOC_MICROMIPS_JMP:
15083     case BFD_RELOC_16_PCREL_S2:
15084     case BFD_RELOC_MIPS_JMP:
15085       /* Return the address of the delay slot.  */
15086       return addr + 4;
15087
15088     default:
15089       /* We have no relocation type for PC relative MIPS16 instructions.  */
15090       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15091         as_bad_where (fixP->fx_file, fixP->fx_line,
15092                       _("PC relative MIPS16 instruction references a different section"));
15093       return addr;
15094     }
15095 }
15096
15097 /* This is called before the symbol table is processed.  In order to
15098    work with gcc when using mips-tfile, we must keep all local labels.
15099    However, in other cases, we want to discard them.  If we were
15100    called with -g, but we didn't see any debugging information, it may
15101    mean that gcc is smuggling debugging information through to
15102    mips-tfile, in which case we must generate all local labels.  */
15103
15104 void
15105 mips_frob_file_before_adjust (void)
15106 {
15107 #ifndef NO_ECOFF_DEBUGGING
15108   if (ECOFF_DEBUGGING
15109       && mips_debug != 0
15110       && ! ecoff_debugging_seen)
15111     flag_keep_locals = 1;
15112 #endif
15113 }
15114
15115 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15116    the corresponding LO16 reloc.  This is called before md_apply_fix and
15117    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15118    relocation operators.
15119
15120    For our purposes, a %lo() expression matches a %got() or %hi()
15121    expression if:
15122
15123       (a) it refers to the same symbol; and
15124       (b) the offset applied in the %lo() expression is no lower than
15125           the offset applied in the %got() or %hi().
15126
15127    (b) allows us to cope with code like:
15128
15129         lui     $4,%hi(foo)
15130         lh      $4,%lo(foo+2)($4)
15131
15132    ...which is legal on RELA targets, and has a well-defined behaviour
15133    if the user knows that adding 2 to "foo" will not induce a carry to
15134    the high 16 bits.
15135
15136    When several %lo()s match a particular %got() or %hi(), we use the
15137    following rules to distinguish them:
15138
15139      (1) %lo()s with smaller offsets are a better match than %lo()s with
15140          higher offsets.
15141
15142      (2) %lo()s with no matching %got() or %hi() are better than those
15143          that already have a matching %got() or %hi().
15144
15145      (3) later %lo()s are better than earlier %lo()s.
15146
15147    These rules are applied in order.
15148
15149    (1) means, among other things, that %lo()s with identical offsets are
15150    chosen if they exist.
15151
15152    (2) means that we won't associate several high-part relocations with
15153    the same low-part relocation unless there's no alternative.  Having
15154    several high parts for the same low part is a GNU extension; this rule
15155    allows careful users to avoid it.
15156
15157    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15158    with the last high-part relocation being at the front of the list.
15159    It therefore makes sense to choose the last matching low-part
15160    relocation, all other things being equal.  It's also easier
15161    to code that way.  */
15162
15163 void
15164 mips_frob_file (void)
15165 {
15166   struct mips_hi_fixup *l;
15167   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15168
15169   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15170     {
15171       segment_info_type *seginfo;
15172       bfd_boolean matched_lo_p;
15173       fixS **hi_pos, **lo_pos, **pos;
15174
15175       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15176
15177       /* If a GOT16 relocation turns out to be against a global symbol,
15178          there isn't supposed to be a matching LO.  */
15179       if (got16_reloc_p (l->fixp->fx_r_type)
15180           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
15181         continue;
15182
15183       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15184       if (fixup_has_matching_lo_p (l->fixp))
15185         continue;
15186
15187       seginfo = seg_info (l->seg);
15188
15189       /* Set HI_POS to the position of this relocation in the chain.
15190          Set LO_POS to the position of the chosen low-part relocation.
15191          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15192          relocation that matches an immediately-preceding high-part
15193          relocation.  */
15194       hi_pos = NULL;
15195       lo_pos = NULL;
15196       matched_lo_p = FALSE;
15197       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15198
15199       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15200         {
15201           if (*pos == l->fixp)
15202             hi_pos = pos;
15203
15204           if ((*pos)->fx_r_type == looking_for_rtype
15205               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15206               && (*pos)->fx_offset >= l->fixp->fx_offset
15207               && (lo_pos == NULL
15208                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15209                   || (!matched_lo_p
15210                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15211             lo_pos = pos;
15212
15213           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15214                           && fixup_has_matching_lo_p (*pos));
15215         }
15216
15217       /* If we found a match, remove the high-part relocation from its
15218          current position and insert it before the low-part relocation.
15219          Make the offsets match so that fixup_has_matching_lo_p()
15220          will return true.
15221
15222          We don't warn about unmatched high-part relocations since some
15223          versions of gcc have been known to emit dead "lui ...%hi(...)"
15224          instructions.  */
15225       if (lo_pos != NULL)
15226         {
15227           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15228           if (l->fixp->fx_next != *lo_pos)
15229             {
15230               *hi_pos = l->fixp->fx_next;
15231               l->fixp->fx_next = *lo_pos;
15232               *lo_pos = l->fixp;
15233             }
15234         }
15235     }
15236 }
15237
15238 /* We may have combined relocations without symbols in the N32/N64 ABI.
15239    We have to prevent gas from dropping them.  */
15240
15241 int
15242 mips_force_relocation (fixS *fixp)
15243 {
15244   if (generic_force_reloc (fixp))
15245     return 1;
15246
15247   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15248      so that the linker relaxation can update targets.  */
15249   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15250       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15251       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15252     return 1;
15253
15254   if (HAVE_NEWABI
15255       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
15256       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
15257           || hi16_reloc_p (fixp->fx_r_type)
15258           || lo16_reloc_p (fixp->fx_r_type)))
15259     return 1;
15260
15261   return 0;
15262 }
15263
15264 /* Apply a fixup to the object file.  */
15265
15266 void
15267 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15268 {
15269   bfd_byte *buf;
15270   long insn;
15271   reloc_howto_type *howto;
15272
15273   /* We ignore generic BFD relocations we don't know about.  */
15274   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15275   if (! howto)
15276     return;
15277
15278   gas_assert (fixP->fx_size == 2
15279               || fixP->fx_size == 4
15280               || fixP->fx_r_type == BFD_RELOC_16
15281               || fixP->fx_r_type == BFD_RELOC_64
15282               || fixP->fx_r_type == BFD_RELOC_CTOR
15283               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15284               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15285               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15286               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15287               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15288
15289   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
15290
15291   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15292               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15293               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15294               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
15295
15296   /* Don't treat parts of a composite relocation as done.  There are two
15297      reasons for this:
15298
15299      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15300          should nevertheless be emitted if the first part is.
15301
15302      (2) In normal usage, composite relocations are never assembly-time
15303          constants.  The easiest way of dealing with the pathological
15304          exceptions is to generate a relocation against STN_UNDEF and
15305          leave everything up to the linker.  */
15306   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15307     fixP->fx_done = 1;
15308
15309   switch (fixP->fx_r_type)
15310     {
15311     case BFD_RELOC_MIPS_TLS_GD:
15312     case BFD_RELOC_MIPS_TLS_LDM:
15313     case BFD_RELOC_MIPS_TLS_DTPREL32:
15314     case BFD_RELOC_MIPS_TLS_DTPREL64:
15315     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15316     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15317     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15318     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15319     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15320     case BFD_RELOC_MICROMIPS_TLS_GD:
15321     case BFD_RELOC_MICROMIPS_TLS_LDM:
15322     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15323     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15324     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15325     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15326     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15327       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15328       /* fall through */
15329
15330     case BFD_RELOC_MIPS_JMP:
15331     case BFD_RELOC_MIPS_SHIFT5:
15332     case BFD_RELOC_MIPS_SHIFT6:
15333     case BFD_RELOC_MIPS_GOT_DISP:
15334     case BFD_RELOC_MIPS_GOT_PAGE:
15335     case BFD_RELOC_MIPS_GOT_OFST:
15336     case BFD_RELOC_MIPS_SUB:
15337     case BFD_RELOC_MIPS_INSERT_A:
15338     case BFD_RELOC_MIPS_INSERT_B:
15339     case BFD_RELOC_MIPS_DELETE:
15340     case BFD_RELOC_MIPS_HIGHEST:
15341     case BFD_RELOC_MIPS_HIGHER:
15342     case BFD_RELOC_MIPS_SCN_DISP:
15343     case BFD_RELOC_MIPS_REL16:
15344     case BFD_RELOC_MIPS_RELGOT:
15345     case BFD_RELOC_MIPS_JALR:
15346     case BFD_RELOC_HI16:
15347     case BFD_RELOC_HI16_S:
15348     case BFD_RELOC_GPREL16:
15349     case BFD_RELOC_MIPS_LITERAL:
15350     case BFD_RELOC_MIPS_CALL16:
15351     case BFD_RELOC_MIPS_GOT16:
15352     case BFD_RELOC_GPREL32:
15353     case BFD_RELOC_MIPS_GOT_HI16:
15354     case BFD_RELOC_MIPS_GOT_LO16:
15355     case BFD_RELOC_MIPS_CALL_HI16:
15356     case BFD_RELOC_MIPS_CALL_LO16:
15357     case BFD_RELOC_MIPS16_GPREL:
15358     case BFD_RELOC_MIPS16_GOT16:
15359     case BFD_RELOC_MIPS16_CALL16:
15360     case BFD_RELOC_MIPS16_HI16:
15361     case BFD_RELOC_MIPS16_HI16_S:
15362     case BFD_RELOC_MIPS16_JMP:
15363     case BFD_RELOC_MICROMIPS_JMP:
15364     case BFD_RELOC_MICROMIPS_GOT_DISP:
15365     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15366     case BFD_RELOC_MICROMIPS_GOT_OFST:
15367     case BFD_RELOC_MICROMIPS_SUB:
15368     case BFD_RELOC_MICROMIPS_HIGHEST:
15369     case BFD_RELOC_MICROMIPS_HIGHER:
15370     case BFD_RELOC_MICROMIPS_SCN_DISP:
15371     case BFD_RELOC_MICROMIPS_JALR:
15372     case BFD_RELOC_MICROMIPS_HI16:
15373     case BFD_RELOC_MICROMIPS_HI16_S:
15374     case BFD_RELOC_MICROMIPS_GPREL16:
15375     case BFD_RELOC_MICROMIPS_LITERAL:
15376     case BFD_RELOC_MICROMIPS_CALL16:
15377     case BFD_RELOC_MICROMIPS_GOT16:
15378     case BFD_RELOC_MICROMIPS_GOT_HI16:
15379     case BFD_RELOC_MICROMIPS_GOT_LO16:
15380     case BFD_RELOC_MICROMIPS_CALL_HI16:
15381     case BFD_RELOC_MICROMIPS_CALL_LO16:
15382       /* Nothing needed to do.  The value comes from the reloc entry.  */
15383       break;
15384
15385     case BFD_RELOC_64:
15386       /* This is handled like BFD_RELOC_32, but we output a sign
15387          extended value if we are only 32 bits.  */
15388       if (fixP->fx_done)
15389         {
15390           if (8 <= sizeof (valueT))
15391             md_number_to_chars ((char *) buf, *valP, 8);
15392           else
15393             {
15394               valueT hiv;
15395
15396               if ((*valP & 0x80000000) != 0)
15397                 hiv = 0xffffffff;
15398               else
15399                 hiv = 0;
15400               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
15401                                   *valP, 4);
15402               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
15403                                   hiv, 4);
15404             }
15405         }
15406       break;
15407
15408     case BFD_RELOC_RVA:
15409     case BFD_RELOC_32:
15410     case BFD_RELOC_16:
15411       /* If we are deleting this reloc entry, we must fill in the
15412          value now.  This can happen if we have a .word which is not
15413          resolved when it appears but is later defined.  */
15414       if (fixP->fx_done)
15415         md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
15416       break;
15417
15418     case BFD_RELOC_LO16:
15419     case BFD_RELOC_MIPS16_LO16:
15420     case BFD_RELOC_MICROMIPS_LO16:
15421       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
15422          may be safe to remove, but if so it's not obvious.  */
15423       /* When handling an embedded PIC switch statement, we can wind
15424          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
15425       if (fixP->fx_done)
15426         {
15427           if (*valP + 0x8000 > 0xffff)
15428             as_bad_where (fixP->fx_file, fixP->fx_line,
15429                           _("relocation overflow"));
15430           /* 32-bit microMIPS instructions are divided into two halfwords.
15431              Relocations always refer to the second halfword, regardless
15432              of endianness.  */
15433           if (target_big_endian || fixP->fx_r_type == BFD_RELOC_MICROMIPS_LO16)
15434             buf += 2;
15435           md_number_to_chars ((char *) buf, *valP, 2);
15436         }
15437       break;
15438
15439     case BFD_RELOC_16_PCREL_S2:
15440       if ((*valP & 0x3) != 0)
15441         as_bad_where (fixP->fx_file, fixP->fx_line,
15442                       _("Branch to misaligned address (%lx)"), (long) *valP);
15443
15444       /* We need to save the bits in the instruction since fixup_segment()
15445          might be deleting the relocation entry (i.e., a branch within
15446          the current segment).  */
15447       if (! fixP->fx_done)
15448         break;
15449
15450       /* Update old instruction data.  */
15451       if (target_big_endian)
15452         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
15453       else
15454         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
15455
15456       if (*valP + 0x20000 <= 0x3ffff)
15457         {
15458           insn |= (*valP >> 2) & 0xffff;
15459           md_number_to_chars ((char *) buf, insn, 4);
15460         }
15461       else if (mips_pic == NO_PIC
15462                && fixP->fx_done
15463                && fixP->fx_frag->fr_address >= text_section->vma
15464                && (fixP->fx_frag->fr_address
15465                    < text_section->vma + bfd_get_section_size (text_section))
15466                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15467                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15468                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15469         {
15470           /* The branch offset is too large.  If this is an
15471              unconditional branch, and we are not generating PIC code,
15472              we can convert it to an absolute jump instruction.  */
15473           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15474             insn = 0x0c000000;  /* jal */
15475           else
15476             insn = 0x08000000;  /* j */
15477           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15478           fixP->fx_done = 0;
15479           fixP->fx_addsy = section_symbol (text_section);
15480           *valP += md_pcrel_from (fixP);
15481           md_number_to_chars ((char *) buf, insn, 4);
15482         }
15483       else
15484         {
15485           /* If we got here, we have branch-relaxation disabled,
15486              and there's nothing we can do to fix this instruction
15487              without turning it into a longer sequence.  */
15488           as_bad_where (fixP->fx_file, fixP->fx_line,
15489                         _("Branch out of range"));
15490         }
15491       break;
15492
15493     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15494     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15495     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15496       /* We adjust the offset back to even.  */
15497       if ((*valP & 0x1) != 0)
15498         --(*valP);
15499
15500       if (! fixP->fx_done)
15501         break;
15502
15503       /* Should never visit here, because we keep the relocation.  */
15504       abort ();
15505       break;
15506
15507     case BFD_RELOC_VTABLE_INHERIT:
15508       fixP->fx_done = 0;
15509       if (fixP->fx_addsy
15510           && !S_IS_DEFINED (fixP->fx_addsy)
15511           && !S_IS_WEAK (fixP->fx_addsy))
15512         S_SET_WEAK (fixP->fx_addsy);
15513       break;
15514
15515     case BFD_RELOC_VTABLE_ENTRY:
15516       fixP->fx_done = 0;
15517       break;
15518
15519     default:
15520       internalError ();
15521     }
15522
15523   /* Remember value for tc_gen_reloc.  */
15524   fixP->fx_addnumber = *valP;
15525 }
15526
15527 static symbolS *
15528 get_symbol (void)
15529 {
15530   int c;
15531   char *name;
15532   symbolS *p;
15533
15534   name = input_line_pointer;
15535   c = get_symbol_end ();
15536   p = (symbolS *) symbol_find_or_make (name);
15537   *input_line_pointer = c;
15538   return p;
15539 }
15540
15541 /* Align the current frag to a given power of two.  If a particular
15542    fill byte should be used, FILL points to an integer that contains
15543    that byte, otherwise FILL is null.
15544
15545    The MIPS assembler also automatically adjusts any preceding
15546    label.  */
15547
15548 static void
15549 mips_align (int to, int *fill, symbolS *label)
15550 {
15551   mips_emit_delays ();
15552   mips_record_compressed_mode ();
15553   if (fill == NULL && subseg_text_p (now_seg))
15554     frag_align_code (to, 0);
15555   else
15556     frag_align (to, fill ? *fill : 0, 0);
15557   record_alignment (now_seg, to);
15558   if (label != NULL)
15559     {
15560       gas_assert (S_GET_SEGMENT (label) == now_seg);
15561       symbol_set_frag (label, frag_now);
15562       S_SET_VALUE (label, (valueT) frag_now_fix ());
15563     }
15564 }
15565
15566 /* Align to a given power of two.  .align 0 turns off the automatic
15567    alignment used by the data creating pseudo-ops.  */
15568
15569 static void
15570 s_align (int x ATTRIBUTE_UNUSED)
15571 {
15572   int temp, fill_value, *fill_ptr;
15573   long max_alignment = 28;
15574
15575   /* o Note that the assembler pulls down any immediately preceding label
15576        to the aligned address.
15577      o It's not documented but auto alignment is reinstated by
15578        a .align pseudo instruction.
15579      o Note also that after auto alignment is turned off the mips assembler
15580        issues an error on attempt to assemble an improperly aligned data item.
15581        We don't.  */
15582
15583   temp = get_absolute_expression ();
15584   if (temp > max_alignment)
15585     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
15586   else if (temp < 0)
15587     {
15588       as_warn (_("Alignment negative: 0 assumed."));
15589       temp = 0;
15590     }
15591   if (*input_line_pointer == ',')
15592     {
15593       ++input_line_pointer;
15594       fill_value = get_absolute_expression ();
15595       fill_ptr = &fill_value;
15596     }
15597   else
15598     fill_ptr = 0;
15599   if (temp)
15600     {
15601       segment_info_type *si = seg_info (now_seg);
15602       struct insn_label_list *l = si->label_list;
15603       /* Auto alignment should be switched on by next section change.  */
15604       auto_align = 1;
15605       mips_align (temp, fill_ptr, l != NULL ? l->label : NULL);
15606     }
15607   else
15608     {
15609       auto_align = 0;
15610     }
15611
15612   demand_empty_rest_of_line ();
15613 }
15614
15615 static void
15616 s_change_sec (int sec)
15617 {
15618   segT seg;
15619
15620 #ifdef OBJ_ELF
15621   /* The ELF backend needs to know that we are changing sections, so
15622      that .previous works correctly.  We could do something like check
15623      for an obj_section_change_hook macro, but that might be confusing
15624      as it would not be appropriate to use it in the section changing
15625      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15626      This should be cleaner, somehow.  */
15627   if (IS_ELF)
15628     obj_elf_section_change_hook ();
15629 #endif
15630
15631   mips_emit_delays ();
15632
15633   switch (sec)
15634     {
15635     case 't':
15636       s_text (0);
15637       break;
15638     case 'd':
15639       s_data (0);
15640       break;
15641     case 'b':
15642       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15643       demand_empty_rest_of_line ();
15644       break;
15645
15646     case 'r':
15647       seg = subseg_new (RDATA_SECTION_NAME,
15648                         (subsegT) get_absolute_expression ());
15649       if (IS_ELF)
15650         {
15651           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15652                                                   | SEC_READONLY | SEC_RELOC
15653                                                   | SEC_DATA));
15654           if (strncmp (TARGET_OS, "elf", 3) != 0)
15655             record_alignment (seg, 4);
15656         }
15657       demand_empty_rest_of_line ();
15658       break;
15659
15660     case 's':
15661       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15662       if (IS_ELF)
15663         {
15664           bfd_set_section_flags (stdoutput, seg,
15665                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15666           if (strncmp (TARGET_OS, "elf", 3) != 0)
15667             record_alignment (seg, 4);
15668         }
15669       demand_empty_rest_of_line ();
15670       break;
15671
15672     case 'B':
15673       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15674       if (IS_ELF)
15675         {
15676           bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15677           if (strncmp (TARGET_OS, "elf", 3) != 0)
15678             record_alignment (seg, 4);
15679         }
15680       demand_empty_rest_of_line ();
15681       break;
15682     }
15683
15684   auto_align = 1;
15685 }
15686
15687 void
15688 s_change_section (int ignore ATTRIBUTE_UNUSED)
15689 {
15690 #ifdef OBJ_ELF
15691   char *section_name;
15692   char c;
15693   char next_c = 0;
15694   int section_type;
15695   int section_flag;
15696   int section_entry_size;
15697   int section_alignment;
15698
15699   if (!IS_ELF)
15700     return;
15701
15702   section_name = input_line_pointer;
15703   c = get_symbol_end ();
15704   if (c)
15705     next_c = *(input_line_pointer + 1);
15706
15707   /* Do we have .section Name<,"flags">?  */
15708   if (c != ',' || (c == ',' && next_c == '"'))
15709     {
15710       /* just after name is now '\0'.  */
15711       *input_line_pointer = c;
15712       input_line_pointer = section_name;
15713       obj_elf_section (ignore);
15714       return;
15715     }
15716   input_line_pointer++;
15717
15718   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15719   if (c == ',')
15720     section_type = get_absolute_expression ();
15721   else
15722     section_type = 0;
15723   if (*input_line_pointer++ == ',')
15724     section_flag = get_absolute_expression ();
15725   else
15726     section_flag = 0;
15727   if (*input_line_pointer++ == ',')
15728     section_entry_size = get_absolute_expression ();
15729   else
15730     section_entry_size = 0;
15731   if (*input_line_pointer++ == ',')
15732     section_alignment = get_absolute_expression ();
15733   else
15734     section_alignment = 0;
15735   /* FIXME: really ignore?  */
15736   (void) section_alignment;
15737
15738   section_name = xstrdup (section_name);
15739
15740   /* When using the generic form of .section (as implemented by obj-elf.c),
15741      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15742      traditionally had to fall back on the more common @progbits instead.
15743
15744      There's nothing really harmful in this, since bfd will correct
15745      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15746      means that, for backwards compatibility, the special_section entries
15747      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15748
15749      Even so, we shouldn't force users of the MIPS .section syntax to
15750      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15751      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15752      generic type-checking code.  */
15753   if (section_type == SHT_MIPS_DWARF)
15754     section_type = SHT_PROGBITS;
15755
15756   obj_elf_change_section (section_name, section_type, section_flag,
15757                           section_entry_size, 0, 0, 0);
15758
15759   if (now_seg->name != section_name)
15760     free (section_name);
15761 #endif /* OBJ_ELF */
15762 }
15763
15764 void
15765 mips_enable_auto_align (void)
15766 {
15767   auto_align = 1;
15768 }
15769
15770 static void
15771 s_cons (int log_size)
15772 {
15773   segment_info_type *si = seg_info (now_seg);
15774   struct insn_label_list *l = si->label_list;
15775   symbolS *label;
15776
15777   label = l != NULL ? l->label : NULL;
15778   mips_emit_delays ();
15779   if (log_size > 0 && auto_align)
15780     mips_align (log_size, 0, label);
15781   cons (1 << log_size);
15782   mips_clear_insn_labels ();
15783 }
15784
15785 static void
15786 s_float_cons (int type)
15787 {
15788   segment_info_type *si = seg_info (now_seg);
15789   struct insn_label_list *l = si->label_list;
15790   symbolS *label;
15791
15792   label = l != NULL ? l->label : NULL;
15793
15794   mips_emit_delays ();
15795
15796   if (auto_align)
15797     {
15798       if (type == 'd')
15799         mips_align (3, 0, label);
15800       else
15801         mips_align (2, 0, label);
15802     }
15803
15804   float_cons (type);
15805   mips_clear_insn_labels ();
15806 }
15807
15808 /* Handle .globl.  We need to override it because on Irix 5 you are
15809    permitted to say
15810        .globl foo .text
15811    where foo is an undefined symbol, to mean that foo should be
15812    considered to be the address of a function.  */
15813
15814 static void
15815 s_mips_globl (int x ATTRIBUTE_UNUSED)
15816 {
15817   char *name;
15818   int c;
15819   symbolS *symbolP;
15820   flagword flag;
15821
15822   do
15823     {
15824       name = input_line_pointer;
15825       c = get_symbol_end ();
15826       symbolP = symbol_find_or_make (name);
15827       S_SET_EXTERNAL (symbolP);
15828
15829       *input_line_pointer = c;
15830       SKIP_WHITESPACE ();
15831
15832       /* On Irix 5, every global symbol that is not explicitly labelled as
15833          being a function is apparently labelled as being an object.  */
15834       flag = BSF_OBJECT;
15835
15836       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15837           && (*input_line_pointer != ','))
15838         {
15839           char *secname;
15840           asection *sec;
15841
15842           secname = input_line_pointer;
15843           c = get_symbol_end ();
15844           sec = bfd_get_section_by_name (stdoutput, secname);
15845           if (sec == NULL)
15846             as_bad (_("%s: no such section"), secname);
15847           *input_line_pointer = c;
15848
15849           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15850             flag = BSF_FUNCTION;
15851         }
15852
15853       symbol_get_bfdsym (symbolP)->flags |= flag;
15854
15855       c = *input_line_pointer;
15856       if (c == ',')
15857         {
15858           input_line_pointer++;
15859           SKIP_WHITESPACE ();
15860           if (is_end_of_line[(unsigned char) *input_line_pointer])
15861             c = '\n';
15862         }
15863     }
15864   while (c == ',');
15865
15866   demand_empty_rest_of_line ();
15867 }
15868
15869 static void
15870 s_option (int x ATTRIBUTE_UNUSED)
15871 {
15872   char *opt;
15873   char c;
15874
15875   opt = input_line_pointer;
15876   c = get_symbol_end ();
15877
15878   if (*opt == 'O')
15879     {
15880       /* FIXME: What does this mean?  */
15881     }
15882   else if (strncmp (opt, "pic", 3) == 0)
15883     {
15884       int i;
15885
15886       i = atoi (opt + 3);
15887       if (i == 0)
15888         mips_pic = NO_PIC;
15889       else if (i == 2)
15890         {
15891         mips_pic = SVR4_PIC;
15892           mips_abicalls = TRUE;
15893         }
15894       else
15895         as_bad (_(".option pic%d not supported"), i);
15896
15897       if (mips_pic == SVR4_PIC)
15898         {
15899           if (g_switch_seen && g_switch_value != 0)
15900             as_warn (_("-G may not be used with SVR4 PIC code"));
15901           g_switch_value = 0;
15902           bfd_set_gp_size (stdoutput, 0);
15903         }
15904     }
15905   else
15906     as_warn (_("Unrecognized option \"%s\""), opt);
15907
15908   *input_line_pointer = c;
15909   demand_empty_rest_of_line ();
15910 }
15911
15912 /* This structure is used to hold a stack of .set values.  */
15913
15914 struct mips_option_stack
15915 {
15916   struct mips_option_stack *next;
15917   struct mips_set_options options;
15918 };
15919
15920 static struct mips_option_stack *mips_opts_stack;
15921
15922 /* Handle the .set pseudo-op.  */
15923
15924 static void
15925 s_mipsset (int x ATTRIBUTE_UNUSED)
15926 {
15927   char *name = input_line_pointer, ch;
15928
15929   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15930     ++input_line_pointer;
15931   ch = *input_line_pointer;
15932   *input_line_pointer = '\0';
15933
15934   if (strcmp (name, "reorder") == 0)
15935     {
15936       if (mips_opts.noreorder)
15937         end_noreorder ();
15938     }
15939   else if (strcmp (name, "noreorder") == 0)
15940     {
15941       if (!mips_opts.noreorder)
15942         start_noreorder ();
15943     }
15944   else if (strncmp (name, "at=", 3) == 0)
15945     {
15946       char *s = name + 3;
15947
15948       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15949         as_bad (_("Unrecognized register name `%s'"), s);
15950     }
15951   else if (strcmp (name, "at") == 0)
15952     {
15953       mips_opts.at = ATREG;
15954     }
15955   else if (strcmp (name, "noat") == 0)
15956     {
15957       mips_opts.at = ZERO;
15958     }
15959   else if (strcmp (name, "macro") == 0)
15960     {
15961       mips_opts.warn_about_macros = 0;
15962     }
15963   else if (strcmp (name, "nomacro") == 0)
15964     {
15965       if (mips_opts.noreorder == 0)
15966         as_bad (_("`noreorder' must be set before `nomacro'"));
15967       mips_opts.warn_about_macros = 1;
15968     }
15969   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15970     {
15971       mips_opts.nomove = 0;
15972     }
15973   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15974     {
15975       mips_opts.nomove = 1;
15976     }
15977   else if (strcmp (name, "bopt") == 0)
15978     {
15979       mips_opts.nobopt = 0;
15980     }
15981   else if (strcmp (name, "nobopt") == 0)
15982     {
15983       mips_opts.nobopt = 1;
15984     }
15985   else if (strcmp (name, "gp=default") == 0)
15986     mips_opts.gp32 = file_mips_gp32;
15987   else if (strcmp (name, "gp=32") == 0)
15988     mips_opts.gp32 = 1;
15989   else if (strcmp (name, "gp=64") == 0)
15990     {
15991       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
15992         as_warn (_("%s isa does not support 64-bit registers"),
15993                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15994       mips_opts.gp32 = 0;
15995     }
15996   else if (strcmp (name, "fp=default") == 0)
15997     mips_opts.fp32 = file_mips_fp32;
15998   else if (strcmp (name, "fp=32") == 0)
15999     mips_opts.fp32 = 1;
16000   else if (strcmp (name, "fp=64") == 0)
16001     {
16002       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
16003         as_warn (_("%s isa does not support 64-bit floating point registers"),
16004                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16005       mips_opts.fp32 = 0;
16006     }
16007   else if (strcmp (name, "softfloat") == 0)
16008     mips_opts.soft_float = 1;
16009   else if (strcmp (name, "hardfloat") == 0)
16010     mips_opts.soft_float = 0;
16011   else if (strcmp (name, "singlefloat") == 0)
16012     mips_opts.single_float = 1;
16013   else if (strcmp (name, "doublefloat") == 0)
16014     mips_opts.single_float = 0;
16015   else if (strcmp (name, "mips16") == 0
16016            || strcmp (name, "MIPS-16") == 0)
16017     {
16018       if (mips_opts.micromips == 1)
16019         as_fatal (_("`mips16' cannot be used with `micromips'"));
16020       mips_opts.mips16 = 1;
16021     }
16022   else if (strcmp (name, "nomips16") == 0
16023            || strcmp (name, "noMIPS-16") == 0)
16024     mips_opts.mips16 = 0;
16025   else if (strcmp (name, "micromips") == 0)
16026     {
16027       if (mips_opts.mips16 == 1)
16028         as_fatal (_("`micromips' cannot be used with `mips16'"));
16029       mips_opts.micromips = 1;
16030     }
16031   else if (strcmp (name, "nomicromips") == 0)
16032     mips_opts.micromips = 0;
16033   else if (strcmp (name, "smartmips") == 0)
16034     {
16035       if (!ISA_SUPPORTS_SMARTMIPS)
16036         as_warn (_("%s ISA does not support SmartMIPS ASE"), 
16037                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16038       mips_opts.ase_smartmips = 1;
16039     }
16040   else if (strcmp (name, "nosmartmips") == 0)
16041     mips_opts.ase_smartmips = 0;
16042   else if (strcmp (name, "mips3d") == 0)
16043     mips_opts.ase_mips3d = 1;
16044   else if (strcmp (name, "nomips3d") == 0)
16045     mips_opts.ase_mips3d = 0;
16046   else if (strcmp (name, "mdmx") == 0)
16047     mips_opts.ase_mdmx = 1;
16048   else if (strcmp (name, "nomdmx") == 0)
16049     mips_opts.ase_mdmx = 0;
16050   else if (strcmp (name, "dsp") == 0)
16051     {
16052       if (!ISA_SUPPORTS_DSP_ASE)
16053         as_warn (_("%s ISA does not support DSP ASE"), 
16054                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16055       mips_opts.ase_dsp = 1;
16056       mips_opts.ase_dspr2 = 0;
16057     }
16058   else if (strcmp (name, "nodsp") == 0)
16059     {
16060       mips_opts.ase_dsp = 0;
16061       mips_opts.ase_dspr2 = 0;
16062     }
16063   else if (strcmp (name, "dspr2") == 0)
16064     {
16065       if (!ISA_SUPPORTS_DSPR2_ASE)
16066         as_warn (_("%s ISA does not support DSP R2 ASE"),
16067                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16068       mips_opts.ase_dspr2 = 1;
16069       mips_opts.ase_dsp = 1;
16070     }
16071   else if (strcmp (name, "nodspr2") == 0)
16072     {
16073       mips_opts.ase_dspr2 = 0;
16074       mips_opts.ase_dsp = 0;
16075     }
16076   else if (strcmp (name, "mt") == 0)
16077     {
16078       if (!ISA_SUPPORTS_MT_ASE)
16079         as_warn (_("%s ISA does not support MT ASE"), 
16080                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16081       mips_opts.ase_mt = 1;
16082     }
16083   else if (strcmp (name, "nomt") == 0)
16084     mips_opts.ase_mt = 0;
16085   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16086     {
16087       int reset = 0;
16088
16089       /* Permit the user to change the ISA and architecture on the fly.
16090          Needless to say, misuse can cause serious problems.  */
16091       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16092         {
16093           reset = 1;
16094           mips_opts.isa = file_mips_isa;
16095           mips_opts.arch = file_mips_arch;
16096         }
16097       else if (strncmp (name, "arch=", 5) == 0)
16098         {
16099           const struct mips_cpu_info *p;
16100
16101           p = mips_parse_cpu("internal use", name + 5);
16102           if (!p)
16103             as_bad (_("unknown architecture %s"), name + 5);
16104           else
16105             {
16106               mips_opts.arch = p->cpu;
16107               mips_opts.isa = p->isa;
16108             }
16109         }
16110       else if (strncmp (name, "mips", 4) == 0)
16111         {
16112           const struct mips_cpu_info *p;
16113
16114           p = mips_parse_cpu("internal use", name);
16115           if (!p)
16116             as_bad (_("unknown ISA level %s"), name + 4);
16117           else
16118             {
16119               mips_opts.arch = p->cpu;
16120               mips_opts.isa = p->isa;
16121             }
16122         }
16123       else
16124         as_bad (_("unknown ISA or architecture %s"), name);
16125
16126       switch (mips_opts.isa)
16127         {
16128         case  0:
16129           break;
16130         case ISA_MIPS1:
16131         case ISA_MIPS2:
16132         case ISA_MIPS32:
16133         case ISA_MIPS32R2:
16134           mips_opts.gp32 = 1;
16135           mips_opts.fp32 = 1;
16136           break;
16137         case ISA_MIPS3:
16138         case ISA_MIPS4:
16139         case ISA_MIPS5:
16140         case ISA_MIPS64:
16141         case ISA_MIPS64R2:
16142           mips_opts.gp32 = 0;
16143           mips_opts.fp32 = 0;
16144           break;
16145         default:
16146           as_bad (_("unknown ISA level %s"), name + 4);
16147           break;
16148         }
16149       if (reset)
16150         {
16151           mips_opts.gp32 = file_mips_gp32;
16152           mips_opts.fp32 = file_mips_fp32;
16153         }
16154     }
16155   else if (strcmp (name, "autoextend") == 0)
16156     mips_opts.noautoextend = 0;
16157   else if (strcmp (name, "noautoextend") == 0)
16158     mips_opts.noautoextend = 1;
16159   else if (strcmp (name, "push") == 0)
16160     {
16161       struct mips_option_stack *s;
16162
16163       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16164       s->next = mips_opts_stack;
16165       s->options = mips_opts;
16166       mips_opts_stack = s;
16167     }
16168   else if (strcmp (name, "pop") == 0)
16169     {
16170       struct mips_option_stack *s;
16171
16172       s = mips_opts_stack;
16173       if (s == NULL)
16174         as_bad (_(".set pop with no .set push"));
16175       else
16176         {
16177           /* If we're changing the reorder mode we need to handle
16178              delay slots correctly.  */
16179           if (s->options.noreorder && ! mips_opts.noreorder)
16180             start_noreorder ();
16181           else if (! s->options.noreorder && mips_opts.noreorder)
16182             end_noreorder ();
16183
16184           mips_opts = s->options;
16185           mips_opts_stack = s->next;
16186           free (s);
16187         }
16188     }
16189   else if (strcmp (name, "sym32") == 0)
16190     mips_opts.sym32 = TRUE;
16191   else if (strcmp (name, "nosym32") == 0)
16192     mips_opts.sym32 = FALSE;
16193   else if (strchr (name, ','))
16194     {
16195       /* Generic ".set" directive; use the generic handler.  */
16196       *input_line_pointer = ch;
16197       input_line_pointer = name;
16198       s_set (0);
16199       return;
16200     }
16201   else
16202     {
16203       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16204     }
16205   *input_line_pointer = ch;
16206   demand_empty_rest_of_line ();
16207 }
16208
16209 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16210    .option pic2.  It means to generate SVR4 PIC calls.  */
16211
16212 static void
16213 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16214 {
16215   mips_pic = SVR4_PIC;
16216   mips_abicalls = TRUE;
16217
16218   if (g_switch_seen && g_switch_value != 0)
16219     as_warn (_("-G may not be used with SVR4 PIC code"));
16220   g_switch_value = 0;
16221
16222   bfd_set_gp_size (stdoutput, 0);
16223   demand_empty_rest_of_line ();
16224 }
16225
16226 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16227    PIC code.  It sets the $gp register for the function based on the
16228    function address, which is in the register named in the argument.
16229    This uses a relocation against _gp_disp, which is handled specially
16230    by the linker.  The result is:
16231         lui     $gp,%hi(_gp_disp)
16232         addiu   $gp,$gp,%lo(_gp_disp)
16233         addu    $gp,$gp,.cpload argument
16234    The .cpload argument is normally $25 == $t9.
16235
16236    The -mno-shared option changes this to:
16237         lui     $gp,%hi(__gnu_local_gp)
16238         addiu   $gp,$gp,%lo(__gnu_local_gp)
16239    and the argument is ignored.  This saves an instruction, but the
16240    resulting code is not position independent; it uses an absolute
16241    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16242    can go into an ordinary executable, but not into a shared library.  */
16243
16244 static void
16245 s_cpload (int ignore ATTRIBUTE_UNUSED)
16246 {
16247   expressionS ex;
16248   int reg;
16249   int in_shared;
16250
16251   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16252      .cpload is ignored.  */
16253   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16254     {
16255       s_ignore (0);
16256       return;
16257     }
16258
16259   /* .cpload should be in a .set noreorder section.  */
16260   if (mips_opts.noreorder == 0)
16261     as_warn (_(".cpload not in noreorder section"));
16262
16263   reg = tc_get_register (0);
16264
16265   /* If we need to produce a 64-bit address, we are better off using
16266      the default instruction sequence.  */
16267   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16268
16269   ex.X_op = O_symbol;
16270   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16271                                          "__gnu_local_gp");
16272   ex.X_op_symbol = NULL;
16273   ex.X_add_number = 0;
16274
16275   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16276   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16277
16278   macro_start ();
16279   macro_build_lui (&ex, mips_gp_register);
16280   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16281                mips_gp_register, BFD_RELOC_LO16);
16282   if (in_shared)
16283     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16284                  mips_gp_register, reg);
16285   macro_end ();
16286
16287   demand_empty_rest_of_line ();
16288 }
16289
16290 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16291      .cpsetup $reg1, offset|$reg2, label
16292
16293    If offset is given, this results in:
16294      sd         $gp, offset($sp)
16295      lui        $gp, %hi(%neg(%gp_rel(label)))
16296      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16297      daddu      $gp, $gp, $reg1
16298
16299    If $reg2 is given, this results in:
16300      daddu      $reg2, $gp, $0
16301      lui        $gp, %hi(%neg(%gp_rel(label)))
16302      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16303      daddu      $gp, $gp, $reg1
16304    $reg1 is normally $25 == $t9.
16305
16306    The -mno-shared option replaces the last three instructions with
16307         lui     $gp,%hi(_gp)
16308         addiu   $gp,$gp,%lo(_gp)  */
16309
16310 static void
16311 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16312 {
16313   expressionS ex_off;
16314   expressionS ex_sym;
16315   int reg1;
16316
16317   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16318      We also need NewABI support.  */
16319   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16320     {
16321       s_ignore (0);
16322       return;
16323     }
16324
16325   reg1 = tc_get_register (0);
16326   SKIP_WHITESPACE ();
16327   if (*input_line_pointer != ',')
16328     {
16329       as_bad (_("missing argument separator ',' for .cpsetup"));
16330       return;
16331     }
16332   else
16333     ++input_line_pointer;
16334   SKIP_WHITESPACE ();
16335   if (*input_line_pointer == '$')
16336     {
16337       mips_cpreturn_register = tc_get_register (0);
16338       mips_cpreturn_offset = -1;
16339     }
16340   else
16341     {
16342       mips_cpreturn_offset = get_absolute_expression ();
16343       mips_cpreturn_register = -1;
16344     }
16345   SKIP_WHITESPACE ();
16346   if (*input_line_pointer != ',')
16347     {
16348       as_bad (_("missing argument separator ',' for .cpsetup"));
16349       return;
16350     }
16351   else
16352     ++input_line_pointer;
16353   SKIP_WHITESPACE ();
16354   expression (&ex_sym);
16355
16356   macro_start ();
16357   if (mips_cpreturn_register == -1)
16358     {
16359       ex_off.X_op = O_constant;
16360       ex_off.X_add_symbol = NULL;
16361       ex_off.X_op_symbol = NULL;
16362       ex_off.X_add_number = mips_cpreturn_offset;
16363
16364       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16365                    BFD_RELOC_LO16, SP);
16366     }
16367   else
16368     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16369                  mips_gp_register, 0);
16370
16371   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16372     {
16373       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16374                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16375                    BFD_RELOC_HI16_S);
16376
16377       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16378                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16379                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16380
16381       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16382                    mips_gp_register, reg1);
16383     }
16384   else
16385     {
16386       expressionS ex;
16387
16388       ex.X_op = O_symbol;
16389       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16390       ex.X_op_symbol = NULL;
16391       ex.X_add_number = 0;
16392
16393       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16394       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16395
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     }
16400
16401   macro_end ();
16402
16403   demand_empty_rest_of_line ();
16404 }
16405
16406 static void
16407 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16408 {
16409   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16410      .cplocal is ignored.  */
16411   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16412     {
16413       s_ignore (0);
16414       return;
16415     }
16416
16417   mips_gp_register = tc_get_register (0);
16418   demand_empty_rest_of_line ();
16419 }
16420
16421 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16422    offset from $sp.  The offset is remembered, and after making a PIC
16423    call $gp is restored from that location.  */
16424
16425 static void
16426 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16427 {
16428   expressionS ex;
16429
16430   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16431      .cprestore is ignored.  */
16432   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16433     {
16434       s_ignore (0);
16435       return;
16436     }
16437
16438   mips_cprestore_offset = get_absolute_expression ();
16439   mips_cprestore_valid = 1;
16440
16441   ex.X_op = O_constant;
16442   ex.X_add_symbol = NULL;
16443   ex.X_op_symbol = NULL;
16444   ex.X_add_number = mips_cprestore_offset;
16445
16446   macro_start ();
16447   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16448                                 SP, HAVE_64BIT_ADDRESSES);
16449   macro_end ();
16450
16451   demand_empty_rest_of_line ();
16452 }
16453
16454 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16455    was given in the preceding .cpsetup, it results in:
16456      ld         $gp, offset($sp)
16457
16458    If a register $reg2 was given there, it results in:
16459      daddu      $gp, $reg2, $0  */
16460
16461 static void
16462 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16463 {
16464   expressionS ex;
16465
16466   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16467      We also need NewABI support.  */
16468   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16469     {
16470       s_ignore (0);
16471       return;
16472     }
16473
16474   macro_start ();
16475   if (mips_cpreturn_register == -1)
16476     {
16477       ex.X_op = O_constant;
16478       ex.X_add_symbol = NULL;
16479       ex.X_op_symbol = NULL;
16480       ex.X_add_number = mips_cpreturn_offset;
16481
16482       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16483     }
16484   else
16485     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
16486                  mips_cpreturn_register, 0);
16487   macro_end ();
16488
16489   demand_empty_rest_of_line ();
16490 }
16491
16492 /* Handle the .dtprelword and .dtpreldword pseudo-ops.  They generate
16493    a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
16494    use in DWARF debug information.  */
16495
16496 static void
16497 s_dtprel_internal (size_t bytes)
16498 {
16499   expressionS ex;
16500   char *p;
16501
16502   expression (&ex);
16503
16504   if (ex.X_op != O_symbol)
16505     {
16506       as_bad (_("Unsupported use of %s"), (bytes == 8
16507                                            ? ".dtpreldword"
16508                                            : ".dtprelword"));
16509       ignore_rest_of_line ();
16510     }
16511
16512   p = frag_more (bytes);
16513   md_number_to_chars (p, 0, bytes);
16514   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
16515                (bytes == 8
16516                 ? BFD_RELOC_MIPS_TLS_DTPREL64
16517                 : BFD_RELOC_MIPS_TLS_DTPREL32));
16518
16519   demand_empty_rest_of_line ();
16520 }
16521
16522 /* Handle .dtprelword.  */
16523
16524 static void
16525 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16526 {
16527   s_dtprel_internal (4);
16528 }
16529
16530 /* Handle .dtpreldword.  */
16531
16532 static void
16533 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16534 {
16535   s_dtprel_internal (8);
16536 }
16537
16538 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16539    code.  It sets the offset to use in gp_rel relocations.  */
16540
16541 static void
16542 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16543 {
16544   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16545      We also need NewABI support.  */
16546   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16547     {
16548       s_ignore (0);
16549       return;
16550     }
16551
16552   mips_gprel_offset = get_absolute_expression ();
16553
16554   demand_empty_rest_of_line ();
16555 }
16556
16557 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16558    code.  It generates a 32 bit GP relative reloc.  */
16559
16560 static void
16561 s_gpword (int ignore ATTRIBUTE_UNUSED)
16562 {
16563   segment_info_type *si;
16564   struct insn_label_list *l;
16565   symbolS *label;
16566   expressionS ex;
16567   char *p;
16568
16569   /* When not generating PIC code, this is treated as .word.  */
16570   if (mips_pic != SVR4_PIC)
16571     {
16572       s_cons (2);
16573       return;
16574     }
16575
16576   si = seg_info (now_seg);
16577   l = si->label_list;
16578   label = l != NULL ? l->label : NULL;
16579   mips_emit_delays ();
16580   if (auto_align)
16581     mips_align (2, 0, label);
16582
16583   expression (&ex);
16584   mips_clear_insn_labels ();
16585
16586   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16587     {
16588       as_bad (_("Unsupported use of .gpword"));
16589       ignore_rest_of_line ();
16590     }
16591
16592   p = frag_more (4);
16593   md_number_to_chars (p, 0, 4);
16594   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16595                BFD_RELOC_GPREL32);
16596
16597   demand_empty_rest_of_line ();
16598 }
16599
16600 static void
16601 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16602 {
16603   segment_info_type *si;
16604   struct insn_label_list *l;
16605   symbolS *label;
16606   expressionS ex;
16607   char *p;
16608
16609   /* When not generating PIC code, this is treated as .dword.  */
16610   if (mips_pic != SVR4_PIC)
16611     {
16612       s_cons (3);
16613       return;
16614     }
16615
16616   si = seg_info (now_seg);
16617   l = si->label_list;
16618   label = l != NULL ? l->label : NULL;
16619   mips_emit_delays ();
16620   if (auto_align)
16621     mips_align (3, 0, label);
16622
16623   expression (&ex);
16624   mips_clear_insn_labels ();
16625
16626   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16627     {
16628       as_bad (_("Unsupported use of .gpdword"));
16629       ignore_rest_of_line ();
16630     }
16631
16632   p = frag_more (8);
16633   md_number_to_chars (p, 0, 8);
16634   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16635                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16636
16637   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16638   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16639            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16640
16641   demand_empty_rest_of_line ();
16642 }
16643
16644 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16645    tables in SVR4 PIC code.  */
16646
16647 static void
16648 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16649 {
16650   int reg;
16651
16652   /* This is ignored when not generating SVR4 PIC code.  */
16653   if (mips_pic != SVR4_PIC)
16654     {
16655       s_ignore (0);
16656       return;
16657     }
16658
16659   /* Add $gp to the register named as an argument.  */
16660   macro_start ();
16661   reg = tc_get_register (0);
16662   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16663   macro_end ();
16664
16665   demand_empty_rest_of_line ();
16666 }
16667
16668 /* Handle the .insn pseudo-op.  This marks instruction labels in
16669    mips16/micromips mode.  This permits the linker to handle them specially,
16670    such as generating jalx instructions when needed.  We also make
16671    them odd for the duration of the assembly, in order to generate the
16672    right sort of code.  We will make them even in the adjust_symtab
16673    routine, while leaving them marked.  This is convenient for the
16674    debugger and the disassembler.  The linker knows to make them odd
16675    again.  */
16676
16677 static void
16678 s_insn (int ignore ATTRIBUTE_UNUSED)
16679 {
16680   mips_mark_labels ();
16681
16682   demand_empty_rest_of_line ();
16683 }
16684
16685 /* Handle a .stabn directive.  We need these in order to mark a label
16686    as being a mips16 text label correctly.  Sometimes the compiler
16687    will emit a label, followed by a .stabn, and then switch sections.
16688    If the label and .stabn are in mips16 mode, then the label is
16689    really a mips16 text label.  */
16690
16691 static void
16692 s_mips_stab (int type)
16693 {
16694   if (type == 'n')
16695     mips_mark_labels ();
16696
16697   s_stab (type);
16698 }
16699
16700 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16701
16702 static void
16703 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16704 {
16705   char *name;
16706   int c;
16707   symbolS *symbolP;
16708   expressionS exp;
16709
16710   name = input_line_pointer;
16711   c = get_symbol_end ();
16712   symbolP = symbol_find_or_make (name);
16713   S_SET_WEAK (symbolP);
16714   *input_line_pointer = c;
16715
16716   SKIP_WHITESPACE ();
16717
16718   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16719     {
16720       if (S_IS_DEFINED (symbolP))
16721         {
16722           as_bad (_("ignoring attempt to redefine symbol %s"),
16723                   S_GET_NAME (symbolP));
16724           ignore_rest_of_line ();
16725           return;
16726         }
16727
16728       if (*input_line_pointer == ',')
16729         {
16730           ++input_line_pointer;
16731           SKIP_WHITESPACE ();
16732         }
16733
16734       expression (&exp);
16735       if (exp.X_op != O_symbol)
16736         {
16737           as_bad (_("bad .weakext directive"));
16738           ignore_rest_of_line ();
16739           return;
16740         }
16741       symbol_set_value_expression (symbolP, &exp);
16742     }
16743
16744   demand_empty_rest_of_line ();
16745 }
16746
16747 /* Parse a register string into a number.  Called from the ECOFF code
16748    to parse .frame.  The argument is non-zero if this is the frame
16749    register, so that we can record it in mips_frame_reg.  */
16750
16751 int
16752 tc_get_register (int frame)
16753 {
16754   unsigned int reg;
16755
16756   SKIP_WHITESPACE ();
16757   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16758     reg = 0;
16759   if (frame)
16760     {
16761       mips_frame_reg = reg != 0 ? reg : SP;
16762       mips_frame_reg_valid = 1;
16763       mips_cprestore_valid = 0;
16764     }
16765   return reg;
16766 }
16767
16768 valueT
16769 md_section_align (asection *seg, valueT addr)
16770 {
16771   int align = bfd_get_section_alignment (stdoutput, seg);
16772
16773   if (IS_ELF)
16774     {
16775       /* We don't need to align ELF sections to the full alignment.
16776          However, Irix 5 may prefer that we align them at least to a 16
16777          byte boundary.  We don't bother to align the sections if we
16778          are targeted for an embedded system.  */
16779       if (strncmp (TARGET_OS, "elf", 3) == 0)
16780         return addr;
16781       if (align > 4)
16782         align = 4;
16783     }
16784
16785   return ((addr + (1 << align) - 1) & (-1 << align));
16786 }
16787
16788 /* Utility routine, called from above as well.  If called while the
16789    input file is still being read, it's only an approximation.  (For
16790    example, a symbol may later become defined which appeared to be
16791    undefined earlier.)  */
16792
16793 static int
16794 nopic_need_relax (symbolS *sym, int before_relaxing)
16795 {
16796   if (sym == 0)
16797     return 0;
16798
16799   if (g_switch_value > 0)
16800     {
16801       const char *symname;
16802       int change;
16803
16804       /* Find out whether this symbol can be referenced off the $gp
16805          register.  It can be if it is smaller than the -G size or if
16806          it is in the .sdata or .sbss section.  Certain symbols can
16807          not be referenced off the $gp, although it appears as though
16808          they can.  */
16809       symname = S_GET_NAME (sym);
16810       if (symname != (const char *) NULL
16811           && (strcmp (symname, "eprol") == 0
16812               || strcmp (symname, "etext") == 0
16813               || strcmp (symname, "_gp") == 0
16814               || strcmp (symname, "edata") == 0
16815               || strcmp (symname, "_fbss") == 0
16816               || strcmp (symname, "_fdata") == 0
16817               || strcmp (symname, "_ftext") == 0
16818               || strcmp (symname, "end") == 0
16819               || strcmp (symname, "_gp_disp") == 0))
16820         change = 1;
16821       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16822                && (0
16823 #ifndef NO_ECOFF_DEBUGGING
16824                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16825                        && (symbol_get_obj (sym)->ecoff_extern_size
16826                            <= g_switch_value))
16827 #endif
16828                    /* We must defer this decision until after the whole
16829                       file has been read, since there might be a .extern
16830                       after the first use of this symbol.  */
16831                    || (before_relaxing
16832 #ifndef NO_ECOFF_DEBUGGING
16833                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16834 #endif
16835                        && S_GET_VALUE (sym) == 0)
16836                    || (S_GET_VALUE (sym) != 0
16837                        && S_GET_VALUE (sym) <= g_switch_value)))
16838         change = 0;
16839       else
16840         {
16841           const char *segname;
16842
16843           segname = segment_name (S_GET_SEGMENT (sym));
16844           gas_assert (strcmp (segname, ".lit8") != 0
16845                   && strcmp (segname, ".lit4") != 0);
16846           change = (strcmp (segname, ".sdata") != 0
16847                     && strcmp (segname, ".sbss") != 0
16848                     && strncmp (segname, ".sdata.", 7) != 0
16849                     && strncmp (segname, ".sbss.", 6) != 0
16850                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16851                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16852         }
16853       return change;
16854     }
16855   else
16856     /* We are not optimizing for the $gp register.  */
16857     return 1;
16858 }
16859
16860
16861 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16862
16863 static bfd_boolean
16864 pic_need_relax (symbolS *sym, asection *segtype)
16865 {
16866   asection *symsec;
16867
16868   /* Handle the case of a symbol equated to another symbol.  */
16869   while (symbol_equated_reloc_p (sym))
16870     {
16871       symbolS *n;
16872
16873       /* It's possible to get a loop here in a badly written program.  */
16874       n = symbol_get_value_expression (sym)->X_add_symbol;
16875       if (n == sym)
16876         break;
16877       sym = n;
16878     }
16879
16880   if (symbol_section_p (sym))
16881     return TRUE;
16882
16883   symsec = S_GET_SEGMENT (sym);
16884
16885   /* This must duplicate the test in adjust_reloc_syms.  */
16886   return (symsec != &bfd_und_section
16887           && symsec != &bfd_abs_section
16888           && !bfd_is_com_section (symsec)
16889           && !s_is_linkonce (sym, segtype)
16890 #ifdef OBJ_ELF
16891           /* A global or weak symbol is treated as external.  */
16892           && (!IS_ELF || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
16893 #endif
16894           );
16895 }
16896
16897
16898 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16899    extended opcode.  SEC is the section the frag is in.  */
16900
16901 static int
16902 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16903 {
16904   int type;
16905   const struct mips16_immed_operand *op;
16906   offsetT val;
16907   int mintiny, maxtiny;
16908   segT symsec;
16909   fragS *sym_frag;
16910
16911   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16912     return 0;
16913   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16914     return 1;
16915
16916   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16917   op = mips16_immed_operands;
16918   while (op->type != type)
16919     {
16920       ++op;
16921       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
16922     }
16923
16924   if (op->unsp)
16925     {
16926       if (type == '<' || type == '>' || type == '[' || type == ']')
16927         {
16928           mintiny = 1;
16929           maxtiny = 1 << op->nbits;
16930         }
16931       else
16932         {
16933           mintiny = 0;
16934           maxtiny = (1 << op->nbits) - 1;
16935         }
16936     }
16937   else
16938     {
16939       mintiny = - (1 << (op->nbits - 1));
16940       maxtiny = (1 << (op->nbits - 1)) - 1;
16941     }
16942
16943   sym_frag = symbol_get_frag (fragp->fr_symbol);
16944   val = S_GET_VALUE (fragp->fr_symbol);
16945   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16946
16947   if (op->pcrel)
16948     {
16949       addressT addr;
16950
16951       /* We won't have the section when we are called from
16952          mips_relax_frag.  However, we will always have been called
16953          from md_estimate_size_before_relax first.  If this is a
16954          branch to a different section, we mark it as such.  If SEC is
16955          NULL, and the frag is not marked, then it must be a branch to
16956          the same section.  */
16957       if (sec == NULL)
16958         {
16959           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16960             return 1;
16961         }
16962       else
16963         {
16964           /* Must have been called from md_estimate_size_before_relax.  */
16965           if (symsec != sec)
16966             {
16967               fragp->fr_subtype =
16968                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16969
16970               /* FIXME: We should support this, and let the linker
16971                  catch branches and loads that are out of range.  */
16972               as_bad_where (fragp->fr_file, fragp->fr_line,
16973                             _("unsupported PC relative reference to different section"));
16974
16975               return 1;
16976             }
16977           if (fragp != sym_frag && sym_frag->fr_address == 0)
16978             /* Assume non-extended on the first relaxation pass.
16979                The address we have calculated will be bogus if this is
16980                a forward branch to another frag, as the forward frag
16981                will have fr_address == 0.  */
16982             return 0;
16983         }
16984
16985       /* In this case, we know for sure that the symbol fragment is in
16986          the same section.  If the relax_marker of the symbol fragment
16987          differs from the relax_marker of this fragment, we have not
16988          yet adjusted the symbol fragment fr_address.  We want to add
16989          in STRETCH in order to get a better estimate of the address.
16990          This particularly matters because of the shift bits.  */
16991       if (stretch != 0
16992           && sym_frag->relax_marker != fragp->relax_marker)
16993         {
16994           fragS *f;
16995
16996           /* Adjust stretch for any alignment frag.  Note that if have
16997              been expanding the earlier code, the symbol may be
16998              defined in what appears to be an earlier frag.  FIXME:
16999              This doesn't handle the fr_subtype field, which specifies
17000              a maximum number of bytes to skip when doing an
17001              alignment.  */
17002           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17003             {
17004               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17005                 {
17006                   if (stretch < 0)
17007                     stretch = - ((- stretch)
17008                                  & ~ ((1 << (int) f->fr_offset) - 1));
17009                   else
17010                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17011                   if (stretch == 0)
17012                     break;
17013                 }
17014             }
17015           if (f != NULL)
17016             val += stretch;
17017         }
17018
17019       addr = fragp->fr_address + fragp->fr_fix;
17020
17021       /* The base address rules are complicated.  The base address of
17022          a branch is the following instruction.  The base address of a
17023          PC relative load or add is the instruction itself, but if it
17024          is in a delay slot (in which case it can not be extended) use
17025          the address of the instruction whose delay slot it is in.  */
17026       if (type == 'p' || type == 'q')
17027         {
17028           addr += 2;
17029
17030           /* If we are currently assuming that this frag should be
17031              extended, then, the current address is two bytes
17032              higher.  */
17033           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17034             addr += 2;
17035
17036           /* Ignore the low bit in the target, since it will be set
17037              for a text label.  */
17038           if ((val & 1) != 0)
17039             --val;
17040         }
17041       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17042         addr -= 4;
17043       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17044         addr -= 2;
17045
17046       val -= addr & ~ ((1 << op->shift) - 1);
17047
17048       /* Branch offsets have an implicit 0 in the lowest bit.  */
17049       if (type == 'p' || type == 'q')
17050         val /= 2;
17051
17052       /* If any of the shifted bits are set, we must use an extended
17053          opcode.  If the address depends on the size of this
17054          instruction, this can lead to a loop, so we arrange to always
17055          use an extended opcode.  We only check this when we are in
17056          the main relaxation loop, when SEC is NULL.  */
17057       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17058         {
17059           fragp->fr_subtype =
17060             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17061           return 1;
17062         }
17063
17064       /* If we are about to mark a frag as extended because the value
17065          is precisely maxtiny + 1, then there is a chance of an
17066          infinite loop as in the following code:
17067              la $4,foo
17068              .skip      1020
17069              .align     2
17070            foo:
17071          In this case when the la is extended, foo is 0x3fc bytes
17072          away, so the la can be shrunk, but then foo is 0x400 away, so
17073          the la must be extended.  To avoid this loop, we mark the
17074          frag as extended if it was small, and is about to become
17075          extended with a value of maxtiny + 1.  */
17076       if (val == ((maxtiny + 1) << op->shift)
17077           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17078           && sec == NULL)
17079         {
17080           fragp->fr_subtype =
17081             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17082           return 1;
17083         }
17084     }
17085   else if (symsec != absolute_section && sec != NULL)
17086     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17087
17088   if ((val & ((1 << op->shift) - 1)) != 0
17089       || val < (mintiny << op->shift)
17090       || val > (maxtiny << op->shift))
17091     return 1;
17092   else
17093     return 0;
17094 }
17095
17096 /* Compute the length of a branch sequence, and adjust the
17097    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17098    worst-case length is computed, with UPDATE being used to indicate
17099    whether an unconditional (-1), branch-likely (+1) or regular (0)
17100    branch is to be computed.  */
17101 static int
17102 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17103 {
17104   bfd_boolean toofar;
17105   int length;
17106
17107   if (fragp
17108       && S_IS_DEFINED (fragp->fr_symbol)
17109       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17110     {
17111       addressT addr;
17112       offsetT val;
17113
17114       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17115
17116       addr = fragp->fr_address + fragp->fr_fix + 4;
17117
17118       val -= addr;
17119
17120       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17121     }
17122   else if (fragp)
17123     /* If the symbol is not defined or it's in a different segment,
17124        assume the user knows what's going on and emit a short
17125        branch.  */
17126     toofar = FALSE;
17127   else
17128     toofar = TRUE;
17129
17130   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17131     fragp->fr_subtype
17132       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17133                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17134                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17135                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17136                              toofar);
17137
17138   length = 4;
17139   if (toofar)
17140     {
17141       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17142         length += 8;
17143
17144       if (mips_pic != NO_PIC)
17145         {
17146           /* Additional space for PIC loading of target address.  */
17147           length += 8;
17148           if (mips_opts.isa == ISA_MIPS1)
17149             /* Additional space for $at-stabilizing nop.  */
17150             length += 4;
17151         }
17152
17153       /* If branch is conditional.  */
17154       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17155         length += 8;
17156     }
17157
17158   return length;
17159 }
17160
17161 /* Compute the length of a branch sequence, and adjust the
17162    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17163    worst-case length is computed, with UPDATE being used to indicate
17164    whether an unconditional (-1), or regular (0) branch is to be
17165    computed.  */
17166
17167 static int
17168 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17169 {
17170   bfd_boolean toofar;
17171   int length;
17172
17173   if (fragp
17174       && S_IS_DEFINED (fragp->fr_symbol)
17175       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17176     {
17177       addressT addr;
17178       offsetT val;
17179
17180       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17181       /* Ignore the low bit in the target, since it will be set
17182          for a text label.  */
17183       if ((val & 1) != 0)
17184         --val;
17185
17186       addr = fragp->fr_address + fragp->fr_fix + 4;
17187
17188       val -= addr;
17189
17190       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17191     }
17192   else if (fragp)
17193     /* If the symbol is not defined or it's in a different segment,
17194        assume the user knows what's going on and emit a short
17195        branch.  */
17196     toofar = FALSE;
17197   else
17198     toofar = TRUE;
17199
17200   if (fragp && update
17201       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17202     fragp->fr_subtype = (toofar
17203                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17204                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17205
17206   length = 4;
17207   if (toofar)
17208     {
17209       bfd_boolean compact_known = fragp != NULL;
17210       bfd_boolean compact = FALSE;
17211       bfd_boolean uncond;
17212
17213       if (compact_known)
17214         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17215       if (fragp)
17216         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17217       else
17218         uncond = update < 0;
17219
17220       /* If label is out of range, we turn branch <br>:
17221
17222                 <br>    label                   # 4 bytes
17223             0:
17224
17225          into:
17226
17227                 j       label                   # 4 bytes
17228                 nop                             # 2 bytes if compact && !PIC
17229             0:
17230        */
17231       if (mips_pic == NO_PIC && (!compact_known || compact))
17232         length += 2;
17233
17234       /* If assembling PIC code, we further turn:
17235
17236                         j       label                   # 4 bytes
17237
17238          into:
17239
17240                         lw/ld   at, %got(label)(gp)     # 4 bytes
17241                         d/addiu at, %lo(label)          # 4 bytes
17242                         jr/c    at                      # 2 bytes
17243        */
17244       if (mips_pic != NO_PIC)
17245         length += 6;
17246
17247       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17248
17249                         <brneg> 0f                      # 4 bytes
17250                         nop                             # 2 bytes if !compact
17251        */
17252       if (!uncond)
17253         length += (compact_known && compact) ? 4 : 6;
17254     }
17255
17256   return length;
17257 }
17258
17259 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17260    bit accordingly.  */
17261
17262 static int
17263 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17264 {
17265   bfd_boolean toofar;
17266
17267   if (RELAX_MICROMIPS_U16BIT (fragp->fr_subtype))
17268     return 2;
17269
17270   if (fragp
17271       && S_IS_DEFINED (fragp->fr_symbol)
17272       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17273     {
17274       addressT addr;
17275       offsetT val;
17276       int type;
17277
17278       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17279       /* Ignore the low bit in the target, since it will be set
17280          for a text label.  */
17281       if ((val & 1) != 0)
17282         --val;
17283
17284       /* Assume this is a 2-byte branch.  */
17285       addr = fragp->fr_address + fragp->fr_fix + 2;
17286
17287       /* We try to avoid the infinite loop by not adding 2 more bytes for
17288          long branches.  */
17289
17290       val -= addr;
17291
17292       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17293       if (type == 'D')
17294         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17295       else if (type == 'E')
17296         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17297       else
17298         abort ();
17299     }
17300   else
17301     /* If the symbol is not defined or it's in a different segment,
17302        we emit a normal 32-bit branch.  */
17303     toofar = TRUE;
17304
17305   if (fragp && update
17306       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17307     fragp->fr_subtype
17308       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17309                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17310
17311   if (toofar)
17312     return 4;
17313
17314   return 2;
17315 }
17316
17317 /* Estimate the size of a frag before relaxing.  Unless this is the
17318    mips16, we are not really relaxing here, and the final size is
17319    encoded in the subtype information.  For the mips16, we have to
17320    decide whether we are using an extended opcode or not.  */
17321
17322 int
17323 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17324 {
17325   int change;
17326
17327   if (RELAX_BRANCH_P (fragp->fr_subtype))
17328     {
17329
17330       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17331
17332       return fragp->fr_var;
17333     }
17334
17335   if (RELAX_MIPS16_P (fragp->fr_subtype))
17336     /* We don't want to modify the EXTENDED bit here; it might get us
17337        into infinite loops.  We change it only in mips_relax_frag().  */
17338     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17339
17340   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17341     {
17342       int length = 4;
17343
17344       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17345         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17346       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17347         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17348       fragp->fr_var = length;
17349
17350       return length;
17351     }
17352
17353   if (mips_pic == NO_PIC)
17354     change = nopic_need_relax (fragp->fr_symbol, 0);
17355   else if (mips_pic == SVR4_PIC)
17356     change = pic_need_relax (fragp->fr_symbol, segtype);
17357   else if (mips_pic == VXWORKS_PIC)
17358     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17359     change = 0;
17360   else
17361     abort ();
17362
17363   if (change)
17364     {
17365       fragp->fr_subtype |= RELAX_USE_SECOND;
17366       return -RELAX_FIRST (fragp->fr_subtype);
17367     }
17368   else
17369     return -RELAX_SECOND (fragp->fr_subtype);
17370 }
17371
17372 /* This is called to see whether a reloc against a defined symbol
17373    should be converted into a reloc against a section.  */
17374
17375 int
17376 mips_fix_adjustable (fixS *fixp)
17377 {
17378   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17379       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17380     return 0;
17381
17382   if (fixp->fx_addsy == NULL)
17383     return 1;
17384
17385   /* If symbol SYM is in a mergeable section, relocations of the form
17386      SYM + 0 can usually be made section-relative.  The mergeable data
17387      is then identified by the section offset rather than by the symbol.
17388
17389      However, if we're generating REL LO16 relocations, the offset is split
17390      between the LO16 and parterning high part relocation.  The linker will
17391      need to recalculate the complete offset in order to correctly identify
17392      the merge data.
17393
17394      The linker has traditionally not looked for the parterning high part
17395      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17396      placed anywhere.  Rather than break backwards compatibility by changing
17397      this, it seems better not to force the issue, and instead keep the
17398      original symbol.  This will work with either linker behavior.  */
17399   if ((lo16_reloc_p (fixp->fx_r_type)
17400        || reloc_needs_lo_p (fixp->fx_r_type))
17401       && HAVE_IN_PLACE_ADDENDS
17402       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17403     return 0;
17404
17405   /* There is no place to store an in-place offset for JALR relocations.
17406      Likewise an in-range offset of PC-relative relocations may overflow
17407      the in-place relocatable field if recalculated against the start
17408      address of the symbol's containing section.  */
17409   if (HAVE_IN_PLACE_ADDENDS
17410       && (fixp->fx_pcrel || jalr_reloc_p (fixp->fx_r_type)))
17411     return 0;
17412
17413 #ifdef OBJ_ELF
17414   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17415      to a floating-point stub.  The same is true for non-R_MIPS16_26
17416      relocations against MIPS16 functions; in this case, the stub becomes
17417      the function's canonical address.
17418
17419      Floating-point stubs are stored in unique .mips16.call.* or
17420      .mips16.fn.* sections.  If a stub T for function F is in section S,
17421      the first relocation in section S must be against F; this is how the
17422      linker determines the target function.  All relocations that might
17423      resolve to T must also be against F.  We therefore have the following
17424      restrictions, which are given in an intentionally-redundant way:
17425
17426        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17427           symbols.
17428
17429        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17430           if that stub might be used.
17431
17432        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17433           symbols.
17434
17435        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17436           that stub might be used.
17437
17438      There is a further restriction:
17439
17440        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17441           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
17442           targets with in-place addends; the relocation field cannot
17443           encode the low bit.
17444
17445      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17446      against a MIPS16 symbol.  We deal with (5) by by not reducing any
17447      such relocations on REL targets.
17448
17449      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17450      relocation against some symbol R, no relocation against R may be
17451      reduced.  (Note that this deals with (2) as well as (1) because
17452      relocations against global symbols will never be reduced on ELF
17453      targets.)  This approach is a little simpler than trying to detect
17454      stub sections, and gives the "all or nothing" per-symbol consistency
17455      that we have for MIPS16 symbols.  */
17456   if (IS_ELF
17457       && fixp->fx_subsy == NULL
17458       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17459           || *symbol_get_tc (fixp->fx_addsy)
17460           || (HAVE_IN_PLACE_ADDENDS
17461               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17462               && jmp_reloc_p (fixp->fx_r_type))))
17463     return 0;
17464 #endif
17465
17466   return 1;
17467 }
17468
17469 /* Translate internal representation of relocation info to BFD target
17470    format.  */
17471
17472 arelent **
17473 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17474 {
17475   static arelent *retval[4];
17476   arelent *reloc;
17477   bfd_reloc_code_real_type code;
17478
17479   memset (retval, 0, sizeof(retval));
17480   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
17481   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
17482   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17483   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17484
17485   if (fixp->fx_pcrel)
17486     {
17487       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17488                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17489                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17490                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
17491
17492       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17493          Relocations want only the symbol offset.  */
17494       reloc->addend = fixp->fx_addnumber + reloc->address;
17495       if (!IS_ELF)
17496         {
17497           /* A gruesome hack which is a result of the gruesome gas
17498              reloc handling.  What's worse, for COFF (as opposed to
17499              ECOFF), we might need yet another copy of reloc->address.
17500              See bfd_install_relocation.  */
17501           reloc->addend += reloc->address;
17502         }
17503     }
17504   else
17505     reloc->addend = fixp->fx_addnumber;
17506
17507   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17508      entry to be used in the relocation's section offset.  */
17509   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17510     {
17511       reloc->address = reloc->addend;
17512       reloc->addend = 0;
17513     }
17514
17515   code = fixp->fx_r_type;
17516
17517   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17518   if (reloc->howto == NULL)
17519     {
17520       as_bad_where (fixp->fx_file, fixp->fx_line,
17521                     _("Can not represent %s relocation in this object file format"),
17522                     bfd_get_reloc_code_name (code));
17523       retval[0] = NULL;
17524     }
17525
17526   return retval;
17527 }
17528
17529 /* Relax a machine dependent frag.  This returns the amount by which
17530    the current size of the frag should change.  */
17531
17532 int
17533 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17534 {
17535   if (RELAX_BRANCH_P (fragp->fr_subtype))
17536     {
17537       offsetT old_var = fragp->fr_var;
17538
17539       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17540
17541       return fragp->fr_var - old_var;
17542     }
17543
17544   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17545     {
17546       offsetT old_var = fragp->fr_var;
17547       offsetT new_var = 4;
17548
17549       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17550         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17551       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17552         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17553       fragp->fr_var = new_var;
17554
17555       return new_var - old_var;
17556     }
17557
17558   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17559     return 0;
17560
17561   if (mips16_extended_frag (fragp, NULL, stretch))
17562     {
17563       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17564         return 0;
17565       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17566       return 2;
17567     }
17568   else
17569     {
17570       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17571         return 0;
17572       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17573       return -2;
17574     }
17575
17576   return 0;
17577 }
17578
17579 /* Convert a machine dependent frag.  */
17580
17581 void
17582 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17583 {
17584   if (RELAX_BRANCH_P (fragp->fr_subtype))
17585     {
17586       bfd_byte *buf;
17587       unsigned long insn;
17588       expressionS exp;
17589       fixS *fixp;
17590
17591       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
17592
17593       if (target_big_endian)
17594         insn = bfd_getb32 (buf);
17595       else
17596         insn = bfd_getl32 (buf);
17597
17598       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17599         {
17600           /* We generate a fixup instead of applying it right now
17601              because, if there are linker relaxations, we're going to
17602              need the relocations.  */
17603           exp.X_op = O_symbol;
17604           exp.X_add_symbol = fragp->fr_symbol;
17605           exp.X_add_number = fragp->fr_offset;
17606
17607           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17608                               4, &exp, TRUE, BFD_RELOC_16_PCREL_S2);
17609           fixp->fx_file = fragp->fr_file;
17610           fixp->fx_line = fragp->fr_line;
17611
17612           md_number_to_chars ((char *) buf, insn, 4);
17613           buf += 4;
17614         }
17615       else
17616         {
17617           int i;
17618
17619           as_warn_where (fragp->fr_file, fragp->fr_line,
17620                          _("Relaxed out-of-range branch into a jump"));
17621
17622           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17623             goto uncond;
17624
17625           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17626             {
17627               /* Reverse the branch.  */
17628               switch ((insn >> 28) & 0xf)
17629                 {
17630                 case 4:
17631                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
17632                      have the condition reversed by tweaking a single
17633                      bit, and their opcodes all have 0x4???????.  */
17634                   gas_assert ((insn & 0xf1000000) == 0x41000000);
17635                   insn ^= 0x00010000;
17636                   break;
17637
17638                 case 0:
17639                   /* bltz       0x04000000      bgez    0x04010000
17640                      bltzal     0x04100000      bgezal  0x04110000  */
17641                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17642                   insn ^= 0x00010000;
17643                   break;
17644
17645                 case 1:
17646                   /* beq        0x10000000      bne     0x14000000
17647                      blez       0x18000000      bgtz    0x1c000000  */
17648                   insn ^= 0x04000000;
17649                   break;
17650
17651                 default:
17652                   abort ();
17653                 }
17654             }
17655
17656           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17657             {
17658               /* Clear the and-link bit.  */
17659               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17660
17661               /* bltzal         0x04100000      bgezal  0x04110000
17662                  bltzall        0x04120000      bgezall 0x04130000  */
17663               insn &= ~0x00100000;
17664             }
17665
17666           /* Branch over the branch (if the branch was likely) or the
17667              full jump (not likely case).  Compute the offset from the
17668              current instruction to branch to.  */
17669           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17670             i = 16;
17671           else
17672             {
17673               /* How many bytes in instructions we've already emitted?  */
17674               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17675               /* How many bytes in instructions from here to the end?  */
17676               i = fragp->fr_var - i;
17677             }
17678           /* Convert to instruction count.  */
17679           i >>= 2;
17680           /* Branch counts from the next instruction.  */
17681           i--;
17682           insn |= i;
17683           /* Branch over the jump.  */
17684           md_number_to_chars ((char *) buf, insn, 4);
17685           buf += 4;
17686
17687           /* nop */
17688           md_number_to_chars ((char *) buf, 0, 4);
17689           buf += 4;
17690
17691           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17692             {
17693               /* beql $0, $0, 2f */
17694               insn = 0x50000000;
17695               /* Compute the PC offset from the current instruction to
17696                  the end of the variable frag.  */
17697               /* How many bytes in instructions we've already emitted?  */
17698               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17699               /* How many bytes in instructions from here to the end?  */
17700               i = fragp->fr_var - i;
17701               /* Convert to instruction count.  */
17702               i >>= 2;
17703               /* Don't decrement i, because we want to branch over the
17704                  delay slot.  */
17705
17706               insn |= i;
17707               md_number_to_chars ((char *) buf, insn, 4);
17708               buf += 4;
17709
17710               md_number_to_chars ((char *) buf, 0, 4);
17711               buf += 4;
17712             }
17713
17714         uncond:
17715           if (mips_pic == NO_PIC)
17716             {
17717               /* j or jal.  */
17718               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17719                       ? 0x0c000000 : 0x08000000);
17720               exp.X_op = O_symbol;
17721               exp.X_add_symbol = fragp->fr_symbol;
17722               exp.X_add_number = fragp->fr_offset;
17723
17724               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17725                                   4, &exp, FALSE, BFD_RELOC_MIPS_JMP);
17726               fixp->fx_file = fragp->fr_file;
17727               fixp->fx_line = fragp->fr_line;
17728
17729               md_number_to_chars ((char *) buf, insn, 4);
17730               buf += 4;
17731             }
17732           else
17733             {
17734               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17735
17736               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17737               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17738               insn |= at << OP_SH_RT;
17739               exp.X_op = O_symbol;
17740               exp.X_add_symbol = fragp->fr_symbol;
17741               exp.X_add_number = fragp->fr_offset;
17742
17743               if (fragp->fr_offset)
17744                 {
17745                   exp.X_add_symbol = make_expr_symbol (&exp);
17746                   exp.X_add_number = 0;
17747                 }
17748
17749               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17750                                   4, &exp, FALSE, BFD_RELOC_MIPS_GOT16);
17751               fixp->fx_file = fragp->fr_file;
17752               fixp->fx_line = fragp->fr_line;
17753
17754               md_number_to_chars ((char *) buf, insn, 4);
17755               buf += 4;
17756
17757               if (mips_opts.isa == ISA_MIPS1)
17758                 {
17759                   /* nop */
17760                   md_number_to_chars ((char *) buf, 0, 4);
17761                   buf += 4;
17762                 }
17763
17764               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17765               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17766               insn |= at << OP_SH_RS | at << OP_SH_RT;
17767
17768               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17769                                   4, &exp, FALSE, BFD_RELOC_LO16);
17770               fixp->fx_file = fragp->fr_file;
17771               fixp->fx_line = fragp->fr_line;
17772
17773               md_number_to_chars ((char *) buf, insn, 4);
17774               buf += 4;
17775
17776               /* j(al)r $at.  */
17777               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17778                 insn = 0x0000f809;
17779               else
17780                 insn = 0x00000008;
17781               insn |= at << OP_SH_RS;
17782
17783               md_number_to_chars ((char *) buf, insn, 4);
17784               buf += 4;
17785             }
17786         }
17787
17788       gas_assert (buf == (bfd_byte *)fragp->fr_literal
17789               + fragp->fr_fix + fragp->fr_var);
17790
17791       fragp->fr_fix += fragp->fr_var;
17792
17793       return;
17794     }
17795
17796   /* Relax microMIPS branches.  */
17797   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17798     {
17799       bfd_byte *buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
17800       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17801       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17802       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17803       unsigned long jal, jalr, jr;
17804
17805       unsigned long insn;
17806       expressionS exp;
17807       fixS *fixp;
17808
17809       exp.X_op = O_symbol;
17810       exp.X_add_symbol = fragp->fr_symbol;
17811       exp.X_add_number = fragp->fr_offset;
17812
17813       fragp->fr_fix += fragp->fr_var;
17814
17815       /* Handle 16-bit branches that fit or are forced to fit.  */
17816       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17817         {
17818           /* We generate a fixup instead of applying it right now,
17819              because if there is linker relaxation, we're going to
17820              need the relocations.  */
17821           if (type == 'D')
17822             fixp = fix_new_exp (fragp,
17823                                 buf - (bfd_byte *) fragp->fr_literal,
17824                                 2, &exp, TRUE,
17825                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17826           else if (type == 'E')
17827             fixp = fix_new_exp (fragp,
17828                                 buf - (bfd_byte *) fragp->fr_literal,
17829                                 2, &exp, TRUE,
17830                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17831           else
17832             abort ();
17833
17834           fixp->fx_file = fragp->fr_file;
17835           fixp->fx_line = fragp->fr_line;
17836
17837           /* These relocations can have an addend that won't fit in
17838              2 octets.  */
17839           fixp->fx_no_overflow = 1;
17840
17841           return;
17842         }
17843
17844       /* Handle 32-bit branches that fit or forced to fit.  */
17845       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17846           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17847         {
17848           /* We generate a fixup instead of applying it right now,
17849              because if there is linker relaxation, we're going to
17850              need the relocations.  */
17851           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
17852                               4, &exp, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
17853           fixp->fx_file = fragp->fr_file;
17854           fixp->fx_line = fragp->fr_line;
17855
17856           if (type == 0)
17857             return;
17858         }
17859
17860       /* Relax 16-bit branches to 32-bit branches.  */
17861       if (type != 0)
17862         {
17863           if (target_big_endian)
17864             insn = bfd_getb16 (buf);
17865           else
17866             insn = bfd_getl16 (buf);
17867
17868           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17869             insn = 0x94000000;                          /* beq  */
17870           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17871             {
17872               unsigned long regno;
17873
17874               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17875               regno = micromips_to_32_reg_d_map [regno];
17876               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17877               insn |= regno << MICROMIPSOP_SH_RS;
17878             }
17879           else
17880             abort ();
17881
17882           /* Nothing else to do, just write it out.  */
17883           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17884               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17885             {
17886               md_number_to_chars ((char *) buf, insn >> 16, 2);
17887               buf += 2;
17888               md_number_to_chars ((char *) buf, insn & 0xffff, 2);
17889               buf += 2;
17890
17891               gas_assert (buf == ((bfd_byte *) fragp->fr_literal
17892                                   + fragp->fr_fix));
17893               return;
17894             }
17895         }
17896       else
17897         {
17898           unsigned long next;
17899
17900           if (target_big_endian)
17901             {
17902               insn = bfd_getb16 (buf);
17903               next = bfd_getb16 (buf + 2);
17904             }
17905           else
17906             {
17907               insn = bfd_getl16 (buf);
17908               next = bfd_getl16 (buf + 2);
17909             }
17910           insn = (insn << 16) | next;
17911         }
17912
17913       /* Relax 32-bit branches to a sequence of instructions.  */
17914       as_warn_where (fragp->fr_file, fragp->fr_line,
17915                      _("Relaxed out-of-range branch into a jump"));
17916
17917       /* Check the short-delay-slot bit.  */
17918       if (al && (insn & 0x02000000) != 0)
17919         {
17920           jal = 0x74000000;                             /* jals  */
17921           jalr = 0x45e0;                                /* jalrs  */
17922         }
17923       else
17924         {
17925           jal = 0xf4000000;                             /* jal  */
17926           jalr = 0x45c0;                                /* jalr  */
17927         }
17928       jr = compact ? 0x45a0 : 0x4580;                   /* jr/c  */
17929
17930       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17931         {
17932           symbolS *l;
17933
17934           /* Reverse the branch.  */
17935           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17936               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17937             insn ^= 0x20000000;
17938           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17939                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17940                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17941                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17942                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17943                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17944                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17945                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17946                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17947                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17948             insn ^= 0x00400000;
17949           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17950                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17951                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17952                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17953             insn ^= 0x00200000;
17954           else
17955             abort ();
17956
17957           if (al)
17958             {
17959               /* Clear the and-link and short-delay-slot bits.  */
17960               gas_assert ((insn & 0xfda00000) == 0x40200000);
17961
17962               /* bltzal  0x40200000     bgezal  0x40600000  */
17963               /* bltzals 0x42200000     bgezals 0x42600000  */
17964               insn &= ~0x02200000;
17965             }
17966
17967           /* Make a label at the end for use with the branch.  */
17968           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17969           micromips_label_inc ();
17970 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
17971           if (IS_ELF)
17972             S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17973 #endif
17974
17975           /* Refer to it.  */
17976           fixp = fix_new (fragp, buf - (bfd_byte *) fragp->fr_literal,
17977                           4, l, 0, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
17978           fixp->fx_file = fragp->fr_file;
17979           fixp->fx_line = fragp->fr_line;
17980
17981           /* Branch over the jump.  */
17982           md_number_to_chars ((char *) buf, insn >> 16, 2);
17983           buf += 2;
17984           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
17985           buf += 2;
17986
17987           if (!compact)
17988             {
17989               /* nop  */
17990               insn = 0x0c00;
17991               md_number_to_chars ((char *) buf, insn, 2);
17992               buf += 2;
17993             }
17994         }
17995
17996       if (mips_pic == NO_PIC)
17997         {
17998           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17999           insn = al ? jal : 0xd4000000;
18000
18001           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18002                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_JMP);
18003           fixp->fx_file = fragp->fr_file;
18004           fixp->fx_line = fragp->fr_line;
18005
18006           md_number_to_chars ((char *) buf, insn >> 16, 2);
18007           buf += 2;
18008           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18009           buf += 2;
18010
18011           if (compact)
18012             {
18013               /* nop  */
18014               insn = 0x0c00;
18015               md_number_to_chars ((char *) buf, insn, 2);
18016               buf += 2;
18017             }
18018         }
18019       else
18020         {
18021           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18022
18023           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18024           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18025           insn |= at << MICROMIPSOP_SH_RT;
18026
18027           if (exp.X_add_number)
18028             {
18029               exp.X_add_symbol = make_expr_symbol (&exp);
18030               exp.X_add_number = 0;
18031             }
18032
18033           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18034                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_GOT16);
18035           fixp->fx_file = fragp->fr_file;
18036           fixp->fx_line = fragp->fr_line;
18037
18038           md_number_to_chars ((char *) buf, insn >> 16, 2);
18039           buf += 2;
18040           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18041           buf += 2;
18042
18043           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18044           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18045           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18046
18047           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18048                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_LO16);
18049           fixp->fx_file = fragp->fr_file;
18050           fixp->fx_line = fragp->fr_line;
18051
18052           md_number_to_chars ((char *) buf, insn >> 16, 2);
18053           buf += 2;
18054           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18055           buf += 2;
18056
18057           /* jr/jrc/jalr/jalrs $at  */
18058           insn = al ? jalr : jr;
18059           insn |= at << MICROMIPSOP_SH_MJ;
18060
18061           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18062           buf += 2;
18063         }
18064
18065       gas_assert (buf == (bfd_byte *) fragp->fr_literal + fragp->fr_fix);
18066       return;
18067     }
18068
18069   if (RELAX_MIPS16_P (fragp->fr_subtype))
18070     {
18071       int type;
18072       const struct mips16_immed_operand *op;
18073       bfd_boolean small, ext;
18074       offsetT val;
18075       bfd_byte *buf;
18076       unsigned long insn;
18077       bfd_boolean use_extend;
18078       unsigned short extend;
18079
18080       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18081       op = mips16_immed_operands;
18082       while (op->type != type)
18083         ++op;
18084
18085       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18086         {
18087           small = FALSE;
18088           ext = TRUE;
18089         }
18090       else
18091         {
18092           small = TRUE;
18093           ext = FALSE;
18094         }
18095
18096       val = resolve_symbol_value (fragp->fr_symbol);
18097       if (op->pcrel)
18098         {
18099           addressT addr;
18100
18101           addr = fragp->fr_address + fragp->fr_fix;
18102
18103           /* The rules for the base address of a PC relative reloc are
18104              complicated; see mips16_extended_frag.  */
18105           if (type == 'p' || type == 'q')
18106             {
18107               addr += 2;
18108               if (ext)
18109                 addr += 2;
18110               /* Ignore the low bit in the target, since it will be
18111                  set for a text label.  */
18112               if ((val & 1) != 0)
18113                 --val;
18114             }
18115           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18116             addr -= 4;
18117           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18118             addr -= 2;
18119
18120           addr &= ~ (addressT) ((1 << op->shift) - 1);
18121           val -= addr;
18122
18123           /* Make sure the section winds up with the alignment we have
18124              assumed.  */
18125           if (op->shift > 0)
18126             record_alignment (asec, op->shift);
18127         }
18128
18129       if (ext
18130           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18131               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18132         as_warn_where (fragp->fr_file, fragp->fr_line,
18133                        _("extended instruction in delay slot"));
18134
18135       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
18136
18137       if (target_big_endian)
18138         insn = bfd_getb16 (buf);
18139       else
18140         insn = bfd_getl16 (buf);
18141
18142       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
18143                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
18144                     small, ext, &insn, &use_extend, &extend);
18145
18146       if (use_extend)
18147         {
18148           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
18149           fragp->fr_fix += 2;
18150           buf += 2;
18151         }
18152
18153       md_number_to_chars ((char *) buf, insn, 2);
18154       fragp->fr_fix += 2;
18155       buf += 2;
18156     }
18157   else
18158     {
18159       relax_substateT subtype = fragp->fr_subtype;
18160       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18161       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18162       int first, second;
18163       fixS *fixp;
18164
18165       first = RELAX_FIRST (subtype);
18166       second = RELAX_SECOND (subtype);
18167       fixp = (fixS *) fragp->fr_opcode;
18168
18169       /* If the delay slot chosen does not match the size of the instruction,
18170          then emit a warning.  */
18171       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18172            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18173         {
18174           relax_substateT s;
18175           const char *msg;
18176
18177           s = subtype & (RELAX_DELAY_SLOT_16BIT
18178                          | RELAX_DELAY_SLOT_SIZE_FIRST
18179                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18180           msg = macro_warning (s);
18181           if (msg != NULL)
18182             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
18183           subtype &= ~s;
18184         }
18185
18186       /* Possibly emit a warning if we've chosen the longer option.  */
18187       if (use_second == second_longer)
18188         {
18189           relax_substateT s;
18190           const char *msg;
18191
18192           s = (subtype
18193                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18194           msg = macro_warning (s);
18195           if (msg != NULL)
18196             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
18197           subtype &= ~s;
18198         }
18199
18200       /* Go through all the fixups for the first sequence.  Disable them
18201          (by marking them as done) if we're going to use the second
18202          sequence instead.  */
18203       while (fixp
18204              && fixp->fx_frag == fragp
18205              && fixp->fx_where < fragp->fr_fix - second)
18206         {
18207           if (subtype & RELAX_USE_SECOND)
18208             fixp->fx_done = 1;
18209           fixp = fixp->fx_next;
18210         }
18211
18212       /* Go through the fixups for the second sequence.  Disable them if
18213          we're going to use the first sequence, otherwise adjust their
18214          addresses to account for the relaxation.  */
18215       while (fixp && fixp->fx_frag == fragp)
18216         {
18217           if (subtype & RELAX_USE_SECOND)
18218             fixp->fx_where -= first;
18219           else
18220             fixp->fx_done = 1;
18221           fixp = fixp->fx_next;
18222         }
18223
18224       /* Now modify the frag contents.  */
18225       if (subtype & RELAX_USE_SECOND)
18226         {
18227           char *start;
18228
18229           start = fragp->fr_literal + fragp->fr_fix - first - second;
18230           memmove (start, start + first, second);
18231           fragp->fr_fix -= first;
18232         }
18233       else
18234         fragp->fr_fix -= second;
18235     }
18236 }
18237
18238 #ifdef OBJ_ELF
18239
18240 /* This function is called after the relocs have been generated.
18241    We've been storing mips16 text labels as odd.  Here we convert them
18242    back to even for the convenience of the debugger.  */
18243
18244 void
18245 mips_frob_file_after_relocs (void)
18246 {
18247   asymbol **syms;
18248   unsigned int count, i;
18249
18250   if (!IS_ELF)
18251     return;
18252
18253   syms = bfd_get_outsymbols (stdoutput);
18254   count = bfd_get_symcount (stdoutput);
18255   for (i = 0; i < count; i++, syms++)
18256     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18257         && ((*syms)->value & 1) != 0)
18258       {
18259         (*syms)->value &= ~1;
18260         /* If the symbol has an odd size, it was probably computed
18261            incorrectly, so adjust that as well.  */
18262         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18263           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18264       }
18265 }
18266
18267 #endif
18268
18269 /* This function is called whenever a label is defined, including fake
18270    labels instantiated off the dot special symbol.  It is used when
18271    handling branch delays; if a branch has a label, we assume we cannot
18272    move it.  This also bumps the value of the symbol by 1 in compressed
18273    code.  */
18274
18275 void
18276 mips_record_label (symbolS *sym)
18277 {
18278   segment_info_type *si = seg_info (now_seg);
18279   struct insn_label_list *l;
18280
18281   if (free_insn_labels == NULL)
18282     l = (struct insn_label_list *) xmalloc (sizeof *l);
18283   else
18284     {
18285       l = free_insn_labels;
18286       free_insn_labels = l->next;
18287     }
18288
18289   l->label = sym;
18290   l->next = si->label_list;
18291   si->label_list = l;
18292 }
18293
18294 /* This function is called as tc_frob_label() whenever a label is defined
18295    and adds a DWARF-2 record we only want for true labels.  */
18296
18297 void
18298 mips_define_label (symbolS *sym)
18299 {
18300   mips_record_label (sym);
18301 #ifdef OBJ_ELF
18302   dwarf2_emit_label (sym);
18303 #endif
18304 }
18305 \f
18306 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
18307
18308 /* Some special processing for a MIPS ELF file.  */
18309
18310 void
18311 mips_elf_final_processing (void)
18312 {
18313   /* Write out the register information.  */
18314   if (mips_abi != N64_ABI)
18315     {
18316       Elf32_RegInfo s;
18317
18318       s.ri_gprmask = mips_gprmask;
18319       s.ri_cprmask[0] = mips_cprmask[0];
18320       s.ri_cprmask[1] = mips_cprmask[1];
18321       s.ri_cprmask[2] = mips_cprmask[2];
18322       s.ri_cprmask[3] = mips_cprmask[3];
18323       /* The gp_value field is set by the MIPS ELF backend.  */
18324
18325       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18326                                        ((Elf32_External_RegInfo *)
18327                                         mips_regmask_frag));
18328     }
18329   else
18330     {
18331       Elf64_Internal_RegInfo s;
18332
18333       s.ri_gprmask = mips_gprmask;
18334       s.ri_pad = 0;
18335       s.ri_cprmask[0] = mips_cprmask[0];
18336       s.ri_cprmask[1] = mips_cprmask[1];
18337       s.ri_cprmask[2] = mips_cprmask[2];
18338       s.ri_cprmask[3] = mips_cprmask[3];
18339       /* The gp_value field is set by the MIPS ELF backend.  */
18340
18341       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18342                                        ((Elf64_External_RegInfo *)
18343                                         mips_regmask_frag));
18344     }
18345
18346   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18347      sort of BFD interface for this.  */
18348   if (mips_any_noreorder)
18349     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18350   if (mips_pic != NO_PIC)
18351     {
18352     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18353       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18354     }
18355   if (mips_abicalls)
18356     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18357
18358   /* Set MIPS ELF flags for ASEs.  */
18359   /* We may need to define a new flag for DSP ASE, and set this flag when
18360      file_ase_dsp is true.  */
18361   /* Same for DSP R2.  */
18362   /* We may need to define a new flag for MT ASE, and set this flag when
18363      file_ase_mt is true.  */
18364   if (file_ase_mips16)
18365     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18366   if (file_ase_micromips)
18367     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18368 #if 0 /* XXX FIXME */
18369   if (file_ase_mips3d)
18370     elf_elfheader (stdoutput)->e_flags |= ???;
18371 #endif
18372   if (file_ase_mdmx)
18373     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18374
18375   /* Set the MIPS ELF ABI flags.  */
18376   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18377     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18378   else if (mips_abi == O64_ABI)
18379     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18380   else if (mips_abi == EABI_ABI)
18381     {
18382       if (!file_mips_gp32)
18383         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18384       else
18385         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18386     }
18387   else if (mips_abi == N32_ABI)
18388     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18389
18390   /* Nothing to do for N64_ABI.  */
18391
18392   if (mips_32bitmode)
18393     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18394
18395 #if 0 /* XXX FIXME */
18396   /* 32 bit code with 64 bit FP registers.  */
18397   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18398     elf_elfheader (stdoutput)->e_flags |= ???;
18399 #endif
18400 }
18401
18402 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
18403 \f
18404 typedef struct proc {
18405   symbolS *func_sym;
18406   symbolS *func_end_sym;
18407   unsigned long reg_mask;
18408   unsigned long reg_offset;
18409   unsigned long fpreg_mask;
18410   unsigned long fpreg_offset;
18411   unsigned long frame_offset;
18412   unsigned long frame_reg;
18413   unsigned long pc_reg;
18414 } procS;
18415
18416 static procS cur_proc;
18417 static procS *cur_proc_ptr;
18418 static int numprocs;
18419
18420 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18421    as "2", and a normal nop as "0".  */
18422
18423 #define NOP_OPCODE_MIPS         0
18424 #define NOP_OPCODE_MIPS16       1
18425 #define NOP_OPCODE_MICROMIPS    2
18426
18427 char
18428 mips_nop_opcode (void)
18429 {
18430   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18431     return NOP_OPCODE_MICROMIPS;
18432   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18433     return NOP_OPCODE_MIPS16;
18434   else
18435     return NOP_OPCODE_MIPS;
18436 }
18437
18438 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18439    32-bit microMIPS NOPs here (if applicable).  */
18440
18441 void
18442 mips_handle_align (fragS *fragp)
18443 {
18444   char nop_opcode;
18445   char *p;
18446   int bytes, size, excess;
18447   valueT opcode;
18448
18449   if (fragp->fr_type != rs_align_code)
18450     return;
18451
18452   p = fragp->fr_literal + fragp->fr_fix;
18453   nop_opcode = *p;
18454   switch (nop_opcode)
18455     {
18456     case NOP_OPCODE_MICROMIPS:
18457       opcode = micromips_nop32_insn.insn_opcode;
18458       size = 4;
18459       break;
18460     case NOP_OPCODE_MIPS16:
18461       opcode = mips16_nop_insn.insn_opcode;
18462       size = 2;
18463       break;
18464     case NOP_OPCODE_MIPS:
18465     default:
18466       opcode = nop_insn.insn_opcode;
18467       size = 4;
18468       break;
18469     }
18470
18471   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18472   excess = bytes % size;
18473
18474   /* Handle the leading part if we're not inserting a whole number of
18475      instructions, and make it the end of the fixed part of the frag.
18476      Try to fit in a short microMIPS NOP if applicable and possible,
18477      and use zeroes otherwise.  */
18478   gas_assert (excess < 4);
18479   fragp->fr_fix += excess;
18480   switch (excess)
18481     {
18482     case 3:
18483       *p++ = '\0';
18484       /* Fall through.  */
18485     case 2:
18486       if (nop_opcode == NOP_OPCODE_MICROMIPS)
18487         {
18488           md_number_to_chars (p, micromips_nop16_insn.insn_opcode, 2);
18489           p += 2;
18490           break;
18491         }
18492       *p++ = '\0';
18493       /* Fall through.  */
18494     case 1:
18495       *p++ = '\0';
18496       /* Fall through.  */
18497     case 0:
18498       break;
18499     }
18500
18501   md_number_to_chars (p, opcode, size);
18502   fragp->fr_var = size;
18503 }
18504
18505 static void
18506 md_obj_begin (void)
18507 {
18508 }
18509
18510 static void
18511 md_obj_end (void)
18512 {
18513   /* Check for premature end, nesting errors, etc.  */
18514   if (cur_proc_ptr)
18515     as_warn (_("missing .end at end of assembly"));
18516 }
18517
18518 static long
18519 get_number (void)
18520 {
18521   int negative = 0;
18522   long val = 0;
18523
18524   if (*input_line_pointer == '-')
18525     {
18526       ++input_line_pointer;
18527       negative = 1;
18528     }
18529   if (!ISDIGIT (*input_line_pointer))
18530     as_bad (_("expected simple number"));
18531   if (input_line_pointer[0] == '0')
18532     {
18533       if (input_line_pointer[1] == 'x')
18534         {
18535           input_line_pointer += 2;
18536           while (ISXDIGIT (*input_line_pointer))
18537             {
18538               val <<= 4;
18539               val |= hex_value (*input_line_pointer++);
18540             }
18541           return negative ? -val : val;
18542         }
18543       else
18544         {
18545           ++input_line_pointer;
18546           while (ISDIGIT (*input_line_pointer))
18547             {
18548               val <<= 3;
18549               val |= *input_line_pointer++ - '0';
18550             }
18551           return negative ? -val : val;
18552         }
18553     }
18554   if (!ISDIGIT (*input_line_pointer))
18555     {
18556       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18557               *input_line_pointer, *input_line_pointer);
18558       as_warn (_("invalid number"));
18559       return -1;
18560     }
18561   while (ISDIGIT (*input_line_pointer))
18562     {
18563       val *= 10;
18564       val += *input_line_pointer++ - '0';
18565     }
18566   return negative ? -val : val;
18567 }
18568
18569 /* The .file directive; just like the usual .file directive, but there
18570    is an initial number which is the ECOFF file index.  In the non-ECOFF
18571    case .file implies DWARF-2.  */
18572
18573 static void
18574 s_mips_file (int x ATTRIBUTE_UNUSED)
18575 {
18576   static int first_file_directive = 0;
18577
18578   if (ECOFF_DEBUGGING)
18579     {
18580       get_number ();
18581       s_app_file (0);
18582     }
18583   else
18584     {
18585       char *filename;
18586
18587       filename = dwarf2_directive_file (0);
18588
18589       /* Versions of GCC up to 3.1 start files with a ".file"
18590          directive even for stabs output.  Make sure that this
18591          ".file" is handled.  Note that you need a version of GCC
18592          after 3.1 in order to support DWARF-2 on MIPS.  */
18593       if (filename != NULL && ! first_file_directive)
18594         {
18595           (void) new_logical_line (filename, -1);
18596           s_app_file_string (filename, 0);
18597         }
18598       first_file_directive = 1;
18599     }
18600 }
18601
18602 /* The .loc directive, implying DWARF-2.  */
18603
18604 static void
18605 s_mips_loc (int x ATTRIBUTE_UNUSED)
18606 {
18607   if (!ECOFF_DEBUGGING)
18608     dwarf2_directive_loc (0);
18609 }
18610
18611 /* The .end directive.  */
18612
18613 static void
18614 s_mips_end (int x ATTRIBUTE_UNUSED)
18615 {
18616   symbolS *p;
18617
18618   /* Following functions need their own .frame and .cprestore directives.  */
18619   mips_frame_reg_valid = 0;
18620   mips_cprestore_valid = 0;
18621
18622   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18623     {
18624       p = get_symbol ();
18625       demand_empty_rest_of_line ();
18626     }
18627   else
18628     p = NULL;
18629
18630   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18631     as_warn (_(".end not in text section"));
18632
18633   if (!cur_proc_ptr)
18634     {
18635       as_warn (_(".end directive without a preceding .ent directive."));
18636       demand_empty_rest_of_line ();
18637       return;
18638     }
18639
18640   if (p != NULL)
18641     {
18642       gas_assert (S_GET_NAME (p));
18643       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18644         as_warn (_(".end symbol does not match .ent symbol."));
18645
18646       if (debug_type == DEBUG_STABS)
18647         stabs_generate_asm_endfunc (S_GET_NAME (p),
18648                                     S_GET_NAME (p));
18649     }
18650   else
18651     as_warn (_(".end directive missing or unknown symbol"));
18652
18653 #ifdef OBJ_ELF
18654   /* Create an expression to calculate the size of the function.  */
18655   if (p && cur_proc_ptr)
18656     {
18657       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18658       expressionS *exp = xmalloc (sizeof (expressionS));
18659
18660       obj->size = exp;
18661       exp->X_op = O_subtract;
18662       exp->X_add_symbol = symbol_temp_new_now ();
18663       exp->X_op_symbol = p;
18664       exp->X_add_number = 0;
18665
18666       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18667     }
18668
18669   /* Generate a .pdr section.  */
18670   if (IS_ELF && !ECOFF_DEBUGGING && mips_flag_pdr)
18671     {
18672       segT saved_seg = now_seg;
18673       subsegT saved_subseg = now_subseg;
18674       expressionS exp;
18675       char *fragp;
18676
18677 #ifdef md_flush_pending_output
18678       md_flush_pending_output ();
18679 #endif
18680
18681       gas_assert (pdr_seg);
18682       subseg_set (pdr_seg, 0);
18683
18684       /* Write the symbol.  */
18685       exp.X_op = O_symbol;
18686       exp.X_add_symbol = p;
18687       exp.X_add_number = 0;
18688       emit_expr (&exp, 4);
18689
18690       fragp = frag_more (7 * 4);
18691
18692       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18693       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18694       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18695       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18696       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18697       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18698       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18699
18700       subseg_set (saved_seg, saved_subseg);
18701     }
18702 #endif /* OBJ_ELF */
18703
18704   cur_proc_ptr = NULL;
18705 }
18706
18707 /* The .aent and .ent directives.  */
18708
18709 static void
18710 s_mips_ent (int aent)
18711 {
18712   symbolS *symbolP;
18713
18714   symbolP = get_symbol ();
18715   if (*input_line_pointer == ',')
18716     ++input_line_pointer;
18717   SKIP_WHITESPACE ();
18718   if (ISDIGIT (*input_line_pointer)
18719       || *input_line_pointer == '-')
18720     get_number ();
18721
18722   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18723     as_warn (_(".ent or .aent not in text section."));
18724
18725   if (!aent && cur_proc_ptr)
18726     as_warn (_("missing .end"));
18727
18728   if (!aent)
18729     {
18730       /* This function needs its own .frame and .cprestore directives.  */
18731       mips_frame_reg_valid = 0;
18732       mips_cprestore_valid = 0;
18733
18734       cur_proc_ptr = &cur_proc;
18735       memset (cur_proc_ptr, '\0', sizeof (procS));
18736
18737       cur_proc_ptr->func_sym = symbolP;
18738
18739       ++numprocs;
18740
18741       if (debug_type == DEBUG_STABS)
18742         stabs_generate_asm_func (S_GET_NAME (symbolP),
18743                                  S_GET_NAME (symbolP));
18744     }
18745
18746   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18747
18748   demand_empty_rest_of_line ();
18749 }
18750
18751 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18752    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18753    s_mips_frame is used so that we can set the PDR information correctly.
18754    We can't use the ecoff routines because they make reference to the ecoff
18755    symbol table (in the mdebug section).  */
18756
18757 static void
18758 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18759 {
18760 #ifdef OBJ_ELF
18761   if (IS_ELF && !ECOFF_DEBUGGING)
18762     {
18763       long val;
18764
18765       if (cur_proc_ptr == (procS *) NULL)
18766         {
18767           as_warn (_(".frame outside of .ent"));
18768           demand_empty_rest_of_line ();
18769           return;
18770         }
18771
18772       cur_proc_ptr->frame_reg = tc_get_register (1);
18773
18774       SKIP_WHITESPACE ();
18775       if (*input_line_pointer++ != ','
18776           || get_absolute_expression_and_terminator (&val) != ',')
18777         {
18778           as_warn (_("Bad .frame directive"));
18779           --input_line_pointer;
18780           demand_empty_rest_of_line ();
18781           return;
18782         }
18783
18784       cur_proc_ptr->frame_offset = val;
18785       cur_proc_ptr->pc_reg = tc_get_register (0);
18786
18787       demand_empty_rest_of_line ();
18788     }
18789   else
18790 #endif /* OBJ_ELF */
18791     s_ignore (ignore);
18792 }
18793
18794 /* The .fmask and .mask directives. If the mdebug section is present
18795    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18796    embedded targets, s_mips_mask is used so that we can set the PDR
18797    information correctly. We can't use the ecoff routines because they
18798    make reference to the ecoff symbol table (in the mdebug section).  */
18799
18800 static void
18801 s_mips_mask (int reg_type)
18802 {
18803 #ifdef OBJ_ELF
18804   if (IS_ELF && !ECOFF_DEBUGGING)
18805     {
18806       long mask, off;
18807
18808       if (cur_proc_ptr == (procS *) NULL)
18809         {
18810           as_warn (_(".mask/.fmask outside of .ent"));
18811           demand_empty_rest_of_line ();
18812           return;
18813         }
18814
18815       if (get_absolute_expression_and_terminator (&mask) != ',')
18816         {
18817           as_warn (_("Bad .mask/.fmask directive"));
18818           --input_line_pointer;
18819           demand_empty_rest_of_line ();
18820           return;
18821         }
18822
18823       off = get_absolute_expression ();
18824
18825       if (reg_type == 'F')
18826         {
18827           cur_proc_ptr->fpreg_mask = mask;
18828           cur_proc_ptr->fpreg_offset = off;
18829         }
18830       else
18831         {
18832           cur_proc_ptr->reg_mask = mask;
18833           cur_proc_ptr->reg_offset = off;
18834         }
18835
18836       demand_empty_rest_of_line ();
18837     }
18838   else
18839 #endif /* OBJ_ELF */
18840     s_ignore (reg_type);
18841 }
18842
18843 /* A table describing all the processors gas knows about.  Names are
18844    matched in the order listed.
18845
18846    To ease comparison, please keep this table in the same order as
18847    gcc's mips_cpu_info_table[].  */
18848 static const struct mips_cpu_info mips_cpu_info_table[] =
18849 {
18850   /* Entries for generic ISAs */
18851   { "mips1",          MIPS_CPU_IS_ISA,          ISA_MIPS1,      CPU_R3000 },
18852   { "mips2",          MIPS_CPU_IS_ISA,          ISA_MIPS2,      CPU_R6000 },
18853   { "mips3",          MIPS_CPU_IS_ISA,          ISA_MIPS3,      CPU_R4000 },
18854   { "mips4",          MIPS_CPU_IS_ISA,          ISA_MIPS4,      CPU_R8000 },
18855   { "mips5",          MIPS_CPU_IS_ISA,          ISA_MIPS5,      CPU_MIPS5 },
18856   { "mips32",         MIPS_CPU_IS_ISA,          ISA_MIPS32,     CPU_MIPS32 },
18857   { "mips32r2",       MIPS_CPU_IS_ISA,          ISA_MIPS32R2,   CPU_MIPS32R2 },
18858   { "mips64",         MIPS_CPU_IS_ISA,          ISA_MIPS64,     CPU_MIPS64 },
18859   { "mips64r2",       MIPS_CPU_IS_ISA,          ISA_MIPS64R2,   CPU_MIPS64R2 },
18860
18861   /* MIPS I */
18862   { "r3000",          0,                        ISA_MIPS1,      CPU_R3000 },
18863   { "r2000",          0,                        ISA_MIPS1,      CPU_R3000 },
18864   { "r3900",          0,                        ISA_MIPS1,      CPU_R3900 },
18865
18866   /* MIPS II */
18867   { "r6000",          0,                        ISA_MIPS2,      CPU_R6000 },
18868
18869   /* MIPS III */
18870   { "r4000",          0,                        ISA_MIPS3,      CPU_R4000 },
18871   { "r4010",          0,                        ISA_MIPS2,      CPU_R4010 },
18872   { "vr4100",         0,                        ISA_MIPS3,      CPU_VR4100 },
18873   { "vr4111",         0,                        ISA_MIPS3,      CPU_R4111 },
18874   { "vr4120",         0,                        ISA_MIPS3,      CPU_VR4120 },
18875   { "vr4130",         0,                        ISA_MIPS3,      CPU_VR4120 },
18876   { "vr4181",         0,                        ISA_MIPS3,      CPU_R4111 },
18877   { "vr4300",         0,                        ISA_MIPS3,      CPU_R4300 },
18878   { "r4400",          0,                        ISA_MIPS3,      CPU_R4400 },
18879   { "r4600",          0,                        ISA_MIPS3,      CPU_R4600 },
18880   { "orion",          0,                        ISA_MIPS3,      CPU_R4600 },
18881   { "r4650",          0,                        ISA_MIPS3,      CPU_R4650 },
18882   /* ST Microelectronics Loongson 2E and 2F cores */
18883   { "loongson2e",     0,                        ISA_MIPS3,   CPU_LOONGSON_2E },
18884   { "loongson2f",     0,                        ISA_MIPS3,   CPU_LOONGSON_2F },
18885
18886   /* MIPS IV */
18887   { "r8000",          0,                        ISA_MIPS4,      CPU_R8000 },
18888   { "r10000",         0,                        ISA_MIPS4,      CPU_R10000 },
18889   { "r12000",         0,                        ISA_MIPS4,      CPU_R12000 },
18890   { "r14000",         0,                        ISA_MIPS4,      CPU_R14000 },
18891   { "r16000",         0,                        ISA_MIPS4,      CPU_R16000 },
18892   { "vr5000",         0,                        ISA_MIPS4,      CPU_R5000 },
18893   { "vr5400",         0,                        ISA_MIPS4,      CPU_VR5400 },
18894   { "vr5500",         0,                        ISA_MIPS4,      CPU_VR5500 },
18895   { "rm5200",         0,                        ISA_MIPS4,      CPU_R5000 },
18896   { "rm5230",         0,                        ISA_MIPS4,      CPU_R5000 },
18897   { "rm5231",         0,                        ISA_MIPS4,      CPU_R5000 },
18898   { "rm5261",         0,                        ISA_MIPS4,      CPU_R5000 },
18899   { "rm5721",         0,                        ISA_MIPS4,      CPU_R5000 },
18900   { "rm7000",         0,                        ISA_MIPS4,      CPU_RM7000 },
18901   { "rm9000",         0,                        ISA_MIPS4,      CPU_RM9000 },
18902
18903   /* MIPS 32 */
18904   { "4kc",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18905   { "4km",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18906   { "4kp",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18907   { "4ksc",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32,     CPU_MIPS32 },
18908
18909   /* MIPS 32 Release 2 */
18910   { "4kec",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18911   { "4kem",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18912   { "4kep",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18913   { "4ksd",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32R2,   CPU_MIPS32R2 },
18914   { "m4k",            0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18915   { "m4kp",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18916   { "24kc",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18917   { "24kf2_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18918   { "24kf",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18919   { "24kf1_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18920   /* Deprecated forms of the above.  */
18921   { "24kfx",          0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18922   { "24kx",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18923   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
18924   { "24kec",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18925   { "24kef2_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18926   { "24kef",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18927   { "24kef1_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18928   /* Deprecated forms of the above.  */
18929   { "24kefx",         MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18930   { "24kex",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18931   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
18932   { "34kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18933                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18934   { "34kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18935                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18936   { "34kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18937                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18938   { "34kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18939                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18940   /* Deprecated forms of the above.  */
18941   { "34kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18942                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18943   { "34kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18944                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18945   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
18946   { "74kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18947                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18948   { "74kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18949                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18950   { "74kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18951                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18952   { "74kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18953                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18954   { "74kf3_2",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18955                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18956   /* Deprecated forms of the above.  */
18957   { "74kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18958                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18959   { "74kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18960                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18961   /* 1004K cores are multiprocessor versions of the 34K.  */
18962   { "1004kc",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18963                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18964   { "1004kf2_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18965                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18966   { "1004kf",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18967                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18968   { "1004kf1_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18969                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18970
18971   /* MIPS 64 */
18972   { "5kc",            0,                        ISA_MIPS64,     CPU_MIPS64 },
18973   { "5kf",            0,                        ISA_MIPS64,     CPU_MIPS64 },
18974   { "20kc",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
18975   { "25kf",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
18976
18977   /* Broadcom SB-1 CPU core */
18978   { "sb1",            MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
18979                                                 ISA_MIPS64,     CPU_SB1 },
18980   /* Broadcom SB-1A CPU core */
18981   { "sb1a",           MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
18982                                                 ISA_MIPS64,     CPU_SB1 },
18983   
18984   { "loongson3a",     0,                        ISA_MIPS64,     CPU_LOONGSON_3A },
18985
18986   /* MIPS 64 Release 2 */
18987
18988   /* Cavium Networks Octeon CPU core */
18989   { "octeon",         0,      ISA_MIPS64R2,   CPU_OCTEON },
18990
18991   /* RMI Xlr */
18992   { "xlr",            0,      ISA_MIPS64,     CPU_XLR },
18993
18994   /* End marker */
18995   { NULL, 0, 0, 0 }
18996 };
18997
18998
18999 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19000    with a final "000" replaced by "k".  Ignore case.
19001
19002    Note: this function is shared between GCC and GAS.  */
19003
19004 static bfd_boolean
19005 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19006 {
19007   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19008     given++, canonical++;
19009
19010   return ((*given == 0 && *canonical == 0)
19011           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19012 }
19013
19014
19015 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19016    CPU name.  We've traditionally allowed a lot of variation here.
19017
19018    Note: this function is shared between GCC and GAS.  */
19019
19020 static bfd_boolean
19021 mips_matching_cpu_name_p (const char *canonical, const char *given)
19022 {
19023   /* First see if the name matches exactly, or with a final "000"
19024      turned into "k".  */
19025   if (mips_strict_matching_cpu_name_p (canonical, given))
19026     return TRUE;
19027
19028   /* If not, try comparing based on numerical designation alone.
19029      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19030   if (TOLOWER (*given) == 'r')
19031     given++;
19032   if (!ISDIGIT (*given))
19033     return FALSE;
19034
19035   /* Skip over some well-known prefixes in the canonical name,
19036      hoping to find a number there too.  */
19037   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19038     canonical += 2;
19039   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19040     canonical += 2;
19041   else if (TOLOWER (canonical[0]) == 'r')
19042     canonical += 1;
19043
19044   return mips_strict_matching_cpu_name_p (canonical, given);
19045 }
19046
19047
19048 /* Parse an option that takes the name of a processor as its argument.
19049    OPTION is the name of the option and CPU_STRING is the argument.
19050    Return the corresponding processor enumeration if the CPU_STRING is
19051    recognized, otherwise report an error and return null.
19052
19053    A similar function exists in GCC.  */
19054
19055 static const struct mips_cpu_info *
19056 mips_parse_cpu (const char *option, const char *cpu_string)
19057 {
19058   const struct mips_cpu_info *p;
19059
19060   /* 'from-abi' selects the most compatible architecture for the given
19061      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19062      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19063      version.  Look first at the -mgp options, if given, otherwise base
19064      the choice on MIPS_DEFAULT_64BIT.
19065
19066      Treat NO_ABI like the EABIs.  One reason to do this is that the
19067      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19068      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19069      'mips64', just as we did in the days before 'from-abi'.  */
19070   if (strcasecmp (cpu_string, "from-abi") == 0)
19071     {
19072       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19073         return mips_cpu_info_from_isa (ISA_MIPS1);
19074
19075       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19076         return mips_cpu_info_from_isa (ISA_MIPS3);
19077
19078       if (file_mips_gp32 >= 0)
19079         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19080
19081       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19082                                      ? ISA_MIPS3
19083                                      : ISA_MIPS1);
19084     }
19085
19086   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19087   if (strcasecmp (cpu_string, "default") == 0)
19088     return 0;
19089
19090   for (p = mips_cpu_info_table; p->name != 0; p++)
19091     if (mips_matching_cpu_name_p (p->name, cpu_string))
19092       return p;
19093
19094   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19095   return 0;
19096 }
19097
19098 /* Return the canonical processor information for ISA (a member of the
19099    ISA_MIPS* enumeration).  */
19100
19101 static const struct mips_cpu_info *
19102 mips_cpu_info_from_isa (int isa)
19103 {
19104   int i;
19105
19106   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19107     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19108         && isa == mips_cpu_info_table[i].isa)
19109       return (&mips_cpu_info_table[i]);
19110
19111   return NULL;
19112 }
19113
19114 static const struct mips_cpu_info *
19115 mips_cpu_info_from_arch (int arch)
19116 {
19117   int i;
19118
19119   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19120     if (arch == mips_cpu_info_table[i].cpu)
19121       return (&mips_cpu_info_table[i]);
19122
19123   return NULL;
19124 }
19125 \f
19126 static void
19127 show (FILE *stream, const char *string, int *col_p, int *first_p)
19128 {
19129   if (*first_p)
19130     {
19131       fprintf (stream, "%24s", "");
19132       *col_p = 24;
19133     }
19134   else
19135     {
19136       fprintf (stream, ", ");
19137       *col_p += 2;
19138     }
19139
19140   if (*col_p + strlen (string) > 72)
19141     {
19142       fprintf (stream, "\n%24s", "");
19143       *col_p = 24;
19144     }
19145
19146   fprintf (stream, "%s", string);
19147   *col_p += strlen (string);
19148
19149   *first_p = 0;
19150 }
19151
19152 void
19153 md_show_usage (FILE *stream)
19154 {
19155   int column, first;
19156   size_t i;
19157
19158   fprintf (stream, _("\
19159 MIPS options:\n\
19160 -EB                     generate big endian output\n\
19161 -EL                     generate little endian output\n\
19162 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19163 -G NUM                  allow referencing objects up to NUM bytes\n\
19164                         implicitly with the gp register [default 8]\n"));
19165   fprintf (stream, _("\
19166 -mips1                  generate MIPS ISA I instructions\n\
19167 -mips2                  generate MIPS ISA II instructions\n\
19168 -mips3                  generate MIPS ISA III instructions\n\
19169 -mips4                  generate MIPS ISA IV instructions\n\
19170 -mips5                  generate MIPS ISA V instructions\n\
19171 -mips32                 generate MIPS32 ISA instructions\n\
19172 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19173 -mips64                 generate MIPS64 ISA instructions\n\
19174 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19175 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19176
19177   first = 1;
19178
19179   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19180     show (stream, mips_cpu_info_table[i].name, &column, &first);
19181   show (stream, "from-abi", &column, &first);
19182   fputc ('\n', stream);
19183
19184   fprintf (stream, _("\
19185 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19186 -no-mCPU                don't generate code specific to CPU.\n\
19187                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19188
19189   first = 1;
19190
19191   show (stream, "3900", &column, &first);
19192   show (stream, "4010", &column, &first);
19193   show (stream, "4100", &column, &first);
19194   show (stream, "4650", &column, &first);
19195   fputc ('\n', stream);
19196
19197   fprintf (stream, _("\
19198 -mips16                 generate mips16 instructions\n\
19199 -no-mips16              do not generate mips16 instructions\n"));
19200   fprintf (stream, _("\
19201 -mmicromips             generate microMIPS instructions\n\
19202 -mno-micromips          do not generate microMIPS instructions\n"));
19203   fprintf (stream, _("\
19204 -msmartmips             generate smartmips instructions\n\
19205 -mno-smartmips          do not generate smartmips instructions\n"));  
19206   fprintf (stream, _("\
19207 -mdsp                   generate DSP instructions\n\
19208 -mno-dsp                do not generate DSP instructions\n"));
19209   fprintf (stream, _("\
19210 -mdspr2                 generate DSP R2 instructions\n\
19211 -mno-dspr2              do not generate DSP R2 instructions\n"));
19212   fprintf (stream, _("\
19213 -mmt                    generate MT instructions\n\
19214 -mno-mt                 do not generate MT instructions\n"));
19215   fprintf (stream, _("\
19216 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19217 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19218 -mfix-vr4120            work around certain VR4120 errata\n\
19219 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19220 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19221 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19222 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19223 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19224 -msym32                 assume all symbols have 32-bit values\n\
19225 -O0                     remove unneeded NOPs, do not swap branches\n\
19226 -O                      remove unneeded NOPs and swap branches\n\
19227 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19228 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19229   fprintf (stream, _("\
19230 -mhard-float            allow floating-point instructions\n\
19231 -msoft-float            do not allow floating-point instructions\n\
19232 -msingle-float          only allow 32-bit floating-point operations\n\
19233 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19234 --[no-]construct-floats [dis]allow floating point values to be constructed\n"
19235                      ));
19236 #ifdef OBJ_ELF
19237   fprintf (stream, _("\
19238 -KPIC, -call_shared     generate SVR4 position independent code\n\
19239 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19240 -mvxworks-pic           generate VxWorks position independent code\n\
19241 -non_shared             do not generate code that can operate with DSOs\n\
19242 -xgot                   assume a 32 bit GOT\n\
19243 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19244 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19245                         position dependent (non shared) code\n\
19246 -mabi=ABI               create ABI conformant object file for:\n"));
19247
19248   first = 1;
19249
19250   show (stream, "32", &column, &first);
19251   show (stream, "o64", &column, &first);
19252   show (stream, "n32", &column, &first);
19253   show (stream, "64", &column, &first);
19254   show (stream, "eabi", &column, &first);
19255
19256   fputc ('\n', stream);
19257
19258   fprintf (stream, _("\
19259 -32                     create o32 ABI object file (default)\n\
19260 -n32                    create n32 ABI object file\n\
19261 -64                     create 64 ABI object file\n"));
19262 #endif
19263 }
19264
19265 #ifdef TE_IRIX
19266 enum dwarf2_format
19267 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19268 {
19269   if (HAVE_64BIT_SYMBOLS)
19270     return dwarf2_format_64bit_irix;
19271   else
19272     return dwarf2_format_32bit;
19273 }
19274 #endif
19275
19276 int
19277 mips_dwarf2_addr_size (void)
19278 {
19279   if (HAVE_64BIT_OBJECTS)
19280     return 8;
19281   else
19282     return 4;
19283 }
19284
19285 /* Standard calling conventions leave the CFA at SP on entry.  */
19286 void
19287 mips_cfi_frame_initial_instructions (void)
19288 {
19289   cfi_add_CFA_def_cfa_register (SP);
19290 }
19291
19292 int
19293 tc_mips_regname_to_dw2regnum (char *regname)
19294 {
19295   unsigned int regnum = -1;
19296   unsigned int reg;
19297
19298   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19299     regnum = reg;
19300
19301   return regnum;
19302 }