gas/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
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 /* Check assumptions made in this file.  */
38 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
39 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
40
41 #ifdef DEBUG
42 #define DBG(x) printf x
43 #else
44 #define DBG(x)
45 #endif
46
47 /* Clean up namespace so we can include obj-elf.h too.  */
48 static int mips_output_flavor (void);
49 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
50 #undef OBJ_PROCESS_STAB
51 #undef OUTPUT_FLAVOR
52 #undef S_GET_ALIGN
53 #undef S_GET_SIZE
54 #undef S_SET_ALIGN
55 #undef S_SET_SIZE
56 #undef obj_frob_file
57 #undef obj_frob_file_after_relocs
58 #undef obj_frob_symbol
59 #undef obj_pop_insert
60 #undef obj_sec_sym_ok_for_reloc
61 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
62
63 #include "obj-elf.h"
64 /* Fix any of them that we actually care about.  */
65 #undef OUTPUT_FLAVOR
66 #define OUTPUT_FLAVOR mips_output_flavor()
67
68 #include "elf/mips.h"
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 static char *mips_regmask_frag;
89
90 #define ZERO 0
91 #define ATREG 1
92 #define S0  16
93 #define S7  23
94 #define TREG 24
95 #define PIC_CALL_REG 25
96 #define KT0 26
97 #define KT1 27
98 #define GP  28
99 #define SP  29
100 #define FP  30
101 #define RA  31
102
103 #define ILLEGAL_REG (32)
104
105 #define AT  mips_opts.at
106
107 extern int target_big_endian;
108
109 /* The name of the readonly data section.  */
110 #define RDATA_SECTION_NAME ".rodata"
111
112 /* Ways in which an instruction can be "appended" to the output.  */
113 enum append_method {
114   /* Just add it normally.  */
115   APPEND_ADD,
116
117   /* Add it normally and then add a nop.  */
118   APPEND_ADD_WITH_NOP,
119
120   /* Turn an instruction with a delay slot into a "compact" version.  */
121   APPEND_ADD_COMPACT,
122
123   /* Insert the instruction before the last one.  */
124   APPEND_SWAP
125 };
126
127 /* Information about an instruction, including its format, operands
128    and fixups.  */
129 struct mips_cl_insn
130 {
131   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
132   const struct mips_opcode *insn_mo;
133
134   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
135      a copy of INSN_MO->match with the operands filled in.  If we have
136      decided to use an extended MIPS16 instruction, this includes the
137      extension.  */
138   unsigned long insn_opcode;
139
140   /* The frag that contains the instruction.  */
141   struct frag *frag;
142
143   /* The offset into FRAG of the first instruction byte.  */
144   long where;
145
146   /* The relocs associated with the instruction, if any.  */
147   fixS *fixp[3];
148
149   /* True if this entry cannot be moved from its current position.  */
150   unsigned int fixed_p : 1;
151
152   /* True if this instruction occurred in a .set noreorder block.  */
153   unsigned int noreorder_p : 1;
154
155   /* True for mips16 instructions that jump to an absolute address.  */
156   unsigned int mips16_absolute_jump_p : 1;
157
158   /* True if this instruction is complete.  */
159   unsigned int complete_p : 1;
160
161   /* True if this instruction is cleared from history by unconditional
162      branch.  */
163   unsigned int cleared_p : 1;
164 };
165
166 /* The ABI to use.  */
167 enum mips_abi_level
168 {
169   NO_ABI = 0,
170   O32_ABI,
171   O64_ABI,
172   N32_ABI,
173   N64_ABI,
174   EABI_ABI
175 };
176
177 /* MIPS ABI we are using for this output file.  */
178 static enum mips_abi_level mips_abi = NO_ABI;
179
180 /* Whether or not we have code that can call pic code.  */
181 int mips_abicalls = FALSE;
182
183 /* Whether or not we have code which can be put into a shared
184    library.  */
185 static bfd_boolean mips_in_shared = TRUE;
186
187 /* This is the set of options which may be modified by the .set
188    pseudo-op.  We use a struct so that .set push and .set pop are more
189    reliable.  */
190
191 struct mips_set_options
192 {
193   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
194      if it has not been initialized.  Changed by `.set mipsN', and the
195      -mipsN command line option, and the default CPU.  */
196   int isa;
197   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
198      <asename>', by command line options, and based on the default
199      architecture.  */
200   int ase;
201   /* Whether we are assembling for the mips16 processor.  0 if we are
202      not, 1 if we are, and -1 if the value has not been initialized.
203      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
204      -nomips16 command line options, and the default CPU.  */
205   int mips16;
206   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
207      1 if we are, and -1 if the value has not been initialized.  Changed
208      by `.set micromips' and `.set nomicromips', and the -mmicromips
209      and -mno-micromips command line options, and the default CPU.  */
210   int micromips;
211   /* Non-zero if we should not reorder instructions.  Changed by `.set
212      reorder' and `.set noreorder'.  */
213   int noreorder;
214   /* Non-zero if we should not permit the register designated "assembler
215      temporary" to be used in instructions.  The value is the register
216      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
217      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
218   unsigned int at;
219   /* Non-zero if we should warn when a macro instruction expands into
220      more than one machine instruction.  Changed by `.set nomacro' and
221      `.set macro'.  */
222   int warn_about_macros;
223   /* Non-zero if we should not move instructions.  Changed by `.set
224      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
225   int nomove;
226   /* Non-zero if we should not optimize branches by moving the target
227      of the branch into the delay slot.  Actually, we don't perform
228      this optimization anyhow.  Changed by `.set bopt' and `.set
229      nobopt'.  */
230   int nobopt;
231   /* Non-zero if we should not autoextend mips16 instructions.
232      Changed by `.set autoextend' and `.set noautoextend'.  */
233   int noautoextend;
234   /* True if we should only emit 32-bit microMIPS instructions.
235      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
236      and -mno-insn32 command line options.  */
237   bfd_boolean insn32;
238   /* Restrict general purpose registers and floating point registers
239      to 32 bit.  This is initially determined when -mgp32 or -mfp32
240      is passed but can changed if the assembler code uses .set mipsN.  */
241   int gp32;
242   int fp32;
243   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
244      command line option, and the default CPU.  */
245   int arch;
246   /* True if ".set sym32" is in effect.  */
247   bfd_boolean sym32;
248   /* True if floating-point operations are not allowed.  Changed by .set
249      softfloat or .set hardfloat, by command line options -msoft-float or
250      -mhard-float.  The default is false.  */
251   bfd_boolean soft_float;
252
253   /* True if only single-precision floating-point operations are allowed.
254      Changed by .set singlefloat or .set doublefloat, command-line options
255      -msingle-float or -mdouble-float.  The default is false.  */
256   bfd_boolean single_float;
257 };
258
259 /* This is the struct we use to hold the current set of options.  Note
260    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
261    -1 to indicate that they have not been initialized.  */
262
263 /* True if -mgp32 was passed.  */
264 static int file_mips_gp32 = -1;
265
266 /* True if -mfp32 was passed.  */
267 static int file_mips_fp32 = -1;
268
269 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
270 static int file_mips_soft_float = 0;
271
272 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
273 static int file_mips_single_float = 0;
274
275 /* True if -mnan=2008, false if -mnan=legacy.  */
276 static bfd_boolean mips_flag_nan2008 = FALSE;
277
278 static struct mips_set_options mips_opts =
279 {
280   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
281   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
282   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
283   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
284   /* soft_float */ FALSE, /* single_float */ FALSE
285 };
286
287 /* The set of ASEs that were selected on the command line, either
288    explicitly via ASE options or implicitly through things like -march.  */
289 static unsigned int file_ase;
290
291 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
292 static unsigned int file_ase_explicit;
293
294 /* These variables are filled in with the masks of registers used.
295    The object format code reads them and puts them in the appropriate
296    place.  */
297 unsigned long mips_gprmask;
298 unsigned long mips_cprmask[4];
299
300 /* MIPS ISA we are using for this output file.  */
301 static int file_mips_isa = ISA_UNKNOWN;
302
303 /* True if any MIPS16 code was produced.  */
304 static int file_ase_mips16;
305
306 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
307                               || mips_opts.isa == ISA_MIPS32R2          \
308                               || mips_opts.isa == ISA_MIPS64            \
309                               || mips_opts.isa == ISA_MIPS64R2)
310
311 /* True if any microMIPS code was produced.  */
312 static int file_ase_micromips;
313
314 /* True if we want to create R_MIPS_JALR for jalr $25.  */
315 #ifdef TE_IRIX
316 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
317 #else
318 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
319    because there's no place for any addend, the only acceptable
320    expression is a bare symbol.  */
321 #define MIPS_JALR_HINT_P(EXPR) \
322   (!HAVE_IN_PLACE_ADDENDS \
323    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
324 #endif
325
326 /* The argument of the -march= flag.  The architecture we are assembling.  */
327 static int file_mips_arch = CPU_UNKNOWN;
328 static const char *mips_arch_string;
329
330 /* The argument of the -mtune= flag.  The architecture for which we
331    are optimizing.  */
332 static int mips_tune = CPU_UNKNOWN;
333 static const char *mips_tune_string;
334
335 /* True when generating 32-bit code for a 64-bit processor.  */
336 static int mips_32bitmode = 0;
337
338 /* True if the given ABI requires 32-bit registers.  */
339 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
340
341 /* Likewise 64-bit registers.  */
342 #define ABI_NEEDS_64BIT_REGS(ABI)       \
343   ((ABI) == N32_ABI                     \
344    || (ABI) == N64_ABI                  \
345    || (ABI) == O64_ABI)
346
347 /*  Return true if ISA supports 64 bit wide gp registers.  */
348 #define ISA_HAS_64BIT_REGS(ISA)         \
349   ((ISA) == ISA_MIPS3                   \
350    || (ISA) == ISA_MIPS4                \
351    || (ISA) == ISA_MIPS5                \
352    || (ISA) == ISA_MIPS64               \
353    || (ISA) == ISA_MIPS64R2)
354
355 /*  Return true if ISA supports 64 bit wide float registers.  */
356 #define ISA_HAS_64BIT_FPRS(ISA)         \
357   ((ISA) == ISA_MIPS3                   \
358    || (ISA) == ISA_MIPS4                \
359    || (ISA) == ISA_MIPS5                \
360    || (ISA) == ISA_MIPS32R2             \
361    || (ISA) == ISA_MIPS64               \
362    || (ISA) == ISA_MIPS64R2)
363
364 /* Return true if ISA supports 64-bit right rotate (dror et al.)
365    instructions.  */
366 #define ISA_HAS_DROR(ISA)               \
367   ((ISA) == ISA_MIPS64R2                \
368    || (mips_opts.micromips              \
369        && ISA_HAS_64BIT_REGS (ISA))     \
370    )
371
372 /* Return true if ISA supports 32-bit right rotate (ror et al.)
373    instructions.  */
374 #define ISA_HAS_ROR(ISA)                \
375   ((ISA) == ISA_MIPS32R2                \
376    || (ISA) == ISA_MIPS64R2             \
377    || (mips_opts.ase & ASE_SMARTMIPS)   \
378    || mips_opts.micromips               \
379    )
380
381 /* Return true if ISA supports single-precision floats in odd registers.  */
382 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
383   ((ISA) == ISA_MIPS32                  \
384    || (ISA) == ISA_MIPS32R2             \
385    || (ISA) == ISA_MIPS64               \
386    || (ISA) == ISA_MIPS64R2)
387
388 /* Return true if ISA supports move to/from high part of a 64-bit
389    floating-point register. */
390 #define ISA_HAS_MXHC1(ISA)              \
391   ((ISA) == ISA_MIPS32R2                \
392    || (ISA) == ISA_MIPS64R2)
393
394 #define HAVE_32BIT_GPRS                            \
395     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
396
397 #define HAVE_32BIT_FPRS                            \
398     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
399
400 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
401 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
402
403 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
404
405 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
406
407 /* True if relocations are stored in-place.  */
408 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
409
410 /* The ABI-derived address size.  */
411 #define HAVE_64BIT_ADDRESSES \
412   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
413 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
414
415 /* The size of symbolic constants (i.e., expressions of the form
416    "SYMBOL" or "SYMBOL + OFFSET").  */
417 #define HAVE_32BIT_SYMBOLS \
418   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
419 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
420
421 /* Addresses are loaded in different ways, depending on the address size
422    in use.  The n32 ABI Documentation also mandates the use of additions
423    with overflow checking, but existing implementations don't follow it.  */
424 #define ADDRESS_ADD_INSN                                                \
425    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
426
427 #define ADDRESS_ADDI_INSN                                               \
428    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
429
430 #define ADDRESS_LOAD_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
432
433 #define ADDRESS_STORE_INSN                                              \
434    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
435
436 /* Return true if the given CPU supports the MIPS16 ASE.  */
437 #define CPU_HAS_MIPS16(cpu)                                             \
438    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
439     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
440
441 /* Return true if the given CPU supports the microMIPS ASE.  */
442 #define CPU_HAS_MICROMIPS(cpu)  0
443
444 /* True if CPU has a dror instruction.  */
445 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
446
447 /* True if CPU has a ror instruction.  */
448 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
449
450 /* True if CPU is in the Octeon family */
451 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
452
453 /* True if CPU has seq/sne and seqi/snei instructions.  */
454 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
455
456 /* True, if CPU has support for ldc1 and sdc1. */
457 #define CPU_HAS_LDC1_SDC1(CPU)  \
458    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
459
460 /* True if mflo and mfhi can be immediately followed by instructions
461    which write to the HI and LO registers.
462
463    According to MIPS specifications, MIPS ISAs I, II, and III need
464    (at least) two instructions between the reads of HI/LO and
465    instructions which write them, and later ISAs do not.  Contradicting
466    the MIPS specifications, some MIPS IV processor user manuals (e.g.
467    the UM for the NEC Vr5000) document needing the instructions between
468    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
469    MIPS64 and later ISAs to have the interlocks, plus any specific
470    earlier-ISA CPUs for which CPU documentation declares that the
471    instructions are really interlocked.  */
472 #define hilo_interlocks \
473   (mips_opts.isa == ISA_MIPS32                        \
474    || mips_opts.isa == ISA_MIPS32R2                   \
475    || mips_opts.isa == ISA_MIPS64                     \
476    || mips_opts.isa == ISA_MIPS64R2                   \
477    || mips_opts.arch == CPU_R4010                     \
478    || mips_opts.arch == CPU_R5900                     \
479    || mips_opts.arch == CPU_R10000                    \
480    || mips_opts.arch == CPU_R12000                    \
481    || mips_opts.arch == CPU_R14000                    \
482    || mips_opts.arch == CPU_R16000                    \
483    || mips_opts.arch == CPU_RM7000                    \
484    || mips_opts.arch == CPU_VR5500                    \
485    || mips_opts.micromips                             \
486    )
487
488 /* Whether the processor uses hardware interlocks to protect reads
489    from the GPRs after they are loaded from memory, and thus does not
490    require nops to be inserted.  This applies to instructions marked
491    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
492    level I and microMIPS mode instructions are always interlocked.  */
493 #define gpr_interlocks                                \
494   (mips_opts.isa != ISA_MIPS1                         \
495    || mips_opts.arch == CPU_R3900                     \
496    || mips_opts.arch == CPU_R5900                     \
497    || mips_opts.micromips                             \
498    )
499
500 /* Whether the processor uses hardware interlocks to avoid delays
501    required by coprocessor instructions, and thus does not require
502    nops to be inserted.  This applies to instructions marked
503    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
504    between instructions marked INSN_WRITE_COND_CODE and ones marked
505    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
506    levels I, II, and III and microMIPS mode instructions are always
507    interlocked.  */
508 /* Itbl support may require additional care here.  */
509 #define cop_interlocks                                \
510   ((mips_opts.isa != ISA_MIPS1                        \
511     && mips_opts.isa != ISA_MIPS2                     \
512     && mips_opts.isa != ISA_MIPS3)                    \
513    || mips_opts.arch == CPU_R4300                     \
514    || mips_opts.micromips                             \
515    )
516
517 /* Whether the processor uses hardware interlocks to protect reads
518    from coprocessor registers after they are loaded from memory, and
519    thus does not require nops to be inserted.  This applies to
520    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
521    requires at MIPS ISA level I and microMIPS mode instructions are
522    always interlocked.  */
523 #define cop_mem_interlocks                            \
524   (mips_opts.isa != ISA_MIPS1                         \
525    || mips_opts.micromips                             \
526    )
527
528 /* Is this a mfhi or mflo instruction?  */
529 #define MF_HILO_INSN(PINFO) \
530   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
531
532 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
533    has been selected.  This implies, in particular, that addresses of text
534    labels have their LSB set.  */
535 #define HAVE_CODE_COMPRESSION                                           \
536   ((mips_opts.mips16 | mips_opts.micromips) != 0)
537
538 /* The minimum and maximum signed values that can be stored in a GPR.  */
539 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
540 #define GPR_SMIN (-GPR_SMAX - 1)
541
542 /* MIPS PIC level.  */
543
544 enum mips_pic_level mips_pic;
545
546 /* 1 if we should generate 32 bit offsets from the $gp register in
547    SVR4_PIC mode.  Currently has no meaning in other modes.  */
548 static int mips_big_got = 0;
549
550 /* 1 if trap instructions should used for overflow rather than break
551    instructions.  */
552 static int mips_trap = 0;
553
554 /* 1 if double width floating point constants should not be constructed
555    by assembling two single width halves into two single width floating
556    point registers which just happen to alias the double width destination
557    register.  On some architectures this aliasing can be disabled by a bit
558    in the status register, and the setting of this bit cannot be determined
559    automatically at assemble time.  */
560 static int mips_disable_float_construction;
561
562 /* Non-zero if any .set noreorder directives were used.  */
563
564 static int mips_any_noreorder;
565
566 /* Non-zero if nops should be inserted when the register referenced in
567    an mfhi/mflo instruction is read in the next two instructions.  */
568 static int mips_7000_hilo_fix;
569
570 /* The size of objects in the small data section.  */
571 static unsigned int g_switch_value = 8;
572 /* Whether the -G option was used.  */
573 static int g_switch_seen = 0;
574
575 #define N_RMASK 0xc4
576 #define N_VFP   0xd4
577
578 /* If we can determine in advance that GP optimization won't be
579    possible, we can skip the relaxation stuff that tries to produce
580    GP-relative references.  This makes delay slot optimization work
581    better.
582
583    This function can only provide a guess, but it seems to work for
584    gcc output.  It needs to guess right for gcc, otherwise gcc
585    will put what it thinks is a GP-relative instruction in a branch
586    delay slot.
587
588    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
589    fixed it for the non-PIC mode.  KR 95/04/07  */
590 static int nopic_need_relax (symbolS *, int);
591
592 /* handle of the OPCODE hash table */
593 static struct hash_control *op_hash = NULL;
594
595 /* The opcode hash table we use for the mips16.  */
596 static struct hash_control *mips16_op_hash = NULL;
597
598 /* The opcode hash table we use for the microMIPS ASE.  */
599 static struct hash_control *micromips_op_hash = NULL;
600
601 /* This array holds the chars that always start a comment.  If the
602     pre-processor is disabled, these aren't very useful */
603 const char comment_chars[] = "#";
604
605 /* This array holds the chars that only start a comment at the beginning of
606    a line.  If the line seems to have the form '# 123 filename'
607    .line and .file directives will appear in the pre-processed output */
608 /* Note that input_file.c hand checks for '#' at the beginning of the
609    first line of the input file.  This is because the compiler outputs
610    #NO_APP at the beginning of its output.  */
611 /* Also note that C style comments are always supported.  */
612 const char line_comment_chars[] = "#";
613
614 /* This array holds machine specific line separator characters.  */
615 const char line_separator_chars[] = ";";
616
617 /* Chars that can be used to separate mant from exp in floating point nums */
618 const char EXP_CHARS[] = "eE";
619
620 /* Chars that mean this number is a floating point constant */
621 /* As in 0f12.456 */
622 /* or    0d1.2345e12 */
623 const char FLT_CHARS[] = "rRsSfFdDxXpP";
624
625 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
626    changed in read.c .  Ideally it shouldn't have to know about it at all,
627    but nothing is ideal around here.
628  */
629
630 static char *insn_error;
631
632 static int auto_align = 1;
633
634 /* When outputting SVR4 PIC code, the assembler needs to know the
635    offset in the stack frame from which to restore the $gp register.
636    This is set by the .cprestore pseudo-op, and saved in this
637    variable.  */
638 static offsetT mips_cprestore_offset = -1;
639
640 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
641    more optimizations, it can use a register value instead of a memory-saved
642    offset and even an other register than $gp as global pointer.  */
643 static offsetT mips_cpreturn_offset = -1;
644 static int mips_cpreturn_register = -1;
645 static int mips_gp_register = GP;
646 static int mips_gprel_offset = 0;
647
648 /* Whether mips_cprestore_offset has been set in the current function
649    (or whether it has already been warned about, if not).  */
650 static int mips_cprestore_valid = 0;
651
652 /* This is the register which holds the stack frame, as set by the
653    .frame pseudo-op.  This is needed to implement .cprestore.  */
654 static int mips_frame_reg = SP;
655
656 /* Whether mips_frame_reg has been set in the current function
657    (or whether it has already been warned about, if not).  */
658 static int mips_frame_reg_valid = 0;
659
660 /* To output NOP instructions correctly, we need to keep information
661    about the previous two instructions.  */
662
663 /* Whether we are optimizing.  The default value of 2 means to remove
664    unneeded NOPs and swap branch instructions when possible.  A value
665    of 1 means to not swap branches.  A value of 0 means to always
666    insert NOPs.  */
667 static int mips_optimize = 2;
668
669 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
670    equivalent to seeing no -g option at all.  */
671 static int mips_debug = 0;
672
673 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
674 #define MAX_VR4130_NOPS 4
675
676 /* The maximum number of NOPs needed to fill delay slots.  */
677 #define MAX_DELAY_NOPS 2
678
679 /* The maximum number of NOPs needed for any purpose.  */
680 #define MAX_NOPS 4
681
682 /* A list of previous instructions, with index 0 being the most recent.
683    We need to look back MAX_NOPS instructions when filling delay slots
684    or working around processor errata.  We need to look back one
685    instruction further if we're thinking about using history[0] to
686    fill a branch delay slot.  */
687 static struct mips_cl_insn history[1 + MAX_NOPS];
688
689 /* Nop instructions used by emit_nop.  */
690 static struct mips_cl_insn nop_insn;
691 static struct mips_cl_insn mips16_nop_insn;
692 static struct mips_cl_insn micromips_nop16_insn;
693 static struct mips_cl_insn micromips_nop32_insn;
694
695 /* The appropriate nop for the current mode.  */
696 #define NOP_INSN (mips_opts.mips16                                      \
697                   ? &mips16_nop_insn                                    \
698                   : (mips_opts.micromips                                \
699                      ? (mips_opts.insn32                                \
700                         ? &micromips_nop32_insn                         \
701                         : &micromips_nop16_insn)                        \
702                      : &nop_insn))
703
704 /* The size of NOP_INSN in bytes.  */
705 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
706                         || (mips_opts.micromips && !mips_opts.insn32))  \
707                        ? 2 : 4)
708
709 /* If this is set, it points to a frag holding nop instructions which
710    were inserted before the start of a noreorder section.  If those
711    nops turn out to be unnecessary, the size of the frag can be
712    decreased.  */
713 static fragS *prev_nop_frag;
714
715 /* The number of nop instructions we created in prev_nop_frag.  */
716 static int prev_nop_frag_holds;
717
718 /* The number of nop instructions that we know we need in
719    prev_nop_frag.  */
720 static int prev_nop_frag_required;
721
722 /* The number of instructions we've seen since prev_nop_frag.  */
723 static int prev_nop_frag_since;
724
725 /* Relocations against symbols are sometimes done in two parts, with a HI
726    relocation and a LO relocation.  Each relocation has only 16 bits of
727    space to store an addend.  This means that in order for the linker to
728    handle carries correctly, it must be able to locate both the HI and
729    the LO relocation.  This means that the relocations must appear in
730    order in the relocation table.
731
732    In order to implement this, we keep track of each unmatched HI
733    relocation.  We then sort them so that they immediately precede the
734    corresponding LO relocation.  */
735
736 struct mips_hi_fixup
737 {
738   /* Next HI fixup.  */
739   struct mips_hi_fixup *next;
740   /* This fixup.  */
741   fixS *fixp;
742   /* The section this fixup is in.  */
743   segT seg;
744 };
745
746 /* The list of unmatched HI relocs.  */
747
748 static struct mips_hi_fixup *mips_hi_fixup_list;
749
750 /* The frag containing the last explicit relocation operator.
751    Null if explicit relocations have not been used.  */
752
753 static fragS *prev_reloc_op_frag;
754
755 /* Map normal MIPS register numbers to mips16 register numbers.  */
756
757 #define X ILLEGAL_REG
758 static const int mips32_to_16_reg_map[] =
759 {
760   X, X, 2, 3, 4, 5, 6, 7,
761   X, X, X, X, X, X, X, X,
762   0, 1, X, X, X, X, X, X,
763   X, X, X, X, X, X, X, X
764 };
765 #undef X
766
767 /* Map mips16 register numbers to normal MIPS register numbers.  */
768
769 static const unsigned int mips16_to_32_reg_map[] =
770 {
771   16, 17, 2, 3, 4, 5, 6, 7
772 };
773
774 /* Map normal MIPS register numbers to microMIPS register numbers.  */
775
776 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
777 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
778 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
779 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
780 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
781 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
782 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
783
784 #define X ILLEGAL_REG
785 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
786 static const int mips32_to_micromips_reg_m_map[] =
787 {
788   0, X, 2, 3, X, X, X, X,
789   X, X, X, X, X, X, X, X,
790   4, 1, 5, 6, 7, X, X, X,
791   X, X, X, X, X, X, X, X
792 };
793
794 /* reg type q: 0, 2-7. 17.  */
795 static const int mips32_to_micromips_reg_q_map[] =
796 {
797   0, X, 2, 3, 4, 5, 6, 7,
798   X, X, X, X, X, X, X, X,
799   X, 1, X, X, X, X, X, X,
800   X, X, X, X, X, X, X, X
801 };
802
803 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
804 #undef X
805
806 /* Map microMIPS register numbers to normal MIPS register numbers.  */
807
808 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
809 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
810 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
811 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
812 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
813 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
814
815 /* The microMIPS registers with type h.  */
816 static const unsigned int micromips_to_32_reg_h_map1[] =
817 {
818   5, 5, 6, 4, 4, 4, 4, 4
819 };
820 static const unsigned int micromips_to_32_reg_h_map2[] =
821 {
822   6, 7, 7, 21, 22, 5, 6, 7
823 };
824
825 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
826
827 /* The microMIPS registers with type m.  */
828 static const unsigned int micromips_to_32_reg_m_map[] =
829 {
830   0, 17, 2, 3, 16, 18, 19, 20
831 };
832
833 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
834
835 /* The microMIPS registers with type q.  */
836 static const unsigned int micromips_to_32_reg_q_map[] =
837 {
838   0, 17, 2, 3, 4, 5, 6, 7
839 };
840
841 /* microMIPS imm type B.  */
842 static const int micromips_imm_b_map[] =
843 {
844   1, 4, 8, 12, 16, 20, 24, -1
845 };
846
847 /* microMIPS imm type C.  */
848 static const int micromips_imm_c_map[] =
849 {
850   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
851 };
852
853 /* Classifies the kind of instructions we're interested in when
854    implementing -mfix-vr4120.  */
855 enum fix_vr4120_class
856 {
857   FIX_VR4120_MACC,
858   FIX_VR4120_DMACC,
859   FIX_VR4120_MULT,
860   FIX_VR4120_DMULT,
861   FIX_VR4120_DIV,
862   FIX_VR4120_MTHILO,
863   NUM_FIX_VR4120_CLASSES
864 };
865
866 /* ...likewise -mfix-loongson2f-jump.  */
867 static bfd_boolean mips_fix_loongson2f_jump;
868
869 /* ...likewise -mfix-loongson2f-nop.  */
870 static bfd_boolean mips_fix_loongson2f_nop;
871
872 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
873 static bfd_boolean mips_fix_loongson2f;
874
875 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
876    there must be at least one other instruction between an instruction
877    of type X and an instruction of type Y.  */
878 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
879
880 /* True if -mfix-vr4120 is in force.  */
881 static int mips_fix_vr4120;
882
883 /* ...likewise -mfix-vr4130.  */
884 static int mips_fix_vr4130;
885
886 /* ...likewise -mfix-24k.  */
887 static int mips_fix_24k;
888
889 /* ...likewise -mfix-cn63xxp1 */
890 static bfd_boolean mips_fix_cn63xxp1;
891
892 /* We don't relax branches by default, since this causes us to expand
893    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
894    fail to compute the offset before expanding the macro to the most
895    efficient expansion.  */
896
897 static int mips_relax_branch;
898 \f
899 /* The expansion of many macros depends on the type of symbol that
900    they refer to.  For example, when generating position-dependent code,
901    a macro that refers to a symbol may have two different expansions,
902    one which uses GP-relative addresses and one which uses absolute
903    addresses.  When generating SVR4-style PIC, a macro may have
904    different expansions for local and global symbols.
905
906    We handle these situations by generating both sequences and putting
907    them in variant frags.  In position-dependent code, the first sequence
908    will be the GP-relative one and the second sequence will be the
909    absolute one.  In SVR4 PIC, the first sequence will be for global
910    symbols and the second will be for local symbols.
911
912    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
913    SECOND are the lengths of the two sequences in bytes.  These fields
914    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
915    the subtype has the following flags:
916
917    RELAX_USE_SECOND
918         Set if it has been decided that we should use the second
919         sequence instead of the first.
920
921    RELAX_SECOND_LONGER
922         Set in the first variant frag if the macro's second implementation
923         is longer than its first.  This refers to the macro as a whole,
924         not an individual relaxation.
925
926    RELAX_NOMACRO
927         Set in the first variant frag if the macro appeared in a .set nomacro
928         block and if one alternative requires a warning but the other does not.
929
930    RELAX_DELAY_SLOT
931         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
932         delay slot.
933
934    RELAX_DELAY_SLOT_16BIT
935         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
936         16-bit instruction.
937
938    RELAX_DELAY_SLOT_SIZE_FIRST
939         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
940         the macro is of the wrong size for the branch delay slot.
941
942    RELAX_DELAY_SLOT_SIZE_SECOND
943         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
944         the macro is of the wrong size for the branch delay slot.
945
946    The frag's "opcode" points to the first fixup for relaxable code.
947
948    Relaxable macros are generated using a sequence such as:
949
950       relax_start (SYMBOL);
951       ... generate first expansion ...
952       relax_switch ();
953       ... generate second expansion ...
954       relax_end ();
955
956    The code and fixups for the unwanted alternative are discarded
957    by md_convert_frag.  */
958 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
959
960 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
961 #define RELAX_SECOND(X) ((X) & 0xff)
962 #define RELAX_USE_SECOND 0x10000
963 #define RELAX_SECOND_LONGER 0x20000
964 #define RELAX_NOMACRO 0x40000
965 #define RELAX_DELAY_SLOT 0x80000
966 #define RELAX_DELAY_SLOT_16BIT 0x100000
967 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
968 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
969
970 /* Branch without likely bit.  If label is out of range, we turn:
971
972         beq reg1, reg2, label
973         delay slot
974
975    into
976
977         bne reg1, reg2, 0f
978         nop
979         j label
980      0: delay slot
981
982    with the following opcode replacements:
983
984         beq <-> bne
985         blez <-> bgtz
986         bltz <-> bgez
987         bc1f <-> bc1t
988
989         bltzal <-> bgezal  (with jal label instead of j label)
990
991    Even though keeping the delay slot instruction in the delay slot of
992    the branch would be more efficient, it would be very tricky to do
993    correctly, because we'd have to introduce a variable frag *after*
994    the delay slot instruction, and expand that instead.  Let's do it
995    the easy way for now, even if the branch-not-taken case now costs
996    one additional instruction.  Out-of-range branches are not supposed
997    to be common, anyway.
998
999    Branch likely.  If label is out of range, we turn:
1000
1001         beql reg1, reg2, label
1002         delay slot (annulled if branch not taken)
1003
1004    into
1005
1006         beql reg1, reg2, 1f
1007         nop
1008         beql $0, $0, 2f
1009         nop
1010      1: j[al] label
1011         delay slot (executed only if branch taken)
1012      2:
1013
1014    It would be possible to generate a shorter sequence by losing the
1015    likely bit, generating something like:
1016
1017         bne reg1, reg2, 0f
1018         nop
1019         j[al] label
1020         delay slot (executed only if branch taken)
1021      0:
1022
1023         beql -> bne
1024         bnel -> beq
1025         blezl -> bgtz
1026         bgtzl -> blez
1027         bltzl -> bgez
1028         bgezl -> bltz
1029         bc1fl -> bc1t
1030         bc1tl -> bc1f
1031
1032         bltzall -> bgezal  (with jal label instead of j label)
1033         bgezall -> bltzal  (ditto)
1034
1035
1036    but it's not clear that it would actually improve performance.  */
1037 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1038   ((relax_substateT)                                            \
1039    (0xc0000000                                                  \
1040     | ((at) & 0x1f)                                             \
1041     | ((toofar) ? 0x20 : 0)                                     \
1042     | ((link) ? 0x40 : 0)                                       \
1043     | ((likely) ? 0x80 : 0)                                     \
1044     | ((uncond) ? 0x100 : 0)))
1045 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1046 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1047 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1048 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1049 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1050 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1051
1052 /* For mips16 code, we use an entirely different form of relaxation.
1053    mips16 supports two versions of most instructions which take
1054    immediate values: a small one which takes some small value, and a
1055    larger one which takes a 16 bit value.  Since branches also follow
1056    this pattern, relaxing these values is required.
1057
1058    We can assemble both mips16 and normal MIPS code in a single
1059    object.  Therefore, we need to support this type of relaxation at
1060    the same time that we support the relaxation described above.  We
1061    use the high bit of the subtype field to distinguish these cases.
1062
1063    The information we store for this type of relaxation is the
1064    argument code found in the opcode file for this relocation, whether
1065    the user explicitly requested a small or extended form, and whether
1066    the relocation is in a jump or jal delay slot.  That tells us the
1067    size of the value, and how it should be stored.  We also store
1068    whether the fragment is considered to be extended or not.  We also
1069    store whether this is known to be a branch to a different section,
1070    whether we have tried to relax this frag yet, and whether we have
1071    ever extended a PC relative fragment because of a shift count.  */
1072 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1073   (0x80000000                                                   \
1074    | ((type) & 0xff)                                            \
1075    | ((small) ? 0x100 : 0)                                      \
1076    | ((ext) ? 0x200 : 0)                                        \
1077    | ((dslot) ? 0x400 : 0)                                      \
1078    | ((jal_dslot) ? 0x800 : 0))
1079 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1080 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1081 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1082 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1083 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1084 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1085 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1086 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1087 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1088 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1089 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1090 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1091
1092 /* For microMIPS code, we use relaxation similar to one we use for
1093    MIPS16 code.  Some instructions that take immediate values support
1094    two encodings: a small one which takes some small value, and a
1095    larger one which takes a 16 bit value.  As some branches also follow
1096    this pattern, relaxing these values is required.
1097
1098    We can assemble both microMIPS and normal MIPS code in a single
1099    object.  Therefore, we need to support this type of relaxation at
1100    the same time that we support the relaxation described above.  We
1101    use one of the high bits of the subtype field to distinguish these
1102    cases.
1103
1104    The information we store for this type of relaxation is the argument
1105    code found in the opcode file for this relocation, the register
1106    selected as the assembler temporary, whether the branch is
1107    unconditional, whether it is compact, whether it stores the link
1108    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1109    branches to a sequence of instructions is enabled, and whether the
1110    displacement of a branch is too large to fit as an immediate argument
1111    of a 16-bit and a 32-bit branch, respectively.  */
1112 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1113                                relax32, toofar16, toofar32)     \
1114   (0x40000000                                                   \
1115    | ((type) & 0xff)                                            \
1116    | (((at) & 0x1f) << 8)                                       \
1117    | ((uncond) ? 0x2000 : 0)                                    \
1118    | ((compact) ? 0x4000 : 0)                                   \
1119    | ((link) ? 0x8000 : 0)                                      \
1120    | ((relax32) ? 0x10000 : 0)                                  \
1121    | ((toofar16) ? 0x20000 : 0)                                 \
1122    | ((toofar32) ? 0x40000 : 0))
1123 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1124 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1125 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1126 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1127 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1128 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1129 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1130
1131 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1132 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1133 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1134 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1135 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1136 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1137
1138 /* Sign-extend 16-bit value X.  */
1139 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1140
1141 /* Is the given value a sign-extended 32-bit value?  */
1142 #define IS_SEXT_32BIT_NUM(x)                                            \
1143   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1144    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1145
1146 /* Is the given value a sign-extended 16-bit value?  */
1147 #define IS_SEXT_16BIT_NUM(x)                                            \
1148   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1149    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1150
1151 /* Is the given value a sign-extended 12-bit value?  */
1152 #define IS_SEXT_12BIT_NUM(x)                                            \
1153   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1154
1155 /* Is the given value a sign-extended 9-bit value?  */
1156 #define IS_SEXT_9BIT_NUM(x)                                             \
1157   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1158
1159 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1160 #define IS_ZEXT_32BIT_NUM(x)                                            \
1161   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1162    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1163
1164 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1165    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1166 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1167   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1168               | (((VALUE) & (MASK)) << (SHIFT)))
1169
1170 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1171    SHIFT places.  */
1172 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1173   (((STRUCT) >> (SHIFT)) & (MASK))
1174
1175 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1176    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1177
1178    include/opcode/mips.h specifies operand fields using the macros
1179    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1180    with "MIPS16OP" instead of "OP".  */
1181 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1182   do \
1183     if (!(MICROMIPS)) \
1184       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1185                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1186     else \
1187       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1188                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1189   while (0)
1190 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1191   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1192                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1193
1194 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1195 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1196   (!(MICROMIPS) \
1197    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1198    : EXTRACT_BITS ((INSN).insn_opcode, \
1199                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1200 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1201   EXTRACT_BITS ((INSN).insn_opcode, \
1202                 MIPS16OP_MASK_##FIELD, \
1203                 MIPS16OP_SH_##FIELD)
1204
1205 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1206 #define MIPS16_EXTEND (0xf000U << 16)
1207 \f
1208 /* Whether or not we are emitting a branch-likely macro.  */
1209 static bfd_boolean emit_branch_likely_macro = FALSE;
1210
1211 /* Global variables used when generating relaxable macros.  See the
1212    comment above RELAX_ENCODE for more details about how relaxation
1213    is used.  */
1214 static struct {
1215   /* 0 if we're not emitting a relaxable macro.
1216      1 if we're emitting the first of the two relaxation alternatives.
1217      2 if we're emitting the second alternative.  */
1218   int sequence;
1219
1220   /* The first relaxable fixup in the current frag.  (In other words,
1221      the first fixup that refers to relaxable code.)  */
1222   fixS *first_fixup;
1223
1224   /* sizes[0] says how many bytes of the first alternative are stored in
1225      the current frag.  Likewise sizes[1] for the second alternative.  */
1226   unsigned int sizes[2];
1227
1228   /* The symbol on which the choice of sequence depends.  */
1229   symbolS *symbol;
1230 } mips_relax;
1231 \f
1232 /* Global variables used to decide whether a macro needs a warning.  */
1233 static struct {
1234   /* True if the macro is in a branch delay slot.  */
1235   bfd_boolean delay_slot_p;
1236
1237   /* Set to the length in bytes required if the macro is in a delay slot
1238      that requires a specific length of instruction, otherwise zero.  */
1239   unsigned int delay_slot_length;
1240
1241   /* For relaxable macros, sizes[0] is the length of the first alternative
1242      in bytes and sizes[1] is the length of the second alternative.
1243      For non-relaxable macros, both elements give the length of the
1244      macro in bytes.  */
1245   unsigned int sizes[2];
1246
1247   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1248      instruction of the first alternative in bytes and first_insn_sizes[1]
1249      is the length of the first instruction of the second alternative.
1250      For non-relaxable macros, both elements give the length of the first
1251      instruction in bytes.
1252
1253      Set to zero if we haven't yet seen the first instruction.  */
1254   unsigned int first_insn_sizes[2];
1255
1256   /* For relaxable macros, insns[0] is the number of instructions for the
1257      first alternative and insns[1] is the number of instructions for the
1258      second alternative.
1259
1260      For non-relaxable macros, both elements give the number of
1261      instructions for the macro.  */
1262   unsigned int insns[2];
1263
1264   /* The first variant frag for this macro.  */
1265   fragS *first_frag;
1266 } mips_macro_warning;
1267 \f
1268 /* Prototypes for static functions.  */
1269
1270 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1271
1272 static void append_insn
1273   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1274    bfd_boolean expansionp);
1275 static void mips_no_prev_insn (void);
1276 static void macro_build (expressionS *, const char *, const char *, ...);
1277 static void mips16_macro_build
1278   (expressionS *, const char *, const char *, va_list *);
1279 static void load_register (int, expressionS *, int);
1280 static void macro_start (void);
1281 static void macro_end (void);
1282 static void macro (struct mips_cl_insn *ip, char *str);
1283 static void mips16_macro (struct mips_cl_insn * ip);
1284 static void mips_ip (char *str, struct mips_cl_insn * ip);
1285 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1286 static void mips16_immed
1287   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1288    unsigned int, unsigned long *);
1289 static size_t my_getSmallExpression
1290   (expressionS *, bfd_reloc_code_real_type *, char *);
1291 static void my_getExpression (expressionS *, char *);
1292 static void s_align (int);
1293 static void s_change_sec (int);
1294 static void s_change_section (int);
1295 static void s_cons (int);
1296 static void s_float_cons (int);
1297 static void s_mips_globl (int);
1298 static void s_option (int);
1299 static void s_mipsset (int);
1300 static void s_abicalls (int);
1301 static void s_cpload (int);
1302 static void s_cpsetup (int);
1303 static void s_cplocal (int);
1304 static void s_cprestore (int);
1305 static void s_cpreturn (int);
1306 static void s_dtprelword (int);
1307 static void s_dtpreldword (int);
1308 static void s_tprelword (int);
1309 static void s_tpreldword (int);
1310 static void s_gpvalue (int);
1311 static void s_gpword (int);
1312 static void s_gpdword (int);
1313 static void s_ehword (int);
1314 static void s_cpadd (int);
1315 static void s_insn (int);
1316 static void s_nan (int);
1317 static void md_obj_begin (void);
1318 static void md_obj_end (void);
1319 static void s_mips_ent (int);
1320 static void s_mips_end (int);
1321 static void s_mips_frame (int);
1322 static void s_mips_mask (int reg_type);
1323 static void s_mips_stab (int);
1324 static void s_mips_weakext (int);
1325 static void s_mips_file (int);
1326 static void s_mips_loc (int);
1327 static bfd_boolean pic_need_relax (symbolS *, asection *);
1328 static int relaxed_branch_length (fragS *, asection *, int);
1329 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1330 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1331
1332 /* Table and functions used to map between CPU/ISA names, and
1333    ISA levels, and CPU numbers.  */
1334
1335 struct mips_cpu_info
1336 {
1337   const char *name;           /* CPU or ISA name.  */
1338   int flags;                  /* MIPS_CPU_* flags.  */
1339   int ase;                    /* Set of ASEs implemented by the CPU.  */
1340   int isa;                    /* ISA level.  */
1341   int cpu;                    /* CPU number (default CPU if ISA).  */
1342 };
1343
1344 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1345
1346 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1347 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1348 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1349 \f
1350 /* Command-line options.  */
1351 const char *md_shortopts = "O::g::G:";
1352
1353 enum options
1354   {
1355     OPTION_MARCH = OPTION_MD_BASE,
1356     OPTION_MTUNE,
1357     OPTION_MIPS1,
1358     OPTION_MIPS2,
1359     OPTION_MIPS3,
1360     OPTION_MIPS4,
1361     OPTION_MIPS5,
1362     OPTION_MIPS32,
1363     OPTION_MIPS64,
1364     OPTION_MIPS32R2,
1365     OPTION_MIPS64R2,
1366     OPTION_MIPS16,
1367     OPTION_NO_MIPS16,
1368     OPTION_MIPS3D,
1369     OPTION_NO_MIPS3D,
1370     OPTION_MDMX,
1371     OPTION_NO_MDMX,
1372     OPTION_DSP,
1373     OPTION_NO_DSP,
1374     OPTION_MT,
1375     OPTION_NO_MT,
1376     OPTION_VIRT,
1377     OPTION_NO_VIRT,
1378     OPTION_SMARTMIPS,
1379     OPTION_NO_SMARTMIPS,
1380     OPTION_DSPR2,
1381     OPTION_NO_DSPR2,
1382     OPTION_EVA,
1383     OPTION_NO_EVA,
1384     OPTION_MICROMIPS,
1385     OPTION_NO_MICROMIPS,
1386     OPTION_MCU,
1387     OPTION_NO_MCU,
1388     OPTION_COMPAT_ARCH_BASE,
1389     OPTION_M4650,
1390     OPTION_NO_M4650,
1391     OPTION_M4010,
1392     OPTION_NO_M4010,
1393     OPTION_M4100,
1394     OPTION_NO_M4100,
1395     OPTION_M3900,
1396     OPTION_NO_M3900,
1397     OPTION_M7000_HILO_FIX,
1398     OPTION_MNO_7000_HILO_FIX,
1399     OPTION_FIX_24K,
1400     OPTION_NO_FIX_24K,
1401     OPTION_FIX_LOONGSON2F_JUMP,
1402     OPTION_NO_FIX_LOONGSON2F_JUMP,
1403     OPTION_FIX_LOONGSON2F_NOP,
1404     OPTION_NO_FIX_LOONGSON2F_NOP,
1405     OPTION_FIX_VR4120,
1406     OPTION_NO_FIX_VR4120,
1407     OPTION_FIX_VR4130,
1408     OPTION_NO_FIX_VR4130,
1409     OPTION_FIX_CN63XXP1,
1410     OPTION_NO_FIX_CN63XXP1,
1411     OPTION_TRAP,
1412     OPTION_BREAK,
1413     OPTION_EB,
1414     OPTION_EL,
1415     OPTION_FP32,
1416     OPTION_GP32,
1417     OPTION_CONSTRUCT_FLOATS,
1418     OPTION_NO_CONSTRUCT_FLOATS,
1419     OPTION_FP64,
1420     OPTION_GP64,
1421     OPTION_RELAX_BRANCH,
1422     OPTION_NO_RELAX_BRANCH,
1423     OPTION_INSN32,
1424     OPTION_NO_INSN32,
1425     OPTION_MSHARED,
1426     OPTION_MNO_SHARED,
1427     OPTION_MSYM32,
1428     OPTION_MNO_SYM32,
1429     OPTION_SOFT_FLOAT,
1430     OPTION_HARD_FLOAT,
1431     OPTION_SINGLE_FLOAT,
1432     OPTION_DOUBLE_FLOAT,
1433     OPTION_32,
1434     OPTION_CALL_SHARED,
1435     OPTION_CALL_NONPIC,
1436     OPTION_NON_SHARED,
1437     OPTION_XGOT,
1438     OPTION_MABI,
1439     OPTION_N32,
1440     OPTION_64,
1441     OPTION_MDEBUG,
1442     OPTION_NO_MDEBUG,
1443     OPTION_PDR,
1444     OPTION_NO_PDR,
1445     OPTION_MVXWORKS_PIC,
1446     OPTION_NAN,
1447     OPTION_END_OF_ENUM
1448   };
1449
1450 struct option md_longopts[] =
1451 {
1452   /* Options which specify architecture.  */
1453   {"march", required_argument, NULL, OPTION_MARCH},
1454   {"mtune", required_argument, NULL, OPTION_MTUNE},
1455   {"mips0", no_argument, NULL, OPTION_MIPS1},
1456   {"mips1", no_argument, NULL, OPTION_MIPS1},
1457   {"mips2", no_argument, NULL, OPTION_MIPS2},
1458   {"mips3", no_argument, NULL, OPTION_MIPS3},
1459   {"mips4", no_argument, NULL, OPTION_MIPS4},
1460   {"mips5", no_argument, NULL, OPTION_MIPS5},
1461   {"mips32", no_argument, NULL, OPTION_MIPS32},
1462   {"mips64", no_argument, NULL, OPTION_MIPS64},
1463   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1464   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1465
1466   /* Options which specify Application Specific Extensions (ASEs).  */
1467   {"mips16", no_argument, NULL, OPTION_MIPS16},
1468   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1469   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1470   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1471   {"mdmx", no_argument, NULL, OPTION_MDMX},
1472   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1473   {"mdsp", no_argument, NULL, OPTION_DSP},
1474   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1475   {"mmt", no_argument, NULL, OPTION_MT},
1476   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1477   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1478   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1479   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1480   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1481   {"meva", no_argument, NULL, OPTION_EVA},
1482   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1483   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1484   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1485   {"mmcu", no_argument, NULL, OPTION_MCU},
1486   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1487   {"mvirt", no_argument, NULL, OPTION_VIRT},
1488   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1489
1490   /* Old-style architecture options.  Don't add more of these.  */
1491   {"m4650", no_argument, NULL, OPTION_M4650},
1492   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1493   {"m4010", no_argument, NULL, OPTION_M4010},
1494   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1495   {"m4100", no_argument, NULL, OPTION_M4100},
1496   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1497   {"m3900", no_argument, NULL, OPTION_M3900},
1498   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1499
1500   /* Options which enable bug fixes.  */
1501   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1502   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1503   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1504   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1505   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1506   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1507   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1508   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1509   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1510   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1511   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1512   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1513   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1514   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1515   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1516
1517   /* Miscellaneous options.  */
1518   {"trap", no_argument, NULL, OPTION_TRAP},
1519   {"no-break", no_argument, NULL, OPTION_TRAP},
1520   {"break", no_argument, NULL, OPTION_BREAK},
1521   {"no-trap", no_argument, NULL, OPTION_BREAK},
1522   {"EB", no_argument, NULL, OPTION_EB},
1523   {"EL", no_argument, NULL, OPTION_EL},
1524   {"mfp32", no_argument, NULL, OPTION_FP32},
1525   {"mgp32", no_argument, NULL, OPTION_GP32},
1526   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1527   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1528   {"mfp64", no_argument, NULL, OPTION_FP64},
1529   {"mgp64", no_argument, NULL, OPTION_GP64},
1530   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1531   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1532   {"minsn32", no_argument, NULL, OPTION_INSN32},
1533   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1534   {"mshared", no_argument, NULL, OPTION_MSHARED},
1535   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1536   {"msym32", no_argument, NULL, OPTION_MSYM32},
1537   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1538   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1539   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1540   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1541   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1542
1543   /* Strictly speaking this next option is ELF specific,
1544      but we allow it for other ports as well in order to
1545      make testing easier.  */
1546   {"32", no_argument, NULL, OPTION_32},
1547
1548   /* ELF-specific options.  */
1549   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1550   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1551   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1552   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1553   {"xgot", no_argument, NULL, OPTION_XGOT},
1554   {"mabi", required_argument, NULL, OPTION_MABI},
1555   {"n32", no_argument, NULL, OPTION_N32},
1556   {"64", no_argument, NULL, OPTION_64},
1557   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1558   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1559   {"mpdr", no_argument, NULL, OPTION_PDR},
1560   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1561   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1562   {"mnan", required_argument, NULL, OPTION_NAN},
1563
1564   {NULL, no_argument, NULL, 0}
1565 };
1566 size_t md_longopts_size = sizeof (md_longopts);
1567 \f
1568 /* Information about either an Application Specific Extension or an
1569    optional architecture feature that, for simplicity, we treat in the
1570    same way as an ASE.  */
1571 struct mips_ase
1572 {
1573   /* The name of the ASE, used in both the command-line and .set options.  */
1574   const char *name;
1575
1576   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1577      and 64-bit architectures, the flags here refer to the subset that
1578      is available on both.  */
1579   unsigned int flags;
1580
1581   /* The ASE_* flag used for instructions that are available on 64-bit
1582      architectures but that are not included in FLAGS.  */
1583   unsigned int flags64;
1584
1585   /* The command-line options that turn the ASE on and off.  */
1586   int option_on;
1587   int option_off;
1588
1589   /* The minimum required architecture revisions for MIPS32, MIPS64,
1590      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1591   int mips32_rev;
1592   int mips64_rev;
1593   int micromips32_rev;
1594   int micromips64_rev;
1595 };
1596
1597 /* A table of all supported ASEs.  */
1598 static const struct mips_ase mips_ases[] = {
1599   { "dsp", ASE_DSP, ASE_DSP64,
1600     OPTION_DSP, OPTION_NO_DSP,
1601     2, 2, 2, 2 },
1602
1603   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1604     OPTION_DSPR2, OPTION_NO_DSPR2,
1605     2, 2, 2, 2 },
1606
1607   { "eva", ASE_EVA, 0,
1608     OPTION_EVA, OPTION_NO_EVA,
1609     2, 2, 2, 2 },
1610
1611   { "mcu", ASE_MCU, 0,
1612     OPTION_MCU, OPTION_NO_MCU,
1613     2, 2, 2, 2 },
1614
1615   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1616   { "mdmx", ASE_MDMX, 0,
1617     OPTION_MDMX, OPTION_NO_MDMX,
1618     -1, 1, -1, -1 },
1619
1620   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1621   { "mips3d", ASE_MIPS3D, 0,
1622     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1623     2, 1, -1, -1 },
1624
1625   { "mt", ASE_MT, 0,
1626     OPTION_MT, OPTION_NO_MT,
1627     2, 2, -1, -1 },
1628
1629   { "smartmips", ASE_SMARTMIPS, 0,
1630     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1631     1, -1, -1, -1 },
1632
1633   { "virt", ASE_VIRT, ASE_VIRT64,
1634     OPTION_VIRT, OPTION_NO_VIRT,
1635     2, 2, 2, 2 }
1636 };
1637
1638 /* The set of ASEs that require -mfp64.  */
1639 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1640
1641 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1642 static const unsigned int mips_ase_groups[] = {
1643   ASE_DSP | ASE_DSPR2
1644 };
1645 \f
1646 /* Pseudo-op table.
1647
1648    The following pseudo-ops from the Kane and Heinrich MIPS book
1649    should be defined here, but are currently unsupported: .alias,
1650    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1651
1652    The following pseudo-ops from the Kane and Heinrich MIPS book are
1653    specific to the type of debugging information being generated, and
1654    should be defined by the object format: .aent, .begin, .bend,
1655    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1656    .vreg.
1657
1658    The following pseudo-ops from the Kane and Heinrich MIPS book are
1659    not MIPS CPU specific, but are also not specific to the object file
1660    format.  This file is probably the best place to define them, but
1661    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1662
1663 static const pseudo_typeS mips_pseudo_table[] =
1664 {
1665   /* MIPS specific pseudo-ops.  */
1666   {"option", s_option, 0},
1667   {"set", s_mipsset, 0},
1668   {"rdata", s_change_sec, 'r'},
1669   {"sdata", s_change_sec, 's'},
1670   {"livereg", s_ignore, 0},
1671   {"abicalls", s_abicalls, 0},
1672   {"cpload", s_cpload, 0},
1673   {"cpsetup", s_cpsetup, 0},
1674   {"cplocal", s_cplocal, 0},
1675   {"cprestore", s_cprestore, 0},
1676   {"cpreturn", s_cpreturn, 0},
1677   {"dtprelword", s_dtprelword, 0},
1678   {"dtpreldword", s_dtpreldword, 0},
1679   {"tprelword", s_tprelword, 0},
1680   {"tpreldword", s_tpreldword, 0},
1681   {"gpvalue", s_gpvalue, 0},
1682   {"gpword", s_gpword, 0},
1683   {"gpdword", s_gpdword, 0},
1684   {"ehword", s_ehword, 0},
1685   {"cpadd", s_cpadd, 0},
1686   {"insn", s_insn, 0},
1687   {"nan", s_nan, 0},
1688
1689   /* Relatively generic pseudo-ops that happen to be used on MIPS
1690      chips.  */
1691   {"asciiz", stringer, 8 + 1},
1692   {"bss", s_change_sec, 'b'},
1693   {"err", s_err, 0},
1694   {"half", s_cons, 1},
1695   {"dword", s_cons, 3},
1696   {"weakext", s_mips_weakext, 0},
1697   {"origin", s_org, 0},
1698   {"repeat", s_rept, 0},
1699
1700   /* For MIPS this is non-standard, but we define it for consistency.  */
1701   {"sbss", s_change_sec, 'B'},
1702
1703   /* These pseudo-ops are defined in read.c, but must be overridden
1704      here for one reason or another.  */
1705   {"align", s_align, 0},
1706   {"byte", s_cons, 0},
1707   {"data", s_change_sec, 'd'},
1708   {"double", s_float_cons, 'd'},
1709   {"float", s_float_cons, 'f'},
1710   {"globl", s_mips_globl, 0},
1711   {"global", s_mips_globl, 0},
1712   {"hword", s_cons, 1},
1713   {"int", s_cons, 2},
1714   {"long", s_cons, 2},
1715   {"octa", s_cons, 4},
1716   {"quad", s_cons, 3},
1717   {"section", s_change_section, 0},
1718   {"short", s_cons, 1},
1719   {"single", s_float_cons, 'f'},
1720   {"stabd", s_mips_stab, 'd'},
1721   {"stabn", s_mips_stab, 'n'},
1722   {"stabs", s_mips_stab, 's'},
1723   {"text", s_change_sec, 't'},
1724   {"word", s_cons, 2},
1725
1726   { "extern", ecoff_directive_extern, 0},
1727
1728   { NULL, NULL, 0 },
1729 };
1730
1731 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1732 {
1733   /* These pseudo-ops should be defined by the object file format.
1734      However, a.out doesn't support them, so we have versions here.  */
1735   {"aent", s_mips_ent, 1},
1736   {"bgnb", s_ignore, 0},
1737   {"end", s_mips_end, 0},
1738   {"endb", s_ignore, 0},
1739   {"ent", s_mips_ent, 0},
1740   {"file", s_mips_file, 0},
1741   {"fmask", s_mips_mask, 'F'},
1742   {"frame", s_mips_frame, 0},
1743   {"loc", s_mips_loc, 0},
1744   {"mask", s_mips_mask, 'R'},
1745   {"verstamp", s_ignore, 0},
1746   { NULL, NULL, 0 },
1747 };
1748
1749 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1750    purpose of the `.dc.a' internal pseudo-op.  */
1751
1752 int
1753 mips_address_bytes (void)
1754 {
1755   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1756 }
1757
1758 extern void pop_insert (const pseudo_typeS *);
1759
1760 void
1761 mips_pop_insert (void)
1762 {
1763   pop_insert (mips_pseudo_table);
1764   if (! ECOFF_DEBUGGING)
1765     pop_insert (mips_nonecoff_pseudo_table);
1766 }
1767 \f
1768 /* Symbols labelling the current insn.  */
1769
1770 struct insn_label_list
1771 {
1772   struct insn_label_list *next;
1773   symbolS *label;
1774 };
1775
1776 static struct insn_label_list *free_insn_labels;
1777 #define label_list tc_segment_info_data.labels
1778
1779 static void mips_clear_insn_labels (void);
1780 static void mips_mark_labels (void);
1781 static void mips_compressed_mark_labels (void);
1782
1783 static inline void
1784 mips_clear_insn_labels (void)
1785 {
1786   register struct insn_label_list **pl;
1787   segment_info_type *si;
1788
1789   if (now_seg)
1790     {
1791       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1792         ;
1793       
1794       si = seg_info (now_seg);
1795       *pl = si->label_list;
1796       si->label_list = NULL;
1797     }
1798 }
1799
1800 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1801
1802 static inline void
1803 mips_mark_labels (void)
1804 {
1805   if (HAVE_CODE_COMPRESSION)
1806     mips_compressed_mark_labels ();
1807 }
1808 \f
1809 static char *expr_end;
1810
1811 /* Expressions which appear in macro instructions.  These are set by
1812    mips_ip and read by macro.  */
1813
1814 static expressionS imm_expr;
1815 static expressionS imm2_expr;
1816
1817 /* The relocatable field in an instruction and the relocs associated
1818    with it.  These variables are used for instructions like LUI and
1819    JAL as well as true offsets.  They are also used for address
1820    operands in macros.  */
1821
1822 static expressionS offset_expr;
1823 static bfd_reloc_code_real_type offset_reloc[3]
1824   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1825
1826 /* This is set to the resulting size of the instruction to be produced
1827    by mips16_ip if an explicit extension is used or by mips_ip if an
1828    explicit size is supplied.  */
1829
1830 static unsigned int forced_insn_length;
1831
1832 /* True if we are assembling an instruction.  All dot symbols defined during
1833    this time should be treated as code labels.  */
1834
1835 static bfd_boolean mips_assembling_insn;
1836
1837 /* The pdr segment for per procedure frame/regmask info.  Not used for
1838    ECOFF debugging.  */
1839
1840 static segT pdr_seg;
1841
1842 /* The default target format to use.  */
1843
1844 #if defined (TE_FreeBSD)
1845 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1846 #elif defined (TE_TMIPS)
1847 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1848 #else
1849 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1850 #endif
1851
1852 const char *
1853 mips_target_format (void)
1854 {
1855   switch (OUTPUT_FLAVOR)
1856     {
1857     case bfd_target_elf_flavour:
1858 #ifdef TE_VXWORKS
1859       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1860         return (target_big_endian
1861                 ? "elf32-bigmips-vxworks"
1862                 : "elf32-littlemips-vxworks");
1863 #endif
1864       return (target_big_endian
1865               ? (HAVE_64BIT_OBJECTS
1866                  ? ELF_TARGET ("elf64-", "big")
1867                  : (HAVE_NEWABI
1868                     ? ELF_TARGET ("elf32-n", "big")
1869                     : ELF_TARGET ("elf32-", "big")))
1870               : (HAVE_64BIT_OBJECTS
1871                  ? ELF_TARGET ("elf64-", "little")
1872                  : (HAVE_NEWABI
1873                     ? ELF_TARGET ("elf32-n", "little")
1874                     : ELF_TARGET ("elf32-", "little"))));
1875     default:
1876       abort ();
1877       return NULL;
1878     }
1879 }
1880
1881 /* Return the ISA revision that is currently in use, or 0 if we are
1882    generating code for MIPS V or below.  */
1883
1884 static int
1885 mips_isa_rev (void)
1886 {
1887   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1888     return 2;
1889
1890   /* microMIPS implies revision 2 or above.  */
1891   if (mips_opts.micromips)
1892     return 2;
1893
1894   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1895     return 1;
1896
1897   return 0;
1898 }
1899
1900 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1901
1902 static unsigned int
1903 mips_ase_mask (unsigned int flags)
1904 {
1905   unsigned int i;
1906
1907   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1908     if (flags & mips_ase_groups[i])
1909       flags |= mips_ase_groups[i];
1910   return flags;
1911 }
1912
1913 /* Check whether the current ISA supports ASE.  Issue a warning if
1914    appropriate.  */
1915
1916 static void
1917 mips_check_isa_supports_ase (const struct mips_ase *ase)
1918 {
1919   const char *base;
1920   int min_rev, size;
1921   static unsigned int warned_isa;
1922   static unsigned int warned_fp32;
1923
1924   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1925     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1926   else
1927     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1928   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1929       && (warned_isa & ase->flags) != ase->flags)
1930     {
1931       warned_isa |= ase->flags;
1932       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1933       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1934       if (min_rev < 0)
1935         as_warn (_("The %d-bit %s architecture does not support the"
1936                    " `%s' extension"), size, base, ase->name);
1937       else
1938         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1939                  ase->name, base, size, min_rev);
1940     }
1941   if ((ase->flags & FP64_ASES)
1942       && mips_opts.fp32
1943       && (warned_fp32 & ase->flags) != ase->flags)
1944     {
1945       warned_fp32 |= ase->flags;
1946       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1947     }
1948 }
1949
1950 /* Check all enabled ASEs to see whether they are supported by the
1951    chosen architecture.  */
1952
1953 static void
1954 mips_check_isa_supports_ases (void)
1955 {
1956   unsigned int i, mask;
1957
1958   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1959     {
1960       mask = mips_ase_mask (mips_ases[i].flags);
1961       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1962         mips_check_isa_supports_ase (&mips_ases[i]);
1963     }
1964 }
1965
1966 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1967    that were affected.  */
1968
1969 static unsigned int
1970 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1971 {
1972   unsigned int mask;
1973
1974   mask = mips_ase_mask (ase->flags);
1975   mips_opts.ase &= ~mask;
1976   if (enabled_p)
1977     mips_opts.ase |= ase->flags;
1978   return mask;
1979 }
1980
1981 /* Return the ASE called NAME, or null if none.  */
1982
1983 static const struct mips_ase *
1984 mips_lookup_ase (const char *name)
1985 {
1986   unsigned int i;
1987
1988   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1989     if (strcmp (name, mips_ases[i].name) == 0)
1990       return &mips_ases[i];
1991   return NULL;
1992 }
1993
1994 /* Return the length of a microMIPS instruction in bytes.  If bits of
1995    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1996    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1997    major opcode) will require further modifications to the opcode
1998    table.  */
1999
2000 static inline unsigned int
2001 micromips_insn_length (const struct mips_opcode *mo)
2002 {
2003   return (mo->mask >> 16) == 0 ? 2 : 4;
2004 }
2005
2006 /* Return the length of MIPS16 instruction OPCODE.  */
2007
2008 static inline unsigned int
2009 mips16_opcode_length (unsigned long opcode)
2010 {
2011   return (opcode >> 16) == 0 ? 2 : 4;
2012 }
2013
2014 /* Return the length of instruction INSN.  */
2015
2016 static inline unsigned int
2017 insn_length (const struct mips_cl_insn *insn)
2018 {
2019   if (mips_opts.micromips)
2020     return micromips_insn_length (insn->insn_mo);
2021   else if (mips_opts.mips16)
2022     return mips16_opcode_length (insn->insn_opcode);
2023   else
2024     return 4;
2025 }
2026
2027 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2028
2029 static void
2030 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2031 {
2032   size_t i;
2033
2034   insn->insn_mo = mo;
2035   insn->insn_opcode = mo->match;
2036   insn->frag = NULL;
2037   insn->where = 0;
2038   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2039     insn->fixp[i] = NULL;
2040   insn->fixed_p = (mips_opts.noreorder > 0);
2041   insn->noreorder_p = (mips_opts.noreorder > 0);
2042   insn->mips16_absolute_jump_p = 0;
2043   insn->complete_p = 0;
2044   insn->cleared_p = 0;
2045 }
2046
2047 /* Install UVAL as the value of OPERAND in INSN.  */
2048
2049 static inline void
2050 insn_insert_operand (struct mips_cl_insn *insn,
2051                      const struct mips_operand *operand, unsigned int uval)
2052 {
2053   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2054 }
2055
2056 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2057
2058 static void
2059 mips_record_compressed_mode (void)
2060 {
2061   segment_info_type *si;
2062
2063   si = seg_info (now_seg);
2064   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2065     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2066   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2067     si->tc_segment_info_data.micromips = mips_opts.micromips;
2068 }
2069
2070 /* Read a standard MIPS instruction from BUF.  */
2071
2072 static unsigned long
2073 read_insn (char *buf)
2074 {
2075   if (target_big_endian)
2076     return bfd_getb32 ((bfd_byte *) buf);
2077   else
2078     return bfd_getl32 ((bfd_byte *) buf);
2079 }
2080
2081 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2082    the next byte.  */
2083
2084 static char *
2085 write_insn (char *buf, unsigned int insn)
2086 {
2087   md_number_to_chars (buf, insn, 4);
2088   return buf + 4;
2089 }
2090
2091 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2092    has length LENGTH.  */
2093
2094 static unsigned long
2095 read_compressed_insn (char *buf, unsigned int length)
2096 {
2097   unsigned long insn;
2098   unsigned int i;
2099
2100   insn = 0;
2101   for (i = 0; i < length; i += 2)
2102     {
2103       insn <<= 16;
2104       if (target_big_endian)
2105         insn |= bfd_getb16 ((char *) buf);
2106       else
2107         insn |= bfd_getl16 ((char *) buf);
2108       buf += 2;
2109     }
2110   return insn;
2111 }
2112
2113 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2114    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2115
2116 static char *
2117 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2118 {
2119   unsigned int i;
2120
2121   for (i = 0; i < length; i += 2)
2122     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2123   return buf + length;
2124 }
2125
2126 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2127
2128 static void
2129 install_insn (const struct mips_cl_insn *insn)
2130 {
2131   char *f = insn->frag->fr_literal + insn->where;
2132   if (HAVE_CODE_COMPRESSION)
2133     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2134   else
2135     write_insn (f, insn->insn_opcode);
2136   mips_record_compressed_mode ();
2137 }
2138
2139 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2140    and install the opcode in the new location.  */
2141
2142 static void
2143 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2144 {
2145   size_t i;
2146
2147   insn->frag = frag;
2148   insn->where = where;
2149   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2150     if (insn->fixp[i] != NULL)
2151       {
2152         insn->fixp[i]->fx_frag = frag;
2153         insn->fixp[i]->fx_where = where;
2154       }
2155   install_insn (insn);
2156 }
2157
2158 /* Add INSN to the end of the output.  */
2159
2160 static void
2161 add_fixed_insn (struct mips_cl_insn *insn)
2162 {
2163   char *f = frag_more (insn_length (insn));
2164   move_insn (insn, frag_now, f - frag_now->fr_literal);
2165 }
2166
2167 /* Start a variant frag and move INSN to the start of the variant part,
2168    marking it as fixed.  The other arguments are as for frag_var.  */
2169
2170 static void
2171 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2172                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2173 {
2174   frag_grow (max_chars);
2175   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2176   insn->fixed_p = 1;
2177   frag_var (rs_machine_dependent, max_chars, var,
2178             subtype, symbol, offset, NULL);
2179 }
2180
2181 /* Insert N copies of INSN into the history buffer, starting at
2182    position FIRST.  Neither FIRST nor N need to be clipped.  */
2183
2184 static void
2185 insert_into_history (unsigned int first, unsigned int n,
2186                      const struct mips_cl_insn *insn)
2187 {
2188   if (mips_relax.sequence != 2)
2189     {
2190       unsigned int i;
2191
2192       for (i = ARRAY_SIZE (history); i-- > first;)
2193         if (i >= first + n)
2194           history[i] = history[i - n];
2195         else
2196           history[i] = *insn;
2197     }
2198 }
2199
2200 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2201    the idea is to make it obvious at a glance that each errata is
2202    included.  */
2203
2204 static void
2205 init_vr4120_conflicts (void)
2206 {
2207 #define CONFLICT(FIRST, SECOND) \
2208     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2209
2210   /* Errata 21 - [D]DIV[U] after [D]MACC */
2211   CONFLICT (MACC, DIV);
2212   CONFLICT (DMACC, DIV);
2213
2214   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2215   CONFLICT (DMULT, DMULT);
2216   CONFLICT (DMULT, DMACC);
2217   CONFLICT (DMACC, DMULT);
2218   CONFLICT (DMACC, DMACC);
2219
2220   /* Errata 24 - MT{LO,HI} after [D]MACC */
2221   CONFLICT (MACC, MTHILO);
2222   CONFLICT (DMACC, MTHILO);
2223
2224   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2225      instruction is executed immediately after a MACC or DMACC
2226      instruction, the result of [either instruction] is incorrect."  */
2227   CONFLICT (MACC, MULT);
2228   CONFLICT (MACC, DMULT);
2229   CONFLICT (DMACC, MULT);
2230   CONFLICT (DMACC, DMULT);
2231
2232   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2233      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2234      DDIV or DDIVU instruction, the result of the MACC or
2235      DMACC instruction is incorrect.".  */
2236   CONFLICT (DMULT, MACC);
2237   CONFLICT (DMULT, DMACC);
2238   CONFLICT (DIV, MACC);
2239   CONFLICT (DIV, DMACC);
2240
2241 #undef CONFLICT
2242 }
2243
2244 struct regname {
2245   const char *name;
2246   unsigned int num;
2247 };
2248
2249 #define RTYPE_MASK      0x1ff00
2250 #define RTYPE_NUM       0x00100
2251 #define RTYPE_FPU       0x00200
2252 #define RTYPE_FCC       0x00400
2253 #define RTYPE_VEC       0x00800
2254 #define RTYPE_GP        0x01000
2255 #define RTYPE_CP0       0x02000
2256 #define RTYPE_PC        0x04000
2257 #define RTYPE_ACC       0x08000
2258 #define RTYPE_CCC       0x10000
2259 #define RNUM_MASK       0x000ff
2260 #define RWARN           0x80000
2261
2262 #define GENERIC_REGISTER_NUMBERS \
2263     {"$0",      RTYPE_NUM | 0},  \
2264     {"$1",      RTYPE_NUM | 1},  \
2265     {"$2",      RTYPE_NUM | 2},  \
2266     {"$3",      RTYPE_NUM | 3},  \
2267     {"$4",      RTYPE_NUM | 4},  \
2268     {"$5",      RTYPE_NUM | 5},  \
2269     {"$6",      RTYPE_NUM | 6},  \
2270     {"$7",      RTYPE_NUM | 7},  \
2271     {"$8",      RTYPE_NUM | 8},  \
2272     {"$9",      RTYPE_NUM | 9},  \
2273     {"$10",     RTYPE_NUM | 10}, \
2274     {"$11",     RTYPE_NUM | 11}, \
2275     {"$12",     RTYPE_NUM | 12}, \
2276     {"$13",     RTYPE_NUM | 13}, \
2277     {"$14",     RTYPE_NUM | 14}, \
2278     {"$15",     RTYPE_NUM | 15}, \
2279     {"$16",     RTYPE_NUM | 16}, \
2280     {"$17",     RTYPE_NUM | 17}, \
2281     {"$18",     RTYPE_NUM | 18}, \
2282     {"$19",     RTYPE_NUM | 19}, \
2283     {"$20",     RTYPE_NUM | 20}, \
2284     {"$21",     RTYPE_NUM | 21}, \
2285     {"$22",     RTYPE_NUM | 22}, \
2286     {"$23",     RTYPE_NUM | 23}, \
2287     {"$24",     RTYPE_NUM | 24}, \
2288     {"$25",     RTYPE_NUM | 25}, \
2289     {"$26",     RTYPE_NUM | 26}, \
2290     {"$27",     RTYPE_NUM | 27}, \
2291     {"$28",     RTYPE_NUM | 28}, \
2292     {"$29",     RTYPE_NUM | 29}, \
2293     {"$30",     RTYPE_NUM | 30}, \
2294     {"$31",     RTYPE_NUM | 31} 
2295
2296 #define FPU_REGISTER_NAMES       \
2297     {"$f0",     RTYPE_FPU | 0},  \
2298     {"$f1",     RTYPE_FPU | 1},  \
2299     {"$f2",     RTYPE_FPU | 2},  \
2300     {"$f3",     RTYPE_FPU | 3},  \
2301     {"$f4",     RTYPE_FPU | 4},  \
2302     {"$f5",     RTYPE_FPU | 5},  \
2303     {"$f6",     RTYPE_FPU | 6},  \
2304     {"$f7",     RTYPE_FPU | 7},  \
2305     {"$f8",     RTYPE_FPU | 8},  \
2306     {"$f9",     RTYPE_FPU | 9},  \
2307     {"$f10",    RTYPE_FPU | 10}, \
2308     {"$f11",    RTYPE_FPU | 11}, \
2309     {"$f12",    RTYPE_FPU | 12}, \
2310     {"$f13",    RTYPE_FPU | 13}, \
2311     {"$f14",    RTYPE_FPU | 14}, \
2312     {"$f15",    RTYPE_FPU | 15}, \
2313     {"$f16",    RTYPE_FPU | 16}, \
2314     {"$f17",    RTYPE_FPU | 17}, \
2315     {"$f18",    RTYPE_FPU | 18}, \
2316     {"$f19",    RTYPE_FPU | 19}, \
2317     {"$f20",    RTYPE_FPU | 20}, \
2318     {"$f21",    RTYPE_FPU | 21}, \
2319     {"$f22",    RTYPE_FPU | 22}, \
2320     {"$f23",    RTYPE_FPU | 23}, \
2321     {"$f24",    RTYPE_FPU | 24}, \
2322     {"$f25",    RTYPE_FPU | 25}, \
2323     {"$f26",    RTYPE_FPU | 26}, \
2324     {"$f27",    RTYPE_FPU | 27}, \
2325     {"$f28",    RTYPE_FPU | 28}, \
2326     {"$f29",    RTYPE_FPU | 29}, \
2327     {"$f30",    RTYPE_FPU | 30}, \
2328     {"$f31",    RTYPE_FPU | 31}
2329
2330 #define FPU_CONDITION_CODE_NAMES \
2331     {"$fcc0",   RTYPE_FCC | 0},  \
2332     {"$fcc1",   RTYPE_FCC | 1},  \
2333     {"$fcc2",   RTYPE_FCC | 2},  \
2334     {"$fcc3",   RTYPE_FCC | 3},  \
2335     {"$fcc4",   RTYPE_FCC | 4},  \
2336     {"$fcc5",   RTYPE_FCC | 5},  \
2337     {"$fcc6",   RTYPE_FCC | 6},  \
2338     {"$fcc7",   RTYPE_FCC | 7}
2339
2340 #define COPROC_CONDITION_CODE_NAMES         \
2341     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2342     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2343     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2344     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2345     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2346     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2347     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2348     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2349
2350 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2351     {"$a4",     RTYPE_GP | 8},  \
2352     {"$a5",     RTYPE_GP | 9},  \
2353     {"$a6",     RTYPE_GP | 10}, \
2354     {"$a7",     RTYPE_GP | 11}, \
2355     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2356     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2357     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2358     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2359     {"$t0",     RTYPE_GP | 12}, \
2360     {"$t1",     RTYPE_GP | 13}, \
2361     {"$t2",     RTYPE_GP | 14}, \
2362     {"$t3",     RTYPE_GP | 15}
2363
2364 #define O32_SYMBOLIC_REGISTER_NAMES \
2365     {"$t0",     RTYPE_GP | 8},  \
2366     {"$t1",     RTYPE_GP | 9},  \
2367     {"$t2",     RTYPE_GP | 10}, \
2368     {"$t3",     RTYPE_GP | 11}, \
2369     {"$t4",     RTYPE_GP | 12}, \
2370     {"$t5",     RTYPE_GP | 13}, \
2371     {"$t6",     RTYPE_GP | 14}, \
2372     {"$t7",     RTYPE_GP | 15}, \
2373     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2374     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2375     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2376     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2377
2378 /* Remaining symbolic register names */
2379 #define SYMBOLIC_REGISTER_NAMES \
2380     {"$zero",   RTYPE_GP | 0},  \
2381     {"$at",     RTYPE_GP | 1},  \
2382     {"$AT",     RTYPE_GP | 1},  \
2383     {"$v0",     RTYPE_GP | 2},  \
2384     {"$v1",     RTYPE_GP | 3},  \
2385     {"$a0",     RTYPE_GP | 4},  \
2386     {"$a1",     RTYPE_GP | 5},  \
2387     {"$a2",     RTYPE_GP | 6},  \
2388     {"$a3",     RTYPE_GP | 7},  \
2389     {"$s0",     RTYPE_GP | 16}, \
2390     {"$s1",     RTYPE_GP | 17}, \
2391     {"$s2",     RTYPE_GP | 18}, \
2392     {"$s3",     RTYPE_GP | 19}, \
2393     {"$s4",     RTYPE_GP | 20}, \
2394     {"$s5",     RTYPE_GP | 21}, \
2395     {"$s6",     RTYPE_GP | 22}, \
2396     {"$s7",     RTYPE_GP | 23}, \
2397     {"$t8",     RTYPE_GP | 24}, \
2398     {"$t9",     RTYPE_GP | 25}, \
2399     {"$k0",     RTYPE_GP | 26}, \
2400     {"$kt0",    RTYPE_GP | 26}, \
2401     {"$k1",     RTYPE_GP | 27}, \
2402     {"$kt1",    RTYPE_GP | 27}, \
2403     {"$gp",     RTYPE_GP | 28}, \
2404     {"$sp",     RTYPE_GP | 29}, \
2405     {"$s8",     RTYPE_GP | 30}, \
2406     {"$fp",     RTYPE_GP | 30}, \
2407     {"$ra",     RTYPE_GP | 31}
2408
2409 #define MIPS16_SPECIAL_REGISTER_NAMES \
2410     {"$pc",     RTYPE_PC | 0}
2411
2412 #define MDMX_VECTOR_REGISTER_NAMES \
2413     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2414     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2415     {"$v2",     RTYPE_VEC | 2},  \
2416     {"$v3",     RTYPE_VEC | 3},  \
2417     {"$v4",     RTYPE_VEC | 4},  \
2418     {"$v5",     RTYPE_VEC | 5},  \
2419     {"$v6",     RTYPE_VEC | 6},  \
2420     {"$v7",     RTYPE_VEC | 7},  \
2421     {"$v8",     RTYPE_VEC | 8},  \
2422     {"$v9",     RTYPE_VEC | 9},  \
2423     {"$v10",    RTYPE_VEC | 10}, \
2424     {"$v11",    RTYPE_VEC | 11}, \
2425     {"$v12",    RTYPE_VEC | 12}, \
2426     {"$v13",    RTYPE_VEC | 13}, \
2427     {"$v14",    RTYPE_VEC | 14}, \
2428     {"$v15",    RTYPE_VEC | 15}, \
2429     {"$v16",    RTYPE_VEC | 16}, \
2430     {"$v17",    RTYPE_VEC | 17}, \
2431     {"$v18",    RTYPE_VEC | 18}, \
2432     {"$v19",    RTYPE_VEC | 19}, \
2433     {"$v20",    RTYPE_VEC | 20}, \
2434     {"$v21",    RTYPE_VEC | 21}, \
2435     {"$v22",    RTYPE_VEC | 22}, \
2436     {"$v23",    RTYPE_VEC | 23}, \
2437     {"$v24",    RTYPE_VEC | 24}, \
2438     {"$v25",    RTYPE_VEC | 25}, \
2439     {"$v26",    RTYPE_VEC | 26}, \
2440     {"$v27",    RTYPE_VEC | 27}, \
2441     {"$v28",    RTYPE_VEC | 28}, \
2442     {"$v29",    RTYPE_VEC | 29}, \
2443     {"$v30",    RTYPE_VEC | 30}, \
2444     {"$v31",    RTYPE_VEC | 31}
2445
2446 #define MIPS_DSP_ACCUMULATOR_NAMES \
2447     {"$ac0",    RTYPE_ACC | 0}, \
2448     {"$ac1",    RTYPE_ACC | 1}, \
2449     {"$ac2",    RTYPE_ACC | 2}, \
2450     {"$ac3",    RTYPE_ACC | 3}
2451
2452 static const struct regname reg_names[] = {
2453   GENERIC_REGISTER_NUMBERS,
2454   FPU_REGISTER_NAMES,
2455   FPU_CONDITION_CODE_NAMES,
2456   COPROC_CONDITION_CODE_NAMES,
2457
2458   /* The $txx registers depends on the abi,
2459      these will be added later into the symbol table from
2460      one of the tables below once mips_abi is set after 
2461      parsing of arguments from the command line. */
2462   SYMBOLIC_REGISTER_NAMES,
2463
2464   MIPS16_SPECIAL_REGISTER_NAMES,
2465   MDMX_VECTOR_REGISTER_NAMES,
2466   MIPS_DSP_ACCUMULATOR_NAMES,
2467   {0, 0}
2468 };
2469
2470 static const struct regname reg_names_o32[] = {
2471   O32_SYMBOLIC_REGISTER_NAMES,
2472   {0, 0}
2473 };
2474
2475 static const struct regname reg_names_n32n64[] = {
2476   N32N64_SYMBOLIC_REGISTER_NAMES,
2477   {0, 0}
2478 };
2479
2480 /* Check if S points at a valid register specifier according to TYPES.
2481    If so, then return 1, advance S to consume the specifier and store
2482    the register's number in REGNOP, otherwise return 0.  */
2483
2484 static int
2485 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2486 {
2487   symbolS *symbolP;
2488   char *e;
2489   char save_c;
2490   int reg = -1;
2491
2492   /* Find end of name.  */
2493   e = *s;
2494   if (is_name_beginner (*e))
2495     ++e;
2496   while (is_part_of_name (*e))
2497     ++e;
2498
2499   /* Terminate name.  */
2500   save_c = *e;
2501   *e = '\0';
2502
2503   /* Look for a register symbol.  */
2504   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2505     {
2506       int r = S_GET_VALUE (symbolP);
2507       if (r & types)
2508         reg = r & RNUM_MASK;
2509       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2510         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2511         reg = (r & RNUM_MASK) - 2;
2512     }
2513   /* Else see if this is a register defined in an itbl entry.  */
2514   else if ((types & RTYPE_GP) && itbl_have_entries)
2515     {
2516       char *n = *s;
2517       unsigned long r;
2518
2519       if (*n == '$')
2520         ++n;
2521       if (itbl_get_reg_val (n, &r))
2522         reg = r & RNUM_MASK;
2523     }
2524
2525   /* Advance to next token if a register was recognised.  */
2526   if (reg >= 0)
2527     *s = e;
2528   else if (types & RWARN)
2529     as_warn (_("Unrecognized register name `%s'"), *s);
2530
2531   *e = save_c;
2532   if (regnop)
2533     *regnop = reg;
2534   return reg >= 0;
2535 }
2536
2537 /* Check if S points at a valid register list according to TYPES.
2538    If so, then return 1, advance S to consume the list and store
2539    the registers present on the list as a bitmask of ones in REGLISTP,
2540    otherwise return 0.  A valid list comprises a comma-separated
2541    enumeration of valid single registers and/or dash-separated
2542    contiguous register ranges as determined by their numbers.
2543
2544    As a special exception if one of s0-s7 registers is specified as
2545    the range's lower delimiter and s8 (fp) is its upper one, then no
2546    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2547    are selected; they have to be listed separately if needed.  */
2548
2549 static int
2550 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2551 {
2552   unsigned int reglist = 0;
2553   unsigned int lastregno;
2554   bfd_boolean ok = TRUE;
2555   unsigned int regmask;
2556   char *s_endlist = *s;
2557   char *s_reset = *s;
2558   unsigned int regno;
2559
2560   while (reg_lookup (s, types, &regno))
2561     {
2562       lastregno = regno;
2563       if (**s == '-')
2564         {
2565           (*s)++;
2566           ok = reg_lookup (s, types, &lastregno);
2567           if (ok && lastregno < regno)
2568             ok = FALSE;
2569           if (!ok)
2570             break;
2571         }
2572
2573       if (lastregno == FP && regno >= S0 && regno <= S7)
2574         {
2575           lastregno = S7;
2576           reglist |= 1 << FP;
2577         }
2578       regmask = 1 << lastregno;
2579       regmask = (regmask << 1) - 1;
2580       regmask ^= (1 << regno) - 1;
2581       reglist |= regmask;
2582
2583       s_endlist = *s;
2584       if (**s != ',')
2585         break;
2586       (*s)++;
2587     }
2588
2589   if (ok)
2590     *s = s_endlist;
2591   else
2592     *s = s_reset;
2593   if (reglistp)
2594     *reglistp = reglist;
2595   return ok && reglist != 0;
2596 }
2597
2598 static unsigned int
2599 mips_lookup_reg_pair (unsigned int regno1, unsigned int regno2,
2600                       const unsigned int *map1, const unsigned int *map2,
2601                       unsigned int count)
2602 {
2603   unsigned int i;
2604
2605   for (i = 0; i < count; i++)
2606     if (map1[i] == regno1 && map2[i] == regno2)
2607       return i;
2608   return ILLEGAL_REG;
2609 }
2610
2611 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2612    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2613
2614 static bfd_boolean
2615 is_opcode_valid (const struct mips_opcode *mo)
2616 {
2617   int isa = mips_opts.isa;
2618   int ase = mips_opts.ase;
2619   int fp_s, fp_d;
2620   unsigned int i;
2621
2622   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2623     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2624       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2625         ase |= mips_ases[i].flags64;
2626
2627   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2628     return FALSE;
2629
2630   /* Check whether the instruction or macro requires single-precision or
2631      double-precision floating-point support.  Note that this information is
2632      stored differently in the opcode table for insns and macros.  */
2633   if (mo->pinfo == INSN_MACRO)
2634     {
2635       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2636       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2637     }
2638   else
2639     {
2640       fp_s = mo->pinfo & FP_S;
2641       fp_d = mo->pinfo & FP_D;
2642     }
2643
2644   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2645     return FALSE;
2646
2647   if (fp_s && mips_opts.soft_float)
2648     return FALSE;
2649
2650   return TRUE;
2651 }
2652
2653 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2654    selected ISA and architecture.  */
2655
2656 static bfd_boolean
2657 is_opcode_valid_16 (const struct mips_opcode *mo)
2658 {
2659   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2660 }
2661
2662 /* Return TRUE if the size of the microMIPS opcode MO matches one
2663    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2664
2665 static bfd_boolean
2666 is_size_valid (const struct mips_opcode *mo)
2667 {
2668   if (!mips_opts.micromips)
2669     return TRUE;
2670
2671   if (mips_opts.insn32)
2672     {
2673       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2674         return FALSE;
2675       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2676         return FALSE;
2677     }
2678   if (!forced_insn_length)
2679     return TRUE;
2680   if (mo->pinfo == INSN_MACRO)
2681     return FALSE;
2682   return forced_insn_length == micromips_insn_length (mo);
2683 }
2684
2685 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2686    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2687
2688    We don't accept macros in 16-bit delay slots to avoid a case where
2689    a macro expansion fails because it relies on a preceding 32-bit real
2690    instruction to have matched and does not handle the operands correctly.
2691    The only macros that may expand to 16-bit instructions are JAL that
2692    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2693    and BGT (that likewise cannot be placed in a delay slot) that decay to
2694    a NOP.  In all these cases the macros precede any corresponding real
2695    instruction definitions in the opcode table, so they will match in the
2696    second pass where the size of the delay slot is ignored and therefore
2697    produce correct code.  */
2698
2699 static bfd_boolean
2700 is_delay_slot_valid (const struct mips_opcode *mo)
2701 {
2702   if (!mips_opts.micromips)
2703     return TRUE;
2704
2705   if (mo->pinfo == INSN_MACRO)
2706     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2707   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2708       && micromips_insn_length (mo) != 4)
2709     return FALSE;
2710   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2711       && micromips_insn_length (mo) != 2)
2712     return FALSE;
2713
2714   return TRUE;
2715 }
2716
2717 /* For consistency checking, verify that all bits of OPCODE are
2718    specified either by the match/mask part of the instruction
2719    definition, or by the operand list.  INSN_BITS says which
2720    bits of the instruction are significant and DECODE_OPERAND
2721    provides the mips_operand description of each operand.  */
2722
2723 static int
2724 validate_mips_insn (const struct mips_opcode *opcode,
2725                     unsigned long insn_bits,
2726                     const struct mips_operand *(*decode_operand) (const char *))
2727 {
2728   const char *s;
2729   unsigned long used_bits, doubled, undefined;
2730   const struct mips_operand *operand;
2731
2732   if ((opcode->mask & opcode->match) != opcode->match)
2733     {
2734       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
2735               opcode->name, opcode->args);
2736       return 0;
2737     }
2738   used_bits = 0;
2739   for (s = opcode->args; *s; ++s)
2740     switch (*s)
2741       {
2742       case ',':
2743       case '(':
2744       case ')':
2745         break;
2746
2747       default:
2748         operand = decode_operand (s);
2749         if (!operand)
2750           {
2751             as_bad (_("internal: unknown operand type: %s %s"),
2752                     opcode->name, opcode->args);
2753             return 0;
2754           }
2755         used_bits |= ((1 << operand->size) - 1) << operand->lsb;
2756         if (operand->type == OP_MDMX_IMM_REG)
2757           /* Bit 5 is the format selector (OB vs QH).  The opcode table
2758              has separate entries for each format.  */
2759           used_bits &= ~(1 << (operand->lsb + 5));
2760         /* Skip prefix characters.  */
2761         if (*s == '+' || *s == 'm')
2762           ++s;
2763         break;
2764       }
2765   doubled = used_bits & opcode->mask & insn_bits;
2766   if (doubled)
2767     {
2768       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
2769                 " %s %s"), doubled, opcode->name, opcode->args);
2770       return 0;
2771     }
2772   used_bits |= opcode->mask;
2773   undefined = ~used_bits & insn_bits;
2774   if (undefined)
2775     {
2776       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
2777               undefined, opcode->name, opcode->args);
2778       return 0;
2779     }
2780   used_bits &= ~insn_bits;
2781   if (used_bits)
2782     {
2783       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
2784               used_bits, opcode->name, opcode->args);
2785       return 0;
2786     }
2787   return 1;
2788 }
2789
2790 /* The microMIPS version of validate_mips_insn.  */
2791
2792 static int
2793 validate_micromips_insn (const struct mips_opcode *opc)
2794 {
2795   unsigned long insn_bits;
2796   unsigned long major;
2797   unsigned int length;
2798
2799   length = micromips_insn_length (opc);
2800   if (length != 2 && length != 4)
2801     {
2802       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
2803                 "%s %s"), length, opc->name, opc->args);
2804       return 0;
2805     }
2806   major = opc->match >> (10 + 8 * (length - 2));
2807   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
2808       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
2809     {
2810       as_bad (_("Internal error: bad microMIPS opcode "
2811                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
2812       return 0;
2813     }
2814
2815   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
2816   insn_bits = 1 << 4 * length;
2817   insn_bits <<= 4 * length;
2818   insn_bits -= 1;
2819   return validate_mips_insn (opc, insn_bits, decode_micromips_operand);
2820 }
2821
2822 /* This function is called once, at assembler startup time.  It should set up
2823    all the tables, etc. that the MD part of the assembler will need.  */
2824
2825 void
2826 md_begin (void)
2827 {
2828   const char *retval = NULL;
2829   int i = 0;
2830   int broken = 0;
2831
2832   if (mips_pic != NO_PIC)
2833     {
2834       if (g_switch_seen && g_switch_value != 0)
2835         as_bad (_("-G may not be used in position-independent code"));
2836       g_switch_value = 0;
2837     }
2838
2839   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2840     as_warn (_("Could not set architecture and machine"));
2841
2842   op_hash = hash_new ();
2843
2844   for (i = 0; i < NUMOPCODES;)
2845     {
2846       const char *name = mips_opcodes[i].name;
2847
2848       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2849       if (retval != NULL)
2850         {
2851           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2852                    mips_opcodes[i].name, retval);
2853           /* Probably a memory allocation problem?  Give up now.  */
2854           as_fatal (_("Broken assembler.  No assembly attempted."));
2855         }
2856       do
2857         {
2858           if (mips_opcodes[i].pinfo != INSN_MACRO)
2859             {
2860               if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
2861                                        decode_mips_operand))
2862                 broken = 1;
2863               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2864                 {
2865                   create_insn (&nop_insn, mips_opcodes + i);
2866                   if (mips_fix_loongson2f_nop)
2867                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2868                   nop_insn.fixed_p = 1;
2869                 }
2870             }
2871           ++i;
2872         }
2873       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2874     }
2875
2876   mips16_op_hash = hash_new ();
2877
2878   i = 0;
2879   while (i < bfd_mips16_num_opcodes)
2880     {
2881       const char *name = mips16_opcodes[i].name;
2882
2883       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2884       if (retval != NULL)
2885         as_fatal (_("internal: can't hash `%s': %s"),
2886                   mips16_opcodes[i].name, retval);
2887       do
2888         {
2889           if (mips16_opcodes[i].pinfo != INSN_MACRO
2890               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2891                   != mips16_opcodes[i].match))
2892             {
2893               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2894                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2895               broken = 1;
2896             }
2897           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2898             {
2899               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2900               mips16_nop_insn.fixed_p = 1;
2901             }
2902           ++i;
2903         }
2904       while (i < bfd_mips16_num_opcodes
2905              && strcmp (mips16_opcodes[i].name, name) == 0);
2906     }
2907
2908   micromips_op_hash = hash_new ();
2909
2910   i = 0;
2911   while (i < bfd_micromips_num_opcodes)
2912     {
2913       const char *name = micromips_opcodes[i].name;
2914
2915       retval = hash_insert (micromips_op_hash, name,
2916                             (void *) &micromips_opcodes[i]);
2917       if (retval != NULL)
2918         as_fatal (_("internal: can't hash `%s': %s"),
2919                   micromips_opcodes[i].name, retval);
2920       do
2921         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2922           {
2923             struct mips_cl_insn *micromips_nop_insn;
2924
2925             if (!validate_micromips_insn (&micromips_opcodes[i]))
2926               broken = 1;
2927
2928             if (micromips_insn_length (micromips_opcodes + i) == 2)
2929               micromips_nop_insn = &micromips_nop16_insn;
2930             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2931               micromips_nop_insn = &micromips_nop32_insn;
2932             else
2933               continue;
2934
2935             if (micromips_nop_insn->insn_mo == NULL
2936                 && strcmp (name, "nop") == 0)
2937               {
2938                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2939                 micromips_nop_insn->fixed_p = 1;
2940               }
2941           }
2942       while (++i < bfd_micromips_num_opcodes
2943              && strcmp (micromips_opcodes[i].name, name) == 0);
2944     }
2945
2946   if (broken)
2947     as_fatal (_("Broken assembler.  No assembly attempted."));
2948
2949   /* We add all the general register names to the symbol table.  This
2950      helps us detect invalid uses of them.  */
2951   for (i = 0; reg_names[i].name; i++) 
2952     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2953                                      reg_names[i].num, /* & RNUM_MASK, */
2954                                      &zero_address_frag));
2955   if (HAVE_NEWABI)
2956     for (i = 0; reg_names_n32n64[i].name; i++) 
2957       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2958                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2959                                        &zero_address_frag));
2960   else
2961     for (i = 0; reg_names_o32[i].name; i++) 
2962       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2963                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2964                                        &zero_address_frag));
2965
2966   mips_no_prev_insn ();
2967
2968   mips_gprmask = 0;
2969   mips_cprmask[0] = 0;
2970   mips_cprmask[1] = 0;
2971   mips_cprmask[2] = 0;
2972   mips_cprmask[3] = 0;
2973
2974   /* set the default alignment for the text section (2**2) */
2975   record_alignment (text_section, 2);
2976
2977   bfd_set_gp_size (stdoutput, g_switch_value);
2978
2979   /* On a native system other than VxWorks, sections must be aligned
2980      to 16 byte boundaries.  When configured for an embedded ELF
2981      target, we don't bother.  */
2982   if (strncmp (TARGET_OS, "elf", 3) != 0
2983       && strncmp (TARGET_OS, "vxworks", 7) != 0)
2984     {
2985       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2986       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2987       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2988     }
2989
2990   /* Create a .reginfo section for register masks and a .mdebug
2991      section for debugging information.  */
2992   {
2993     segT seg;
2994     subsegT subseg;
2995     flagword flags;
2996     segT sec;
2997
2998     seg = now_seg;
2999     subseg = now_subseg;
3000
3001     /* The ABI says this section should be loaded so that the
3002        running program can access it.  However, we don't load it
3003        if we are configured for an embedded target */
3004     flags = SEC_READONLY | SEC_DATA;
3005     if (strncmp (TARGET_OS, "elf", 3) != 0)
3006       flags |= SEC_ALLOC | SEC_LOAD;
3007
3008     if (mips_abi != N64_ABI)
3009       {
3010         sec = subseg_new (".reginfo", (subsegT) 0);
3011
3012         bfd_set_section_flags (stdoutput, sec, flags);
3013         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3014
3015         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3016       }
3017     else
3018       {
3019         /* The 64-bit ABI uses a .MIPS.options section rather than
3020            .reginfo section.  */
3021         sec = subseg_new (".MIPS.options", (subsegT) 0);
3022         bfd_set_section_flags (stdoutput, sec, flags);
3023         bfd_set_section_alignment (stdoutput, sec, 3);
3024
3025         /* Set up the option header.  */
3026         {
3027           Elf_Internal_Options opthdr;
3028           char *f;
3029
3030           opthdr.kind = ODK_REGINFO;
3031           opthdr.size = (sizeof (Elf_External_Options)
3032                          + sizeof (Elf64_External_RegInfo));
3033           opthdr.section = 0;
3034           opthdr.info = 0;
3035           f = frag_more (sizeof (Elf_External_Options));
3036           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3037                                          (Elf_External_Options *) f);
3038
3039           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3040         }
3041       }
3042
3043     if (ECOFF_DEBUGGING)
3044       {
3045         sec = subseg_new (".mdebug", (subsegT) 0);
3046         (void) bfd_set_section_flags (stdoutput, sec,
3047                                       SEC_HAS_CONTENTS | SEC_READONLY);
3048         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3049       }
3050     else if (mips_flag_pdr)
3051       {
3052         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3053         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3054                                       SEC_READONLY | SEC_RELOC
3055                                       | SEC_DEBUGGING);
3056         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3057       }
3058
3059     subseg_set (seg, subseg);
3060   }
3061
3062   if (! ECOFF_DEBUGGING)
3063     md_obj_begin ();
3064
3065   if (mips_fix_vr4120)
3066     init_vr4120_conflicts ();
3067 }
3068
3069 void
3070 md_mips_end (void)
3071 {
3072   mips_emit_delays ();
3073   if (! ECOFF_DEBUGGING)
3074     md_obj_end ();
3075 }
3076
3077 void
3078 md_assemble (char *str)
3079 {
3080   struct mips_cl_insn insn;
3081   bfd_reloc_code_real_type unused_reloc[3]
3082     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3083
3084   imm_expr.X_op = O_absent;
3085   imm2_expr.X_op = O_absent;
3086   offset_expr.X_op = O_absent;
3087   offset_reloc[0] = BFD_RELOC_UNUSED;
3088   offset_reloc[1] = BFD_RELOC_UNUSED;
3089   offset_reloc[2] = BFD_RELOC_UNUSED;
3090
3091   mips_mark_labels ();
3092   mips_assembling_insn = TRUE;
3093
3094   if (mips_opts.mips16)
3095     mips16_ip (str, &insn);
3096   else
3097     {
3098       mips_ip (str, &insn);
3099       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3100             str, insn.insn_opcode));
3101     }
3102
3103   if (insn_error)
3104     as_bad ("%s `%s'", insn_error, str);
3105   else if (insn.insn_mo->pinfo == INSN_MACRO)
3106     {
3107       macro_start ();
3108       if (mips_opts.mips16)
3109         mips16_macro (&insn);
3110       else
3111         macro (&insn, str);
3112       macro_end ();
3113     }
3114   else
3115     {
3116       if (offset_expr.X_op != O_absent)
3117         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3118       else
3119         append_insn (&insn, NULL, unused_reloc, FALSE);
3120     }
3121
3122   mips_assembling_insn = FALSE;
3123 }
3124
3125 /* Convenience functions for abstracting away the differences between
3126    MIPS16 and non-MIPS16 relocations.  */
3127
3128 static inline bfd_boolean
3129 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3130 {
3131   switch (reloc)
3132     {
3133     case BFD_RELOC_MIPS16_JMP:
3134     case BFD_RELOC_MIPS16_GPREL:
3135     case BFD_RELOC_MIPS16_GOT16:
3136     case BFD_RELOC_MIPS16_CALL16:
3137     case BFD_RELOC_MIPS16_HI16_S:
3138     case BFD_RELOC_MIPS16_HI16:
3139     case BFD_RELOC_MIPS16_LO16:
3140       return TRUE;
3141
3142     default:
3143       return FALSE;
3144     }
3145 }
3146
3147 static inline bfd_boolean
3148 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3149 {
3150   switch (reloc)
3151     {
3152     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3153     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3154     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3155     case BFD_RELOC_MICROMIPS_GPREL16:
3156     case BFD_RELOC_MICROMIPS_JMP:
3157     case BFD_RELOC_MICROMIPS_HI16:
3158     case BFD_RELOC_MICROMIPS_HI16_S:
3159     case BFD_RELOC_MICROMIPS_LO16:
3160     case BFD_RELOC_MICROMIPS_LITERAL:
3161     case BFD_RELOC_MICROMIPS_GOT16:
3162     case BFD_RELOC_MICROMIPS_CALL16:
3163     case BFD_RELOC_MICROMIPS_GOT_HI16:
3164     case BFD_RELOC_MICROMIPS_GOT_LO16:
3165     case BFD_RELOC_MICROMIPS_CALL_HI16:
3166     case BFD_RELOC_MICROMIPS_CALL_LO16:
3167     case BFD_RELOC_MICROMIPS_SUB:
3168     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3169     case BFD_RELOC_MICROMIPS_GOT_OFST:
3170     case BFD_RELOC_MICROMIPS_GOT_DISP:
3171     case BFD_RELOC_MICROMIPS_HIGHEST:
3172     case BFD_RELOC_MICROMIPS_HIGHER:
3173     case BFD_RELOC_MICROMIPS_SCN_DISP:
3174     case BFD_RELOC_MICROMIPS_JALR:
3175       return TRUE;
3176
3177     default:
3178       return FALSE;
3179     }
3180 }
3181
3182 static inline bfd_boolean
3183 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3184 {
3185   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3186 }
3187
3188 static inline bfd_boolean
3189 got16_reloc_p (bfd_reloc_code_real_type reloc)
3190 {
3191   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3192           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3193 }
3194
3195 static inline bfd_boolean
3196 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3197 {
3198   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3199           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3200 }
3201
3202 static inline bfd_boolean
3203 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3204 {
3205   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3206           || reloc == BFD_RELOC_MICROMIPS_LO16);
3207 }
3208
3209 static inline bfd_boolean
3210 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3211 {
3212   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3213 }
3214
3215 static inline bfd_boolean
3216 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3217 {
3218   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3219           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3220 }
3221
3222 /* Return true if RELOC is a PC-relative relocation that does not have
3223    full address range.  */
3224
3225 static inline bfd_boolean
3226 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3227 {
3228   switch (reloc)
3229     {
3230     case BFD_RELOC_16_PCREL_S2:
3231     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3232     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3233     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3234       return TRUE;
3235
3236     case BFD_RELOC_32_PCREL:
3237       return HAVE_64BIT_ADDRESSES;
3238
3239     default:
3240       return FALSE;
3241     }
3242 }
3243
3244 /* Return true if the given relocation might need a matching %lo().
3245    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3246    need a matching %lo() when applied to local symbols.  */
3247
3248 static inline bfd_boolean
3249 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3250 {
3251   return (HAVE_IN_PLACE_ADDENDS
3252           && (hi16_reloc_p (reloc)
3253               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3254                  all GOT16 relocations evaluate to "G".  */
3255               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3256 }
3257
3258 /* Return the type of %lo() reloc needed by RELOC, given that
3259    reloc_needs_lo_p.  */
3260
3261 static inline bfd_reloc_code_real_type
3262 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3263 {
3264   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3265           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3266              : BFD_RELOC_LO16));
3267 }
3268
3269 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3270    relocation.  */
3271
3272 static inline bfd_boolean
3273 fixup_has_matching_lo_p (fixS *fixp)
3274 {
3275   return (fixp->fx_next != NULL
3276           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3277           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3278           && fixp->fx_offset == fixp->fx_next->fx_offset);
3279 }
3280
3281 /* This function returns true if modifying a register requires a
3282    delay.  */
3283
3284 static int
3285 reg_needs_delay (unsigned int reg)
3286 {
3287   unsigned long prev_pinfo;
3288
3289   prev_pinfo = history[0].insn_mo->pinfo;
3290   if (! mips_opts.noreorder
3291       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3292            && ! gpr_interlocks)
3293           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3294               && ! cop_interlocks)))
3295     {
3296       /* A load from a coprocessor or from memory.  All load delays
3297          delay the use of general register rt for one instruction.  */
3298       /* Itbl support may require additional care here.  */
3299       know (prev_pinfo & INSN_WRITE_GPR_T);
3300       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3301         return 1;
3302     }
3303
3304   return 0;
3305 }
3306
3307 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3308    says whether the labels refer to text or data.  */
3309
3310 static void
3311 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3312 {
3313   struct insn_label_list *l;
3314   valueT val;
3315
3316   for (l = labels; l != NULL; l = l->next)
3317     {
3318       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3319       symbol_set_frag (l->label, frag_now);
3320       val = (valueT) frag_now_fix ();
3321       /* MIPS16/microMIPS text labels are stored as odd.  */
3322       if (text_p && HAVE_CODE_COMPRESSION)
3323         ++val;
3324       S_SET_VALUE (l->label, val);
3325     }
3326 }
3327
3328 /* Move all labels in insn_labels to the current insertion point
3329    and treat them as text labels.  */
3330
3331 static void
3332 mips_move_text_labels (void)
3333 {
3334   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3335 }
3336
3337 static bfd_boolean
3338 s_is_linkonce (symbolS *sym, segT from_seg)
3339 {
3340   bfd_boolean linkonce = FALSE;
3341   segT symseg = S_GET_SEGMENT (sym);
3342
3343   if (symseg != from_seg && !S_IS_LOCAL (sym))
3344     {
3345       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3346         linkonce = TRUE;
3347       /* The GNU toolchain uses an extension for ELF: a section
3348          beginning with the magic string .gnu.linkonce is a
3349          linkonce section.  */
3350       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3351                    sizeof ".gnu.linkonce" - 1) == 0)
3352         linkonce = TRUE;
3353     }
3354   return linkonce;
3355 }
3356
3357 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3358    linker to handle them specially, such as generating jalx instructions
3359    when needed.  We also make them odd for the duration of the assembly,
3360    in order to generate the right sort of code.  We will make them even
3361    in the adjust_symtab routine, while leaving them marked.  This is
3362    convenient for the debugger and the disassembler.  The linker knows
3363    to make them odd again.  */
3364
3365 static void
3366 mips_compressed_mark_label (symbolS *label)
3367 {
3368   gas_assert (HAVE_CODE_COMPRESSION);
3369
3370   if (mips_opts.mips16)
3371     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3372   else
3373     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3374   if ((S_GET_VALUE (label) & 1) == 0
3375       /* Don't adjust the address if the label is global or weak, or
3376          in a link-once section, since we'll be emitting symbol reloc
3377          references to it which will be patched up by the linker, and
3378          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3379       && !S_IS_WEAK (label)
3380       && !S_IS_EXTERNAL (label)
3381       && !s_is_linkonce (label, now_seg))
3382     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3383 }
3384
3385 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3386
3387 static void
3388 mips_compressed_mark_labels (void)
3389 {
3390   struct insn_label_list *l;
3391
3392   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3393     mips_compressed_mark_label (l->label);
3394 }
3395
3396 /* End the current frag.  Make it a variant frag and record the
3397    relaxation info.  */
3398
3399 static void
3400 relax_close_frag (void)
3401 {
3402   mips_macro_warning.first_frag = frag_now;
3403   frag_var (rs_machine_dependent, 0, 0,
3404             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3405             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3406
3407   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3408   mips_relax.first_fixup = 0;
3409 }
3410
3411 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3412    See the comment above RELAX_ENCODE for more details.  */
3413
3414 static void
3415 relax_start (symbolS *symbol)
3416 {
3417   gas_assert (mips_relax.sequence == 0);
3418   mips_relax.sequence = 1;
3419   mips_relax.symbol = symbol;
3420 }
3421
3422 /* Start generating the second version of a relaxable sequence.
3423    See the comment above RELAX_ENCODE for more details.  */
3424
3425 static void
3426 relax_switch (void)
3427 {
3428   gas_assert (mips_relax.sequence == 1);
3429   mips_relax.sequence = 2;
3430 }
3431
3432 /* End the current relaxable sequence.  */
3433
3434 static void
3435 relax_end (void)
3436 {
3437   gas_assert (mips_relax.sequence == 2);
3438   relax_close_frag ();
3439   mips_relax.sequence = 0;
3440 }
3441
3442 /* Return true if IP is a delayed branch or jump.  */
3443
3444 static inline bfd_boolean
3445 delayed_branch_p (const struct mips_cl_insn *ip)
3446 {
3447   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3448                                 | INSN_COND_BRANCH_DELAY
3449                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3450 }
3451
3452 /* Return true if IP is a compact branch or jump.  */
3453
3454 static inline bfd_boolean
3455 compact_branch_p (const struct mips_cl_insn *ip)
3456 {
3457   if (mips_opts.mips16)
3458     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3459                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3460   else
3461     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3462                                    | INSN2_COND_BRANCH)) != 0;
3463 }
3464
3465 /* Return true if IP is an unconditional branch or jump.  */
3466
3467 static inline bfd_boolean
3468 uncond_branch_p (const struct mips_cl_insn *ip)
3469 {
3470   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3471           || (mips_opts.mips16
3472               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3473               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3474 }
3475
3476 /* Return true if IP is a branch-likely instruction.  */
3477
3478 static inline bfd_boolean
3479 branch_likely_p (const struct mips_cl_insn *ip)
3480 {
3481   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3482 }
3483
3484 /* Return the type of nop that should be used to fill the delay slot
3485    of delayed branch IP.  */
3486
3487 static struct mips_cl_insn *
3488 get_delay_slot_nop (const struct mips_cl_insn *ip)
3489 {
3490   if (mips_opts.micromips
3491       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3492     return &micromips_nop32_insn;
3493   return NOP_INSN;
3494 }
3495
3496 /* Return the mask of core registers that IP reads or writes.  */
3497
3498 static unsigned int
3499 gpr_mod_mask (const struct mips_cl_insn *ip)
3500 {
3501   unsigned long pinfo2;
3502   unsigned int mask;
3503
3504   mask = 0;
3505   pinfo2 = ip->insn_mo->pinfo2;
3506   if (mips_opts.micromips)
3507     {
3508       if (pinfo2 & INSN2_MOD_GPR_MD)
3509         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3510       if (pinfo2 & INSN2_MOD_GPR_MF)
3511         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3512       if (pinfo2 & INSN2_MOD_SP)
3513         mask |= 1 << SP;
3514     }
3515   return mask;
3516 }
3517
3518 /* Return the mask of core registers that IP reads.  */
3519
3520 static unsigned int
3521 gpr_read_mask (const struct mips_cl_insn *ip)
3522 {
3523   unsigned long pinfo, pinfo2;
3524   unsigned int mask;
3525
3526   mask = gpr_mod_mask (ip);
3527   pinfo = ip->insn_mo->pinfo;
3528   pinfo2 = ip->insn_mo->pinfo2;
3529   if (mips_opts.mips16)
3530     {
3531       if (pinfo & MIPS16_INSN_READ_X)
3532         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3533       if (pinfo & MIPS16_INSN_READ_Y)
3534         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3535       if (pinfo & MIPS16_INSN_READ_T)
3536         mask |= 1 << TREG;
3537       if (pinfo & MIPS16_INSN_READ_SP)
3538         mask |= 1 << SP;
3539       if (pinfo & MIPS16_INSN_READ_31)
3540         mask |= 1 << RA;
3541       if (pinfo & MIPS16_INSN_READ_Z)
3542         mask |= 1 << (mips16_to_32_reg_map
3543                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3544       if (pinfo & MIPS16_INSN_READ_GPR_X)
3545         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3546     }
3547   else
3548     {
3549       if (pinfo2 & INSN2_READ_GPR_D)
3550         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3551       if (pinfo & INSN_READ_GPR_T)
3552         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3553       if (pinfo & INSN_READ_GPR_S)
3554         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3555       if (pinfo2 & INSN2_READ_GP)
3556         mask |= 1 << GP;
3557       if (pinfo2 & INSN2_READ_GPR_31)
3558         mask |= 1 << RA;
3559       if (pinfo2 & INSN2_READ_GPR_Z)
3560         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3561     }
3562   if (mips_opts.micromips)
3563     {
3564       if (pinfo2 & INSN2_READ_GPR_MC)
3565         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3566       if (pinfo2 & INSN2_READ_GPR_ME)
3567         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3568       if (pinfo2 & INSN2_READ_GPR_MG)
3569         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3570       if (pinfo2 & INSN2_READ_GPR_MJ)
3571         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3572       if (pinfo2 & INSN2_READ_GPR_MMN)
3573         {
3574           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3575           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3576         }
3577       if (pinfo2 & INSN2_READ_GPR_MP)
3578         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3579       if (pinfo2 & INSN2_READ_GPR_MQ)
3580         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3581     }
3582   /* Don't include register 0.  */
3583   return mask & ~1;
3584 }
3585
3586 /* Return the mask of core registers that IP writes.  */
3587
3588 static unsigned int
3589 gpr_write_mask (const struct mips_cl_insn *ip)
3590 {
3591   unsigned long pinfo, pinfo2;
3592   unsigned int mask;
3593
3594   mask = gpr_mod_mask (ip);
3595   pinfo = ip->insn_mo->pinfo;
3596   pinfo2 = ip->insn_mo->pinfo2;
3597   if (mips_opts.mips16)
3598     {
3599       if (pinfo & MIPS16_INSN_WRITE_X)
3600         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3601       if (pinfo & MIPS16_INSN_WRITE_Y)
3602         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3603       if (pinfo & MIPS16_INSN_WRITE_Z)
3604         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3605       if (pinfo & MIPS16_INSN_WRITE_T)
3606         mask |= 1 << TREG;
3607       if (pinfo & MIPS16_INSN_WRITE_SP)
3608         mask |= 1 << SP;
3609       if (pinfo & MIPS16_INSN_WRITE_31)
3610         mask |= 1 << RA;
3611       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3612         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3613     }
3614   else
3615     {
3616       if (pinfo & INSN_WRITE_GPR_D)
3617         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3618       if (pinfo & INSN_WRITE_GPR_T)
3619         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3620       if (pinfo & INSN_WRITE_GPR_S)
3621         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3622       if (pinfo & INSN_WRITE_GPR_31)
3623         mask |= 1 << RA;
3624       if (pinfo2 & INSN2_WRITE_GPR_Z)
3625         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3626     }
3627   if (mips_opts.micromips)
3628     {
3629       if (pinfo2 & INSN2_WRITE_GPR_MB)
3630         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3631       if (pinfo2 & INSN2_WRITE_GPR_MH)
3632         {
3633           mask |= 1 << micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
3634           mask |= 1 << micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
3635         }
3636       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3637         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3638       if (pinfo2 & INSN2_WRITE_GPR_MP)
3639         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3640     }
3641   /* Don't include register 0.  */
3642   return mask & ~1;
3643 }
3644
3645 /* Return the mask of floating-point registers that IP reads.  */
3646
3647 static unsigned int
3648 fpr_read_mask (const struct mips_cl_insn *ip)
3649 {
3650   unsigned long pinfo, pinfo2;
3651   unsigned int mask;
3652
3653   mask = 0;
3654   pinfo = ip->insn_mo->pinfo;
3655   pinfo2 = ip->insn_mo->pinfo2;
3656   if (!mips_opts.mips16)
3657     {
3658       if (pinfo2 & INSN2_READ_FPR_D)
3659         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3660       if (pinfo & INSN_READ_FPR_S)
3661         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3662       if (pinfo & INSN_READ_FPR_T)
3663         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3664       if (pinfo & INSN_READ_FPR_R)
3665         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3666       if (pinfo2 & INSN2_READ_FPR_Z)
3667         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3668     }
3669   /* Conservatively treat all operands to an FP_D instruction are doubles.
3670      (This is overly pessimistic for things like cvt.d.s.)  */
3671   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3672     mask |= mask << 1;
3673   return mask;
3674 }
3675
3676 /* Return the mask of floating-point registers that IP writes.  */
3677
3678 static unsigned int
3679 fpr_write_mask (const struct mips_cl_insn *ip)
3680 {
3681   unsigned long pinfo, pinfo2;
3682   unsigned int mask;
3683
3684   mask = 0;
3685   pinfo = ip->insn_mo->pinfo;
3686   pinfo2 = ip->insn_mo->pinfo2;
3687   if (!mips_opts.mips16)
3688     {
3689       if (pinfo & INSN_WRITE_FPR_D)
3690         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3691       if (pinfo & INSN_WRITE_FPR_S)
3692         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3693       if (pinfo & INSN_WRITE_FPR_T)
3694         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3695       if (pinfo2 & INSN2_WRITE_FPR_Z)
3696         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3697     }
3698   /* Conservatively treat all operands to an FP_D instruction are doubles.
3699      (This is overly pessimistic for things like cvt.s.d.)  */
3700   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3701     mask |= mask << 1;
3702   return mask;
3703 }
3704
3705 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3706    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3707    by VR4120 errata.  */
3708
3709 static unsigned int
3710 classify_vr4120_insn (const char *name)
3711 {
3712   if (strncmp (name, "macc", 4) == 0)
3713     return FIX_VR4120_MACC;
3714   if (strncmp (name, "dmacc", 5) == 0)
3715     return FIX_VR4120_DMACC;
3716   if (strncmp (name, "mult", 4) == 0)
3717     return FIX_VR4120_MULT;
3718   if (strncmp (name, "dmult", 5) == 0)
3719     return FIX_VR4120_DMULT;
3720   if (strstr (name, "div"))
3721     return FIX_VR4120_DIV;
3722   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3723     return FIX_VR4120_MTHILO;
3724   return NUM_FIX_VR4120_CLASSES;
3725 }
3726
3727 #define INSN_ERET  0x42000018
3728 #define INSN_DERET 0x4200001f
3729
3730 /* Return the number of instructions that must separate INSN1 and INSN2,
3731    where INSN1 is the earlier instruction.  Return the worst-case value
3732    for any INSN2 if INSN2 is null.  */
3733
3734 static unsigned int
3735 insns_between (const struct mips_cl_insn *insn1,
3736                const struct mips_cl_insn *insn2)
3737 {
3738   unsigned long pinfo1, pinfo2;
3739   unsigned int mask;
3740
3741   /* This function needs to know which pinfo flags are set for INSN2
3742      and which registers INSN2 uses.  The former is stored in PINFO2 and
3743      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3744      will have every flag set and INSN2_USES_GPR will always return true.  */
3745   pinfo1 = insn1->insn_mo->pinfo;
3746   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3747
3748 #define INSN2_USES_GPR(REG) \
3749   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3750
3751   /* For most targets, write-after-read dependencies on the HI and LO
3752      registers must be separated by at least two instructions.  */
3753   if (!hilo_interlocks)
3754     {
3755       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3756         return 2;
3757       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3758         return 2;
3759     }
3760
3761   /* If we're working around r7000 errata, there must be two instructions
3762      between an mfhi or mflo and any instruction that uses the result.  */
3763   if (mips_7000_hilo_fix
3764       && !mips_opts.micromips
3765       && MF_HILO_INSN (pinfo1)
3766       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3767     return 2;
3768
3769   /* If we're working around 24K errata, one instruction is required
3770      if an ERET or DERET is followed by a branch instruction.  */
3771   if (mips_fix_24k && !mips_opts.micromips)
3772     {
3773       if (insn1->insn_opcode == INSN_ERET
3774           || insn1->insn_opcode == INSN_DERET)
3775         {
3776           if (insn2 == NULL
3777               || insn2->insn_opcode == INSN_ERET
3778               || insn2->insn_opcode == INSN_DERET
3779               || delayed_branch_p (insn2))
3780             return 1;
3781         }
3782     }
3783
3784   /* If working around VR4120 errata, check for combinations that need
3785      a single intervening instruction.  */
3786   if (mips_fix_vr4120 && !mips_opts.micromips)
3787     {
3788       unsigned int class1, class2;
3789
3790       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3791       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3792         {
3793           if (insn2 == NULL)
3794             return 1;
3795           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3796           if (vr4120_conflicts[class1] & (1 << class2))
3797             return 1;
3798         }
3799     }
3800
3801   if (!HAVE_CODE_COMPRESSION)
3802     {
3803       /* Check for GPR or coprocessor load delays.  All such delays
3804          are on the RT register.  */
3805       /* Itbl support may require additional care here.  */
3806       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3807           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3808         {
3809           know (pinfo1 & INSN_WRITE_GPR_T);
3810           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3811             return 1;
3812         }
3813
3814       /* Check for generic coprocessor hazards.
3815
3816          This case is not handled very well.  There is no special
3817          knowledge of CP0 handling, and the coprocessors other than
3818          the floating point unit are not distinguished at all.  */
3819       /* Itbl support may require additional care here. FIXME!
3820          Need to modify this to include knowledge about
3821          user specified delays!  */
3822       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3823                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3824         {
3825           /* Handle cases where INSN1 writes to a known general coprocessor
3826              register.  There must be a one instruction delay before INSN2
3827              if INSN2 reads that register, otherwise no delay is needed.  */
3828           mask = fpr_write_mask (insn1);
3829           if (mask != 0)
3830             {
3831               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3832                 return 1;
3833             }
3834           else
3835             {
3836               /* Read-after-write dependencies on the control registers
3837                  require a two-instruction gap.  */
3838               if ((pinfo1 & INSN_WRITE_COND_CODE)
3839                   && (pinfo2 & INSN_READ_COND_CODE))
3840                 return 2;
3841
3842               /* We don't know exactly what INSN1 does.  If INSN2 is
3843                  also a coprocessor instruction, assume there must be
3844                  a one instruction gap.  */
3845               if (pinfo2 & INSN_COP)
3846                 return 1;
3847             }
3848         }
3849
3850       /* Check for read-after-write dependencies on the coprocessor
3851          control registers in cases where INSN1 does not need a general
3852          coprocessor delay.  This means that INSN1 is a floating point
3853          comparison instruction.  */
3854       /* Itbl support may require additional care here.  */
3855       else if (!cop_interlocks
3856                && (pinfo1 & INSN_WRITE_COND_CODE)
3857                && (pinfo2 & INSN_READ_COND_CODE))
3858         return 1;
3859     }
3860
3861 #undef INSN2_USES_GPR
3862
3863   return 0;
3864 }
3865
3866 /* Return the number of nops that would be needed to work around the
3867    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3868    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3869    that are contained within the first IGNORE instructions of HIST.  */
3870
3871 static int
3872 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3873                  const struct mips_cl_insn *insn)
3874 {
3875   int i, j;
3876   unsigned int mask;
3877
3878   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3879      are not affected by the errata.  */
3880   if (insn != 0
3881       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3882           || strcmp (insn->insn_mo->name, "mtlo") == 0
3883           || strcmp (insn->insn_mo->name, "mthi") == 0))
3884     return 0;
3885
3886   /* Search for the first MFLO or MFHI.  */
3887   for (i = 0; i < MAX_VR4130_NOPS; i++)
3888     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3889       {
3890         /* Extract the destination register.  */
3891         mask = gpr_write_mask (&hist[i]);
3892
3893         /* No nops are needed if INSN reads that register.  */
3894         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3895           return 0;
3896
3897         /* ...or if any of the intervening instructions do.  */
3898         for (j = 0; j < i; j++)
3899           if (gpr_read_mask (&hist[j]) & mask)
3900             return 0;
3901
3902         if (i >= ignore)
3903           return MAX_VR4130_NOPS - i;
3904       }
3905   return 0;
3906 }
3907
3908 #define BASE_REG_EQ(INSN1, INSN2)       \
3909   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3910       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3911
3912 /* Return the minimum alignment for this store instruction.  */
3913
3914 static int
3915 fix_24k_align_to (const struct mips_opcode *mo)
3916 {
3917   if (strcmp (mo->name, "sh") == 0)
3918     return 2;
3919
3920   if (strcmp (mo->name, "swc1") == 0
3921       || strcmp (mo->name, "swc2") == 0
3922       || strcmp (mo->name, "sw") == 0
3923       || strcmp (mo->name, "sc") == 0
3924       || strcmp (mo->name, "s.s") == 0)
3925     return 4;
3926
3927   if (strcmp (mo->name, "sdc1") == 0
3928       || strcmp (mo->name, "sdc2") == 0
3929       || strcmp (mo->name, "s.d") == 0)
3930     return 8;
3931
3932   /* sb, swl, swr */
3933   return 1;
3934 }
3935
3936 struct fix_24k_store_info
3937   {
3938     /* Immediate offset, if any, for this store instruction.  */
3939     short off;
3940     /* Alignment required by this store instruction.  */
3941     int align_to;
3942     /* True for register offsets.  */
3943     int register_offset;
3944   };
3945
3946 /* Comparison function used by qsort.  */
3947
3948 static int
3949 fix_24k_sort (const void *a, const void *b)
3950 {
3951   const struct fix_24k_store_info *pos1 = a;
3952   const struct fix_24k_store_info *pos2 = b;
3953
3954   return (pos1->off - pos2->off);
3955 }
3956
3957 /* INSN is a store instruction.  Try to record the store information
3958    in STINFO.  Return false if the information isn't known.  */
3959
3960 static bfd_boolean
3961 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3962                            const struct mips_cl_insn *insn)
3963 {
3964   /* The instruction must have a known offset.  */
3965   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3966     return FALSE;
3967
3968   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3969   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3970   return TRUE;
3971 }
3972
3973 /* Return the number of nops that would be needed to work around the 24k
3974    "lost data on stores during refill" errata if instruction INSN
3975    immediately followed the 2 instructions described by HIST.
3976    Ignore hazards that are contained within the first IGNORE
3977    instructions of HIST.
3978
3979    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3980    for the data cache refills and store data. The following describes
3981    the scenario where the store data could be lost.
3982
3983    * A data cache miss, due to either a load or a store, causing fill
3984      data to be supplied by the memory subsystem
3985    * The first three doublewords of fill data are returned and written
3986      into the cache
3987    * A sequence of four stores occurs in consecutive cycles around the
3988      final doubleword of the fill:
3989    * Store A
3990    * Store B
3991    * Store C
3992    * Zero, One or more instructions
3993    * Store D
3994
3995    The four stores A-D must be to different doublewords of the line that
3996    is being filled. The fourth instruction in the sequence above permits
3997    the fill of the final doubleword to be transferred from the FSB into
3998    the cache. In the sequence above, the stores may be either integer
3999    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
4000    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
4001    different doublewords on the line. If the floating point unit is
4002    running in 1:2 mode, it is not possible to create the sequence above
4003    using only floating point store instructions.
4004
4005    In this case, the cache line being filled is incorrectly marked
4006    invalid, thereby losing the data from any store to the line that
4007    occurs between the original miss and the completion of the five
4008    cycle sequence shown above.
4009
4010    The workarounds are:
4011
4012    * Run the data cache in write-through mode.
4013    * Insert a non-store instruction between
4014      Store A and Store B or Store B and Store C.  */
4015   
4016 static int
4017 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
4018               const struct mips_cl_insn *insn)
4019 {
4020   struct fix_24k_store_info pos[3];
4021   int align, i, base_offset;
4022
4023   if (ignore >= 2)
4024     return 0;
4025
4026   /* If the previous instruction wasn't a store, there's nothing to
4027      worry about.  */
4028   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4029     return 0;
4030
4031   /* If the instructions after the previous one are unknown, we have
4032      to assume the worst.  */
4033   if (!insn)
4034     return 1;
4035
4036   /* Check whether we are dealing with three consecutive stores.  */
4037   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
4038       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4039     return 0;
4040
4041   /* If we don't know the relationship between the store addresses,
4042      assume the worst.  */
4043   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
4044       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
4045     return 1;
4046
4047   if (!fix_24k_record_store_info (&pos[0], insn)
4048       || !fix_24k_record_store_info (&pos[1], &hist[0])
4049       || !fix_24k_record_store_info (&pos[2], &hist[1]))
4050     return 1;
4051
4052   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
4053
4054   /* Pick a value of ALIGN and X such that all offsets are adjusted by
4055      X bytes and such that the base register + X is known to be aligned
4056      to align bytes.  */
4057
4058   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
4059     align = 8;
4060   else
4061     {
4062       align = pos[0].align_to;
4063       base_offset = pos[0].off;
4064       for (i = 1; i < 3; i++)
4065         if (align < pos[i].align_to)
4066           {
4067             align = pos[i].align_to;
4068             base_offset = pos[i].off;
4069           }
4070       for (i = 0; i < 3; i++)
4071         pos[i].off -= base_offset;
4072     }
4073
4074   pos[0].off &= ~align + 1;
4075   pos[1].off &= ~align + 1;
4076   pos[2].off &= ~align + 1;
4077
4078   /* If any two stores write to the same chunk, they also write to the
4079      same doubleword.  The offsets are still sorted at this point.  */
4080   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
4081     return 0;
4082
4083   /* A range of at least 9 bytes is needed for the stores to be in
4084      non-overlapping doublewords.  */
4085   if (pos[2].off - pos[0].off <= 8)
4086     return 0;
4087
4088   if (pos[2].off - pos[1].off >= 24
4089       || pos[1].off - pos[0].off >= 24
4090       || pos[2].off - pos[0].off >= 32)
4091     return 0;
4092
4093   return 1;
4094 }
4095
4096 /* Return the number of nops that would be needed if instruction INSN
4097    immediately followed the MAX_NOPS instructions given by HIST,
4098    where HIST[0] is the most recent instruction.  Ignore hazards
4099    between INSN and the first IGNORE instructions in HIST.
4100
4101    If INSN is null, return the worse-case number of nops for any
4102    instruction.  */
4103
4104 static int
4105 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
4106                const struct mips_cl_insn *insn)
4107 {
4108   int i, nops, tmp_nops;
4109
4110   nops = 0;
4111   for (i = ignore; i < MAX_DELAY_NOPS; i++)
4112     {
4113       tmp_nops = insns_between (hist + i, insn) - i;
4114       if (tmp_nops > nops)
4115         nops = tmp_nops;
4116     }
4117
4118   if (mips_fix_vr4130 && !mips_opts.micromips)
4119     {
4120       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
4121       if (tmp_nops > nops)
4122         nops = tmp_nops;
4123     }
4124
4125   if (mips_fix_24k && !mips_opts.micromips)
4126     {
4127       tmp_nops = nops_for_24k (ignore, hist, insn);
4128       if (tmp_nops > nops)
4129         nops = tmp_nops;
4130     }
4131
4132   return nops;
4133 }
4134
4135 /* The variable arguments provide NUM_INSNS extra instructions that
4136    might be added to HIST.  Return the largest number of nops that
4137    would be needed after the extended sequence, ignoring hazards
4138    in the first IGNORE instructions.  */
4139
4140 static int
4141 nops_for_sequence (int num_insns, int ignore,
4142                    const struct mips_cl_insn *hist, ...)
4143 {
4144   va_list args;
4145   struct mips_cl_insn buffer[MAX_NOPS];
4146   struct mips_cl_insn *cursor;
4147   int nops;
4148
4149   va_start (args, hist);
4150   cursor = buffer + num_insns;
4151   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
4152   while (cursor > buffer)
4153     *--cursor = *va_arg (args, const struct mips_cl_insn *);
4154
4155   nops = nops_for_insn (ignore, buffer, NULL);
4156   va_end (args);
4157   return nops;
4158 }
4159
4160 /* Like nops_for_insn, but if INSN is a branch, take into account the
4161    worst-case delay for the branch target.  */
4162
4163 static int
4164 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
4165                          const struct mips_cl_insn *insn)
4166 {
4167   int nops, tmp_nops;
4168
4169   nops = nops_for_insn (ignore, hist, insn);
4170   if (delayed_branch_p (insn))
4171     {
4172       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
4173                                     hist, insn, get_delay_slot_nop (insn));
4174       if (tmp_nops > nops)
4175         nops = tmp_nops;
4176     }
4177   else if (compact_branch_p (insn))
4178     {
4179       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
4180       if (tmp_nops > nops)
4181         nops = tmp_nops;
4182     }
4183   return nops;
4184 }
4185
4186 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
4187
4188 static void
4189 fix_loongson2f_nop (struct mips_cl_insn * ip)
4190 {
4191   gas_assert (!HAVE_CODE_COMPRESSION);
4192   if (strcmp (ip->insn_mo->name, "nop") == 0)
4193     ip->insn_opcode = LOONGSON2F_NOP_INSN;
4194 }
4195
4196 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
4197                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
4198
4199 static void
4200 fix_loongson2f_jump (struct mips_cl_insn * ip)
4201 {
4202   gas_assert (!HAVE_CODE_COMPRESSION);
4203   if (strcmp (ip->insn_mo->name, "j") == 0
4204       || strcmp (ip->insn_mo->name, "jr") == 0
4205       || strcmp (ip->insn_mo->name, "jalr") == 0)
4206     {
4207       int sreg;
4208       expressionS ep;
4209
4210       if (! mips_opts.at)
4211         return;
4212
4213       sreg = EXTRACT_OPERAND (0, RS, *ip);
4214       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
4215         return;
4216
4217       ep.X_op = O_constant;
4218       ep.X_add_number = 0xcfff0000;
4219       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
4220       ep.X_add_number = 0xffff;
4221       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
4222       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
4223     }
4224 }
4225
4226 static void
4227 fix_loongson2f (struct mips_cl_insn * ip)
4228 {
4229   if (mips_fix_loongson2f_nop)
4230     fix_loongson2f_nop (ip);
4231
4232   if (mips_fix_loongson2f_jump)
4233     fix_loongson2f_jump (ip);
4234 }
4235
4236 /* IP is a branch that has a delay slot, and we need to fill it
4237    automatically.   Return true if we can do that by swapping IP
4238    with the previous instruction.
4239    ADDRESS_EXPR is an operand of the instruction to be used with
4240    RELOC_TYPE.  */
4241
4242 static bfd_boolean
4243 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
4244   bfd_reloc_code_real_type *reloc_type)
4245 {
4246   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
4247   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
4248
4249   /* -O2 and above is required for this optimization.  */
4250   if (mips_optimize < 2)
4251     return FALSE;
4252
4253   /* If we have seen .set volatile or .set nomove, don't optimize.  */
4254   if (mips_opts.nomove)
4255     return FALSE;
4256
4257   /* We can't swap if the previous instruction's position is fixed.  */
4258   if (history[0].fixed_p)
4259     return FALSE;
4260
4261   /* If the previous previous insn was in a .set noreorder, we can't
4262      swap.  Actually, the MIPS assembler will swap in this situation.
4263      However, gcc configured -with-gnu-as will generate code like
4264
4265         .set    noreorder
4266         lw      $4,XXX
4267         .set    reorder
4268         INSN
4269         bne     $4,$0,foo
4270
4271      in which we can not swap the bne and INSN.  If gcc is not configured
4272      -with-gnu-as, it does not output the .set pseudo-ops.  */
4273   if (history[1].noreorder_p)
4274     return FALSE;
4275
4276   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
4277      This means that the previous instruction was a 4-byte one anyhow.  */
4278   if (mips_opts.mips16 && history[0].fixp[0])
4279     return FALSE;
4280
4281   /* If the branch is itself the target of a branch, we can not swap.
4282      We cheat on this; all we check for is whether there is a label on
4283      this instruction.  If there are any branches to anything other than
4284      a label, users must use .set noreorder.  */
4285   if (seg_info (now_seg)->label_list)
4286     return FALSE;
4287
4288   /* If the previous instruction is in a variant frag other than this
4289      branch's one, we cannot do the swap.  This does not apply to
4290      MIPS16 code, which uses variant frags for different purposes.  */
4291   if (!mips_opts.mips16
4292       && history[0].frag
4293       && history[0].frag->fr_type == rs_machine_dependent)
4294     return FALSE;
4295
4296   /* We do not swap with instructions that cannot architecturally
4297      be placed in a branch delay slot, such as SYNC or ERET.  We
4298      also refrain from swapping with a trap instruction, since it
4299      complicates trap handlers to have the trap instruction be in
4300      a delay slot.  */
4301   prev_pinfo = history[0].insn_mo->pinfo;
4302   if (prev_pinfo & INSN_NO_DELAY_SLOT)
4303     return FALSE;
4304
4305   /* Check for conflicts between the branch and the instructions
4306      before the candidate delay slot.  */
4307   if (nops_for_insn (0, history + 1, ip) > 0)
4308     return FALSE;
4309
4310   /* Check for conflicts between the swapped sequence and the
4311      target of the branch.  */
4312   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
4313     return FALSE;
4314
4315   /* If the branch reads a register that the previous
4316      instruction sets, we can not swap.  */
4317   gpr_read = gpr_read_mask (ip);
4318   prev_gpr_write = gpr_write_mask (&history[0]);
4319   if (gpr_read & prev_gpr_write)
4320     return FALSE;
4321
4322   /* If the branch writes a register that the previous
4323      instruction sets, we can not swap.  */
4324   gpr_write = gpr_write_mask (ip);
4325   if (gpr_write & prev_gpr_write)
4326     return FALSE;
4327
4328   /* If the branch writes a register that the previous
4329      instruction reads, we can not swap.  */
4330   prev_gpr_read = gpr_read_mask (&history[0]);
4331   if (gpr_write & prev_gpr_read)
4332     return FALSE;
4333
4334   /* If one instruction sets a condition code and the
4335      other one uses a condition code, we can not swap.  */
4336   pinfo = ip->insn_mo->pinfo;
4337   if ((pinfo & INSN_READ_COND_CODE)
4338       && (prev_pinfo & INSN_WRITE_COND_CODE))
4339     return FALSE;
4340   if ((pinfo & INSN_WRITE_COND_CODE)
4341       && (prev_pinfo & INSN_READ_COND_CODE))
4342     return FALSE;
4343
4344   /* If the previous instruction uses the PC, we can not swap.  */
4345   prev_pinfo2 = history[0].insn_mo->pinfo2;
4346   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
4347     return FALSE;
4348   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
4349     return FALSE;
4350
4351   /* If the previous instruction has an incorrect size for a fixed
4352      branch delay slot in microMIPS mode, we cannot swap.  */
4353   pinfo2 = ip->insn_mo->pinfo2;
4354   if (mips_opts.micromips
4355       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
4356       && insn_length (history) != 2)
4357     return FALSE;
4358   if (mips_opts.micromips
4359       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
4360       && insn_length (history) != 4)
4361     return FALSE;
4362
4363   /* On R5900 short loops need to be fixed by inserting a nop in
4364      the branch delay slots.
4365      A short loop can be terminated too early.  */
4366   if (mips_opts.arch == CPU_R5900
4367       /* Check if instruction has a parameter, ignore "j $31". */
4368       && (address_expr != NULL)
4369       /* Parameter must be 16 bit. */
4370       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
4371       /* Branch to same segment. */
4372       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
4373       /* Branch to same code fragment. */
4374       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
4375       /* Can only calculate branch offset if value is known. */
4376       && symbol_constant_p(address_expr->X_add_symbol)
4377       /* Check if branch is really conditional. */
4378       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
4379         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
4380         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
4381     {
4382       int distance;
4383       /* Check if loop is shorter than 6 instructions including
4384          branch and delay slot.  */
4385       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
4386       if (distance <= 20)
4387         {
4388           int i;
4389           int rv;
4390
4391           rv = FALSE;
4392           /* When the loop includes branches or jumps,
4393              it is not a short loop. */
4394           for (i = 0; i < (distance / 4); i++)
4395             {
4396               if ((history[i].cleared_p)
4397                   || delayed_branch_p(&history[i]))
4398                 {
4399                   rv = TRUE;
4400                   break;
4401                 }
4402             }
4403           if (rv == FALSE)
4404             {
4405               /* Insert nop after branch to fix short loop. */
4406               return FALSE;
4407             }
4408         }
4409     }
4410
4411   return TRUE;
4412 }
4413
4414 /* Decide how we should add IP to the instruction stream.
4415    ADDRESS_EXPR is an operand of the instruction to be used with
4416    RELOC_TYPE.  */
4417
4418 static enum append_method
4419 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
4420   bfd_reloc_code_real_type *reloc_type)
4421 {
4422   unsigned long pinfo;
4423
4424   /* The relaxed version of a macro sequence must be inherently
4425      hazard-free.  */
4426   if (mips_relax.sequence == 2)
4427     return APPEND_ADD;
4428
4429   /* We must not dabble with instructions in a ".set norerorder" block.  */
4430   if (mips_opts.noreorder)
4431     return APPEND_ADD;
4432
4433   /* Otherwise, it's our responsibility to fill branch delay slots.  */
4434   if (delayed_branch_p (ip))
4435     {
4436       if (!branch_likely_p (ip)
4437           && can_swap_branch_p (ip, address_expr, reloc_type))
4438         return APPEND_SWAP;
4439
4440       pinfo = ip->insn_mo->pinfo;
4441       if (mips_opts.mips16
4442           && ISA_SUPPORTS_MIPS16E
4443           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
4444         return APPEND_ADD_COMPACT;
4445
4446       return APPEND_ADD_WITH_NOP;
4447     }
4448
4449   return APPEND_ADD;
4450 }
4451
4452 /* IP is a MIPS16 instruction whose opcode we have just changed.
4453    Point IP->insn_mo to the new opcode's definition.  */
4454
4455 static void
4456 find_altered_mips16_opcode (struct mips_cl_insn *ip)
4457 {
4458   const struct mips_opcode *mo, *end;
4459
4460   end = &mips16_opcodes[bfd_mips16_num_opcodes];
4461   for (mo = ip->insn_mo; mo < end; mo++)
4462     if ((ip->insn_opcode & mo->mask) == mo->match)
4463       {
4464         ip->insn_mo = mo;
4465         return;
4466       }
4467   abort ();
4468 }
4469
4470 /* For microMIPS macros, we need to generate a local number label
4471    as the target of branches.  */
4472 #define MICROMIPS_LABEL_CHAR            '\037'
4473 static unsigned long micromips_target_label;
4474 static char micromips_target_name[32];
4475
4476 static char *
4477 micromips_label_name (void)
4478 {
4479   char *p = micromips_target_name;
4480   char symbol_name_temporary[24];
4481   unsigned long l;
4482   int i;
4483
4484   if (*p)
4485     return p;
4486
4487   i = 0;
4488   l = micromips_target_label;
4489 #ifdef LOCAL_LABEL_PREFIX
4490   *p++ = LOCAL_LABEL_PREFIX;
4491 #endif
4492   *p++ = 'L';
4493   *p++ = MICROMIPS_LABEL_CHAR;
4494   do
4495     {
4496       symbol_name_temporary[i++] = l % 10 + '0';
4497       l /= 10;
4498     }
4499   while (l != 0);
4500   while (i > 0)
4501     *p++ = symbol_name_temporary[--i];
4502   *p = '\0';
4503
4504   return micromips_target_name;
4505 }
4506
4507 static void
4508 micromips_label_expr (expressionS *label_expr)
4509 {
4510   label_expr->X_op = O_symbol;
4511   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
4512   label_expr->X_add_number = 0;
4513 }
4514
4515 static void
4516 micromips_label_inc (void)
4517 {
4518   micromips_target_label++;
4519   *micromips_target_name = '\0';
4520 }
4521
4522 static void
4523 micromips_add_label (void)
4524 {
4525   symbolS *s;
4526
4527   s = colon (micromips_label_name ());
4528   micromips_label_inc ();
4529   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
4530 }
4531
4532 /* If assembling microMIPS code, then return the microMIPS reloc
4533    corresponding to the requested one if any.  Otherwise return
4534    the reloc unchanged.  */
4535
4536 static bfd_reloc_code_real_type
4537 micromips_map_reloc (bfd_reloc_code_real_type reloc)
4538 {
4539   static const bfd_reloc_code_real_type relocs[][2] =
4540     {
4541       /* Keep sorted incrementally by the left-hand key.  */
4542       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
4543       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
4544       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
4545       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
4546       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
4547       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
4548       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
4549       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
4550       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
4551       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
4552       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
4553       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
4554       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
4555       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
4556       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
4557       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
4558       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
4559       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
4560       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
4561       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
4562       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
4563       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
4564       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
4565       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
4566       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
4567       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
4568       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
4569     };
4570   bfd_reloc_code_real_type r;
4571   size_t i;
4572
4573   if (!mips_opts.micromips)
4574     return reloc;
4575   for (i = 0; i < ARRAY_SIZE (relocs); i++)
4576     {
4577       r = relocs[i][0];
4578       if (r > reloc)
4579         return reloc;
4580       if (r == reloc)
4581         return relocs[i][1];
4582     }
4583   return reloc;
4584 }
4585
4586 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
4587    Return true on success, storing the resolved value in RESULT.  */
4588
4589 static bfd_boolean
4590 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
4591                  offsetT *result)
4592 {
4593   switch (reloc)
4594     {
4595     case BFD_RELOC_MIPS_HIGHEST:
4596     case BFD_RELOC_MICROMIPS_HIGHEST:
4597       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
4598       return TRUE;
4599
4600     case BFD_RELOC_MIPS_HIGHER:
4601     case BFD_RELOC_MICROMIPS_HIGHER:
4602       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
4603       return TRUE;
4604
4605     case BFD_RELOC_HI16_S:
4606     case BFD_RELOC_MICROMIPS_HI16_S:
4607     case BFD_RELOC_MIPS16_HI16_S:
4608       *result = ((operand + 0x8000) >> 16) & 0xffff;
4609       return TRUE;
4610
4611     case BFD_RELOC_HI16:
4612     case BFD_RELOC_MICROMIPS_HI16:
4613     case BFD_RELOC_MIPS16_HI16:
4614       *result = (operand >> 16) & 0xffff;
4615       return TRUE;
4616
4617     case BFD_RELOC_LO16:
4618     case BFD_RELOC_MICROMIPS_LO16:
4619     case BFD_RELOC_MIPS16_LO16:
4620       *result = operand & 0xffff;
4621       return TRUE;
4622
4623     case BFD_RELOC_UNUSED:
4624       *result = operand;
4625       return TRUE;
4626
4627     default:
4628       return FALSE;
4629     }
4630 }
4631
4632 /* Output an instruction.  IP is the instruction information.
4633    ADDRESS_EXPR is an operand of the instruction to be used with
4634    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
4635    a macro expansion.  */
4636
4637 static void
4638 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
4639              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
4640 {
4641   unsigned long prev_pinfo2, pinfo;
4642   bfd_boolean relaxed_branch = FALSE;
4643   enum append_method method;
4644   bfd_boolean relax32;
4645   int branch_disp;
4646
4647   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
4648     fix_loongson2f (ip);
4649
4650   file_ase_mips16 |= mips_opts.mips16;
4651   file_ase_micromips |= mips_opts.micromips;
4652
4653   prev_pinfo2 = history[0].insn_mo->pinfo2;
4654   pinfo = ip->insn_mo->pinfo;
4655
4656   if (mips_opts.micromips
4657       && !expansionp
4658       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
4659            && micromips_insn_length (ip->insn_mo) != 2)
4660           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
4661               && micromips_insn_length (ip->insn_mo) != 4)))
4662     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
4663              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
4664
4665   if (address_expr == NULL)
4666     ip->complete_p = 1;
4667   else if (reloc_type[0] <= BFD_RELOC_UNUSED
4668            && reloc_type[1] == BFD_RELOC_UNUSED
4669            && reloc_type[2] == BFD_RELOC_UNUSED
4670            && address_expr->X_op == O_constant)
4671     {
4672       switch (*reloc_type)
4673         {
4674         case BFD_RELOC_MIPS_JMP:
4675           {
4676             int shift;
4677
4678             shift = mips_opts.micromips ? 1 : 2;
4679             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4680               as_bad (_("jump to misaligned address (0x%lx)"),
4681                       (unsigned long) address_expr->X_add_number);
4682             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4683                                 & 0x3ffffff);
4684             ip->complete_p = 1;
4685           }
4686           break;
4687
4688         case BFD_RELOC_MIPS16_JMP:
4689           if ((address_expr->X_add_number & 3) != 0)
4690             as_bad (_("jump to misaligned address (0x%lx)"),
4691                     (unsigned long) address_expr->X_add_number);
4692           ip->insn_opcode |=
4693             (((address_expr->X_add_number & 0x7c0000) << 3)
4694                | ((address_expr->X_add_number & 0xf800000) >> 7)
4695                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4696           ip->complete_p = 1;
4697           break;
4698
4699         case BFD_RELOC_16_PCREL_S2:
4700           {
4701             int shift;
4702
4703             shift = mips_opts.micromips ? 1 : 2;
4704             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4705               as_bad (_("branch to misaligned address (0x%lx)"),
4706                       (unsigned long) address_expr->X_add_number);
4707             if (!mips_relax_branch)
4708               {
4709                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4710                     & ~((1 << (shift + 16)) - 1))
4711                   as_bad (_("branch address range overflow (0x%lx)"),
4712                           (unsigned long) address_expr->X_add_number);
4713                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4714                                     & 0xffff);
4715               }
4716           }
4717           break;
4718
4719         default:
4720           {
4721             offsetT value;
4722
4723             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
4724                                  &value))
4725               {
4726                 ip->insn_opcode |= value & 0xffff;
4727                 ip->complete_p = 1;
4728               }
4729           }
4730           break;
4731         }
4732     }
4733
4734   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4735     {
4736       /* There are a lot of optimizations we could do that we don't.
4737          In particular, we do not, in general, reorder instructions.
4738          If you use gcc with optimization, it will reorder
4739          instructions and generally do much more optimization then we
4740          do here; repeating all that work in the assembler would only
4741          benefit hand written assembly code, and does not seem worth
4742          it.  */
4743       int nops = (mips_optimize == 0
4744                   ? nops_for_insn (0, history, NULL)
4745                   : nops_for_insn_or_target (0, history, ip));
4746       if (nops > 0)
4747         {
4748           fragS *old_frag;
4749           unsigned long old_frag_offset;
4750           int i;
4751
4752           old_frag = frag_now;
4753           old_frag_offset = frag_now_fix ();
4754
4755           for (i = 0; i < nops; i++)
4756             add_fixed_insn (NOP_INSN);
4757           insert_into_history (0, nops, NOP_INSN);
4758
4759           if (listing)
4760             {
4761               listing_prev_line ();
4762               /* We may be at the start of a variant frag.  In case we
4763                  are, make sure there is enough space for the frag
4764                  after the frags created by listing_prev_line.  The
4765                  argument to frag_grow here must be at least as large
4766                  as the argument to all other calls to frag_grow in
4767                  this file.  We don't have to worry about being in the
4768                  middle of a variant frag, because the variants insert
4769                  all needed nop instructions themselves.  */
4770               frag_grow (40);
4771             }
4772
4773           mips_move_text_labels ();
4774
4775 #ifndef NO_ECOFF_DEBUGGING
4776           if (ECOFF_DEBUGGING)
4777             ecoff_fix_loc (old_frag, old_frag_offset);
4778 #endif
4779         }
4780     }
4781   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4782     {
4783       int nops;
4784
4785       /* Work out how many nops in prev_nop_frag are needed by IP,
4786          ignoring hazards generated by the first prev_nop_frag_since
4787          instructions.  */
4788       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4789       gas_assert (nops <= prev_nop_frag_holds);
4790
4791       /* Enforce NOPS as a minimum.  */
4792       if (nops > prev_nop_frag_required)
4793         prev_nop_frag_required = nops;
4794
4795       if (prev_nop_frag_holds == prev_nop_frag_required)
4796         {
4797           /* Settle for the current number of nops.  Update the history
4798              accordingly (for the benefit of any future .set reorder code).  */
4799           prev_nop_frag = NULL;
4800           insert_into_history (prev_nop_frag_since,
4801                                prev_nop_frag_holds, NOP_INSN);
4802         }
4803       else
4804         {
4805           /* Allow this instruction to replace one of the nops that was
4806              tentatively added to prev_nop_frag.  */
4807           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4808           prev_nop_frag_holds--;
4809           prev_nop_frag_since++;
4810         }
4811     }
4812
4813   method = get_append_method (ip, address_expr, reloc_type);
4814   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
4815
4816   dwarf2_emit_insn (0);
4817   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
4818      so "move" the instruction address accordingly.
4819
4820      Also, it doesn't seem appropriate for the assembler to reorder .loc
4821      entries.  If this instruction is a branch that we are going to swap
4822      with the previous instruction, the two instructions should be
4823      treated as a unit, and the debug information for both instructions
4824      should refer to the start of the branch sequence.  Using the
4825      current position is certainly wrong when swapping a 32-bit branch
4826      and a 16-bit delay slot, since the current position would then be
4827      in the middle of a branch.  */
4828   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
4829
4830   relax32 = (mips_relax_branch
4831              /* Don't try branch relaxation within .set nomacro, or within
4832                 .set noat if we use $at for PIC computations.  If it turns
4833                 out that the branch was out-of-range, we'll get an error.  */
4834              && !mips_opts.warn_about_macros
4835              && (mips_opts.at || mips_pic == NO_PIC)
4836              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
4837                 as they have no complementing branches.  */
4838              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
4839
4840   if (!HAVE_CODE_COMPRESSION
4841       && address_expr
4842       && relax32
4843       && *reloc_type == BFD_RELOC_16_PCREL_S2
4844       && delayed_branch_p (ip))
4845     {
4846       relaxed_branch = TRUE;
4847       add_relaxed_insn (ip, (relaxed_branch_length
4848                              (NULL, NULL,
4849                               uncond_branch_p (ip) ? -1
4850                               : branch_likely_p (ip) ? 1
4851                               : 0)), 4,
4852                         RELAX_BRANCH_ENCODE
4853                         (AT,
4854                          uncond_branch_p (ip),
4855                          branch_likely_p (ip),
4856                          pinfo & INSN_WRITE_GPR_31,
4857                          0),
4858                         address_expr->X_add_symbol,
4859                         address_expr->X_add_number);
4860       *reloc_type = BFD_RELOC_UNUSED;
4861     }
4862   else if (mips_opts.micromips
4863            && address_expr
4864            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4865                || *reloc_type > BFD_RELOC_UNUSED)
4866            && (delayed_branch_p (ip) || compact_branch_p (ip))
4867            /* Don't try branch relaxation when users specify
4868               16-bit/32-bit instructions.  */
4869            && !forced_insn_length)
4870     {
4871       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4872       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4873       int uncond = uncond_branch_p (ip) ? -1 : 0;
4874       int compact = compact_branch_p (ip);
4875       int al = pinfo & INSN_WRITE_GPR_31;
4876       int length32;
4877
4878       gas_assert (address_expr != NULL);
4879       gas_assert (!mips_relax.sequence);
4880
4881       relaxed_branch = TRUE;
4882       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4883       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4884                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
4885                                                 relax32, 0, 0),
4886                         address_expr->X_add_symbol,
4887                         address_expr->X_add_number);
4888       *reloc_type = BFD_RELOC_UNUSED;
4889     }
4890   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4891     {
4892       /* We need to set up a variant frag.  */
4893       gas_assert (address_expr != NULL);
4894       add_relaxed_insn (ip, 4, 0,
4895                         RELAX_MIPS16_ENCODE
4896                         (*reloc_type - BFD_RELOC_UNUSED,
4897                          forced_insn_length == 2, forced_insn_length == 4,
4898                          delayed_branch_p (&history[0]),
4899                          history[0].mips16_absolute_jump_p),
4900                         make_expr_symbol (address_expr), 0);
4901     }
4902   else if (mips_opts.mips16 && insn_length (ip) == 2)
4903     {
4904       if (!delayed_branch_p (ip))
4905         /* Make sure there is enough room to swap this instruction with
4906            a following jump instruction.  */
4907         frag_grow (6);
4908       add_fixed_insn (ip);
4909     }
4910   else
4911     {
4912       if (mips_opts.mips16
4913           && mips_opts.noreorder
4914           && delayed_branch_p (&history[0]))
4915         as_warn (_("extended instruction in delay slot"));
4916
4917       if (mips_relax.sequence)
4918         {
4919           /* If we've reached the end of this frag, turn it into a variant
4920              frag and record the information for the instructions we've
4921              written so far.  */
4922           if (frag_room () < 4)
4923             relax_close_frag ();
4924           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4925         }
4926
4927       if (mips_relax.sequence != 2)
4928         {
4929           if (mips_macro_warning.first_insn_sizes[0] == 0)
4930             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4931           mips_macro_warning.sizes[0] += insn_length (ip);
4932           mips_macro_warning.insns[0]++;
4933         }
4934       if (mips_relax.sequence != 1)
4935         {
4936           if (mips_macro_warning.first_insn_sizes[1] == 0)
4937             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4938           mips_macro_warning.sizes[1] += insn_length (ip);
4939           mips_macro_warning.insns[1]++;
4940         }
4941
4942       if (mips_opts.mips16)
4943         {
4944           ip->fixed_p = 1;
4945           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4946         }
4947       add_fixed_insn (ip);
4948     }
4949
4950   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4951     {
4952       bfd_reloc_code_real_type final_type[3];
4953       reloc_howto_type *howto0;
4954       reloc_howto_type *howto;
4955       int i;
4956
4957       /* Perform any necessary conversion to microMIPS relocations
4958          and find out how many relocations there actually are.  */
4959       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4960         final_type[i] = micromips_map_reloc (reloc_type[i]);
4961
4962       /* In a compound relocation, it is the final (outermost)
4963          operator that determines the relocated field.  */
4964       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4965       if (!howto)
4966         abort ();
4967
4968       if (i > 1)
4969         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4970       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4971                                  bfd_get_reloc_size (howto),
4972                                  address_expr,
4973                                  howto0 && howto0->pc_relative,
4974                                  final_type[0]);
4975
4976       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4977       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
4978         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4979
4980       /* These relocations can have an addend that won't fit in
4981          4 octets for 64bit assembly.  */
4982       if (HAVE_64BIT_GPRS
4983           && ! howto->partial_inplace
4984           && (reloc_type[0] == BFD_RELOC_16
4985               || reloc_type[0] == BFD_RELOC_32
4986               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4987               || reloc_type[0] == BFD_RELOC_GPREL16
4988               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4989               || reloc_type[0] == BFD_RELOC_GPREL32
4990               || reloc_type[0] == BFD_RELOC_64
4991               || reloc_type[0] == BFD_RELOC_CTOR
4992               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4993               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4994               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4995               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4996               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4997               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4998               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4999               || hi16_reloc_p (reloc_type[0])
5000               || lo16_reloc_p (reloc_type[0])))
5001         ip->fixp[0]->fx_no_overflow = 1;
5002
5003       /* These relocations can have an addend that won't fit in 2 octets.  */
5004       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
5005           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
5006         ip->fixp[0]->fx_no_overflow = 1;
5007
5008       if (mips_relax.sequence)
5009         {
5010           if (mips_relax.first_fixup == 0)
5011             mips_relax.first_fixup = ip->fixp[0];
5012         }
5013       else if (reloc_needs_lo_p (*reloc_type))
5014         {
5015           struct mips_hi_fixup *hi_fixup;
5016
5017           /* Reuse the last entry if it already has a matching %lo.  */
5018           hi_fixup = mips_hi_fixup_list;
5019           if (hi_fixup == 0
5020               || !fixup_has_matching_lo_p (hi_fixup->fixp))
5021             {
5022               hi_fixup = ((struct mips_hi_fixup *)
5023                           xmalloc (sizeof (struct mips_hi_fixup)));
5024               hi_fixup->next = mips_hi_fixup_list;
5025               mips_hi_fixup_list = hi_fixup;
5026             }
5027           hi_fixup->fixp = ip->fixp[0];
5028           hi_fixup->seg = now_seg;
5029         }
5030
5031       /* Add fixups for the second and third relocations, if given.
5032          Note that the ABI allows the second relocation to be
5033          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
5034          moment we only use RSS_UNDEF, but we could add support
5035          for the others if it ever becomes necessary.  */
5036       for (i = 1; i < 3; i++)
5037         if (reloc_type[i] != BFD_RELOC_UNUSED)
5038           {
5039             ip->fixp[i] = fix_new (ip->frag, ip->where,
5040                                    ip->fixp[0]->fx_size, NULL, 0,
5041                                    FALSE, final_type[i]);
5042
5043             /* Use fx_tcbit to mark compound relocs.  */
5044             ip->fixp[0]->fx_tcbit = 1;
5045             ip->fixp[i]->fx_tcbit = 1;
5046           }
5047     }
5048   install_insn (ip);
5049
5050   /* Update the register mask information.  */
5051   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
5052   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
5053
5054   switch (method)
5055     {
5056     case APPEND_ADD:
5057       insert_into_history (0, 1, ip);
5058       break;
5059
5060     case APPEND_ADD_WITH_NOP:
5061       {
5062         struct mips_cl_insn *nop;
5063
5064         insert_into_history (0, 1, ip);
5065         nop = get_delay_slot_nop (ip);
5066         add_fixed_insn (nop);
5067         insert_into_history (0, 1, nop);
5068         if (mips_relax.sequence)
5069           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
5070       }
5071       break;
5072
5073     case APPEND_ADD_COMPACT:
5074       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
5075       gas_assert (mips_opts.mips16);
5076       ip->insn_opcode |= 0x0080;
5077       find_altered_mips16_opcode (ip);
5078       install_insn (ip);
5079       insert_into_history (0, 1, ip);
5080       break;
5081
5082     case APPEND_SWAP:
5083       {
5084         struct mips_cl_insn delay = history[0];
5085         if (mips_opts.mips16)
5086           {
5087             know (delay.frag == ip->frag);
5088             move_insn (ip, delay.frag, delay.where);
5089             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
5090           }
5091         else if (relaxed_branch || delay.frag != ip->frag)
5092           {
5093             /* Add the delay slot instruction to the end of the
5094                current frag and shrink the fixed part of the
5095                original frag.  If the branch occupies the tail of
5096                the latter, move it backwards to cover the gap.  */
5097             delay.frag->fr_fix -= branch_disp;
5098             if (delay.frag == ip->frag)
5099               move_insn (ip, ip->frag, ip->where - branch_disp);
5100             add_fixed_insn (&delay);
5101           }
5102         else
5103           {
5104             move_insn (&delay, ip->frag,
5105                        ip->where - branch_disp + insn_length (ip));
5106             move_insn (ip, history[0].frag, history[0].where);
5107           }
5108         history[0] = *ip;
5109         delay.fixed_p = 1;
5110         insert_into_history (0, 1, &delay);
5111       }
5112       break;
5113     }
5114
5115   /* If we have just completed an unconditional branch, clear the history.  */
5116   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
5117       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
5118     {
5119       unsigned int i;
5120
5121       mips_no_prev_insn ();
5122
5123       for (i = 0; i < ARRAY_SIZE (history); i++)
5124         history[i].cleared_p = 1;
5125     }
5126
5127   /* We need to emit a label at the end of branch-likely macros.  */
5128   if (emit_branch_likely_macro)
5129     {
5130       emit_branch_likely_macro = FALSE;
5131       micromips_add_label ();
5132     }
5133
5134   /* We just output an insn, so the next one doesn't have a label.  */
5135   mips_clear_insn_labels ();
5136 }
5137
5138 /* Forget that there was any previous instruction or label.
5139    When BRANCH is true, the branch history is also flushed.  */
5140
5141 static void
5142 mips_no_prev_insn (void)
5143 {
5144   prev_nop_frag = NULL;
5145   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
5146   mips_clear_insn_labels ();
5147 }
5148
5149 /* This function must be called before we emit something other than
5150    instructions.  It is like mips_no_prev_insn except that it inserts
5151    any NOPS that might be needed by previous instructions.  */
5152
5153 void
5154 mips_emit_delays (void)
5155 {
5156   if (! mips_opts.noreorder)
5157     {
5158       int nops = nops_for_insn (0, history, NULL);
5159       if (nops > 0)
5160         {
5161           while (nops-- > 0)
5162             add_fixed_insn (NOP_INSN);
5163           mips_move_text_labels ();
5164         }
5165     }
5166   mips_no_prev_insn ();
5167 }
5168
5169 /* Start a (possibly nested) noreorder block.  */
5170
5171 static void
5172 start_noreorder (void)
5173 {
5174   if (mips_opts.noreorder == 0)
5175     {
5176       unsigned int i;
5177       int nops;
5178
5179       /* None of the instructions before the .set noreorder can be moved.  */
5180       for (i = 0; i < ARRAY_SIZE (history); i++)
5181         history[i].fixed_p = 1;
5182
5183       /* Insert any nops that might be needed between the .set noreorder
5184          block and the previous instructions.  We will later remove any
5185          nops that turn out not to be needed.  */
5186       nops = nops_for_insn (0, history, NULL);
5187       if (nops > 0)
5188         {
5189           if (mips_optimize != 0)
5190             {
5191               /* Record the frag which holds the nop instructions, so
5192                  that we can remove them if we don't need them.  */
5193               frag_grow (nops * NOP_INSN_SIZE);
5194               prev_nop_frag = frag_now;
5195               prev_nop_frag_holds = nops;
5196               prev_nop_frag_required = 0;
5197               prev_nop_frag_since = 0;
5198             }
5199
5200           for (; nops > 0; --nops)
5201             add_fixed_insn (NOP_INSN);
5202
5203           /* Move on to a new frag, so that it is safe to simply
5204              decrease the size of prev_nop_frag.  */
5205           frag_wane (frag_now);
5206           frag_new (0);
5207           mips_move_text_labels ();
5208         }
5209       mips_mark_labels ();
5210       mips_clear_insn_labels ();
5211     }
5212   mips_opts.noreorder++;
5213   mips_any_noreorder = 1;
5214 }
5215
5216 /* End a nested noreorder block.  */
5217
5218 static void
5219 end_noreorder (void)
5220 {
5221   mips_opts.noreorder--;
5222   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
5223     {
5224       /* Commit to inserting prev_nop_frag_required nops and go back to
5225          handling nop insertion the .set reorder way.  */
5226       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
5227                                 * NOP_INSN_SIZE);
5228       insert_into_history (prev_nop_frag_since,
5229                            prev_nop_frag_required, NOP_INSN);
5230       prev_nop_frag = NULL;
5231     }
5232 }
5233
5234 /* Set up global variables for the start of a new macro.  */
5235
5236 static void
5237 macro_start (void)
5238 {
5239   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
5240   memset (&mips_macro_warning.first_insn_sizes, 0,
5241           sizeof (mips_macro_warning.first_insn_sizes));
5242   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
5243   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
5244                                      && delayed_branch_p (&history[0]));
5245   switch (history[0].insn_mo->pinfo2
5246           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
5247     {
5248     case INSN2_BRANCH_DELAY_32BIT:
5249       mips_macro_warning.delay_slot_length = 4;
5250       break;
5251     case INSN2_BRANCH_DELAY_16BIT:
5252       mips_macro_warning.delay_slot_length = 2;
5253       break;
5254     default:
5255       mips_macro_warning.delay_slot_length = 0;
5256       break;
5257     }
5258   mips_macro_warning.first_frag = NULL;
5259 }
5260
5261 /* Given that a macro is longer than one instruction or of the wrong size,
5262    return the appropriate warning for it.  Return null if no warning is
5263    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
5264    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
5265    and RELAX_NOMACRO.  */
5266
5267 static const char *
5268 macro_warning (relax_substateT subtype)
5269 {
5270   if (subtype & RELAX_DELAY_SLOT)
5271     return _("Macro instruction expanded into multiple instructions"
5272              " in a branch delay slot");
5273   else if (subtype & RELAX_NOMACRO)
5274     return _("Macro instruction expanded into multiple instructions");
5275   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
5276                       | RELAX_DELAY_SLOT_SIZE_SECOND))
5277     return ((subtype & RELAX_DELAY_SLOT_16BIT)
5278             ? _("Macro instruction expanded into a wrong size instruction"
5279                 " in a 16-bit branch delay slot")
5280             : _("Macro instruction expanded into a wrong size instruction"
5281                 " in a 32-bit branch delay slot"));
5282   else
5283     return 0;
5284 }
5285
5286 /* Finish up a macro.  Emit warnings as appropriate.  */
5287
5288 static void
5289 macro_end (void)
5290 {
5291   /* Relaxation warning flags.  */
5292   relax_substateT subtype = 0;
5293
5294   /* Check delay slot size requirements.  */
5295   if (mips_macro_warning.delay_slot_length == 2)
5296     subtype |= RELAX_DELAY_SLOT_16BIT;
5297   if (mips_macro_warning.delay_slot_length != 0)
5298     {
5299       if (mips_macro_warning.delay_slot_length
5300           != mips_macro_warning.first_insn_sizes[0])
5301         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
5302       if (mips_macro_warning.delay_slot_length
5303           != mips_macro_warning.first_insn_sizes[1])
5304         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
5305     }
5306
5307   /* Check instruction count requirements.  */
5308   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
5309     {
5310       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
5311         subtype |= RELAX_SECOND_LONGER;
5312       if (mips_opts.warn_about_macros)
5313         subtype |= RELAX_NOMACRO;
5314       if (mips_macro_warning.delay_slot_p)
5315         subtype |= RELAX_DELAY_SLOT;
5316     }
5317
5318   /* If both alternatives fail to fill a delay slot correctly,
5319      emit the warning now.  */
5320   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
5321       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
5322     {
5323       relax_substateT s;
5324       const char *msg;
5325
5326       s = subtype & (RELAX_DELAY_SLOT_16BIT
5327                      | RELAX_DELAY_SLOT_SIZE_FIRST
5328                      | RELAX_DELAY_SLOT_SIZE_SECOND);
5329       msg = macro_warning (s);
5330       if (msg != NULL)
5331         as_warn ("%s", msg);
5332       subtype &= ~s;
5333     }
5334
5335   /* If both implementations are longer than 1 instruction, then emit the
5336      warning now.  */
5337   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
5338     {
5339       relax_substateT s;
5340       const char *msg;
5341
5342       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
5343       msg = macro_warning (s);
5344       if (msg != NULL)
5345         as_warn ("%s", msg);
5346       subtype &= ~s;
5347     }
5348
5349   /* If any flags still set, then one implementation might need a warning
5350      and the other either will need one of a different kind or none at all.
5351      Pass any remaining flags over to relaxation.  */
5352   if (mips_macro_warning.first_frag != NULL)
5353     mips_macro_warning.first_frag->fr_subtype |= subtype;
5354 }
5355
5356 /* Instruction operand formats used in macros that vary between
5357    standard MIPS and microMIPS code.  */
5358
5359 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
5360 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
5361 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
5362 static const char * const lui_fmt[2] = { "t,u", "s,u" };
5363 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
5364 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
5365 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
5366 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
5367
5368 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
5369 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
5370 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
5371 #define LUI_FMT (lui_fmt[mips_opts.micromips])
5372 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
5373 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
5374 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
5375 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
5376
5377 /* Read a macro's relocation codes from *ARGS and store them in *R.
5378    The first argument in *ARGS will be either the code for a single
5379    relocation or -1 followed by the three codes that make up a
5380    composite relocation.  */
5381
5382 static void
5383 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
5384 {
5385   int i, next;
5386
5387   next = va_arg (*args, int);
5388   if (next >= 0)
5389     r[0] = (bfd_reloc_code_real_type) next;
5390   else
5391     {
5392       for (i = 0; i < 3; i++)
5393         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
5394       /* This function is only used for 16-bit relocation fields.
5395          To make the macro code simpler, treat an unrelocated value
5396          in the same way as BFD_RELOC_LO16.  */
5397       if (r[0] == BFD_RELOC_UNUSED)
5398         r[0] = BFD_RELOC_LO16;
5399     }
5400 }
5401
5402 /* Build an instruction created by a macro expansion.  This is passed
5403    a pointer to the count of instructions created so far, an
5404    expression, the name of the instruction to build, an operand format
5405    string, and corresponding arguments.  */
5406
5407 static void
5408 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
5409 {
5410   const struct mips_opcode *mo = NULL;
5411   bfd_reloc_code_real_type r[3];
5412   const struct mips_opcode *amo;
5413   const struct mips_operand *operand;
5414   struct hash_control *hash;
5415   struct mips_cl_insn insn;
5416   va_list args;
5417   unsigned int uval;
5418
5419   va_start (args, fmt);
5420
5421   if (mips_opts.mips16)
5422     {
5423       mips16_macro_build (ep, name, fmt, &args);
5424       va_end (args);
5425       return;
5426     }
5427
5428   r[0] = BFD_RELOC_UNUSED;
5429   r[1] = BFD_RELOC_UNUSED;
5430   r[2] = BFD_RELOC_UNUSED;
5431   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
5432   amo = (struct mips_opcode *) hash_find (hash, name);
5433   gas_assert (amo);
5434   gas_assert (strcmp (name, amo->name) == 0);
5435
5436   do
5437     {
5438       /* Search until we get a match for NAME.  It is assumed here that
5439          macros will never generate MDMX, MIPS-3D, or MT instructions.
5440          We try to match an instruction that fulfils the branch delay
5441          slot instruction length requirement (if any) of the previous
5442          instruction.  While doing this we record the first instruction
5443          seen that matches all the other conditions and use it anyway
5444          if the requirement cannot be met; we will issue an appropriate
5445          warning later on.  */
5446       if (strcmp (fmt, amo->args) == 0
5447           && amo->pinfo != INSN_MACRO
5448           && is_opcode_valid (amo)
5449           && is_size_valid (amo))
5450         {
5451           if (is_delay_slot_valid (amo))
5452             {
5453               mo = amo;
5454               break;
5455             }
5456           else if (!mo)
5457             mo = amo;
5458         }
5459
5460       ++amo;
5461       gas_assert (amo->name);
5462     }
5463   while (strcmp (name, amo->name) == 0);
5464
5465   gas_assert (mo);
5466   create_insn (&insn, mo);
5467   for (; *fmt; ++fmt)
5468     {
5469       switch (*fmt)
5470         {
5471         case ',':
5472         case '(':
5473         case ')':
5474         case 'z':
5475           break;
5476
5477         case 'i':
5478         case 'j':
5479           macro_read_relocs (&args, r);
5480           gas_assert (*r == BFD_RELOC_GPREL16
5481                       || *r == BFD_RELOC_MIPS_HIGHER
5482                       || *r == BFD_RELOC_HI16_S
5483                       || *r == BFD_RELOC_LO16
5484                       || *r == BFD_RELOC_MIPS_GOT_OFST);
5485           break;
5486
5487         case 'o':
5488           macro_read_relocs (&args, r);
5489           break;
5490
5491         case 'u':
5492           macro_read_relocs (&args, r);
5493           gas_assert (ep != NULL
5494                       && (ep->X_op == O_constant
5495                           || (ep->X_op == O_symbol
5496                               && (*r == BFD_RELOC_MIPS_HIGHEST
5497                                   || *r == BFD_RELOC_HI16_S
5498                                   || *r == BFD_RELOC_HI16
5499                                   || *r == BFD_RELOC_GPREL16
5500                                   || *r == BFD_RELOC_MIPS_GOT_HI16
5501                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
5502           break;
5503
5504         case 'p':
5505           gas_assert (ep != NULL);
5506
5507           /*
5508            * This allows macro() to pass an immediate expression for
5509            * creating short branches without creating a symbol.
5510            *
5511            * We don't allow branch relaxation for these branches, as
5512            * they should only appear in ".set nomacro" anyway.
5513            */
5514           if (ep->X_op == O_constant)
5515             {
5516               /* For microMIPS we always use relocations for branches.
5517                  So we should not resolve immediate values.  */
5518               gas_assert (!mips_opts.micromips);
5519
5520               if ((ep->X_add_number & 3) != 0)
5521                 as_bad (_("branch to misaligned address (0x%lx)"),
5522                         (unsigned long) ep->X_add_number);
5523               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5524                 as_bad (_("branch address range overflow (0x%lx)"),
5525                         (unsigned long) ep->X_add_number);
5526               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5527               ep = NULL;
5528             }
5529           else
5530             *r = BFD_RELOC_16_PCREL_S2;
5531           break;
5532
5533         case 'a':
5534           gas_assert (ep != NULL);
5535           *r = BFD_RELOC_MIPS_JMP;
5536           break;
5537
5538         default:
5539           operand = (mips_opts.micromips
5540                      ? decode_micromips_operand (fmt)
5541                      : decode_mips_operand (fmt));
5542           if (!operand)
5543             abort ();
5544
5545           uval = va_arg (args, int);
5546           if (operand->type == OP_CLO_CLZ_DEST)
5547             uval |= (uval << 5);
5548           insn_insert_operand (&insn, operand, uval);
5549
5550           if (*fmt == '+' || *fmt == 'm')
5551             ++fmt;
5552           break;
5553         }
5554     }
5555   va_end (args);
5556   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5557
5558   append_insn (&insn, ep, r, TRUE);
5559 }
5560
5561 static void
5562 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5563                     va_list *args)
5564 {
5565   struct mips_opcode *mo;
5566   struct mips_cl_insn insn;
5567   const struct mips_operand *operand;
5568   bfd_reloc_code_real_type r[3]
5569     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5570
5571   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5572   gas_assert (mo);
5573   gas_assert (strcmp (name, mo->name) == 0);
5574
5575   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5576     {
5577       ++mo;
5578       gas_assert (mo->name);
5579       gas_assert (strcmp (name, mo->name) == 0);
5580     }
5581
5582   create_insn (&insn, mo);
5583   for (; *fmt; ++fmt)
5584     {
5585       int c;
5586
5587       c = *fmt;
5588       switch (c)
5589         {
5590         case ',':
5591         case '(':
5592         case ')':
5593           break;
5594
5595         case '0':
5596         case 'S':
5597         case 'P':
5598         case 'R':
5599           break;
5600
5601         case '<':
5602         case '>':
5603         case '4':
5604         case '5':
5605         case 'H':
5606         case 'W':
5607         case 'D':
5608         case 'j':
5609         case '8':
5610         case 'V':
5611         case 'C':
5612         case 'U':
5613         case 'k':
5614         case 'K':
5615         case 'p':
5616         case 'q':
5617           {
5618             offsetT value;
5619
5620             gas_assert (ep != NULL);
5621
5622             if (ep->X_op != O_constant)
5623               *r = (int) BFD_RELOC_UNUSED + c;
5624             else if (calculate_reloc (*r, ep->X_add_number, &value))
5625               {
5626                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
5627                 ep = NULL;
5628                 *r = BFD_RELOC_UNUSED;
5629               }
5630           }
5631           break;
5632
5633         default:
5634           operand = decode_mips16_operand (c, FALSE);
5635           if (!operand)
5636             abort ();
5637
5638           insn_insert_operand (&insn, operand, va_arg (args, int));
5639           break;
5640         }
5641     }
5642
5643   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5644
5645   append_insn (&insn, ep, r, TRUE);
5646 }
5647
5648 /*
5649  * Sign-extend 32-bit mode constants that have bit 31 set and all
5650  * higher bits unset.
5651  */
5652 static void
5653 normalize_constant_expr (expressionS *ex)
5654 {
5655   if (ex->X_op == O_constant
5656       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5657     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5658                         - 0x80000000);
5659 }
5660
5661 /*
5662  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5663  * all higher bits unset.
5664  */
5665 static void
5666 normalize_address_expr (expressionS *ex)
5667 {
5668   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5669         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5670       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5671     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5672                         - 0x80000000);
5673 }
5674
5675 /*
5676  * Generate a "jalr" instruction with a relocation hint to the called
5677  * function.  This occurs in NewABI PIC code.
5678  */
5679 static void
5680 macro_build_jalr (expressionS *ep, int cprestore)
5681 {
5682   static const bfd_reloc_code_real_type jalr_relocs[2]
5683     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5684   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5685   const char *jalr;
5686   char *f = NULL;
5687
5688   if (MIPS_JALR_HINT_P (ep))
5689     {
5690       frag_grow (8);
5691       f = frag_more (0);
5692     }
5693   if (mips_opts.micromips)
5694     {
5695       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
5696               ? "jalr" : "jalrs");
5697       if (MIPS_JALR_HINT_P (ep)
5698           || mips_opts.insn32
5699           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5700         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5701       else
5702         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5703     }
5704   else
5705     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5706   if (MIPS_JALR_HINT_P (ep))
5707     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5708 }
5709
5710 /*
5711  * Generate a "lui" instruction.
5712  */
5713 static void
5714 macro_build_lui (expressionS *ep, int regnum)
5715 {
5716   gas_assert (! mips_opts.mips16);
5717
5718   if (ep->X_op != O_constant)
5719     {
5720       gas_assert (ep->X_op == O_symbol);
5721       /* _gp_disp is a special case, used from s_cpload.
5722          __gnu_local_gp is used if mips_no_shared.  */
5723       gas_assert (mips_pic == NO_PIC
5724               || (! HAVE_NEWABI
5725                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5726               || (! mips_in_shared
5727                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5728                              "__gnu_local_gp") == 0));
5729     }
5730
5731   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5732 }
5733
5734 /* Generate a sequence of instructions to do a load or store from a constant
5735    offset off of a base register (breg) into/from a target register (treg),
5736    using AT if necessary.  */
5737 static void
5738 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5739                               int treg, int breg, int dbl)
5740 {
5741   gas_assert (ep->X_op == O_constant);
5742
5743   /* Sign-extending 32-bit constants makes their handling easier.  */
5744   if (!dbl)
5745     normalize_constant_expr (ep);
5746
5747   /* Right now, this routine can only handle signed 32-bit constants.  */
5748   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5749     as_warn (_("operand overflow"));
5750
5751   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5752     {
5753       /* Signed 16-bit offset will fit in the op.  Easy!  */
5754       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5755     }
5756   else
5757     {
5758       /* 32-bit offset, need multiple instructions and AT, like:
5759            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5760            addu     $tempreg,$tempreg,$breg
5761            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5762          to handle the complete offset.  */
5763       macro_build_lui (ep, AT);
5764       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5765       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5766
5767       if (!mips_opts.at)
5768         as_bad (_("Macro used $at after \".set noat\""));
5769     }
5770 }
5771
5772 /*                      set_at()
5773  * Generates code to set the $at register to true (one)
5774  * if reg is less than the immediate expression.
5775  */
5776 static void
5777 set_at (int reg, int unsignedp)
5778 {
5779   if (imm_expr.X_op == O_constant
5780       && imm_expr.X_add_number >= -0x8000
5781       && imm_expr.X_add_number < 0x8000)
5782     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5783                  AT, reg, BFD_RELOC_LO16);
5784   else
5785     {
5786       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5787       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5788     }
5789 }
5790
5791 /* Warn if an expression is not a constant.  */
5792
5793 static void
5794 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5795 {
5796   if (ex->X_op == O_big)
5797     as_bad (_("unsupported large constant"));
5798   else if (ex->X_op != O_constant)
5799     as_bad (_("Instruction %s requires absolute expression"),
5800             ip->insn_mo->name);
5801
5802   if (HAVE_32BIT_GPRS)
5803     normalize_constant_expr (ex);
5804 }
5805
5806 /* Count the leading zeroes by performing a binary chop. This is a
5807    bulky bit of source, but performance is a LOT better for the
5808    majority of values than a simple loop to count the bits:
5809        for (lcnt = 0; (lcnt < 32); lcnt++)
5810          if ((v) & (1 << (31 - lcnt)))
5811            break;
5812   However it is not code size friendly, and the gain will drop a bit
5813   on certain cached systems.
5814 */
5815 #define COUNT_TOP_ZEROES(v)             \
5816   (((v) & ~0xffff) == 0                 \
5817    ? ((v) & ~0xff) == 0                 \
5818      ? ((v) & ~0xf) == 0                \
5819        ? ((v) & ~0x3) == 0              \
5820          ? ((v) & ~0x1) == 0            \
5821            ? !(v)                       \
5822              ? 32                       \
5823              : 31                       \
5824            : 30                         \
5825          : ((v) & ~0x7) == 0            \
5826            ? 29                         \
5827            : 28                         \
5828        : ((v) & ~0x3f) == 0             \
5829          ? ((v) & ~0x1f) == 0           \
5830            ? 27                         \
5831            : 26                         \
5832          : ((v) & ~0x7f) == 0           \
5833            ? 25                         \
5834            : 24                         \
5835      : ((v) & ~0xfff) == 0              \
5836        ? ((v) & ~0x3ff) == 0            \
5837          ? ((v) & ~0x1ff) == 0          \
5838            ? 23                         \
5839            : 22                         \
5840          : ((v) & ~0x7ff) == 0          \
5841            ? 21                         \
5842            : 20                         \
5843        : ((v) & ~0x3fff) == 0           \
5844          ? ((v) & ~0x1fff) == 0         \
5845            ? 19                         \
5846            : 18                         \
5847          : ((v) & ~0x7fff) == 0         \
5848            ? 17                         \
5849            : 16                         \
5850    : ((v) & ~0xffffff) == 0             \
5851      ? ((v) & ~0xfffff) == 0            \
5852        ? ((v) & ~0x3ffff) == 0          \
5853          ? ((v) & ~0x1ffff) == 0        \
5854            ? 15                         \
5855            : 14                         \
5856          : ((v) & ~0x7ffff) == 0        \
5857            ? 13                         \
5858            : 12                         \
5859        : ((v) & ~0x3fffff) == 0         \
5860          ? ((v) & ~0x1fffff) == 0       \
5861            ? 11                         \
5862            : 10                         \
5863          : ((v) & ~0x7fffff) == 0       \
5864            ? 9                          \
5865            : 8                          \
5866      : ((v) & ~0xfffffff) == 0          \
5867        ? ((v) & ~0x3ffffff) == 0        \
5868          ? ((v) & ~0x1ffffff) == 0      \
5869            ? 7                          \
5870            : 6                          \
5871          : ((v) & ~0x7ffffff) == 0      \
5872            ? 5                          \
5873            : 4                          \
5874        : ((v) & ~0x3fffffff) == 0       \
5875          ? ((v) & ~0x1fffffff) == 0     \
5876            ? 3                          \
5877            : 2                          \
5878          : ((v) & ~0x7fffffff) == 0     \
5879            ? 1                          \
5880            : 0)
5881
5882 /*                      load_register()
5883  *  This routine generates the least number of instructions necessary to load
5884  *  an absolute expression value into a register.
5885  */
5886 static void
5887 load_register (int reg, expressionS *ep, int dbl)
5888 {
5889   int freg;
5890   expressionS hi32, lo32;
5891
5892   if (ep->X_op != O_big)
5893     {
5894       gas_assert (ep->X_op == O_constant);
5895
5896       /* Sign-extending 32-bit constants makes their handling easier.  */
5897       if (!dbl)
5898         normalize_constant_expr (ep);
5899
5900       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
5901         {
5902           /* We can handle 16 bit signed values with an addiu to
5903              $zero.  No need to ever use daddiu here, since $zero and
5904              the result are always correct in 32 bit mode.  */
5905           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5906           return;
5907         }
5908       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
5909         {
5910           /* We can handle 16 bit unsigned values with an ori to
5911              $zero.  */
5912           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5913           return;
5914         }
5915       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
5916         {
5917           /* 32 bit values require an lui.  */
5918           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5919           if ((ep->X_add_number & 0xffff) != 0)
5920             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5921           return;
5922         }
5923     }
5924
5925   /* The value is larger than 32 bits.  */
5926
5927   if (!dbl || HAVE_32BIT_GPRS)
5928     {
5929       char value[32];
5930
5931       sprintf_vma (value, ep->X_add_number);
5932       as_bad (_("Number (0x%s) larger than 32 bits"), value);
5933       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5934       return;
5935     }
5936
5937   if (ep->X_op != O_big)
5938     {
5939       hi32 = *ep;
5940       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5941       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5942       hi32.X_add_number &= 0xffffffff;
5943       lo32 = *ep;
5944       lo32.X_add_number &= 0xffffffff;
5945     }
5946   else
5947     {
5948       gas_assert (ep->X_add_number > 2);
5949       if (ep->X_add_number == 3)
5950         generic_bignum[3] = 0;
5951       else if (ep->X_add_number > 4)
5952         as_bad (_("Number larger than 64 bits"));
5953       lo32.X_op = O_constant;
5954       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
5955       hi32.X_op = O_constant;
5956       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
5957     }
5958
5959   if (hi32.X_add_number == 0)
5960     freg = 0;
5961   else
5962     {
5963       int shift, bit;
5964       unsigned long hi, lo;
5965
5966       if (hi32.X_add_number == (offsetT) 0xffffffff)
5967         {
5968           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
5969             {
5970               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5971               return;
5972             }
5973           if (lo32.X_add_number & 0x80000000)
5974             {
5975               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5976               if (lo32.X_add_number & 0xffff)
5977                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5978               return;
5979             }
5980         }
5981
5982       /* Check for 16bit shifted constant.  We know that hi32 is
5983          non-zero, so start the mask on the first bit of the hi32
5984          value.  */
5985       shift = 17;
5986       do
5987         {
5988           unsigned long himask, lomask;
5989
5990           if (shift < 32)
5991             {
5992               himask = 0xffff >> (32 - shift);
5993               lomask = (0xffff << shift) & 0xffffffff;
5994             }
5995           else
5996             {
5997               himask = 0xffff << (shift - 32);
5998               lomask = 0;
5999             }
6000           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6001               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6002             {
6003               expressionS tmp;
6004
6005               tmp.X_op = O_constant;
6006               if (shift < 32)
6007                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6008                                     | (lo32.X_add_number >> shift));
6009               else
6010                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
6011               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6012               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6013                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6014               return;
6015             }
6016           ++shift;
6017         }
6018       while (shift <= (64 - 16));
6019
6020       /* Find the bit number of the lowest one bit, and store the
6021          shifted value in hi/lo.  */
6022       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
6023       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
6024       if (lo != 0)
6025         {
6026           bit = 0;
6027           while ((lo & 1) == 0)
6028             {
6029               lo >>= 1;
6030               ++bit;
6031             }
6032           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
6033           hi >>= bit;
6034         }
6035       else
6036         {
6037           bit = 32;
6038           while ((hi & 1) == 0)
6039             {
6040               hi >>= 1;
6041               ++bit;
6042             }
6043           lo = hi;
6044           hi = 0;
6045         }
6046
6047       /* Optimize if the shifted value is a (power of 2) - 1.  */
6048       if ((hi == 0 && ((lo + 1) & lo) == 0)
6049           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
6050         {
6051           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
6052           if (shift != 0)
6053             {
6054               expressionS tmp;
6055
6056               /* This instruction will set the register to be all
6057                  ones.  */
6058               tmp.X_op = O_constant;
6059               tmp.X_add_number = (offsetT) -1;
6060               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6061               if (bit != 0)
6062                 {
6063                   bit += shift;
6064                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6065                                reg, reg, (bit >= 32) ? bit - 32 : bit);
6066                 }
6067               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
6068                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6069               return;
6070             }
6071         }
6072
6073       /* Sign extend hi32 before calling load_register, because we can
6074          generally get better code when we load a sign extended value.  */
6075       if ((hi32.X_add_number & 0x80000000) != 0)
6076         hi32.X_add_number |= ~(offsetT) 0xffffffff;
6077       load_register (reg, &hi32, 0);
6078       freg = reg;
6079     }
6080   if ((lo32.X_add_number & 0xffff0000) == 0)
6081     {
6082       if (freg != 0)
6083         {
6084           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
6085           freg = reg;
6086         }
6087     }
6088   else
6089     {
6090       expressionS mid16;
6091
6092       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
6093         {
6094           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6095           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
6096           return;
6097         }
6098
6099       if (freg != 0)
6100         {
6101           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
6102           freg = reg;
6103         }
6104       mid16 = lo32;
6105       mid16.X_add_number >>= 16;
6106       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6107       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6108       freg = reg;
6109     }
6110   if ((lo32.X_add_number & 0xffff) != 0)
6111     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6112 }
6113
6114 static inline void
6115 load_delay_nop (void)
6116 {
6117   if (!gpr_interlocks)
6118     macro_build (NULL, "nop", "");
6119 }
6120
6121 /* Load an address into a register.  */
6122
6123 static void
6124 load_address (int reg, expressionS *ep, int *used_at)
6125 {
6126   if (ep->X_op != O_constant
6127       && ep->X_op != O_symbol)
6128     {
6129       as_bad (_("expression too complex"));
6130       ep->X_op = O_constant;
6131     }
6132
6133   if (ep->X_op == O_constant)
6134     {
6135       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
6136       return;
6137     }
6138
6139   if (mips_pic == NO_PIC)
6140     {
6141       /* If this is a reference to a GP relative symbol, we want
6142            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
6143          Otherwise we want
6144            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
6145            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6146          If we have an addend, we always use the latter form.
6147
6148          With 64bit address space and a usable $at we want
6149            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6150            lui          $at,<sym>               (BFD_RELOC_HI16_S)
6151            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6152            daddiu       $at,<sym>               (BFD_RELOC_LO16)
6153            dsll32       $reg,0
6154            daddu        $reg,$reg,$at
6155
6156          If $at is already in use, we use a path which is suboptimal
6157          on superscalar processors.
6158            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6159            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6160            dsll         $reg,16
6161            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
6162            dsll         $reg,16
6163            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
6164
6165          For GP relative symbols in 64bit address space we can use
6166          the same sequence as in 32bit address space.  */
6167       if (HAVE_64BIT_SYMBOLS)
6168         {
6169           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6170               && !nopic_need_relax (ep->X_add_symbol, 1))
6171             {
6172               relax_start (ep->X_add_symbol);
6173               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6174                            mips_gp_register, BFD_RELOC_GPREL16);
6175               relax_switch ();
6176             }
6177
6178           if (*used_at == 0 && mips_opts.at)
6179             {
6180               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6181               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
6182               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6183                            BFD_RELOC_MIPS_HIGHER);
6184               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
6185               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
6186               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
6187               *used_at = 1;
6188             }
6189           else
6190             {
6191               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6192               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6193                            BFD_RELOC_MIPS_HIGHER);
6194               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6195               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
6196               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6197               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
6198             }
6199
6200           if (mips_relax.sequence)
6201             relax_end ();
6202         }
6203       else
6204         {
6205           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6206               && !nopic_need_relax (ep->X_add_symbol, 1))
6207             {
6208               relax_start (ep->X_add_symbol);
6209               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6210                            mips_gp_register, BFD_RELOC_GPREL16);
6211               relax_switch ();
6212             }
6213           macro_build_lui (ep, reg);
6214           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
6215                        reg, reg, BFD_RELOC_LO16);
6216           if (mips_relax.sequence)
6217             relax_end ();
6218         }
6219     }
6220   else if (!mips_big_got)
6221     {
6222       expressionS ex;
6223
6224       /* If this is a reference to an external symbol, we want
6225            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6226          Otherwise we want
6227            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6228            nop
6229            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6230          If there is a constant, it must be added in after.
6231
6232          If we have NewABI, we want
6233            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
6234          unless we're referencing a global symbol with a non-zero
6235          offset, in which case cst must be added separately.  */
6236       if (HAVE_NEWABI)
6237         {
6238           if (ep->X_add_number)
6239             {
6240               ex.X_add_number = ep->X_add_number;
6241               ep->X_add_number = 0;
6242               relax_start (ep->X_add_symbol);
6243               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6244                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6245               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6246                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6247               ex.X_op = O_constant;
6248               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6249                            reg, reg, BFD_RELOC_LO16);
6250               ep->X_add_number = ex.X_add_number;
6251               relax_switch ();
6252             }
6253           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6254                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6255           if (mips_relax.sequence)
6256             relax_end ();
6257         }
6258       else
6259         {
6260           ex.X_add_number = ep->X_add_number;
6261           ep->X_add_number = 0;
6262           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6263                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6264           load_delay_nop ();
6265           relax_start (ep->X_add_symbol);
6266           relax_switch ();
6267           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6268                        BFD_RELOC_LO16);
6269           relax_end ();
6270
6271           if (ex.X_add_number != 0)
6272             {
6273               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6274                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6275               ex.X_op = O_constant;
6276               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6277                            reg, reg, BFD_RELOC_LO16);
6278             }
6279         }
6280     }
6281   else if (mips_big_got)
6282     {
6283       expressionS ex;
6284
6285       /* This is the large GOT case.  If this is a reference to an
6286          external symbol, we want
6287            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
6288            addu         $reg,$reg,$gp
6289            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
6290
6291          Otherwise, for a reference to a local symbol in old ABI, we want
6292            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6293            nop
6294            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6295          If there is a constant, it must be added in after.
6296
6297          In the NewABI, for local symbols, with or without offsets, we want:
6298            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
6299            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
6300       */
6301       if (HAVE_NEWABI)
6302         {
6303           ex.X_add_number = ep->X_add_number;
6304           ep->X_add_number = 0;
6305           relax_start (ep->X_add_symbol);
6306           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6307           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6308                        reg, reg, mips_gp_register);
6309           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6310                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6311           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6312             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6313           else if (ex.X_add_number)
6314             {
6315               ex.X_op = O_constant;
6316               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6317                            BFD_RELOC_LO16);
6318             }
6319
6320           ep->X_add_number = ex.X_add_number;
6321           relax_switch ();
6322           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6323                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6324           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6325                        BFD_RELOC_MIPS_GOT_OFST);
6326           relax_end ();
6327         }
6328       else
6329         {
6330           ex.X_add_number = ep->X_add_number;
6331           ep->X_add_number = 0;
6332           relax_start (ep->X_add_symbol);
6333           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6334           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6335                        reg, reg, mips_gp_register);
6336           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6337                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6338           relax_switch ();
6339           if (reg_needs_delay (mips_gp_register))
6340             {
6341               /* We need a nop before loading from $gp.  This special
6342                  check is required because the lui which starts the main
6343                  instruction stream does not refer to $gp, and so will not
6344                  insert the nop which may be required.  */
6345               macro_build (NULL, "nop", "");
6346             }
6347           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6348                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6349           load_delay_nop ();
6350           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6351                        BFD_RELOC_LO16);
6352           relax_end ();
6353
6354           if (ex.X_add_number != 0)
6355             {
6356               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6357                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6358               ex.X_op = O_constant;
6359               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6360                            BFD_RELOC_LO16);
6361             }
6362         }
6363     }
6364   else
6365     abort ();
6366
6367   if (!mips_opts.at && *used_at == 1)
6368     as_bad (_("Macro used $at after \".set noat\""));
6369 }
6370
6371 /* Move the contents of register SOURCE into register DEST.  */
6372
6373 static void
6374 move_register (int dest, int source)
6375 {
6376   /* Prefer to use a 16-bit microMIPS instruction unless the previous
6377      instruction specifically requires a 32-bit one.  */
6378   if (mips_opts.micromips
6379       && !mips_opts.insn32
6380       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6381     macro_build (NULL, "move", "mp,mj", dest, source);
6382   else
6383     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
6384                  dest, source, 0);
6385 }
6386
6387 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
6388    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
6389    The two alternatives are:
6390
6391    Global symbol                Local sybmol
6392    -------------                ------------
6393    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
6394    ...                          ...
6395    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
6396
6397    load_got_offset emits the first instruction and add_got_offset
6398    emits the second for a 16-bit offset or add_got_offset_hilo emits
6399    a sequence to add a 32-bit offset using a scratch register.  */
6400
6401 static void
6402 load_got_offset (int dest, expressionS *local)
6403 {
6404   expressionS global;
6405
6406   global = *local;
6407   global.X_add_number = 0;
6408
6409   relax_start (local->X_add_symbol);
6410   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6411                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6412   relax_switch ();
6413   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6414                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6415   relax_end ();
6416 }
6417
6418 static void
6419 add_got_offset (int dest, expressionS *local)
6420 {
6421   expressionS global;
6422
6423   global.X_op = O_constant;
6424   global.X_op_symbol = NULL;
6425   global.X_add_symbol = NULL;
6426   global.X_add_number = local->X_add_number;
6427
6428   relax_start (local->X_add_symbol);
6429   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
6430                dest, dest, BFD_RELOC_LO16);
6431   relax_switch ();
6432   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
6433   relax_end ();
6434 }
6435
6436 static void
6437 add_got_offset_hilo (int dest, expressionS *local, int tmp)
6438 {
6439   expressionS global;
6440   int hold_mips_optimize;
6441
6442   global.X_op = O_constant;
6443   global.X_op_symbol = NULL;
6444   global.X_add_symbol = NULL;
6445   global.X_add_number = local->X_add_number;
6446
6447   relax_start (local->X_add_symbol);
6448   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6449   relax_switch ();
6450   /* Set mips_optimize around the lui instruction to avoid
6451      inserting an unnecessary nop after the lw.  */
6452   hold_mips_optimize = mips_optimize;
6453   mips_optimize = 2;
6454   macro_build_lui (&global, tmp);
6455   mips_optimize = hold_mips_optimize;
6456   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6457   relax_end ();
6458
6459   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6460 }
6461
6462 /* Emit a sequence of instructions to emulate a branch likely operation.
6463    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6464    is its complementing branch with the original condition negated.
6465    CALL is set if the original branch specified the link operation.
6466    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6467
6468    Code like this is produced in the noreorder mode:
6469
6470         BRNEG   <args>, 1f
6471          nop
6472         b       <sym>
6473          delay slot (executed only if branch taken)
6474     1:
6475
6476    or, if CALL is set:
6477
6478         BRNEG   <args>, 1f
6479          nop
6480         bal     <sym>
6481          delay slot (executed only if branch taken)
6482     1:
6483
6484    In the reorder mode the delay slot would be filled with a nop anyway,
6485    so code produced is simply:
6486
6487         BR      <args>, <sym>
6488          nop
6489
6490    This function is used when producing code for the microMIPS ASE that
6491    does not implement branch likely instructions in hardware.  */
6492
6493 static void
6494 macro_build_branch_likely (const char *br, const char *brneg,
6495                            int call, expressionS *ep, const char *fmt,
6496                            unsigned int sreg, unsigned int treg)
6497 {
6498   int noreorder = mips_opts.noreorder;
6499   expressionS expr1;
6500
6501   gas_assert (mips_opts.micromips);
6502   start_noreorder ();
6503   if (noreorder)
6504     {
6505       micromips_label_expr (&expr1);
6506       macro_build (&expr1, brneg, fmt, sreg, treg);
6507       macro_build (NULL, "nop", "");
6508       macro_build (ep, call ? "bal" : "b", "p");
6509
6510       /* Set to true so that append_insn adds a label.  */
6511       emit_branch_likely_macro = TRUE;
6512     }
6513   else
6514     {
6515       macro_build (ep, br, fmt, sreg, treg);
6516       macro_build (NULL, "nop", "");
6517     }
6518   end_noreorder ();
6519 }
6520
6521 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6522    the condition code tested.  EP specifies the branch target.  */
6523
6524 static void
6525 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6526 {
6527   const int call = 0;
6528   const char *brneg;
6529   const char *br;
6530
6531   switch (type)
6532     {
6533     case M_BC1FL:
6534       br = "bc1f";
6535       brneg = "bc1t";
6536       break;
6537     case M_BC1TL:
6538       br = "bc1t";
6539       brneg = "bc1f";
6540       break;
6541     case M_BC2FL:
6542       br = "bc2f";
6543       brneg = "bc2t";
6544       break;
6545     case M_BC2TL:
6546       br = "bc2t";
6547       brneg = "bc2f";
6548       break;
6549     default:
6550       abort ();
6551     }
6552   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6553 }
6554
6555 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6556    the register tested.  EP specifies the branch target.  */
6557
6558 static void
6559 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6560 {
6561   const char *brneg = NULL;
6562   const char *br;
6563   int call = 0;
6564
6565   switch (type)
6566     {
6567     case M_BGEZ:
6568       br = "bgez";
6569       break;
6570     case M_BGEZL:
6571       br = mips_opts.micromips ? "bgez" : "bgezl";
6572       brneg = "bltz";
6573       break;
6574     case M_BGEZALL:
6575       gas_assert (mips_opts.micromips);
6576       br = mips_opts.insn32 ? "bgezal" : "bgezals";
6577       brneg = "bltz";
6578       call = 1;
6579       break;
6580     case M_BGTZ:
6581       br = "bgtz";
6582       break;
6583     case M_BGTZL:
6584       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6585       brneg = "blez";
6586       break;
6587     case M_BLEZ:
6588       br = "blez";
6589       break;
6590     case M_BLEZL:
6591       br = mips_opts.micromips ? "blez" : "blezl";
6592       brneg = "bgtz";
6593       break;
6594     case M_BLTZ:
6595       br = "bltz";
6596       break;
6597     case M_BLTZL:
6598       br = mips_opts.micromips ? "bltz" : "bltzl";
6599       brneg = "bgez";
6600       break;
6601     case M_BLTZALL:
6602       gas_assert (mips_opts.micromips);
6603       br = mips_opts.insn32 ? "bltzal" : "bltzals";
6604       brneg = "bgez";
6605       call = 1;
6606       break;
6607     default:
6608       abort ();
6609     }
6610   if (mips_opts.micromips && brneg)
6611     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6612   else
6613     macro_build (ep, br, "s,p", sreg);
6614 }
6615
6616 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6617    TREG as the registers tested.  EP specifies the branch target.  */
6618
6619 static void
6620 macro_build_branch_rsrt (int type, expressionS *ep,
6621                          unsigned int sreg, unsigned int treg)
6622 {
6623   const char *brneg = NULL;
6624   const int call = 0;
6625   const char *br;
6626
6627   switch (type)
6628     {
6629     case M_BEQ:
6630     case M_BEQ_I:
6631       br = "beq";
6632       break;
6633     case M_BEQL:
6634     case M_BEQL_I:
6635       br = mips_opts.micromips ? "beq" : "beql";
6636       brneg = "bne";
6637       break;
6638     case M_BNE:
6639     case M_BNE_I:
6640       br = "bne";
6641       break;
6642     case M_BNEL:
6643     case M_BNEL_I:
6644       br = mips_opts.micromips ? "bne" : "bnel";
6645       brneg = "beq";
6646       break;
6647     default:
6648       abort ();
6649     }
6650   if (mips_opts.micromips && brneg)
6651     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6652   else
6653     macro_build (ep, br, "s,t,p", sreg, treg);
6654 }
6655
6656 /* Return the high part that should be loaded in order to make the low
6657    part of VALUE accessible using an offset of OFFBITS bits.  */
6658
6659 static offsetT
6660 offset_high_part (offsetT value, unsigned int offbits)
6661 {
6662   offsetT bias;
6663   addressT low_mask;
6664
6665   if (offbits == 0)
6666     return value;
6667   bias = 1 << (offbits - 1);
6668   low_mask = bias * 2 - 1;
6669   return (value + bias) & ~low_mask;
6670 }
6671
6672 /* Return true if the value stored in offset_expr and offset_reloc
6673    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
6674    amount that the caller wants to add without inducing overflow
6675    and ALIGN is the known alignment of the value in bytes.  */
6676
6677 static bfd_boolean
6678 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
6679 {
6680   if (offbits == 16)
6681     {
6682       /* Accept any relocation operator if overflow isn't a concern.  */
6683       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
6684         return TRUE;
6685
6686       /* These relocations are guaranteed not to overflow in correct links.  */
6687       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
6688           || gprel16_reloc_p (*offset_reloc))
6689         return TRUE;
6690     }
6691   if (offset_expr.X_op == O_constant
6692       && offset_high_part (offset_expr.X_add_number, offbits) == 0
6693       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
6694     return TRUE;
6695   return FALSE;
6696 }
6697
6698 /*
6699  *                      Build macros
6700  *   This routine implements the seemingly endless macro or synthesized
6701  * instructions and addressing modes in the mips assembly language. Many
6702  * of these macros are simple and are similar to each other. These could
6703  * probably be handled by some kind of table or grammar approach instead of
6704  * this verbose method. Others are not simple macros but are more like
6705  * optimizing code generation.
6706  *   One interesting optimization is when several store macros appear
6707  * consecutively that would load AT with the upper half of the same address.
6708  * The ensuing load upper instructions are ommited. This implies some kind
6709  * of global optimization. We currently only optimize within a single macro.
6710  *   For many of the load and store macros if the address is specified as a
6711  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6712  * first load register 'at' with zero and use it as the base register. The
6713  * mips assembler simply uses register $zero. Just one tiny optimization
6714  * we're missing.
6715  */
6716 static void
6717 macro (struct mips_cl_insn *ip, char *str)
6718 {
6719   unsigned int treg, sreg, dreg, breg;
6720   unsigned int tempreg;
6721   int mask;
6722   int used_at = 0;
6723   expressionS label_expr;
6724   expressionS expr1;
6725   expressionS *ep;
6726   const char *s;
6727   const char *s2;
6728   const char *fmt;
6729   int likely = 0;
6730   int coproc = 0;
6731   int offbits = 16;
6732   int call = 0;
6733   int jals = 0;
6734   int dbl = 0;
6735   int imm = 0;
6736   int ust = 0;
6737   int lp = 0;
6738   bfd_boolean large_offset;
6739   int off;
6740   int hold_mips_optimize;
6741   unsigned int align;
6742
6743   gas_assert (! mips_opts.mips16);
6744
6745   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6746   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6747   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6748   mask = ip->insn_mo->mask;
6749
6750   label_expr.X_op = O_constant;
6751   label_expr.X_op_symbol = NULL;
6752   label_expr.X_add_symbol = NULL;
6753   label_expr.X_add_number = 0;
6754
6755   expr1.X_op = O_constant;
6756   expr1.X_op_symbol = NULL;
6757   expr1.X_add_symbol = NULL;
6758   expr1.X_add_number = 1;
6759   align = 1;
6760
6761   switch (mask)
6762     {
6763     case M_DABS:
6764       dbl = 1;
6765     case M_ABS:
6766       /*    bgez    $a0,1f
6767             move    v0,$a0
6768             sub     v0,$zero,$a0
6769          1:
6770        */
6771
6772       start_noreorder ();
6773
6774       if (mips_opts.micromips)
6775         micromips_label_expr (&label_expr);
6776       else
6777         label_expr.X_add_number = 8;
6778       macro_build (&label_expr, "bgez", "s,p", sreg);
6779       if (dreg == sreg)
6780         macro_build (NULL, "nop", "");
6781       else
6782         move_register (dreg, sreg);
6783       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6784       if (mips_opts.micromips)
6785         micromips_add_label ();
6786
6787       end_noreorder ();
6788       break;
6789
6790     case M_ADD_I:
6791       s = "addi";
6792       s2 = "add";
6793       goto do_addi;
6794     case M_ADDU_I:
6795       s = "addiu";
6796       s2 = "addu";
6797       goto do_addi;
6798     case M_DADD_I:
6799       dbl = 1;
6800       s = "daddi";
6801       s2 = "dadd";
6802       if (!mips_opts.micromips)
6803         goto do_addi;
6804       if (imm_expr.X_op == O_constant
6805           && imm_expr.X_add_number >= -0x200
6806           && imm_expr.X_add_number < 0x200)
6807         {
6808           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
6809           break;
6810         }
6811       goto do_addi_i;
6812     case M_DADDU_I:
6813       dbl = 1;
6814       s = "daddiu";
6815       s2 = "daddu";
6816     do_addi:
6817       if (imm_expr.X_op == O_constant
6818           && imm_expr.X_add_number >= -0x8000
6819           && imm_expr.X_add_number < 0x8000)
6820         {
6821           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
6822           break;
6823         }
6824     do_addi_i:
6825       used_at = 1;
6826       load_register (AT, &imm_expr, dbl);
6827       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6828       break;
6829
6830     case M_AND_I:
6831       s = "andi";
6832       s2 = "and";
6833       goto do_bit;
6834     case M_OR_I:
6835       s = "ori";
6836       s2 = "or";
6837       goto do_bit;
6838     case M_NOR_I:
6839       s = "";
6840       s2 = "nor";
6841       goto do_bit;
6842     case M_XOR_I:
6843       s = "xori";
6844       s2 = "xor";
6845     do_bit:
6846       if (imm_expr.X_op == O_constant
6847           && imm_expr.X_add_number >= 0
6848           && imm_expr.X_add_number < 0x10000)
6849         {
6850           if (mask != M_NOR_I)
6851             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
6852           else
6853             {
6854               macro_build (&imm_expr, "ori", "t,r,i",
6855                            treg, sreg, BFD_RELOC_LO16);
6856               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
6857             }
6858           break;
6859         }
6860
6861       used_at = 1;
6862       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6863       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6864       break;
6865
6866     case M_BALIGN:
6867       switch (imm_expr.X_add_number)
6868         {
6869         case 0:
6870           macro_build (NULL, "nop", "");
6871           break;
6872         case 2:
6873           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
6874           break;
6875         case 1:
6876         case 3:
6877           macro_build (NULL, "balign", "t,s,2", treg, sreg,
6878                        (int) imm_expr.X_add_number);
6879           break;
6880         default:
6881           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
6882                   (unsigned long) imm_expr.X_add_number);
6883           break;
6884         }
6885       break;
6886
6887     case M_BC1FL:
6888     case M_BC1TL:
6889     case M_BC2FL:
6890     case M_BC2TL:
6891       gas_assert (mips_opts.micromips);
6892       macro_build_branch_ccl (mask, &offset_expr,
6893                               EXTRACT_OPERAND (1, BCC, *ip));
6894       break;
6895
6896     case M_BEQ_I:
6897     case M_BEQL_I:
6898     case M_BNE_I:
6899     case M_BNEL_I:
6900       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6901         treg = 0;
6902       else
6903         {
6904           treg = AT;
6905           used_at = 1;
6906           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
6907         }
6908       /* Fall through.  */
6909     case M_BEQL:
6910     case M_BNEL:
6911       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
6912       break;
6913
6914     case M_BGEL:
6915       likely = 1;
6916     case M_BGE:
6917       if (treg == 0)
6918         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
6919       else if (sreg == 0)
6920         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
6921       else
6922         {
6923           used_at = 1;
6924           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6925           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6926                                    &offset_expr, AT, ZERO);
6927         }
6928       break;
6929
6930     case M_BGEZL:
6931     case M_BGEZALL:
6932     case M_BGTZL:
6933     case M_BLEZL:
6934     case M_BLTZL:
6935     case M_BLTZALL:
6936       macro_build_branch_rs (mask, &offset_expr, sreg);
6937       break;
6938
6939     case M_BGTL_I:
6940       likely = 1;
6941     case M_BGT_I:
6942       /* Check for > max integer.  */
6943       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
6944         {
6945         do_false:
6946           /* Result is always false.  */
6947           if (! likely)
6948             macro_build (NULL, "nop", "");
6949           else
6950             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
6951           break;
6952         }
6953       if (imm_expr.X_op != O_constant)
6954         as_bad (_("Unsupported large constant"));
6955       ++imm_expr.X_add_number;
6956       /* FALLTHROUGH */
6957     case M_BGE_I:
6958     case M_BGEL_I:
6959       if (mask == M_BGEL_I)
6960         likely = 1;
6961       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6962         {
6963           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
6964                                  &offset_expr, sreg);
6965           break;
6966         }
6967       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6968         {
6969           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
6970                                  &offset_expr, sreg);
6971           break;
6972         }
6973       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
6974         {
6975         do_true:
6976           /* result is always true */
6977           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
6978           macro_build (&offset_expr, "b", "p");
6979           break;
6980         }
6981       used_at = 1;
6982       set_at (sreg, 0);
6983       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6984                                &offset_expr, AT, ZERO);
6985       break;
6986
6987     case M_BGEUL:
6988       likely = 1;
6989     case M_BGEU:
6990       if (treg == 0)
6991         goto do_true;
6992       else if (sreg == 0)
6993         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6994                                  &offset_expr, ZERO, treg);
6995       else
6996         {
6997           used_at = 1;
6998           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6999           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7000                                    &offset_expr, AT, ZERO);
7001         }
7002       break;
7003
7004     case M_BGTUL_I:
7005       likely = 1;
7006     case M_BGTU_I:
7007       if (sreg == 0
7008           || (HAVE_32BIT_GPRS
7009               && imm_expr.X_op == O_constant
7010               && imm_expr.X_add_number == -1))
7011         goto do_false;
7012       if (imm_expr.X_op != O_constant)
7013         as_bad (_("Unsupported large constant"));
7014       ++imm_expr.X_add_number;
7015       /* FALLTHROUGH */
7016     case M_BGEU_I:
7017     case M_BGEUL_I:
7018       if (mask == M_BGEUL_I)
7019         likely = 1;
7020       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7021         goto do_true;
7022       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7023         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7024                                  &offset_expr, sreg, ZERO);
7025       else
7026         {
7027           used_at = 1;
7028           set_at (sreg, 1);
7029           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7030                                    &offset_expr, AT, ZERO);
7031         }
7032       break;
7033
7034     case M_BGTL:
7035       likely = 1;
7036     case M_BGT:
7037       if (treg == 0)
7038         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
7039       else if (sreg == 0)
7040         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
7041       else
7042         {
7043           used_at = 1;
7044           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7045           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7046                                    &offset_expr, AT, ZERO);
7047         }
7048       break;
7049
7050     case M_BGTUL:
7051       likely = 1;
7052     case M_BGTU:
7053       if (treg == 0)
7054         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7055                                  &offset_expr, sreg, ZERO);
7056       else if (sreg == 0)
7057         goto do_false;
7058       else
7059         {
7060           used_at = 1;
7061           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7062           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7063                                    &offset_expr, AT, ZERO);
7064         }
7065       break;
7066
7067     case M_BLEL:
7068       likely = 1;
7069     case M_BLE:
7070       if (treg == 0)
7071         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7072       else if (sreg == 0)
7073         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
7074       else
7075         {
7076           used_at = 1;
7077           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7078           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7079                                    &offset_expr, AT, ZERO);
7080         }
7081       break;
7082
7083     case M_BLEL_I:
7084       likely = 1;
7085     case M_BLE_I:
7086       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7087         goto do_true;
7088       if (imm_expr.X_op != O_constant)
7089         as_bad (_("Unsupported large constant"));
7090       ++imm_expr.X_add_number;
7091       /* FALLTHROUGH */
7092     case M_BLT_I:
7093     case M_BLTL_I:
7094       if (mask == M_BLTL_I)
7095         likely = 1;
7096       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7097         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7098       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7099         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7100       else
7101         {
7102           used_at = 1;
7103           set_at (sreg, 0);
7104           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7105                                    &offset_expr, AT, ZERO);
7106         }
7107       break;
7108
7109     case M_BLEUL:
7110       likely = 1;
7111     case M_BLEU:
7112       if (treg == 0)
7113         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7114                                  &offset_expr, sreg, ZERO);
7115       else if (sreg == 0)
7116         goto do_true;
7117       else
7118         {
7119           used_at = 1;
7120           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7121           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7122                                    &offset_expr, AT, ZERO);
7123         }
7124       break;
7125
7126     case M_BLEUL_I:
7127       likely = 1;
7128     case M_BLEU_I:
7129       if (sreg == 0
7130           || (HAVE_32BIT_GPRS
7131               && imm_expr.X_op == O_constant
7132               && imm_expr.X_add_number == -1))
7133         goto do_true;
7134       if (imm_expr.X_op != O_constant)
7135         as_bad (_("Unsupported large constant"));
7136       ++imm_expr.X_add_number;
7137       /* FALLTHROUGH */
7138     case M_BLTU_I:
7139     case M_BLTUL_I:
7140       if (mask == M_BLTUL_I)
7141         likely = 1;
7142       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7143         goto do_false;
7144       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7145         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7146                                  &offset_expr, sreg, ZERO);
7147       else
7148         {
7149           used_at = 1;
7150           set_at (sreg, 1);
7151           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7152                                    &offset_expr, AT, ZERO);
7153         }
7154       break;
7155
7156     case M_BLTL:
7157       likely = 1;
7158     case M_BLT:
7159       if (treg == 0)
7160         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7161       else if (sreg == 0)
7162         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
7163       else
7164         {
7165           used_at = 1;
7166           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7167           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7168                                    &offset_expr, AT, ZERO);
7169         }
7170       break;
7171
7172     case M_BLTUL:
7173       likely = 1;
7174     case M_BLTU:
7175       if (treg == 0)
7176         goto do_false;
7177       else if (sreg == 0)
7178         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7179                                  &offset_expr, ZERO, treg);
7180       else
7181         {
7182           used_at = 1;
7183           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7184           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7185                                    &offset_expr, AT, ZERO);
7186         }
7187       break;
7188
7189     case M_DEXT:
7190       {
7191         /* Use unsigned arithmetic.  */
7192         addressT pos;
7193         addressT size;
7194
7195         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7196           {
7197             as_bad (_("Unsupported large constant"));
7198             pos = size = 1;
7199           }
7200         else
7201           {
7202             pos = imm_expr.X_add_number;
7203             size = imm2_expr.X_add_number;
7204           }
7205
7206         if (pos > 63)
7207           {
7208             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7209             pos = 1;
7210           }
7211         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7212           {
7213             as_bad (_("Improper extract size (%lu, position %lu)"),
7214                     (unsigned long) size, (unsigned long) pos);
7215             size = 1;
7216           }
7217
7218         if (size <= 32 && pos < 32)
7219           {
7220             s = "dext";
7221             fmt = "t,r,+A,+C";
7222           }
7223         else if (size <= 32)
7224           {
7225             s = "dextu";
7226             fmt = "t,r,+E,+H";
7227           }
7228         else
7229           {
7230             s = "dextm";
7231             fmt = "t,r,+A,+G";
7232           }
7233         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7234                      (int) (size - 1));
7235       }
7236       break;
7237
7238     case M_DINS:
7239       {
7240         /* Use unsigned arithmetic.  */
7241         addressT pos;
7242         addressT size;
7243
7244         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7245           {
7246             as_bad (_("Unsupported large constant"));
7247             pos = size = 1;
7248           }
7249         else
7250           {
7251             pos = imm_expr.X_add_number;
7252             size = imm2_expr.X_add_number;
7253           }
7254
7255         if (pos > 63)
7256           {
7257             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7258             pos = 1;
7259           }
7260         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7261           {
7262             as_bad (_("Improper insert size (%lu, position %lu)"),
7263                     (unsigned long) size, (unsigned long) pos);
7264             size = 1;
7265           }
7266
7267         if (pos < 32 && (pos + size - 1) < 32)
7268           {
7269             s = "dins";
7270             fmt = "t,r,+A,+B";
7271           }
7272         else if (pos >= 32)
7273           {
7274             s = "dinsu";
7275             fmt = "t,r,+E,+F";
7276           }
7277         else
7278           {
7279             s = "dinsm";
7280             fmt = "t,r,+A,+F";
7281           }
7282         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7283                      (int) (pos + size - 1));
7284       }
7285       break;
7286
7287     case M_DDIV_3:
7288       dbl = 1;
7289     case M_DIV_3:
7290       s = "mflo";
7291       goto do_div3;
7292     case M_DREM_3:
7293       dbl = 1;
7294     case M_REM_3:
7295       s = "mfhi";
7296     do_div3:
7297       if (treg == 0)
7298         {
7299           as_warn (_("Divide by zero."));
7300           if (mips_trap)
7301             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7302           else
7303             macro_build (NULL, "break", BRK_FMT, 7);
7304           break;
7305         }
7306
7307       start_noreorder ();
7308       if (mips_trap)
7309         {
7310           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7311           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7312         }
7313       else
7314         {
7315           if (mips_opts.micromips)
7316             micromips_label_expr (&label_expr);
7317           else
7318             label_expr.X_add_number = 8;
7319           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7320           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7321           macro_build (NULL, "break", BRK_FMT, 7);
7322           if (mips_opts.micromips)
7323             micromips_add_label ();
7324         }
7325       expr1.X_add_number = -1;
7326       used_at = 1;
7327       load_register (AT, &expr1, dbl);
7328       if (mips_opts.micromips)
7329         micromips_label_expr (&label_expr);
7330       else
7331         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
7332       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
7333       if (dbl)
7334         {
7335           expr1.X_add_number = 1;
7336           load_register (AT, &expr1, dbl);
7337           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
7338         }
7339       else
7340         {
7341           expr1.X_add_number = 0x80000000;
7342           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
7343         }
7344       if (mips_trap)
7345         {
7346           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
7347           /* We want to close the noreorder block as soon as possible, so
7348              that later insns are available for delay slot filling.  */
7349           end_noreorder ();
7350         }
7351       else
7352         {
7353           if (mips_opts.micromips)
7354             micromips_label_expr (&label_expr);
7355           else
7356             label_expr.X_add_number = 8;
7357           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
7358           macro_build (NULL, "nop", "");
7359
7360           /* We want to close the noreorder block as soon as possible, so
7361              that later insns are available for delay slot filling.  */
7362           end_noreorder ();
7363
7364           macro_build (NULL, "break", BRK_FMT, 6);
7365         }
7366       if (mips_opts.micromips)
7367         micromips_add_label ();
7368       macro_build (NULL, s, MFHL_FMT, dreg);
7369       break;
7370
7371     case M_DIV_3I:
7372       s = "div";
7373       s2 = "mflo";
7374       goto do_divi;
7375     case M_DIVU_3I:
7376       s = "divu";
7377       s2 = "mflo";
7378       goto do_divi;
7379     case M_REM_3I:
7380       s = "div";
7381       s2 = "mfhi";
7382       goto do_divi;
7383     case M_REMU_3I:
7384       s = "divu";
7385       s2 = "mfhi";
7386       goto do_divi;
7387     case M_DDIV_3I:
7388       dbl = 1;
7389       s = "ddiv";
7390       s2 = "mflo";
7391       goto do_divi;
7392     case M_DDIVU_3I:
7393       dbl = 1;
7394       s = "ddivu";
7395       s2 = "mflo";
7396       goto do_divi;
7397     case M_DREM_3I:
7398       dbl = 1;
7399       s = "ddiv";
7400       s2 = "mfhi";
7401       goto do_divi;
7402     case M_DREMU_3I:
7403       dbl = 1;
7404       s = "ddivu";
7405       s2 = "mfhi";
7406     do_divi:
7407       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7408         {
7409           as_warn (_("Divide by zero."));
7410           if (mips_trap)
7411             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7412           else
7413             macro_build (NULL, "break", BRK_FMT, 7);
7414           break;
7415         }
7416       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7417         {
7418           if (strcmp (s2, "mflo") == 0)
7419             move_register (dreg, sreg);
7420           else
7421             move_register (dreg, ZERO);
7422           break;
7423         }
7424       if (imm_expr.X_op == O_constant
7425           && imm_expr.X_add_number == -1
7426           && s[strlen (s) - 1] != 'u')
7427         {
7428           if (strcmp (s2, "mflo") == 0)
7429             {
7430               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
7431             }
7432           else
7433             move_register (dreg, ZERO);
7434           break;
7435         }
7436
7437       used_at = 1;
7438       load_register (AT, &imm_expr, dbl);
7439       macro_build (NULL, s, "z,s,t", sreg, AT);
7440       macro_build (NULL, s2, MFHL_FMT, dreg);
7441       break;
7442
7443     case M_DIVU_3:
7444       s = "divu";
7445       s2 = "mflo";
7446       goto do_divu3;
7447     case M_REMU_3:
7448       s = "divu";
7449       s2 = "mfhi";
7450       goto do_divu3;
7451     case M_DDIVU_3:
7452       s = "ddivu";
7453       s2 = "mflo";
7454       goto do_divu3;
7455     case M_DREMU_3:
7456       s = "ddivu";
7457       s2 = "mfhi";
7458     do_divu3:
7459       start_noreorder ();
7460       if (mips_trap)
7461         {
7462           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7463           macro_build (NULL, s, "z,s,t", sreg, treg);
7464           /* We want to close the noreorder block as soon as possible, so
7465              that later insns are available for delay slot filling.  */
7466           end_noreorder ();
7467         }
7468       else
7469         {
7470           if (mips_opts.micromips)
7471             micromips_label_expr (&label_expr);
7472           else
7473             label_expr.X_add_number = 8;
7474           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7475           macro_build (NULL, s, "z,s,t", sreg, treg);
7476
7477           /* We want to close the noreorder block as soon as possible, so
7478              that later insns are available for delay slot filling.  */
7479           end_noreorder ();
7480           macro_build (NULL, "break", BRK_FMT, 7);
7481           if (mips_opts.micromips)
7482             micromips_add_label ();
7483         }
7484       macro_build (NULL, s2, MFHL_FMT, dreg);
7485       break;
7486
7487     case M_DLCA_AB:
7488       dbl = 1;
7489     case M_LCA_AB:
7490       call = 1;
7491       goto do_la;
7492     case M_DLA_AB:
7493       dbl = 1;
7494     case M_LA_AB:
7495     do_la:
7496       /* Load the address of a symbol into a register.  If breg is not
7497          zero, we then add a base register to it.  */
7498
7499       if (dbl && HAVE_32BIT_GPRS)
7500         as_warn (_("dla used to load 32-bit register"));
7501
7502       if (!dbl && HAVE_64BIT_OBJECTS)
7503         as_warn (_("la used to load 64-bit address"));
7504
7505       if (small_offset_p (0, align, 16))
7506         {
7507           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
7508                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
7509           break;
7510         }
7511
7512       if (mips_opts.at && (treg == breg))
7513         {
7514           tempreg = AT;
7515           used_at = 1;
7516         }
7517       else
7518         {
7519           tempreg = treg;
7520         }
7521
7522       if (offset_expr.X_op != O_symbol
7523           && offset_expr.X_op != O_constant)
7524         {
7525           as_bad (_("Expression too complex"));
7526           offset_expr.X_op = O_constant;
7527         }
7528
7529       if (offset_expr.X_op == O_constant)
7530         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7531       else if (mips_pic == NO_PIC)
7532         {
7533           /* If this is a reference to a GP relative symbol, we want
7534                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7535              Otherwise we want
7536                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7537                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7538              If we have a constant, we need two instructions anyhow,
7539              so we may as well always use the latter form.
7540
7541              With 64bit address space and a usable $at we want
7542                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7543                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7544                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7545                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7546                dsll32   $tempreg,0
7547                daddu    $tempreg,$tempreg,$at
7548
7549              If $at is already in use, we use a path which is suboptimal
7550              on superscalar processors.
7551                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7552                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7553                dsll     $tempreg,16
7554                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7555                dsll     $tempreg,16
7556                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7557
7558              For GP relative symbols in 64bit address space we can use
7559              the same sequence as in 32bit address space.  */
7560           if (HAVE_64BIT_SYMBOLS)
7561             {
7562               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7563                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7564                 {
7565                   relax_start (offset_expr.X_add_symbol);
7566                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7567                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7568                   relax_switch ();
7569                 }
7570
7571               if (used_at == 0 && mips_opts.at)
7572                 {
7573                   macro_build (&offset_expr, "lui", LUI_FMT,
7574                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7575                   macro_build (&offset_expr, "lui", LUI_FMT,
7576                                AT, BFD_RELOC_HI16_S);
7577                   macro_build (&offset_expr, "daddiu", "t,r,j",
7578                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7579                   macro_build (&offset_expr, "daddiu", "t,r,j",
7580                                AT, AT, BFD_RELOC_LO16);
7581                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7582                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7583                   used_at = 1;
7584                 }
7585               else
7586                 {
7587                   macro_build (&offset_expr, "lui", LUI_FMT,
7588                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7589                   macro_build (&offset_expr, "daddiu", "t,r,j",
7590                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7591                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7592                   macro_build (&offset_expr, "daddiu", "t,r,j",
7593                                tempreg, tempreg, BFD_RELOC_HI16_S);
7594                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7595                   macro_build (&offset_expr, "daddiu", "t,r,j",
7596                                tempreg, tempreg, BFD_RELOC_LO16);
7597                 }
7598
7599               if (mips_relax.sequence)
7600                 relax_end ();
7601             }
7602           else
7603             {
7604               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7605                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7606                 {
7607                   relax_start (offset_expr.X_add_symbol);
7608                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7609                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7610                   relax_switch ();
7611                 }
7612               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7613                 as_bad (_("Offset too large"));
7614               macro_build_lui (&offset_expr, tempreg);
7615               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7616                            tempreg, tempreg, BFD_RELOC_LO16);
7617               if (mips_relax.sequence)
7618                 relax_end ();
7619             }
7620         }
7621       else if (!mips_big_got && !HAVE_NEWABI)
7622         {
7623           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7624
7625           /* If this is a reference to an external symbol, and there
7626              is no constant, we want
7627                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7628              or for lca or if tempreg is PIC_CALL_REG
7629                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7630              For a local symbol, we want
7631                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7632                nop
7633                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7634
7635              If we have a small constant, and this is a reference to
7636              an external symbol, we want
7637                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7638                nop
7639                addiu    $tempreg,$tempreg,<constant>
7640              For a local symbol, we want the same instruction
7641              sequence, but we output a BFD_RELOC_LO16 reloc on the
7642              addiu instruction.
7643
7644              If we have a large constant, and this is a reference to
7645              an external symbol, we want
7646                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7647                lui      $at,<hiconstant>
7648                addiu    $at,$at,<loconstant>
7649                addu     $tempreg,$tempreg,$at
7650              For a local symbol, we want the same instruction
7651              sequence, but we output a BFD_RELOC_LO16 reloc on the
7652              addiu instruction.
7653            */
7654
7655           if (offset_expr.X_add_number == 0)
7656             {
7657               if (mips_pic == SVR4_PIC
7658                   && breg == 0
7659                   && (call || tempreg == PIC_CALL_REG))
7660                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7661
7662               relax_start (offset_expr.X_add_symbol);
7663               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7664                            lw_reloc_type, mips_gp_register);
7665               if (breg != 0)
7666                 {
7667                   /* We're going to put in an addu instruction using
7668                      tempreg, so we may as well insert the nop right
7669                      now.  */
7670                   load_delay_nop ();
7671                 }
7672               relax_switch ();
7673               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7674                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7675               load_delay_nop ();
7676               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7677                            tempreg, tempreg, BFD_RELOC_LO16);
7678               relax_end ();
7679               /* FIXME: If breg == 0, and the next instruction uses
7680                  $tempreg, then if this variant case is used an extra
7681                  nop will be generated.  */
7682             }
7683           else if (offset_expr.X_add_number >= -0x8000
7684                    && offset_expr.X_add_number < 0x8000)
7685             {
7686               load_got_offset (tempreg, &offset_expr);
7687               load_delay_nop ();
7688               add_got_offset (tempreg, &offset_expr);
7689             }
7690           else
7691             {
7692               expr1.X_add_number = offset_expr.X_add_number;
7693               offset_expr.X_add_number =
7694                 SEXT_16BIT (offset_expr.X_add_number);
7695               load_got_offset (tempreg, &offset_expr);
7696               offset_expr.X_add_number = expr1.X_add_number;
7697               /* If we are going to add in a base register, and the
7698                  target register and the base register are the same,
7699                  then we are using AT as a temporary register.  Since
7700                  we want to load the constant into AT, we add our
7701                  current AT (from the global offset table) and the
7702                  register into the register now, and pretend we were
7703                  not using a base register.  */
7704               if (breg == treg)
7705                 {
7706                   load_delay_nop ();
7707                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7708                                treg, AT, breg);
7709                   breg = 0;
7710                   tempreg = treg;
7711                 }
7712               add_got_offset_hilo (tempreg, &offset_expr, AT);
7713               used_at = 1;
7714             }
7715         }
7716       else if (!mips_big_got && HAVE_NEWABI)
7717         {
7718           int add_breg_early = 0;
7719
7720           /* If this is a reference to an external, and there is no
7721              constant, or local symbol (*), with or without a
7722              constant, we want
7723                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7724              or for lca or if tempreg is PIC_CALL_REG
7725                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7726
7727              If we have a small constant, and this is a reference to
7728              an external symbol, we want
7729                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7730                addiu    $tempreg,$tempreg,<constant>
7731
7732              If we have a large constant, and this is a reference to
7733              an external symbol, we want
7734                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7735                lui      $at,<hiconstant>
7736                addiu    $at,$at,<loconstant>
7737                addu     $tempreg,$tempreg,$at
7738
7739              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7740              local symbols, even though it introduces an additional
7741              instruction.  */
7742
7743           if (offset_expr.X_add_number)
7744             {
7745               expr1.X_add_number = offset_expr.X_add_number;
7746               offset_expr.X_add_number = 0;
7747
7748               relax_start (offset_expr.X_add_symbol);
7749               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7750                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7751
7752               if (expr1.X_add_number >= -0x8000
7753                   && expr1.X_add_number < 0x8000)
7754                 {
7755                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7756                                tempreg, tempreg, BFD_RELOC_LO16);
7757                 }
7758               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7759                 {
7760                   /* If we are going to add in a base register, and the
7761                      target register and the base register are the same,
7762                      then we are using AT as a temporary register.  Since
7763                      we want to load the constant into AT, we add our
7764                      current AT (from the global offset table) and the
7765                      register into the register now, and pretend we were
7766                      not using a base register.  */
7767                   if (breg != treg)
7768                     dreg = tempreg;
7769                   else
7770                     {
7771                       gas_assert (tempreg == AT);
7772                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7773                                    treg, AT, breg);
7774                       dreg = treg;
7775                       add_breg_early = 1;
7776                     }
7777
7778                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7779                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7780                                dreg, dreg, AT);
7781
7782                   used_at = 1;
7783                 }
7784               else
7785                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7786
7787               relax_switch ();
7788               offset_expr.X_add_number = expr1.X_add_number;
7789
7790               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7791                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7792               if (add_breg_early)
7793                 {
7794                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7795                                treg, tempreg, breg);
7796                   breg = 0;
7797                   tempreg = treg;
7798                 }
7799               relax_end ();
7800             }
7801           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7802             {
7803               relax_start (offset_expr.X_add_symbol);
7804               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7805                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7806               relax_switch ();
7807               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7808                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7809               relax_end ();
7810             }
7811           else
7812             {
7813               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7814                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7815             }
7816         }
7817       else if (mips_big_got && !HAVE_NEWABI)
7818         {
7819           int gpdelay;
7820           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7821           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7822           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7823
7824           /* This is the large GOT case.  If this is a reference to an
7825              external symbol, and there is no constant, we want
7826                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7827                addu     $tempreg,$tempreg,$gp
7828                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7829              or for lca or if tempreg is PIC_CALL_REG
7830                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7831                addu     $tempreg,$tempreg,$gp
7832                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7833              For a local symbol, we want
7834                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7835                nop
7836                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7837
7838              If we have a small constant, and this is a reference to
7839              an external symbol, we want
7840                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7841                addu     $tempreg,$tempreg,$gp
7842                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7843                nop
7844                addiu    $tempreg,$tempreg,<constant>
7845              For a local symbol, we want
7846                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7847                nop
7848                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
7849
7850              If we have a large constant, and this is a reference to
7851              an external symbol, we want
7852                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7853                addu     $tempreg,$tempreg,$gp
7854                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7855                lui      $at,<hiconstant>
7856                addiu    $at,$at,<loconstant>
7857                addu     $tempreg,$tempreg,$at
7858              For a local symbol, we want
7859                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7860                lui      $at,<hiconstant>
7861                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
7862                addu     $tempreg,$tempreg,$at
7863           */
7864
7865           expr1.X_add_number = offset_expr.X_add_number;
7866           offset_expr.X_add_number = 0;
7867           relax_start (offset_expr.X_add_symbol);
7868           gpdelay = reg_needs_delay (mips_gp_register);
7869           if (expr1.X_add_number == 0 && breg == 0
7870               && (call || tempreg == PIC_CALL_REG))
7871             {
7872               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7873               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7874             }
7875           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7876           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7877                        tempreg, tempreg, mips_gp_register);
7878           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7879                        tempreg, lw_reloc_type, tempreg);
7880           if (expr1.X_add_number == 0)
7881             {
7882               if (breg != 0)
7883                 {
7884                   /* We're going to put in an addu instruction using
7885                      tempreg, so we may as well insert the nop right
7886                      now.  */
7887                   load_delay_nop ();
7888                 }
7889             }
7890           else if (expr1.X_add_number >= -0x8000
7891                    && expr1.X_add_number < 0x8000)
7892             {
7893               load_delay_nop ();
7894               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7895                            tempreg, tempreg, BFD_RELOC_LO16);
7896             }
7897           else
7898             {
7899               /* If we are going to add in a base register, and the
7900                  target register and the base register are the same,
7901                  then we are using AT as a temporary register.  Since
7902                  we want to load the constant into AT, we add our
7903                  current AT (from the global offset table) and the
7904                  register into the register now, and pretend we were
7905                  not using a base register.  */
7906               if (breg != treg)
7907                 dreg = tempreg;
7908               else
7909                 {
7910                   gas_assert (tempreg == AT);
7911                   load_delay_nop ();
7912                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7913                                treg, AT, breg);
7914                   dreg = treg;
7915                 }
7916
7917               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7918               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7919
7920               used_at = 1;
7921             }
7922           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
7923           relax_switch ();
7924
7925           if (gpdelay)
7926             {
7927               /* This is needed because this instruction uses $gp, but
7928                  the first instruction on the main stream does not.  */
7929               macro_build (NULL, "nop", "");
7930             }
7931
7932           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7933                        local_reloc_type, mips_gp_register);
7934           if (expr1.X_add_number >= -0x8000
7935               && expr1.X_add_number < 0x8000)
7936             {
7937               load_delay_nop ();
7938               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7939                            tempreg, tempreg, BFD_RELOC_LO16);
7940               /* FIXME: If add_number is 0, and there was no base
7941                  register, the external symbol case ended with a load,
7942                  so if the symbol turns out to not be external, and
7943                  the next instruction uses tempreg, an unnecessary nop
7944                  will be inserted.  */
7945             }
7946           else
7947             {
7948               if (breg == treg)
7949                 {
7950                   /* We must add in the base register now, as in the
7951                      external symbol case.  */
7952                   gas_assert (tempreg == AT);
7953                   load_delay_nop ();
7954                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7955                                treg, AT, breg);
7956                   tempreg = treg;
7957                   /* We set breg to 0 because we have arranged to add
7958                      it in in both cases.  */
7959                   breg = 0;
7960                 }
7961
7962               macro_build_lui (&expr1, AT);
7963               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7964                            AT, AT, BFD_RELOC_LO16);
7965               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7966                            tempreg, tempreg, AT);
7967               used_at = 1;
7968             }
7969           relax_end ();
7970         }
7971       else if (mips_big_got && HAVE_NEWABI)
7972         {
7973           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7974           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7975           int add_breg_early = 0;
7976
7977           /* This is the large GOT case.  If this is a reference to an
7978              external symbol, and there is no constant, we want
7979                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7980                add      $tempreg,$tempreg,$gp
7981                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7982              or for lca or if tempreg is PIC_CALL_REG
7983                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7984                add      $tempreg,$tempreg,$gp
7985                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7986
7987              If we have a small constant, and this is a reference to
7988              an external symbol, we want
7989                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7990                add      $tempreg,$tempreg,$gp
7991                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7992                addi     $tempreg,$tempreg,<constant>
7993
7994              If we have a large constant, and this is a reference to
7995              an external symbol, we want
7996                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7997                addu     $tempreg,$tempreg,$gp
7998                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7999                lui      $at,<hiconstant>
8000                addi     $at,$at,<loconstant>
8001                add      $tempreg,$tempreg,$at
8002
8003              If we have NewABI, and we know it's a local symbol, we want
8004                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8005                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8006              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8007
8008           relax_start (offset_expr.X_add_symbol);
8009
8010           expr1.X_add_number = offset_expr.X_add_number;
8011           offset_expr.X_add_number = 0;
8012
8013           if (expr1.X_add_number == 0 && breg == 0
8014               && (call || tempreg == PIC_CALL_REG))
8015             {
8016               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8017               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8018             }
8019           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8020           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8021                        tempreg, tempreg, mips_gp_register);
8022           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8023                        tempreg, lw_reloc_type, tempreg);
8024
8025           if (expr1.X_add_number == 0)
8026             ;
8027           else if (expr1.X_add_number >= -0x8000
8028                    && expr1.X_add_number < 0x8000)
8029             {
8030               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8031                            tempreg, tempreg, BFD_RELOC_LO16);
8032             }
8033           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8034             {
8035               /* If we are going to add in a base register, and the
8036                  target register and the base register are the same,
8037                  then we are using AT as a temporary register.  Since
8038                  we want to load the constant into AT, we add our
8039                  current AT (from the global offset table) and the
8040                  register into the register now, and pretend we were
8041                  not using a base register.  */
8042               if (breg != treg)
8043                 dreg = tempreg;
8044               else
8045                 {
8046                   gas_assert (tempreg == AT);
8047                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8048                                treg, AT, breg);
8049                   dreg = treg;
8050                   add_breg_early = 1;
8051                 }
8052
8053               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8054               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8055
8056               used_at = 1;
8057             }
8058           else
8059             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8060
8061           relax_switch ();
8062           offset_expr.X_add_number = expr1.X_add_number;
8063           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8064                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8065           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8066                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
8067           if (add_breg_early)
8068             {
8069               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8070                            treg, tempreg, breg);
8071               breg = 0;
8072               tempreg = treg;
8073             }
8074           relax_end ();
8075         }
8076       else
8077         abort ();
8078
8079       if (breg != 0)
8080         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
8081       break;
8082
8083     case M_MSGSND:
8084       gas_assert (!mips_opts.micromips);
8085       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
8086       break;
8087
8088     case M_MSGLD:
8089       gas_assert (!mips_opts.micromips);
8090       macro_build (NULL, "c2", "C", 0x02);
8091       break;
8092
8093     case M_MSGLD_T:
8094       gas_assert (!mips_opts.micromips);
8095       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
8096       break;
8097
8098     case M_MSGWAIT:
8099       gas_assert (!mips_opts.micromips);
8100       macro_build (NULL, "c2", "C", 3);
8101       break;
8102
8103     case M_MSGWAIT_T:
8104       gas_assert (!mips_opts.micromips);
8105       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
8106       break;
8107
8108     case M_J_A:
8109       /* The j instruction may not be used in PIC code, since it
8110          requires an absolute address.  We convert it to a b
8111          instruction.  */
8112       if (mips_pic == NO_PIC)
8113         macro_build (&offset_expr, "j", "a");
8114       else
8115         macro_build (&offset_expr, "b", "p");
8116       break;
8117
8118       /* The jal instructions must be handled as macros because when
8119          generating PIC code they expand to multi-instruction
8120          sequences.  Normally they are simple instructions.  */
8121     case M_JALS_1:
8122       dreg = RA;
8123       /* Fall through.  */
8124     case M_JALS_2:
8125       gas_assert (mips_opts.micromips);
8126       if (mips_opts.insn32)
8127         {
8128           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
8129           break;
8130         }
8131       jals = 1;
8132       goto jal;
8133     case M_JAL_1:
8134       dreg = RA;
8135       /* Fall through.  */
8136     case M_JAL_2:
8137     jal:
8138       if (mips_pic == NO_PIC)
8139         {
8140           s = jals ? "jalrs" : "jalr";
8141           if (mips_opts.micromips
8142               && !mips_opts.insn32
8143               && dreg == RA
8144               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8145             macro_build (NULL, s, "mj", sreg);
8146           else
8147             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8148         }
8149       else
8150         {
8151           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
8152                            && mips_cprestore_offset >= 0);
8153
8154           if (sreg != PIC_CALL_REG)
8155             as_warn (_("MIPS PIC call to register other than $25"));
8156
8157           s = ((mips_opts.micromips
8158                 && !mips_opts.insn32
8159                 && (!mips_opts.noreorder || cprestore))
8160                ? "jalrs" : "jalr");
8161           if (mips_opts.micromips
8162               && !mips_opts.insn32
8163               && dreg == RA
8164               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8165             macro_build (NULL, s, "mj", sreg);
8166           else
8167             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8168           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
8169             {
8170               if (mips_cprestore_offset < 0)
8171                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8172               else
8173                 {
8174                   if (!mips_frame_reg_valid)
8175                     {
8176                       as_warn (_("No .frame pseudo-op used in PIC code"));
8177                       /* Quiet this warning.  */
8178                       mips_frame_reg_valid = 1;
8179                     }
8180                   if (!mips_cprestore_valid)
8181                     {
8182                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8183                       /* Quiet this warning.  */
8184                       mips_cprestore_valid = 1;
8185                     }
8186                   if (mips_opts.noreorder)
8187                     macro_build (NULL, "nop", "");
8188                   expr1.X_add_number = mips_cprestore_offset;
8189                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8190                                                 mips_gp_register,
8191                                                 mips_frame_reg,
8192                                                 HAVE_64BIT_ADDRESSES);
8193                 }
8194             }
8195         }
8196
8197       break;
8198
8199     case M_JALS_A:
8200       gas_assert (mips_opts.micromips);
8201       if (mips_opts.insn32)
8202         {
8203           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
8204           break;
8205         }
8206       jals = 1;
8207       /* Fall through.  */
8208     case M_JAL_A:
8209       if (mips_pic == NO_PIC)
8210         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
8211       else if (mips_pic == SVR4_PIC)
8212         {
8213           /* If this is a reference to an external symbol, and we are
8214              using a small GOT, we want
8215                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
8216                nop
8217                jalr     $ra,$25
8218                nop
8219                lw       $gp,cprestore($sp)
8220              The cprestore value is set using the .cprestore
8221              pseudo-op.  If we are using a big GOT, we want
8222                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
8223                addu     $25,$25,$gp
8224                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
8225                nop
8226                jalr     $ra,$25
8227                nop
8228                lw       $gp,cprestore($sp)
8229              If the symbol is not external, we want
8230                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8231                nop
8232                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
8233                jalr     $ra,$25
8234                nop
8235                lw $gp,cprestore($sp)
8236
8237              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
8238              sequences above, minus nops, unless the symbol is local,
8239              which enables us to use GOT_PAGE/GOT_OFST (big got) or
8240              GOT_DISP.  */
8241           if (HAVE_NEWABI)
8242             {
8243               if (!mips_big_got)
8244                 {
8245                   relax_start (offset_expr.X_add_symbol);
8246                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8247                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8248                                mips_gp_register);
8249                   relax_switch ();
8250                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8251                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
8252                                mips_gp_register);
8253                   relax_end ();
8254                 }
8255               else
8256                 {
8257                   relax_start (offset_expr.X_add_symbol);
8258                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8259                                BFD_RELOC_MIPS_CALL_HI16);
8260                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8261                                PIC_CALL_REG, mips_gp_register);
8262                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8263                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8264                                PIC_CALL_REG);
8265                   relax_switch ();
8266                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8267                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
8268                                mips_gp_register);
8269                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8270                                PIC_CALL_REG, PIC_CALL_REG,
8271                                BFD_RELOC_MIPS_GOT_OFST);
8272                   relax_end ();
8273                 }
8274
8275               macro_build_jalr (&offset_expr, 0);
8276             }
8277           else
8278             {
8279               relax_start (offset_expr.X_add_symbol);
8280               if (!mips_big_got)
8281                 {
8282                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8283                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8284                                mips_gp_register);
8285                   load_delay_nop ();
8286                   relax_switch ();
8287                 }
8288               else
8289                 {
8290                   int gpdelay;
8291
8292                   gpdelay = reg_needs_delay (mips_gp_register);
8293                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8294                                BFD_RELOC_MIPS_CALL_HI16);
8295                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8296                                PIC_CALL_REG, mips_gp_register);
8297                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8298                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8299                                PIC_CALL_REG);
8300                   load_delay_nop ();
8301                   relax_switch ();
8302                   if (gpdelay)
8303                     macro_build (NULL, "nop", "");
8304                 }
8305               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8306                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
8307                            mips_gp_register);
8308               load_delay_nop ();
8309               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8310                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
8311               relax_end ();
8312               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
8313
8314               if (mips_cprestore_offset < 0)
8315                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8316               else
8317                 {
8318                   if (!mips_frame_reg_valid)
8319                     {
8320                       as_warn (_("No .frame pseudo-op used in PIC code"));
8321                       /* Quiet this warning.  */
8322                       mips_frame_reg_valid = 1;
8323                     }
8324                   if (!mips_cprestore_valid)
8325                     {
8326                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8327                       /* Quiet this warning.  */
8328                       mips_cprestore_valid = 1;
8329                     }
8330                   if (mips_opts.noreorder)
8331                     macro_build (NULL, "nop", "");
8332                   expr1.X_add_number = mips_cprestore_offset;
8333                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8334                                                 mips_gp_register,
8335                                                 mips_frame_reg,
8336                                                 HAVE_64BIT_ADDRESSES);
8337                 }
8338             }
8339         }
8340       else if (mips_pic == VXWORKS_PIC)
8341         as_bad (_("Non-PIC jump used in PIC library"));
8342       else
8343         abort ();
8344
8345       break;
8346
8347     case M_LBUE_AB:
8348       s = "lbue";
8349       fmt = "t,+j(b)";
8350       offbits = 9;
8351       goto ld_st;
8352     case M_LHUE_AB:
8353       s = "lhue";
8354       fmt = "t,+j(b)";
8355       offbits = 9;
8356       goto ld_st;
8357     case M_LBE_AB:
8358       s = "lbe";
8359       fmt = "t,+j(b)";
8360       offbits = 9;
8361       goto ld_st;
8362     case M_LHE_AB:
8363       s = "lhe";
8364       fmt = "t,+j(b)";
8365       offbits = 9;
8366       goto ld_st;
8367     case M_LLE_AB:
8368       s = "lle";
8369       fmt = "t,+j(b)";
8370       offbits = 9;
8371       goto ld_st;
8372     case M_LWE_AB:
8373       s = "lwe";
8374       fmt = "t,+j(b)";
8375       offbits = 9;
8376       goto ld_st;
8377     case M_LWLE_AB:
8378       s = "lwle";
8379       fmt = "t,+j(b)";
8380       offbits = 9;
8381       goto ld_st;
8382     case M_LWRE_AB:
8383       s = "lwre";
8384       fmt = "t,+j(b)";
8385       offbits = 9;
8386       goto ld_st;
8387     case M_SBE_AB:
8388       s = "sbe";
8389       fmt = "t,+j(b)";
8390       offbits = 9;
8391       goto ld_st;
8392     case M_SCE_AB:
8393       s = "sce";
8394       fmt = "t,+j(b)";
8395       offbits = 9;
8396       goto ld_st;
8397     case M_SHE_AB:
8398       s = "she";
8399       fmt = "t,+j(b)";
8400       offbits = 9;
8401       goto ld_st;
8402     case M_SWE_AB:
8403       s = "swe";
8404       fmt = "t,+j(b)";
8405       offbits = 9;
8406       goto ld_st;
8407     case M_SWLE_AB:
8408       s = "swle";
8409       fmt = "t,+j(b)";
8410       offbits = 9;
8411       goto ld_st;
8412     case M_SWRE_AB:
8413       s = "swre";
8414       fmt = "t,+j(b)";
8415       offbits = 9;
8416       goto ld_st;
8417     case M_ACLR_AB:
8418       s = "aclr";
8419       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8420       fmt = "\\,~(b)";
8421       offbits = 12;
8422       goto ld_st;
8423     case M_ASET_AB:
8424       s = "aset";
8425       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8426       fmt = "\\,~(b)";
8427       offbits = 12;
8428       goto ld_st;
8429     case M_LB_AB:
8430       s = "lb";
8431       fmt = "t,o(b)";
8432       goto ld;
8433     case M_LBU_AB:
8434       s = "lbu";
8435       fmt = "t,o(b)";
8436       goto ld;
8437     case M_LH_AB:
8438       s = "lh";
8439       fmt = "t,o(b)";
8440       goto ld;
8441     case M_LHU_AB:
8442       s = "lhu";
8443       fmt = "t,o(b)";
8444       goto ld;
8445     case M_LW_AB:
8446       s = "lw";
8447       fmt = "t,o(b)";
8448       goto ld;
8449     case M_LWC0_AB:
8450       gas_assert (!mips_opts.micromips);
8451       s = "lwc0";
8452       fmt = "E,o(b)";
8453       /* Itbl support may require additional care here.  */
8454       coproc = 1;
8455       goto ld_st;
8456     case M_LWC1_AB:
8457       s = "lwc1";
8458       fmt = "T,o(b)";
8459       /* Itbl support may require additional care here.  */
8460       coproc = 1;
8461       goto ld_st;
8462     case M_LWC2_AB:
8463       s = "lwc2";
8464       fmt = COP12_FMT;
8465       offbits = (mips_opts.micromips ? 12 : 16);
8466       /* Itbl support may require additional care here.  */
8467       coproc = 1;
8468       goto ld_st;
8469     case M_LWC3_AB:
8470       gas_assert (!mips_opts.micromips);
8471       s = "lwc3";
8472       fmt = "E,o(b)";
8473       /* Itbl support may require additional care here.  */
8474       coproc = 1;
8475       goto ld_st;
8476     case M_LWL_AB:
8477       s = "lwl";
8478       fmt = MEM12_FMT;
8479       offbits = (mips_opts.micromips ? 12 : 16);
8480       goto ld_st;
8481     case M_LWR_AB:
8482       s = "lwr";
8483       fmt = MEM12_FMT;
8484       offbits = (mips_opts.micromips ? 12 : 16);
8485       goto ld_st;
8486     case M_LDC1_AB:
8487       s = "ldc1";
8488       fmt = "T,o(b)";
8489       /* Itbl support may require additional care here.  */
8490       coproc = 1;
8491       goto ld_st;
8492     case M_LDC2_AB:
8493       s = "ldc2";
8494       fmt = COP12_FMT;
8495       offbits = (mips_opts.micromips ? 12 : 16);
8496       /* Itbl support may require additional care here.  */
8497       coproc = 1;
8498       goto ld_st;
8499     case M_LQC2_AB:
8500       s = "lqc2";
8501       fmt = "E,o(b)";
8502       /* Itbl support may require additional care here.  */
8503       coproc = 1;
8504       goto ld_st;
8505     case M_LDC3_AB:
8506       s = "ldc3";
8507       fmt = "E,o(b)";
8508       /* Itbl support may require additional care here.  */
8509       coproc = 1;
8510       goto ld_st;
8511     case M_LDL_AB:
8512       s = "ldl";
8513       fmt = MEM12_FMT;
8514       offbits = (mips_opts.micromips ? 12 : 16);
8515       goto ld_st;
8516     case M_LDR_AB:
8517       s = "ldr";
8518       fmt = MEM12_FMT;
8519       offbits = (mips_opts.micromips ? 12 : 16);
8520       goto ld_st;
8521     case M_LL_AB:
8522       s = "ll";
8523       fmt = MEM12_FMT;
8524       offbits = (mips_opts.micromips ? 12 : 16);
8525       goto ld;
8526     case M_LLD_AB:
8527       s = "lld";
8528       fmt = MEM12_FMT;
8529       offbits = (mips_opts.micromips ? 12 : 16);
8530       goto ld;
8531     case M_LWU_AB:
8532       s = "lwu";
8533       fmt = MEM12_FMT;
8534       offbits = (mips_opts.micromips ? 12 : 16);
8535       goto ld;
8536     case M_LWP_AB:
8537       gas_assert (mips_opts.micromips);
8538       s = "lwp";
8539       fmt = "t,~(b)";
8540       offbits = 12;
8541       lp = 1;
8542       goto ld;
8543     case M_LDP_AB:
8544       gas_assert (mips_opts.micromips);
8545       s = "ldp";
8546       fmt = "t,~(b)";
8547       offbits = 12;
8548       lp = 1;
8549       goto ld;
8550     case M_LWM_AB:
8551       gas_assert (mips_opts.micromips);
8552       s = "lwm";
8553       fmt = "n,~(b)";
8554       offbits = 12;
8555       goto ld_st;
8556     case M_LDM_AB:
8557       gas_assert (mips_opts.micromips);
8558       s = "ldm";
8559       fmt = "n,~(b)";
8560       offbits = 12;
8561       goto ld_st;
8562
8563     ld:
8564       /* We don't want to use $0 as tempreg.  */
8565       if (breg == treg + lp || treg + lp == ZERO)
8566         goto ld_st;
8567       else
8568         tempreg = treg + lp;
8569       goto ld_noat;
8570
8571     case M_SB_AB:
8572       s = "sb";
8573       fmt = "t,o(b)";
8574       goto ld_st;
8575     case M_SH_AB:
8576       s = "sh";
8577       fmt = "t,o(b)";
8578       goto ld_st;
8579     case M_SW_AB:
8580       s = "sw";
8581       fmt = "t,o(b)";
8582       goto ld_st;
8583     case M_SWC0_AB:
8584       gas_assert (!mips_opts.micromips);
8585       s = "swc0";
8586       fmt = "E,o(b)";
8587       /* Itbl support may require additional care here.  */
8588       coproc = 1;
8589       goto ld_st;
8590     case M_SWC1_AB:
8591       s = "swc1";
8592       fmt = "T,o(b)";
8593       /* Itbl support may require additional care here.  */
8594       coproc = 1;
8595       goto ld_st;
8596     case M_SWC2_AB:
8597       s = "swc2";
8598       fmt = COP12_FMT;
8599       offbits = (mips_opts.micromips ? 12 : 16);
8600       /* Itbl support may require additional care here.  */
8601       coproc = 1;
8602       goto ld_st;
8603     case M_SWC3_AB:
8604       gas_assert (!mips_opts.micromips);
8605       s = "swc3";
8606       fmt = "E,o(b)";
8607       /* Itbl support may require additional care here.  */
8608       coproc = 1;
8609       goto ld_st;
8610     case M_SWL_AB:
8611       s = "swl";
8612       fmt = MEM12_FMT;
8613       offbits = (mips_opts.micromips ? 12 : 16);
8614       goto ld_st;
8615     case M_SWR_AB:
8616       s = "swr";
8617       fmt = MEM12_FMT;
8618       offbits = (mips_opts.micromips ? 12 : 16);
8619       goto ld_st;
8620     case M_SC_AB:
8621       s = "sc";
8622       fmt = MEM12_FMT;
8623       offbits = (mips_opts.micromips ? 12 : 16);
8624       goto ld_st;
8625     case M_SCD_AB:
8626       s = "scd";
8627       fmt = MEM12_FMT;
8628       offbits = (mips_opts.micromips ? 12 : 16);
8629       goto ld_st;
8630     case M_CACHE_AB:
8631       s = "cache";
8632       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8633       offbits = (mips_opts.micromips ? 12 : 16);
8634       goto ld_st;
8635     case M_CACHEE_AB:
8636       s = "cachee";
8637       fmt = "k,+j(b)";
8638       offbits = 9;
8639       goto ld_st;
8640     case M_PREF_AB:
8641       s = "pref";
8642       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8643       offbits = (mips_opts.micromips ? 12 : 16);
8644       goto ld_st;
8645     case M_PREFE_AB:
8646       s = "prefe";
8647       fmt = "k,+j(b)";
8648       offbits = 9;
8649       goto ld_st;
8650     case M_SDC1_AB:
8651       s = "sdc1";
8652       fmt = "T,o(b)";
8653       coproc = 1;
8654       /* Itbl support may require additional care here.  */
8655       goto ld_st;
8656     case M_SDC2_AB:
8657       s = "sdc2";
8658       fmt = COP12_FMT;
8659       offbits = (mips_opts.micromips ? 12 : 16);
8660       /* Itbl support may require additional care here.  */
8661       coproc = 1;
8662       goto ld_st;
8663     case M_SQC2_AB:
8664       s = "sqc2";
8665       fmt = "E,o(b)";
8666       /* Itbl support may require additional care here.  */
8667       coproc = 1;
8668       goto ld_st;
8669     case M_SDC3_AB:
8670       gas_assert (!mips_opts.micromips);
8671       s = "sdc3";
8672       fmt = "E,o(b)";
8673       /* Itbl support may require additional care here.  */
8674       coproc = 1;
8675       goto ld_st;
8676     case M_SDL_AB:
8677       s = "sdl";
8678       fmt = MEM12_FMT;
8679       offbits = (mips_opts.micromips ? 12 : 16);
8680       goto ld_st;
8681     case M_SDR_AB:
8682       s = "sdr";
8683       fmt = MEM12_FMT;
8684       offbits = (mips_opts.micromips ? 12 : 16);
8685       goto ld_st;
8686     case M_SWP_AB:
8687       gas_assert (mips_opts.micromips);
8688       s = "swp";
8689       fmt = "t,~(b)";
8690       offbits = 12;
8691       goto ld_st;
8692     case M_SDP_AB:
8693       gas_assert (mips_opts.micromips);
8694       s = "sdp";
8695       fmt = "t,~(b)";
8696       offbits = 12;
8697       goto ld_st;
8698     case M_SWM_AB:
8699       gas_assert (mips_opts.micromips);
8700       s = "swm";
8701       fmt = "n,~(b)";
8702       offbits = 12;
8703       goto ld_st;
8704     case M_SDM_AB:
8705       gas_assert (mips_opts.micromips);
8706       s = "sdm";
8707       fmt = "n,~(b)";
8708       offbits = 12;
8709
8710     ld_st:
8711       tempreg = AT;
8712     ld_noat:
8713       if (small_offset_p (0, align, 16))
8714         {
8715           /* The first case exists for M_LD_AB and M_SD_AB, which are
8716              macros for o32 but which should act like normal instructions
8717              otherwise.  */
8718           if (offbits == 16)
8719             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
8720                          offset_reloc[1], offset_reloc[2], breg);
8721           else if (small_offset_p (0, align, offbits))
8722             {
8723               if (offbits == 0)
8724                 macro_build (NULL, s, fmt, treg, breg);
8725               else
8726                 macro_build (NULL, s, fmt, treg,
8727                              (int) offset_expr.X_add_number, breg);
8728             }
8729           else
8730             {
8731               if (tempreg == AT)
8732                 used_at = 1;
8733               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8734                            tempreg, breg, -1, offset_reloc[0],
8735                            offset_reloc[1], offset_reloc[2]);
8736               if (offbits == 0)
8737                 macro_build (NULL, s, fmt, treg, tempreg);
8738               else
8739                 macro_build (NULL, s, fmt, treg, 0, tempreg);
8740             }
8741           break;
8742         }
8743
8744       if (tempreg == AT)
8745         used_at = 1;
8746
8747       if (offset_expr.X_op != O_constant
8748           && offset_expr.X_op != O_symbol)
8749         {
8750           as_bad (_("Expression too complex"));
8751           offset_expr.X_op = O_constant;
8752         }
8753
8754       if (HAVE_32BIT_ADDRESSES
8755           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8756         {
8757           char value [32];
8758
8759           sprintf_vma (value, offset_expr.X_add_number);
8760           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8761         }
8762
8763       /* A constant expression in PIC code can be handled just as it
8764          is in non PIC code.  */
8765       if (offset_expr.X_op == O_constant)
8766         {
8767           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
8768                                                  offbits == 0 ? 16 : offbits);
8769           offset_expr.X_add_number -= expr1.X_add_number;
8770
8771           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8772           if (breg != 0)
8773             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8774                          tempreg, tempreg, breg);
8775           if (offbits == 0)
8776             {
8777               if (offset_expr.X_add_number != 0)
8778                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
8779                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
8780               macro_build (NULL, s, fmt, treg, tempreg);
8781             }
8782           else if (offbits == 16)
8783             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8784           else
8785             macro_build (NULL, s, fmt, treg,
8786                          (int) offset_expr.X_add_number, tempreg);
8787         }
8788       else if (offbits != 16)
8789         {
8790           /* The offset field is too narrow to be used for a low-part
8791              relocation, so load the whole address into the auxillary
8792              register.  */
8793           load_address (tempreg, &offset_expr, &used_at);
8794           if (breg != 0)
8795             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8796                          tempreg, tempreg, breg);
8797           if (offbits == 0)
8798             macro_build (NULL, s, fmt, treg, tempreg);
8799           else
8800             macro_build (NULL, s, fmt, treg, 0, tempreg);
8801         }
8802       else if (mips_pic == NO_PIC)
8803         {
8804           /* If this is a reference to a GP relative symbol, and there
8805              is no base register, we want
8806                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8807              Otherwise, if there is no base register, we want
8808                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8809                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8810              If we have a constant, we need two instructions anyhow,
8811              so we always use the latter form.
8812
8813              If we have a base register, and this is a reference to a
8814              GP relative symbol, we want
8815                addu     $tempreg,$breg,$gp
8816                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
8817              Otherwise we want
8818                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8819                addu     $tempreg,$tempreg,$breg
8820                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8821              With a constant we always use the latter case.
8822
8823              With 64bit address space and no base register and $at usable,
8824              we want
8825                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8826                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8827                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8828                dsll32   $tempreg,0
8829                daddu    $tempreg,$at
8830                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8831              If we have a base register, we want
8832                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8833                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8834                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8835                daddu    $at,$breg
8836                dsll32   $tempreg,0
8837                daddu    $tempreg,$at
8838                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8839
8840              Without $at we can't generate the optimal path for superscalar
8841              processors here since this would require two temporary registers.
8842                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8843                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8844                dsll     $tempreg,16
8845                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8846                dsll     $tempreg,16
8847                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8848              If we have a base register, we want
8849                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8850                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8851                dsll     $tempreg,16
8852                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8853                dsll     $tempreg,16
8854                daddu    $tempreg,$tempreg,$breg
8855                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8856
8857              For GP relative symbols in 64bit address space we can use
8858              the same sequence as in 32bit address space.  */
8859           if (HAVE_64BIT_SYMBOLS)
8860             {
8861               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8862                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8863                 {
8864                   relax_start (offset_expr.X_add_symbol);
8865                   if (breg == 0)
8866                     {
8867                       macro_build (&offset_expr, s, fmt, treg,
8868                                    BFD_RELOC_GPREL16, mips_gp_register);
8869                     }
8870                   else
8871                     {
8872                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8873                                    tempreg, breg, mips_gp_register);
8874                       macro_build (&offset_expr, s, fmt, treg,
8875                                    BFD_RELOC_GPREL16, tempreg);
8876                     }
8877                   relax_switch ();
8878                 }
8879
8880               if (used_at == 0 && mips_opts.at)
8881                 {
8882                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8883                                BFD_RELOC_MIPS_HIGHEST);
8884                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
8885                                BFD_RELOC_HI16_S);
8886                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8887                                tempreg, BFD_RELOC_MIPS_HIGHER);
8888                   if (breg != 0)
8889                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
8890                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8891                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8892                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
8893                                tempreg);
8894                   used_at = 1;
8895                 }
8896               else
8897                 {
8898                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8899                                BFD_RELOC_MIPS_HIGHEST);
8900                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8901                                tempreg, BFD_RELOC_MIPS_HIGHER);
8902                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8903                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8904                                tempreg, BFD_RELOC_HI16_S);
8905                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8906                   if (breg != 0)
8907                     macro_build (NULL, "daddu", "d,v,t",
8908                                  tempreg, tempreg, breg);
8909                   macro_build (&offset_expr, s, fmt, treg,
8910                                BFD_RELOC_LO16, tempreg);
8911                 }
8912
8913               if (mips_relax.sequence)
8914                 relax_end ();
8915               break;
8916             }
8917
8918           if (breg == 0)
8919             {
8920               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8921                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8922                 {
8923                   relax_start (offset_expr.X_add_symbol);
8924                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
8925                                mips_gp_register);
8926                   relax_switch ();
8927                 }
8928               macro_build_lui (&offset_expr, tempreg);
8929               macro_build (&offset_expr, s, fmt, treg,
8930                            BFD_RELOC_LO16, tempreg);
8931               if (mips_relax.sequence)
8932                 relax_end ();
8933             }
8934           else
8935             {
8936               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8937                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8938                 {
8939                   relax_start (offset_expr.X_add_symbol);
8940                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8941                                tempreg, breg, mips_gp_register);
8942                   macro_build (&offset_expr, s, fmt, treg,
8943                                BFD_RELOC_GPREL16, tempreg);
8944                   relax_switch ();
8945                 }
8946               macro_build_lui (&offset_expr, tempreg);
8947               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8948                            tempreg, tempreg, breg);
8949               macro_build (&offset_expr, s, fmt, treg,
8950                            BFD_RELOC_LO16, tempreg);
8951               if (mips_relax.sequence)
8952                 relax_end ();
8953             }
8954         }
8955       else if (!mips_big_got)
8956         {
8957           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8958
8959           /* If this is a reference to an external symbol, we want
8960                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8961                nop
8962                <op>     $treg,0($tempreg)
8963              Otherwise we want
8964                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8965                nop
8966                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8967                <op>     $treg,0($tempreg)
8968
8969              For NewABI, we want
8970                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8971                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
8972
8973              If there is a base register, we add it to $tempreg before
8974              the <op>.  If there is a constant, we stick it in the
8975              <op> instruction.  We don't handle constants larger than
8976              16 bits, because we have no way to load the upper 16 bits
8977              (actually, we could handle them for the subset of cases
8978              in which we are not using $at).  */
8979           gas_assert (offset_expr.X_op == O_symbol);
8980           if (HAVE_NEWABI)
8981             {
8982               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8983                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8984               if (breg != 0)
8985                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8986                              tempreg, tempreg, breg);
8987               macro_build (&offset_expr, s, fmt, treg,
8988                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
8989               break;
8990             }
8991           expr1.X_add_number = offset_expr.X_add_number;
8992           offset_expr.X_add_number = 0;
8993           if (expr1.X_add_number < -0x8000
8994               || expr1.X_add_number >= 0x8000)
8995             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8996           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8997                        lw_reloc_type, mips_gp_register);
8998           load_delay_nop ();
8999           relax_start (offset_expr.X_add_symbol);
9000           relax_switch ();
9001           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9002                        tempreg, BFD_RELOC_LO16);
9003           relax_end ();
9004           if (breg != 0)
9005             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9006                          tempreg, tempreg, breg);
9007           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9008         }
9009       else if (mips_big_got && !HAVE_NEWABI)
9010         {
9011           int gpdelay;
9012
9013           /* If this is a reference to an external symbol, we want
9014                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9015                addu     $tempreg,$tempreg,$gp
9016                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9017                <op>     $treg,0($tempreg)
9018              Otherwise we want
9019                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9020                nop
9021                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9022                <op>     $treg,0($tempreg)
9023              If there is a base register, we add it to $tempreg before
9024              the <op>.  If there is a constant, we stick it in the
9025              <op> instruction.  We don't handle constants larger than
9026              16 bits, because we have no way to load the upper 16 bits
9027              (actually, we could handle them for the subset of cases
9028              in which we are not using $at).  */
9029           gas_assert (offset_expr.X_op == O_symbol);
9030           expr1.X_add_number = offset_expr.X_add_number;
9031           offset_expr.X_add_number = 0;
9032           if (expr1.X_add_number < -0x8000
9033               || expr1.X_add_number >= 0x8000)
9034             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9035           gpdelay = reg_needs_delay (mips_gp_register);
9036           relax_start (offset_expr.X_add_symbol);
9037           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9038                        BFD_RELOC_MIPS_GOT_HI16);
9039           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9040                        mips_gp_register);
9041           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9042                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9043           relax_switch ();
9044           if (gpdelay)
9045             macro_build (NULL, "nop", "");
9046           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9047                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9048           load_delay_nop ();
9049           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9050                        tempreg, BFD_RELOC_LO16);
9051           relax_end ();
9052
9053           if (breg != 0)
9054             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9055                          tempreg, tempreg, breg);
9056           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9057         }
9058       else if (mips_big_got && HAVE_NEWABI)
9059         {
9060           /* If this is a reference to an external symbol, we want
9061                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9062                add      $tempreg,$tempreg,$gp
9063                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9064                <op>     $treg,<ofst>($tempreg)
9065              Otherwise, for local symbols, we want:
9066                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9067                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
9068           gas_assert (offset_expr.X_op == O_symbol);
9069           expr1.X_add_number = offset_expr.X_add_number;
9070           offset_expr.X_add_number = 0;
9071           if (expr1.X_add_number < -0x8000
9072               || expr1.X_add_number >= 0x8000)
9073             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9074           relax_start (offset_expr.X_add_symbol);
9075           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9076                        BFD_RELOC_MIPS_GOT_HI16);
9077           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9078                        mips_gp_register);
9079           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9080                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9081           if (breg != 0)
9082             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9083                          tempreg, tempreg, breg);
9084           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9085
9086           relax_switch ();
9087           offset_expr.X_add_number = expr1.X_add_number;
9088           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9089                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9090           if (breg != 0)
9091             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9092                          tempreg, tempreg, breg);
9093           macro_build (&offset_expr, s, fmt, treg,
9094                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
9095           relax_end ();
9096         }
9097       else
9098         abort ();
9099
9100       break;
9101
9102     case M_JRADDIUSP:
9103       gas_assert (mips_opts.micromips);
9104       gas_assert (mips_opts.insn32);
9105       start_noreorder ();
9106       macro_build (NULL, "jr", "s", RA);
9107       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
9108       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
9109       end_noreorder ();
9110       break;
9111
9112     case M_JRC:
9113       gas_assert (mips_opts.micromips);
9114       gas_assert (mips_opts.insn32);
9115       macro_build (NULL, "jr", "s", sreg);
9116       if (mips_opts.noreorder)
9117         macro_build (NULL, "nop", "");
9118       break;
9119
9120     case M_LI:
9121     case M_LI_S:
9122       load_register (treg, &imm_expr, 0);
9123       break;
9124
9125     case M_DLI:
9126       load_register (treg, &imm_expr, 1);
9127       break;
9128
9129     case M_LI_SS:
9130       if (imm_expr.X_op == O_constant)
9131         {
9132           used_at = 1;
9133           load_register (AT, &imm_expr, 0);
9134           macro_build (NULL, "mtc1", "t,G", AT, treg);
9135           break;
9136         }
9137       else
9138         {
9139           gas_assert (offset_expr.X_op == O_symbol
9140                       && strcmp (segment_name (S_GET_SEGMENT
9141                                                (offset_expr.X_add_symbol)),
9142                                  ".lit4") == 0
9143                       && offset_expr.X_add_number == 0);
9144           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
9145                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
9146           break;
9147         }
9148
9149     case M_LI_D:
9150       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
9151          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
9152          order 32 bits of the value and the low order 32 bits are either
9153          zero or in OFFSET_EXPR.  */
9154       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9155         {
9156           if (HAVE_64BIT_GPRS)
9157             load_register (treg, &imm_expr, 1);
9158           else
9159             {
9160               int hreg, lreg;
9161
9162               if (target_big_endian)
9163                 {
9164                   hreg = treg;
9165                   lreg = treg + 1;
9166                 }
9167               else
9168                 {
9169                   hreg = treg + 1;
9170                   lreg = treg;
9171                 }
9172
9173               if (hreg <= 31)
9174                 load_register (hreg, &imm_expr, 0);
9175               if (lreg <= 31)
9176                 {
9177                   if (offset_expr.X_op == O_absent)
9178                     move_register (lreg, 0);
9179                   else
9180                     {
9181                       gas_assert (offset_expr.X_op == O_constant);
9182                       load_register (lreg, &offset_expr, 0);
9183                     }
9184                 }
9185             }
9186           break;
9187         }
9188
9189       /* We know that sym is in the .rdata section.  First we get the
9190          upper 16 bits of the address.  */
9191       if (mips_pic == NO_PIC)
9192         {
9193           macro_build_lui (&offset_expr, AT);
9194           used_at = 1;
9195         }
9196       else
9197         {
9198           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9199                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9200           used_at = 1;
9201         }
9202
9203       /* Now we load the register(s).  */
9204       if (HAVE_64BIT_GPRS)
9205         {
9206           used_at = 1;
9207           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9208         }
9209       else
9210         {
9211           used_at = 1;
9212           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9213           if (treg != RA)
9214             {
9215               /* FIXME: How in the world do we deal with the possible
9216                  overflow here?  */
9217               offset_expr.X_add_number += 4;
9218               macro_build (&offset_expr, "lw", "t,o(b)",
9219                            treg + 1, BFD_RELOC_LO16, AT);
9220             }
9221         }
9222       break;
9223
9224     case M_LI_DD:
9225       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
9226          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
9227          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
9228          the value and the low order 32 bits are either zero or in
9229          OFFSET_EXPR.  */
9230       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9231         {
9232           used_at = 1;
9233           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
9234           if (HAVE_64BIT_FPRS)
9235             {
9236               gas_assert (HAVE_64BIT_GPRS);
9237               macro_build (NULL, "dmtc1", "t,S", AT, treg);
9238             }
9239           else
9240             {
9241               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
9242               if (offset_expr.X_op == O_absent)
9243                 macro_build (NULL, "mtc1", "t,G", 0, treg);
9244               else
9245                 {
9246                   gas_assert (offset_expr.X_op == O_constant);
9247                   load_register (AT, &offset_expr, 0);
9248                   macro_build (NULL, "mtc1", "t,G", AT, treg);
9249                 }
9250             }
9251           break;
9252         }
9253
9254       gas_assert (offset_expr.X_op == O_symbol
9255                   && offset_expr.X_add_number == 0);
9256       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
9257       if (strcmp (s, ".lit8") == 0)
9258         {
9259           breg = mips_gp_register;
9260           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
9261           offset_reloc[1] = BFD_RELOC_UNUSED;
9262           offset_reloc[2] = BFD_RELOC_UNUSED;
9263         }
9264       else
9265         {
9266           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
9267           used_at = 1;
9268           if (mips_pic != NO_PIC)
9269             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9270                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
9271           else
9272             {
9273               /* FIXME: This won't work for a 64 bit address.  */
9274               macro_build_lui (&offset_expr, AT);
9275             }
9276
9277           breg = AT;
9278           offset_reloc[0] = BFD_RELOC_LO16;
9279           offset_reloc[1] = BFD_RELOC_UNUSED;
9280           offset_reloc[2] = BFD_RELOC_UNUSED;
9281         }
9282       align = 8;
9283       /* Fall through */
9284
9285     case M_L_DAB:
9286       /*
9287        * The MIPS assembler seems to check for X_add_number not
9288        * being double aligned and generating:
9289        *        lui     at,%hi(foo+1)
9290        *        addu    at,at,v1
9291        *        addiu   at,at,%lo(foo+1)
9292        *        lwc1    f2,0(at)
9293        *        lwc1    f3,4(at)
9294        * But, the resulting address is the same after relocation so why
9295        * generate the extra instruction?
9296        */
9297       /* Itbl support may require additional care here.  */
9298       coproc = 1;
9299       fmt = "T,o(b)";
9300       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9301         {
9302           s = "ldc1";
9303           goto ld_st;
9304         }
9305       s = "lwc1";
9306       goto ldd_std;
9307
9308     case M_S_DAB:
9309       gas_assert (!mips_opts.micromips);
9310       /* Itbl support may require additional care here.  */
9311       coproc = 1;
9312       fmt = "T,o(b)";
9313       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9314         {
9315           s = "sdc1";
9316           goto ld_st;
9317         }
9318       s = "swc1";
9319       goto ldd_std;
9320
9321     case M_LQ_AB:
9322       fmt = "t,o(b)";
9323       s = "lq";
9324       goto ld;
9325
9326     case M_SQ_AB:
9327       fmt = "t,o(b)";
9328       s = "sq";
9329       goto ld_st;
9330
9331     case M_LD_AB:
9332       fmt = "t,o(b)";
9333       if (HAVE_64BIT_GPRS)
9334         {
9335           s = "ld";
9336           goto ld;
9337         }
9338       s = "lw";
9339       goto ldd_std;
9340
9341     case M_SD_AB:
9342       fmt = "t,o(b)";
9343       if (HAVE_64BIT_GPRS)
9344         {
9345           s = "sd";
9346           goto ld_st;
9347         }
9348       s = "sw";
9349
9350     ldd_std:
9351       /* Even on a big endian machine $fn comes before $fn+1.  We have
9352          to adjust when loading from memory.  We set coproc if we must
9353          load $fn+1 first.  */
9354       /* Itbl support may require additional care here.  */
9355       if (!target_big_endian)
9356         coproc = 0;
9357
9358       if (small_offset_p (0, align, 16))
9359         {
9360           ep = &offset_expr;
9361           if (!small_offset_p (4, align, 16))
9362             {
9363               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
9364                            -1, offset_reloc[0], offset_reloc[1],
9365                            offset_reloc[2]);
9366               expr1.X_add_number = 0;
9367               ep = &expr1;
9368               breg = AT;
9369               used_at = 1;
9370               offset_reloc[0] = BFD_RELOC_LO16;
9371               offset_reloc[1] = BFD_RELOC_UNUSED;
9372               offset_reloc[2] = BFD_RELOC_UNUSED;
9373             }
9374           if (strcmp (s, "lw") == 0 && treg == breg)
9375             {
9376               ep->X_add_number += 4;
9377               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
9378                            offset_reloc[1], offset_reloc[2], breg);
9379               ep->X_add_number -= 4;
9380               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
9381                            offset_reloc[1], offset_reloc[2], breg);
9382             }
9383           else
9384             {
9385               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
9386                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
9387                            breg);
9388               ep->X_add_number += 4;
9389               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
9390                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
9391                            breg);
9392             }
9393           break;
9394         }
9395
9396       if (offset_expr.X_op != O_symbol
9397           && offset_expr.X_op != O_constant)
9398         {
9399           as_bad (_("Expression too complex"));
9400           offset_expr.X_op = O_constant;
9401         }
9402
9403       if (HAVE_32BIT_ADDRESSES
9404           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9405         {
9406           char value [32];
9407
9408           sprintf_vma (value, offset_expr.X_add_number);
9409           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9410         }
9411
9412       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
9413         {
9414           /* If this is a reference to a GP relative symbol, we want
9415                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9416                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
9417              If we have a base register, we use this
9418                addu     $at,$breg,$gp
9419                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
9420                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
9421              If this is not a GP relative symbol, we want
9422                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9423                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9424                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9425              If there is a base register, we add it to $at after the
9426              lui instruction.  If there is a constant, we always use
9427              the last case.  */
9428           if (offset_expr.X_op == O_symbol
9429               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9430               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9431             {
9432               relax_start (offset_expr.X_add_symbol);
9433               if (breg == 0)
9434                 {
9435                   tempreg = mips_gp_register;
9436                 }
9437               else
9438                 {
9439                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9440                                AT, breg, mips_gp_register);
9441                   tempreg = AT;
9442                   used_at = 1;
9443                 }
9444
9445               /* Itbl support may require additional care here.  */
9446               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9447                            BFD_RELOC_GPREL16, tempreg);
9448               offset_expr.X_add_number += 4;
9449
9450               /* Set mips_optimize to 2 to avoid inserting an
9451                  undesired nop.  */
9452               hold_mips_optimize = mips_optimize;
9453               mips_optimize = 2;
9454               /* Itbl support may require additional care here.  */
9455               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9456                            BFD_RELOC_GPREL16, tempreg);
9457               mips_optimize = hold_mips_optimize;
9458
9459               relax_switch ();
9460
9461               offset_expr.X_add_number -= 4;
9462             }
9463           used_at = 1;
9464           if (offset_high_part (offset_expr.X_add_number, 16)
9465               != offset_high_part (offset_expr.X_add_number + 4, 16))
9466             {
9467               load_address (AT, &offset_expr, &used_at);
9468               offset_expr.X_op = O_constant;
9469               offset_expr.X_add_number = 0;
9470             }
9471           else
9472             macro_build_lui (&offset_expr, AT);
9473           if (breg != 0)
9474             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9475           /* Itbl support may require additional care here.  */
9476           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9477                        BFD_RELOC_LO16, AT);
9478           /* FIXME: How do we handle overflow here?  */
9479           offset_expr.X_add_number += 4;
9480           /* Itbl support may require additional care here.  */
9481           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9482                        BFD_RELOC_LO16, AT);
9483           if (mips_relax.sequence)
9484             relax_end ();
9485         }
9486       else if (!mips_big_got)
9487         {
9488           /* If this is a reference to an external symbol, we want
9489                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9490                nop
9491                <op>     $treg,0($at)
9492                <op>     $treg+1,4($at)
9493              Otherwise we want
9494                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9495                nop
9496                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9497                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9498              If there is a base register we add it to $at before the
9499              lwc1 instructions.  If there is a constant we include it
9500              in the lwc1 instructions.  */
9501           used_at = 1;
9502           expr1.X_add_number = offset_expr.X_add_number;
9503           if (expr1.X_add_number < -0x8000
9504               || expr1.X_add_number >= 0x8000 - 4)
9505             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9506           load_got_offset (AT, &offset_expr);
9507           load_delay_nop ();
9508           if (breg != 0)
9509             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9510
9511           /* Set mips_optimize to 2 to avoid inserting an undesired
9512              nop.  */
9513           hold_mips_optimize = mips_optimize;
9514           mips_optimize = 2;
9515
9516           /* Itbl support may require additional care here.  */
9517           relax_start (offset_expr.X_add_symbol);
9518           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9519                        BFD_RELOC_LO16, AT);
9520           expr1.X_add_number += 4;
9521           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9522                        BFD_RELOC_LO16, AT);
9523           relax_switch ();
9524           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9525                        BFD_RELOC_LO16, AT);
9526           offset_expr.X_add_number += 4;
9527           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9528                        BFD_RELOC_LO16, AT);
9529           relax_end ();
9530
9531           mips_optimize = hold_mips_optimize;
9532         }
9533       else if (mips_big_got)
9534         {
9535           int gpdelay;
9536
9537           /* If this is a reference to an external symbol, we want
9538                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9539                addu     $at,$at,$gp
9540                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9541                nop
9542                <op>     $treg,0($at)
9543                <op>     $treg+1,4($at)
9544              Otherwise we want
9545                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9546                nop
9547                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9548                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9549              If there is a base register we add it to $at before the
9550              lwc1 instructions.  If there is a constant we include it
9551              in the lwc1 instructions.  */
9552           used_at = 1;
9553           expr1.X_add_number = offset_expr.X_add_number;
9554           offset_expr.X_add_number = 0;
9555           if (expr1.X_add_number < -0x8000
9556               || expr1.X_add_number >= 0x8000 - 4)
9557             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9558           gpdelay = reg_needs_delay (mips_gp_register);
9559           relax_start (offset_expr.X_add_symbol);
9560           macro_build (&offset_expr, "lui", LUI_FMT,
9561                        AT, BFD_RELOC_MIPS_GOT_HI16);
9562           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9563                        AT, AT, mips_gp_register);
9564           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9565                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9566           load_delay_nop ();
9567           if (breg != 0)
9568             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9569           /* Itbl support may require additional care here.  */
9570           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9571                        BFD_RELOC_LO16, AT);
9572           expr1.X_add_number += 4;
9573
9574           /* Set mips_optimize to 2 to avoid inserting an undesired
9575              nop.  */
9576           hold_mips_optimize = mips_optimize;
9577           mips_optimize = 2;
9578           /* Itbl support may require additional care here.  */
9579           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9580                        BFD_RELOC_LO16, AT);
9581           mips_optimize = hold_mips_optimize;
9582           expr1.X_add_number -= 4;
9583
9584           relax_switch ();
9585           offset_expr.X_add_number = expr1.X_add_number;
9586           if (gpdelay)
9587             macro_build (NULL, "nop", "");
9588           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9589                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9590           load_delay_nop ();
9591           if (breg != 0)
9592             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9593           /* Itbl support may require additional care here.  */
9594           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9595                        BFD_RELOC_LO16, AT);
9596           offset_expr.X_add_number += 4;
9597
9598           /* Set mips_optimize to 2 to avoid inserting an undesired
9599              nop.  */
9600           hold_mips_optimize = mips_optimize;
9601           mips_optimize = 2;
9602           /* Itbl support may require additional care here.  */
9603           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9604                        BFD_RELOC_LO16, AT);
9605           mips_optimize = hold_mips_optimize;
9606           relax_end ();
9607         }
9608       else
9609         abort ();
9610
9611       break;
9612         
9613     case M_SAA_AB:
9614       s = "saa";
9615       offbits = 0;
9616       fmt = "t,(b)";
9617       goto ld_st;
9618     case M_SAAD_AB:
9619       s = "saad";
9620       offbits = 0;
9621       fmt = "t,(b)";
9622       goto ld_st;
9623
9624    /* New code added to support COPZ instructions.
9625       This code builds table entries out of the macros in mip_opcodes.
9626       R4000 uses interlocks to handle coproc delays.
9627       Other chips (like the R3000) require nops to be inserted for delays.
9628
9629       FIXME: Currently, we require that the user handle delays.
9630       In order to fill delay slots for non-interlocked chips,
9631       we must have a way to specify delays based on the coprocessor.
9632       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9633       What are the side-effects of the cop instruction?
9634       What cache support might we have and what are its effects?
9635       Both coprocessor & memory require delays. how long???
9636       What registers are read/set/modified?
9637
9638       If an itbl is provided to interpret cop instructions,
9639       this knowledge can be encoded in the itbl spec.  */
9640
9641     case M_COP0:
9642       s = "c0";
9643       goto copz;
9644     case M_COP1:
9645       s = "c1";
9646       goto copz;
9647     case M_COP2:
9648       s = "c2";
9649       goto copz;
9650     case M_COP3:
9651       s = "c3";
9652     copz:
9653       gas_assert (!mips_opts.micromips);
9654       /* For now we just do C (same as Cz).  The parameter will be
9655          stored in insn_opcode by mips_ip.  */
9656       macro_build (NULL, s, "C", (int) ip->insn_opcode);
9657       break;
9658
9659     case M_MOVE:
9660       move_register (dreg, sreg);
9661       break;
9662
9663     case M_MOVEP:
9664       gas_assert (mips_opts.micromips);
9665       gas_assert (mips_opts.insn32);
9666       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
9667       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
9668       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
9669       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
9670       move_register (dreg, sreg);
9671       move_register (breg, treg);
9672       break;
9673
9674     case M_DMUL:
9675       dbl = 1;
9676     case M_MUL:
9677       if (mips_opts.arch == CPU_R5900)
9678         {
9679           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
9680         }
9681       else
9682         {
9683       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9684       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9685         }
9686       break;
9687
9688     case M_DMUL_I:
9689       dbl = 1;
9690     case M_MUL_I:
9691       /* The MIPS assembler some times generates shifts and adds.  I'm
9692          not trying to be that fancy. GCC should do this for us
9693          anyway.  */
9694       used_at = 1;
9695       load_register (AT, &imm_expr, dbl);
9696       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9697       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9698       break;
9699
9700     case M_DMULO_I:
9701       dbl = 1;
9702     case M_MULO_I:
9703       imm = 1;
9704       goto do_mulo;
9705
9706     case M_DMULO:
9707       dbl = 1;
9708     case M_MULO:
9709     do_mulo:
9710       start_noreorder ();
9711       used_at = 1;
9712       if (imm)
9713         load_register (AT, &imm_expr, dbl);
9714       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9715       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9716       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9717       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9718       if (mips_trap)
9719         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9720       else
9721         {
9722           if (mips_opts.micromips)
9723             micromips_label_expr (&label_expr);
9724           else
9725             label_expr.X_add_number = 8;
9726           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9727           macro_build (NULL, "nop", "");
9728           macro_build (NULL, "break", BRK_FMT, 6);
9729           if (mips_opts.micromips)
9730             micromips_add_label ();
9731         }
9732       end_noreorder ();
9733       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9734       break;
9735
9736     case M_DMULOU_I:
9737       dbl = 1;
9738     case M_MULOU_I:
9739       imm = 1;
9740       goto do_mulou;
9741
9742     case M_DMULOU:
9743       dbl = 1;
9744     case M_MULOU:
9745     do_mulou:
9746       start_noreorder ();
9747       used_at = 1;
9748       if (imm)
9749         load_register (AT, &imm_expr, dbl);
9750       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9751                    sreg, imm ? AT : treg);
9752       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9753       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9754       if (mips_trap)
9755         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9756       else
9757         {
9758           if (mips_opts.micromips)
9759             micromips_label_expr (&label_expr);
9760           else
9761             label_expr.X_add_number = 8;
9762           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9763           macro_build (NULL, "nop", "");
9764           macro_build (NULL, "break", BRK_FMT, 6);
9765           if (mips_opts.micromips)
9766             micromips_add_label ();
9767         }
9768       end_noreorder ();
9769       break;
9770
9771     case M_DROL:
9772       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9773         {
9774           if (dreg == sreg)
9775             {
9776               tempreg = AT;
9777               used_at = 1;
9778             }
9779           else
9780             {
9781               tempreg = dreg;
9782             }
9783           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9784           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9785           break;
9786         }
9787       used_at = 1;
9788       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9789       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9790       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9791       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9792       break;
9793
9794     case M_ROL:
9795       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9796         {
9797           if (dreg == sreg)
9798             {
9799               tempreg = AT;
9800               used_at = 1;
9801             }
9802           else
9803             {
9804               tempreg = dreg;
9805             }
9806           macro_build (NULL, "negu", "d,w", tempreg, treg);
9807           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
9808           break;
9809         }
9810       used_at = 1;
9811       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9812       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
9813       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
9814       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9815       break;
9816
9817     case M_DROL_I:
9818       {
9819         unsigned int rot;
9820         char *l;
9821         char *rr;
9822
9823         if (imm_expr.X_op != O_constant)
9824           as_bad (_("Improper rotate count"));
9825         rot = imm_expr.X_add_number & 0x3f;
9826         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9827           {
9828             rot = (64 - rot) & 0x3f;
9829             if (rot >= 32)
9830               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9831             else
9832               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9833             break;
9834           }
9835         if (rot == 0)
9836           {
9837             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9838             break;
9839           }
9840         l = (rot < 0x20) ? "dsll" : "dsll32";
9841         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
9842         rot &= 0x1f;
9843         used_at = 1;
9844         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
9845         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9846         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9847       }
9848       break;
9849
9850     case M_ROL_I:
9851       {
9852         unsigned int rot;
9853
9854         if (imm_expr.X_op != O_constant)
9855           as_bad (_("Improper rotate count"));
9856         rot = imm_expr.X_add_number & 0x1f;
9857         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9858           {
9859             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
9860             break;
9861           }
9862         if (rot == 0)
9863           {
9864             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9865             break;
9866           }
9867         used_at = 1;
9868         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
9869         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9870         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9871       }
9872       break;
9873
9874     case M_DROR:
9875       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9876         {
9877           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
9878           break;
9879         }
9880       used_at = 1;
9881       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9882       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
9883       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
9884       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9885       break;
9886
9887     case M_ROR:
9888       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9889         {
9890           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
9891           break;
9892         }
9893       used_at = 1;
9894       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9895       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
9896       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
9897       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9898       break;
9899
9900     case M_DROR_I:
9901       {
9902         unsigned int rot;
9903         char *l;
9904         char *rr;
9905
9906         if (imm_expr.X_op != O_constant)
9907           as_bad (_("Improper rotate count"));
9908         rot = imm_expr.X_add_number & 0x3f;
9909         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9910           {
9911             if (rot >= 32)
9912               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9913             else
9914               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9915             break;
9916           }
9917         if (rot == 0)
9918           {
9919             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9920             break;
9921           }
9922         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
9923         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
9924         rot &= 0x1f;
9925         used_at = 1;
9926         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
9927         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9928         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9929       }
9930       break;
9931
9932     case M_ROR_I:
9933       {
9934         unsigned int rot;
9935
9936         if (imm_expr.X_op != O_constant)
9937           as_bad (_("Improper rotate count"));
9938         rot = imm_expr.X_add_number & 0x1f;
9939         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9940           {
9941             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
9942             break;
9943           }
9944         if (rot == 0)
9945           {
9946             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9947             break;
9948           }
9949         used_at = 1;
9950         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
9951         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9952         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9953       }
9954       break;
9955
9956     case M_SEQ:
9957       if (sreg == 0)
9958         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
9959       else if (treg == 0)
9960         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9961       else
9962         {
9963           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9964           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9965         }
9966       break;
9967
9968     case M_SEQ_I:
9969       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9970         {
9971           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9972           break;
9973         }
9974       if (sreg == 0)
9975         {
9976           as_warn (_("Instruction %s: result is always false"),
9977                    ip->insn_mo->name);
9978           move_register (dreg, 0);
9979           break;
9980         }
9981       if (CPU_HAS_SEQ (mips_opts.arch)
9982           && -512 <= imm_expr.X_add_number
9983           && imm_expr.X_add_number < 512)
9984         {
9985           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
9986                        (int) imm_expr.X_add_number);
9987           break;
9988         }
9989       if (imm_expr.X_op == O_constant
9990           && imm_expr.X_add_number >= 0
9991           && imm_expr.X_add_number < 0x10000)
9992         {
9993           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9994         }
9995       else if (imm_expr.X_op == O_constant
9996                && imm_expr.X_add_number > -0x8000
9997                && imm_expr.X_add_number < 0)
9998         {
9999           imm_expr.X_add_number = -imm_expr.X_add_number;
10000           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10001                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10002         }
10003       else if (CPU_HAS_SEQ (mips_opts.arch))
10004         {
10005           used_at = 1;
10006           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10007           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10008           break;
10009         }
10010       else
10011         {
10012           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10013           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10014           used_at = 1;
10015         }
10016       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10017       break;
10018
10019     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
10020       s = "slt";
10021       goto sge;
10022     case M_SGEU:
10023       s = "sltu";
10024     sge:
10025       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
10026       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10027       break;
10028
10029     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
10030     case M_SGEU_I:
10031       if (imm_expr.X_op == O_constant
10032           && imm_expr.X_add_number >= -0x8000
10033           && imm_expr.X_add_number < 0x8000)
10034         {
10035           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
10036                        dreg, sreg, BFD_RELOC_LO16);
10037         }
10038       else
10039         {
10040           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10041           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
10042                        dreg, sreg, AT);
10043           used_at = 1;
10044         }
10045       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10046       break;
10047
10048     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
10049       s = "slt";
10050       goto sgt;
10051     case M_SGTU:
10052       s = "sltu";
10053     sgt:
10054       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10055       break;
10056
10057     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
10058       s = "slt";
10059       goto sgti;
10060     case M_SGTU_I:
10061       s = "sltu";
10062     sgti:
10063       used_at = 1;
10064       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10065       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10066       break;
10067
10068     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
10069       s = "slt";
10070       goto sle;
10071     case M_SLEU:
10072       s = "sltu";
10073     sle:
10074       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10075       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10076       break;
10077
10078     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
10079       s = "slt";
10080       goto slei;
10081     case M_SLEU_I:
10082       s = "sltu";
10083     slei:
10084       used_at = 1;
10085       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10086       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10087       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10088       break;
10089
10090     case M_SLT_I:
10091       if (imm_expr.X_op == O_constant
10092           && imm_expr.X_add_number >= -0x8000
10093           && imm_expr.X_add_number < 0x8000)
10094         {
10095           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10096           break;
10097         }
10098       used_at = 1;
10099       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10100       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
10101       break;
10102
10103     case M_SLTU_I:
10104       if (imm_expr.X_op == O_constant
10105           && imm_expr.X_add_number >= -0x8000
10106           && imm_expr.X_add_number < 0x8000)
10107         {
10108           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
10109                        BFD_RELOC_LO16);
10110           break;
10111         }
10112       used_at = 1;
10113       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10114       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
10115       break;
10116
10117     case M_SNE:
10118       if (sreg == 0)
10119         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
10120       else if (treg == 0)
10121         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10122       else
10123         {
10124           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10125           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10126         }
10127       break;
10128
10129     case M_SNE_I:
10130       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10131         {
10132           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10133           break;
10134         }
10135       if (sreg == 0)
10136         {
10137           as_warn (_("Instruction %s: result is always true"),
10138                    ip->insn_mo->name);
10139           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
10140                        dreg, 0, BFD_RELOC_LO16);
10141           break;
10142         }
10143       if (CPU_HAS_SEQ (mips_opts.arch)
10144           && -512 <= imm_expr.X_add_number
10145           && imm_expr.X_add_number < 512)
10146         {
10147           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
10148                        (int) imm_expr.X_add_number);
10149           break;
10150         }
10151       if (imm_expr.X_op == O_constant
10152           && imm_expr.X_add_number >= 0
10153           && imm_expr.X_add_number < 0x10000)
10154         {
10155           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10156         }
10157       else if (imm_expr.X_op == O_constant
10158                && imm_expr.X_add_number > -0x8000
10159                && imm_expr.X_add_number < 0)
10160         {
10161           imm_expr.X_add_number = -imm_expr.X_add_number;
10162           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10163                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10164         }
10165       else if (CPU_HAS_SEQ (mips_opts.arch))
10166         {
10167           used_at = 1;
10168           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10169           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
10170           break;
10171         }
10172       else
10173         {
10174           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10175           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10176           used_at = 1;
10177         }
10178       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10179       break;
10180
10181     case M_SUB_I:
10182       s = "addi";
10183       s2 = "sub";
10184       goto do_subi;
10185     case M_SUBU_I:
10186       s = "addiu";
10187       s2 = "subu";
10188       goto do_subi;
10189     case M_DSUB_I:
10190       dbl = 1;
10191       s = "daddi";
10192       s2 = "dsub";
10193       if (!mips_opts.micromips)
10194         goto do_subi;
10195       if (imm_expr.X_op == O_constant
10196           && imm_expr.X_add_number > -0x200
10197           && imm_expr.X_add_number <= 0x200)
10198         {
10199           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
10200           break;
10201         }
10202       goto do_subi_i;
10203     case M_DSUBU_I:
10204       dbl = 1;
10205       s = "daddiu";
10206       s2 = "dsubu";
10207     do_subi:
10208       if (imm_expr.X_op == O_constant
10209           && imm_expr.X_add_number > -0x8000
10210           && imm_expr.X_add_number <= 0x8000)
10211         {
10212           imm_expr.X_add_number = -imm_expr.X_add_number;
10213           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10214           break;
10215         }
10216     do_subi_i:
10217       used_at = 1;
10218       load_register (AT, &imm_expr, dbl);
10219       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
10220       break;
10221
10222     case M_TEQ_I:
10223       s = "teq";
10224       goto trap;
10225     case M_TGE_I:
10226       s = "tge";
10227       goto trap;
10228     case M_TGEU_I:
10229       s = "tgeu";
10230       goto trap;
10231     case M_TLT_I:
10232       s = "tlt";
10233       goto trap;
10234     case M_TLTU_I:
10235       s = "tltu";
10236       goto trap;
10237     case M_TNE_I:
10238       s = "tne";
10239     trap:
10240       used_at = 1;
10241       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10242       macro_build (NULL, s, "s,t", sreg, AT);
10243       break;
10244
10245     case M_TRUNCWS:
10246     case M_TRUNCWD:
10247       gas_assert (!mips_opts.micromips);
10248       gas_assert (mips_opts.isa == ISA_MIPS1);
10249       used_at = 1;
10250       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
10251       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
10252
10253       /*
10254        * Is the double cfc1 instruction a bug in the mips assembler;
10255        * or is there a reason for it?
10256        */
10257       start_noreorder ();
10258       macro_build (NULL, "cfc1", "t,G", treg, RA);
10259       macro_build (NULL, "cfc1", "t,G", treg, RA);
10260       macro_build (NULL, "nop", "");
10261       expr1.X_add_number = 3;
10262       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
10263       expr1.X_add_number = 2;
10264       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
10265       macro_build (NULL, "ctc1", "t,G", AT, RA);
10266       macro_build (NULL, "nop", "");
10267       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
10268                    dreg, sreg);
10269       macro_build (NULL, "ctc1", "t,G", treg, RA);
10270       macro_build (NULL, "nop", "");
10271       end_noreorder ();
10272       break;
10273
10274     case M_ULH_AB:
10275       s = "lb";
10276       s2 = "lbu";
10277       off = 1;
10278       goto uld_st;
10279     case M_ULHU_AB:
10280       s = "lbu";
10281       s2 = "lbu";
10282       off = 1;
10283       goto uld_st;
10284     case M_ULW_AB:
10285       s = "lwl";
10286       s2 = "lwr";
10287       offbits = (mips_opts.micromips ? 12 : 16);
10288       off = 3;
10289       goto uld_st;
10290     case M_ULD_AB:
10291       s = "ldl";
10292       s2 = "ldr";
10293       offbits = (mips_opts.micromips ? 12 : 16);
10294       off = 7;
10295       goto uld_st;
10296     case M_USH_AB:
10297       s = "sb";
10298       s2 = "sb";
10299       off = 1;
10300       ust = 1;
10301       goto uld_st;
10302     case M_USW_AB:
10303       s = "swl";
10304       s2 = "swr";
10305       offbits = (mips_opts.micromips ? 12 : 16);
10306       off = 3;
10307       ust = 1;
10308       goto uld_st;
10309     case M_USD_AB:
10310       s = "sdl";
10311       s2 = "sdr";
10312       offbits = (mips_opts.micromips ? 12 : 16);
10313       off = 7;
10314       ust = 1;
10315
10316     uld_st:
10317       large_offset = !small_offset_p (off, align, offbits);
10318       ep = &offset_expr;
10319       expr1.X_add_number = 0;
10320       if (large_offset)
10321         {
10322           used_at = 1;
10323           tempreg = AT;
10324           if (small_offset_p (0, align, 16))
10325             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
10326                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10327           else
10328             {
10329               load_address (tempreg, ep, &used_at);
10330               if (breg != 0)
10331                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10332                              tempreg, tempreg, breg);
10333             }
10334           offset_reloc[0] = BFD_RELOC_LO16;
10335           offset_reloc[1] = BFD_RELOC_UNUSED;
10336           offset_reloc[2] = BFD_RELOC_UNUSED;
10337           breg = tempreg;
10338           tempreg = treg;
10339           ep = &expr1;
10340         }
10341       else if (!ust && treg == breg)
10342         {
10343           used_at = 1;
10344           tempreg = AT;
10345         }
10346       else
10347         tempreg = treg;
10348
10349       if (off == 1)
10350         goto ulh_sh;
10351
10352       if (!target_big_endian)
10353         ep->X_add_number += off;
10354       if (offbits == 12)
10355         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
10356       else
10357         macro_build (ep, s, "t,o(b)", tempreg, -1,
10358                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10359
10360       if (!target_big_endian)
10361         ep->X_add_number -= off;
10362       else
10363         ep->X_add_number += off;
10364       if (offbits == 12)
10365         macro_build (NULL, s2, "t,~(b)",
10366                      tempreg, (int) ep->X_add_number, breg);
10367       else
10368         macro_build (ep, s2, "t,o(b)", tempreg, -1,
10369                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10370
10371       /* If necessary, move the result in tempreg to the final destination.  */
10372       if (!ust && treg != tempreg)
10373         {
10374           /* Protect second load's delay slot.  */
10375           load_delay_nop ();
10376           move_register (treg, tempreg);
10377         }
10378       break;
10379
10380     ulh_sh:
10381       used_at = 1;
10382       if (target_big_endian == ust)
10383         ep->X_add_number += off;
10384       tempreg = ust || large_offset ? treg : AT;
10385       macro_build (ep, s, "t,o(b)", tempreg, -1,
10386                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10387
10388       /* For halfword transfers we need a temporary register to shuffle
10389          bytes.  Unfortunately for M_USH_A we have none available before
10390          the next store as AT holds the base address.  We deal with this
10391          case by clobbering TREG and then restoring it as with ULH.  */
10392       tempreg = ust == large_offset ? treg : AT;
10393       if (ust)
10394         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
10395
10396       if (target_big_endian == ust)
10397         ep->X_add_number -= off;
10398       else
10399         ep->X_add_number += off;
10400       macro_build (ep, s2, "t,o(b)", tempreg, -1,
10401                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10402
10403       /* For M_USH_A re-retrieve the LSB.  */
10404       if (ust && large_offset)
10405         {
10406           if (target_big_endian)
10407             ep->X_add_number += off;
10408           else
10409             ep->X_add_number -= off;
10410           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
10411                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
10412         }
10413       /* For ULH and M_USH_A OR the LSB in.  */
10414       if (!ust || large_offset)
10415         {
10416           tempreg = !large_offset ? AT : treg;
10417           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
10418           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
10419         }
10420       break;
10421
10422     default:
10423       /* FIXME: Check if this is one of the itbl macros, since they
10424          are added dynamically.  */
10425       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
10426       break;
10427     }
10428   if (!mips_opts.at && used_at)
10429     as_bad (_("Macro used $at after \".set noat\""));
10430 }
10431
10432 /* Implement macros in mips16 mode.  */
10433
10434 static void
10435 mips16_macro (struct mips_cl_insn *ip)
10436 {
10437   int mask;
10438   int xreg, yreg, zreg, tmp;
10439   expressionS expr1;
10440   int dbl;
10441   const char *s, *s2, *s3;
10442
10443   mask = ip->insn_mo->mask;
10444
10445   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
10446   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
10447   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
10448
10449   expr1.X_op = O_constant;
10450   expr1.X_op_symbol = NULL;
10451   expr1.X_add_symbol = NULL;
10452   expr1.X_add_number = 1;
10453
10454   dbl = 0;
10455
10456   switch (mask)
10457     {
10458     default:
10459       abort ();
10460
10461     case M_DDIV_3:
10462       dbl = 1;
10463     case M_DIV_3:
10464       s = "mflo";
10465       goto do_div3;
10466     case M_DREM_3:
10467       dbl = 1;
10468     case M_REM_3:
10469       s = "mfhi";
10470     do_div3:
10471       start_noreorder ();
10472       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
10473       expr1.X_add_number = 2;
10474       macro_build (&expr1, "bnez", "x,p", yreg);
10475       macro_build (NULL, "break", "6", 7);
10476
10477       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
10478          since that causes an overflow.  We should do that as well,
10479          but I don't see how to do the comparisons without a temporary
10480          register.  */
10481       end_noreorder ();
10482       macro_build (NULL, s, "x", zreg);
10483       break;
10484
10485     case M_DIVU_3:
10486       s = "divu";
10487       s2 = "mflo";
10488       goto do_divu3;
10489     case M_REMU_3:
10490       s = "divu";
10491       s2 = "mfhi";
10492       goto do_divu3;
10493     case M_DDIVU_3:
10494       s = "ddivu";
10495       s2 = "mflo";
10496       goto do_divu3;
10497     case M_DREMU_3:
10498       s = "ddivu";
10499       s2 = "mfhi";
10500     do_divu3:
10501       start_noreorder ();
10502       macro_build (NULL, s, "0,x,y", xreg, yreg);
10503       expr1.X_add_number = 2;
10504       macro_build (&expr1, "bnez", "x,p", yreg);
10505       macro_build (NULL, "break", "6", 7);
10506       end_noreorder ();
10507       macro_build (NULL, s2, "x", zreg);
10508       break;
10509
10510     case M_DMUL:
10511       dbl = 1;
10512     case M_MUL:
10513       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
10514       macro_build (NULL, "mflo", "x", zreg);
10515       break;
10516
10517     case M_DSUBU_I:
10518       dbl = 1;
10519       goto do_subu;
10520     case M_SUBU_I:
10521     do_subu:
10522       if (imm_expr.X_op != O_constant)
10523         as_bad (_("Unsupported large constant"));
10524       imm_expr.X_add_number = -imm_expr.X_add_number;
10525       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10526       break;
10527
10528     case M_SUBU_I_2:
10529       if (imm_expr.X_op != O_constant)
10530         as_bad (_("Unsupported large constant"));
10531       imm_expr.X_add_number = -imm_expr.X_add_number;
10532       macro_build (&imm_expr, "addiu", "x,k", xreg);
10533       break;
10534
10535     case M_DSUBU_I_2:
10536       if (imm_expr.X_op != O_constant)
10537         as_bad (_("Unsupported large constant"));
10538       imm_expr.X_add_number = -imm_expr.X_add_number;
10539       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10540       break;
10541
10542     case M_BEQ:
10543       s = "cmp";
10544       s2 = "bteqz";
10545       goto do_branch;
10546     case M_BNE:
10547       s = "cmp";
10548       s2 = "btnez";
10549       goto do_branch;
10550     case M_BLT:
10551       s = "slt";
10552       s2 = "btnez";
10553       goto do_branch;
10554     case M_BLTU:
10555       s = "sltu";
10556       s2 = "btnez";
10557       goto do_branch;
10558     case M_BLE:
10559       s = "slt";
10560       s2 = "bteqz";
10561       goto do_reverse_branch;
10562     case M_BLEU:
10563       s = "sltu";
10564       s2 = "bteqz";
10565       goto do_reverse_branch;
10566     case M_BGE:
10567       s = "slt";
10568       s2 = "bteqz";
10569       goto do_branch;
10570     case M_BGEU:
10571       s = "sltu";
10572       s2 = "bteqz";
10573       goto do_branch;
10574     case M_BGT:
10575       s = "slt";
10576       s2 = "btnez";
10577       goto do_reverse_branch;
10578     case M_BGTU:
10579       s = "sltu";
10580       s2 = "btnez";
10581
10582     do_reverse_branch:
10583       tmp = xreg;
10584       xreg = yreg;
10585       yreg = tmp;
10586
10587     do_branch:
10588       macro_build (NULL, s, "x,y", xreg, yreg);
10589       macro_build (&offset_expr, s2, "p");
10590       break;
10591
10592     case M_BEQ_I:
10593       s = "cmpi";
10594       s2 = "bteqz";
10595       s3 = "x,U";
10596       goto do_branch_i;
10597     case M_BNE_I:
10598       s = "cmpi";
10599       s2 = "btnez";
10600       s3 = "x,U";
10601       goto do_branch_i;
10602     case M_BLT_I:
10603       s = "slti";
10604       s2 = "btnez";
10605       s3 = "x,8";
10606       goto do_branch_i;
10607     case M_BLTU_I:
10608       s = "sltiu";
10609       s2 = "btnez";
10610       s3 = "x,8";
10611       goto do_branch_i;
10612     case M_BLE_I:
10613       s = "slti";
10614       s2 = "btnez";
10615       s3 = "x,8";
10616       goto do_addone_branch_i;
10617     case M_BLEU_I:
10618       s = "sltiu";
10619       s2 = "btnez";
10620       s3 = "x,8";
10621       goto do_addone_branch_i;
10622     case M_BGE_I:
10623       s = "slti";
10624       s2 = "bteqz";
10625       s3 = "x,8";
10626       goto do_branch_i;
10627     case M_BGEU_I:
10628       s = "sltiu";
10629       s2 = "bteqz";
10630       s3 = "x,8";
10631       goto do_branch_i;
10632     case M_BGT_I:
10633       s = "slti";
10634       s2 = "bteqz";
10635       s3 = "x,8";
10636       goto do_addone_branch_i;
10637     case M_BGTU_I:
10638       s = "sltiu";
10639       s2 = "bteqz";
10640       s3 = "x,8";
10641
10642     do_addone_branch_i:
10643       if (imm_expr.X_op != O_constant)
10644         as_bad (_("Unsupported large constant"));
10645       ++imm_expr.X_add_number;
10646
10647     do_branch_i:
10648       macro_build (&imm_expr, s, s3, xreg);
10649       macro_build (&offset_expr, s2, "p");
10650       break;
10651
10652     case M_ABS:
10653       expr1.X_add_number = 0;
10654       macro_build (&expr1, "slti", "x,8", yreg);
10655       if (xreg != yreg)
10656         move_register (xreg, yreg);
10657       expr1.X_add_number = 2;
10658       macro_build (&expr1, "bteqz", "p");
10659       macro_build (NULL, "neg", "x,w", xreg, xreg);
10660     }
10661 }
10662
10663 /* UDI immediates.  */
10664 struct mips_immed {
10665   char          type;
10666   unsigned int  shift;
10667   unsigned long mask;
10668   const char *  desc;
10669 };
10670
10671 static const struct mips_immed mips_immed[] = {
10672   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
10673   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
10674   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
10675   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
10676   { 0,0,0,0 }
10677 };
10678
10679 /* Check whether an odd floating-point register is allowed.  */
10680 static int
10681 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
10682 {
10683   const char *s = insn->name;
10684
10685   if (insn->pinfo == INSN_MACRO)
10686     /* Let a macro pass, we'll catch it later when it is expanded.  */
10687     return 1;
10688
10689   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || (mips_opts.arch == CPU_R5900))
10690     {
10691       /* Allow odd registers for single-precision ops.  */
10692       switch (insn->pinfo & (FP_S | FP_D))
10693         {
10694         case FP_S:
10695         case 0:
10696           return 1;     /* both single precision - ok */
10697         case FP_D:
10698           return 0;     /* both double precision - fail */
10699         default:
10700           break;
10701         }
10702
10703       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
10704       s = strchr (insn->name, '.');
10705       if (argnum == 2)
10706         s = s != NULL ? strchr (s + 1, '.') : NULL;
10707       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
10708     } 
10709
10710   /* Single-precision coprocessor loads and moves are OK too.  */
10711   if ((insn->pinfo & FP_S)
10712       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
10713                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
10714     return 1;
10715
10716   return 0;
10717 }
10718
10719 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
10720    taking bits from BIT up.  */
10721 static int
10722 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
10723 {
10724   return (ep->X_op == O_constant
10725           && (ep->X_add_number & ((1 << bit) - 1)) == 0
10726           && ep->X_add_number >= min << bit
10727           && ep->X_add_number < max << bit);
10728 }
10729
10730 /* Assemble an instruction into its binary format.  If the instruction
10731    is a macro, set imm_expr, imm2_expr and offset_expr to the values
10732    associated with "I", "+I" and "A" operands respectively.  Otherwise
10733    store the value of the relocatable field (if any) in offset_expr.
10734    In both cases set offset_reloc to the relocation operators applied
10735    to offset_expr.  */
10736
10737 static void
10738 mips_ip (char *str, struct mips_cl_insn *ip)
10739 {
10740   bfd_boolean wrong_delay_slot_insns = FALSE;
10741   bfd_boolean need_delay_slot_ok = TRUE;
10742   struct mips_opcode *firstinsn = NULL;
10743   const struct mips_opcode *past;
10744   struct hash_control *hash;
10745   char *s;
10746   const char *args;
10747   char c = 0;
10748   struct mips_opcode *insn;
10749   char *argsStart;
10750   unsigned int regno, regno2;
10751   unsigned int lastregno;
10752   unsigned int destregno = 0;
10753   unsigned int lastpos = 0;
10754   unsigned int limlo, limhi;
10755   int sizelo;
10756   char *s_reset;
10757   offsetT min_range, max_range;
10758   long opend;
10759   char *name;
10760   int argnum;
10761   unsigned int rtype;
10762   char *dot;
10763   long end;
10764
10765   insn_error = NULL;
10766
10767   if (mips_opts.micromips)
10768     {
10769       hash = micromips_op_hash;
10770       past = &micromips_opcodes[bfd_micromips_num_opcodes];
10771     }
10772   else
10773     {
10774       hash = op_hash;
10775       past = &mips_opcodes[NUMOPCODES];
10776     }
10777   forced_insn_length = 0;
10778   insn = NULL;
10779
10780   /* We first try to match an instruction up to a space or to the end.  */
10781   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
10782     continue;
10783
10784   /* Make a copy of the instruction so that we can fiddle with it.  */
10785   name = alloca (end + 1);
10786   memcpy (name, str, end);
10787   name[end] = '\0';
10788
10789   for (;;)
10790     {
10791       insn = (struct mips_opcode *) hash_find (hash, name);
10792
10793       if (insn != NULL || !mips_opts.micromips)
10794         break;
10795       if (forced_insn_length)
10796         break;
10797
10798       /* See if there's an instruction size override suffix,
10799          either `16' or `32', at the end of the mnemonic proper,
10800          that defines the operation, i.e. before the first `.'
10801          character if any.  Strip it and retry.  */
10802       dot = strchr (name, '.');
10803       opend = dot != NULL ? dot - name : end;
10804       if (opend < 3)
10805         break;
10806       if (name[opend - 2] == '1' && name[opend - 1] == '6')
10807         forced_insn_length = 2;
10808       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
10809         forced_insn_length = 4;
10810       else
10811         break;
10812       memcpy (name + opend - 2, name + opend, end - opend + 1);
10813     }
10814   if (insn == NULL)
10815     {
10816       insn_error = _("Unrecognized opcode");
10817       return;
10818     }
10819
10820   /* For microMIPS instructions placed in a fixed-length branch delay slot
10821      we make up to two passes over the relevant fragment of the opcode
10822      table.  First we try instructions that meet the delay slot's length
10823      requirement.  If none matched, then we retry with the remaining ones
10824      and if one matches, then we use it and then issue an appropriate
10825      warning later on.  */
10826   argsStart = s = str + end;
10827   for (;;)
10828     {
10829       bfd_boolean delay_slot_ok;
10830       bfd_boolean size_ok;
10831       bfd_boolean ok;
10832
10833       gas_assert (strcmp (insn->name, name) == 0);
10834
10835       ok = is_opcode_valid (insn);
10836       size_ok = is_size_valid (insn);
10837       delay_slot_ok = is_delay_slot_valid (insn);
10838       if (!delay_slot_ok && !wrong_delay_slot_insns)
10839         {
10840           firstinsn = insn;
10841           wrong_delay_slot_insns = TRUE;
10842         }
10843       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
10844         {
10845           static char buf[256];
10846
10847           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
10848             {
10849               ++insn;
10850               continue;
10851             }
10852           if (wrong_delay_slot_insns && need_delay_slot_ok)
10853             {
10854               gas_assert (firstinsn);
10855               need_delay_slot_ok = FALSE;
10856               past = insn + 1;
10857               insn = firstinsn;
10858               continue;
10859             }
10860
10861           if (insn_error)
10862             return;
10863
10864           if (!ok)
10865             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
10866                      mips_cpu_info_from_arch (mips_opts.arch)->name,
10867                      mips_cpu_info_from_isa (mips_opts.isa)->name);
10868           else if (mips_opts.insn32)
10869             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
10870           else
10871             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
10872                      8 * forced_insn_length);
10873           insn_error = buf;
10874
10875           return;
10876         }
10877
10878       imm_expr.X_op = O_absent;
10879       imm2_expr.X_op = O_absent;
10880       offset_expr.X_op = O_absent;
10881       offset_reloc[0] = BFD_RELOC_UNUSED;
10882       offset_reloc[1] = BFD_RELOC_UNUSED;
10883       offset_reloc[2] = BFD_RELOC_UNUSED;
10884
10885       create_insn (ip, insn);
10886       insn_error = NULL;
10887       argnum = 1;
10888       lastregno = 0xffffffff;
10889       for (args = insn->args;; ++args)
10890         {
10891           int is_mdmx;
10892
10893           s += strspn (s, " \t");
10894           is_mdmx = 0;
10895           switch (*args)
10896             {
10897             case '\0':          /* end of args */
10898               if (*s == '\0')
10899                 return;
10900               break;
10901
10902             case '2':
10903               /* DSP 2-bit unsigned immediate in bit 11 (for standard MIPS
10904                  code) or 14 (for microMIPS code).  */
10905               my_getExpression (&imm_expr, s);
10906               check_absolute_expr (ip, &imm_expr);
10907               if ((unsigned long) imm_expr.X_add_number != 1
10908                   && (unsigned long) imm_expr.X_add_number != 3)
10909                 {
10910                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
10911                           (unsigned long) imm_expr.X_add_number);
10912                 }
10913               INSERT_OPERAND (mips_opts.micromips,
10914                               BP, *ip, imm_expr.X_add_number);
10915               imm_expr.X_op = O_absent;
10916               s = expr_end;
10917               continue;
10918
10919             case '3':
10920               /* DSP 3-bit unsigned immediate in bit 21 (for standard MIPS
10921                  code) or 13 (for microMIPS code).  */
10922               {
10923                 unsigned long mask = (mips_opts.micromips
10924                                       ? MICROMIPSOP_MASK_SA3 : OP_MASK_SA3);
10925
10926                 my_getExpression (&imm_expr, s);
10927                 check_absolute_expr (ip, &imm_expr);
10928                 if ((unsigned long) imm_expr.X_add_number > mask)
10929                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
10930                           mask, (unsigned long) imm_expr.X_add_number);
10931                 INSERT_OPERAND (mips_opts.micromips,
10932                                 SA3, *ip, imm_expr.X_add_number);
10933                 imm_expr.X_op = O_absent;
10934                 s = expr_end;
10935               }
10936               continue;
10937
10938             case '4':
10939               /* DSP 4-bit unsigned immediate in bit 21 (for standard MIPS
10940                  code) or 12 (for microMIPS code).  */
10941               {
10942                 unsigned long mask = (mips_opts.micromips
10943                                       ? MICROMIPSOP_MASK_SA4 : OP_MASK_SA4);
10944
10945                 my_getExpression (&imm_expr, s);
10946                 check_absolute_expr (ip, &imm_expr);
10947                 if ((unsigned long) imm_expr.X_add_number > mask)
10948                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
10949                           mask, (unsigned long) imm_expr.X_add_number);
10950                 INSERT_OPERAND (mips_opts.micromips,
10951                                 SA4, *ip, imm_expr.X_add_number);
10952                 imm_expr.X_op = O_absent;
10953                 s = expr_end;
10954               }
10955               continue;
10956
10957             case '5':
10958               /* DSP 8-bit unsigned immediate in bit 16 (for standard MIPS
10959                  code) or 13 (for microMIPS code).  */
10960               {
10961                 unsigned long mask = (mips_opts.micromips
10962                                       ? MICROMIPSOP_MASK_IMM8 : OP_MASK_IMM8);
10963
10964                 my_getExpression (&imm_expr, s);
10965                 check_absolute_expr (ip, &imm_expr);
10966                 if ((unsigned long) imm_expr.X_add_number > mask)
10967                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
10968                           mask, (unsigned long) imm_expr.X_add_number);
10969                 INSERT_OPERAND (mips_opts.micromips,
10970                                 IMM8, *ip, imm_expr.X_add_number);
10971                 imm_expr.X_op = O_absent;
10972                 s = expr_end;
10973               }
10974               continue;
10975
10976             case '6':
10977               /* DSP 5-bit unsigned immediate in bit 21 (for standard MIPS
10978                  code) or 16 (for microMIPS code).  */
10979               {
10980                 unsigned long mask = (mips_opts.micromips
10981                                       ? MICROMIPSOP_MASK_RS : OP_MASK_RS);
10982
10983                 my_getExpression (&imm_expr, s);
10984                 check_absolute_expr (ip, &imm_expr);
10985                 if ((unsigned long) imm_expr.X_add_number > mask)
10986                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
10987                           mask, (unsigned long) imm_expr.X_add_number);
10988                 INSERT_OPERAND (mips_opts.micromips,
10989                                 RS, *ip, imm_expr.X_add_number);
10990                 imm_expr.X_op = O_absent;
10991                 s = expr_end;
10992               }
10993               continue;
10994
10995             case '7':
10996               /* Four DSP accumulators in bit 11 (for standard MIPS code)
10997                  or 14 (for microMIPS code).  */
10998               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
10999                   && s[3] >= '0' && s[3] <= '3')
11000                 {
11001                   regno = s[3] - '0';
11002                   s += 4;
11003                   INSERT_OPERAND (mips_opts.micromips, DSPACC, *ip, regno);
11004                   continue;
11005                 }
11006               else
11007                 as_bad (_("Invalid dsp acc register"));
11008               break;
11009
11010             case '8':
11011               /* DSP 6-bit unsigned immediate in bit 11 (for standard MIPS
11012                  code) or 14 (for microMIPS code).  */
11013               {
11014                 unsigned long mask = (mips_opts.micromips
11015                                       ? MICROMIPSOP_MASK_WRDSP
11016                                       : OP_MASK_WRDSP);
11017
11018                 my_getExpression (&imm_expr, s);
11019                 check_absolute_expr (ip, &imm_expr);
11020                 if ((unsigned long) imm_expr.X_add_number > mask)
11021                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11022                           mask, (unsigned long) imm_expr.X_add_number);
11023                 INSERT_OPERAND (mips_opts.micromips,
11024                                 WRDSP, *ip, imm_expr.X_add_number);
11025                 imm_expr.X_op = O_absent;
11026                 s = expr_end;
11027               }
11028               continue;
11029
11030             case '9': /* Four DSP accumulators in bits 21,22.  */
11031               gas_assert (!mips_opts.micromips);
11032               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11033                   && s[3] >= '0' && s[3] <= '3')
11034                 {
11035                   regno = s[3] - '0';
11036                   s += 4;
11037                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
11038                   continue;
11039                 }
11040               else
11041                 as_bad (_("Invalid dsp acc register"));
11042               break;
11043
11044             case '0':
11045               /* DSP 6-bit signed immediate in bit 20 (for standard MIPS
11046                  code) or 16 (for microMIPS code).  */
11047               {
11048                 long mask = (mips_opts.micromips
11049                              ? MICROMIPSOP_MASK_DSPSFT : OP_MASK_DSPSFT);
11050
11051                 my_getExpression (&imm_expr, s);
11052                 check_absolute_expr (ip, &imm_expr);
11053                 min_range = -((mask + 1) >> 1);
11054                 max_range = ((mask + 1) >> 1) - 1;
11055                 if (imm_expr.X_add_number < min_range
11056                     || imm_expr.X_add_number > max_range)
11057                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11058                           (long) min_range, (long) max_range,
11059                           (long) imm_expr.X_add_number);
11060                 INSERT_OPERAND (mips_opts.micromips,
11061                                 DSPSFT, *ip, imm_expr.X_add_number);
11062                 imm_expr.X_op = O_absent;
11063                 s = expr_end;
11064               }
11065               continue;
11066
11067             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
11068               gas_assert (!mips_opts.micromips);
11069               my_getExpression (&imm_expr, s);
11070               check_absolute_expr (ip, &imm_expr);
11071               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
11072                 {
11073                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11074                           OP_MASK_RDDSP,
11075                           (unsigned long) imm_expr.X_add_number);
11076                 }
11077               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
11078               imm_expr.X_op = O_absent;
11079               s = expr_end;
11080               continue;
11081
11082             case ':': /* DSP 7-bit signed immediate in bit 19.  */
11083               gas_assert (!mips_opts.micromips);
11084               my_getExpression (&imm_expr, s);
11085               check_absolute_expr (ip, &imm_expr);
11086               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
11087               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
11088               if (imm_expr.X_add_number < min_range ||
11089                   imm_expr.X_add_number > max_range)
11090                 {
11091                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11092                           (long) min_range, (long) max_range,
11093                           (long) imm_expr.X_add_number);
11094                 }
11095               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
11096               imm_expr.X_op = O_absent;
11097               s = expr_end;
11098               continue;
11099
11100             case '@': /* DSP 10-bit signed immediate in bit 16.  */
11101               {
11102                 long mask = (mips_opts.micromips
11103                              ? MICROMIPSOP_MASK_IMM10 : OP_MASK_IMM10);
11104
11105                 my_getExpression (&imm_expr, s);
11106                 check_absolute_expr (ip, &imm_expr);
11107                 min_range = -((mask + 1) >> 1);
11108                 max_range = ((mask + 1) >> 1) - 1;
11109                 if (imm_expr.X_add_number < min_range
11110                     || imm_expr.X_add_number > max_range)
11111                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11112                           (long) min_range, (long) max_range,
11113                           (long) imm_expr.X_add_number);
11114                 INSERT_OPERAND (mips_opts.micromips,
11115                                 IMM10, *ip, imm_expr.X_add_number);
11116                 imm_expr.X_op = O_absent;
11117                 s = expr_end;
11118               }
11119               continue;
11120
11121             case '^': /* DSP 5-bit unsigned immediate in bit 11.  */
11122               gas_assert (mips_opts.micromips);
11123               my_getExpression (&imm_expr, s);
11124               check_absolute_expr (ip, &imm_expr);
11125               if (imm_expr.X_add_number & ~MICROMIPSOP_MASK_RD)
11126                 as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11127                         MICROMIPSOP_MASK_RD,
11128                         (unsigned long) imm_expr.X_add_number);
11129               INSERT_OPERAND (1, RD, *ip, imm_expr.X_add_number);
11130               imm_expr.X_op = O_absent;
11131               s = expr_end;
11132               continue;
11133
11134             case '!': /* MT usermode flag bit.  */
11135               gas_assert (!mips_opts.micromips);
11136               my_getExpression (&imm_expr, s);
11137               check_absolute_expr (ip, &imm_expr);
11138               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
11139                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
11140                         (unsigned long) imm_expr.X_add_number);
11141               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
11142               imm_expr.X_op = O_absent;
11143               s = expr_end;
11144               continue;
11145
11146             case '$': /* MT load high flag bit.  */
11147               gas_assert (!mips_opts.micromips);
11148               my_getExpression (&imm_expr, s);
11149               check_absolute_expr (ip, &imm_expr);
11150               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
11151                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
11152                         (unsigned long) imm_expr.X_add_number);
11153               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
11154               imm_expr.X_op = O_absent;
11155               s = expr_end;
11156               continue;
11157
11158             case '*': /* Four DSP accumulators in bits 18,19.  */
11159               gas_assert (!mips_opts.micromips);
11160               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11161                   s[3] >= '0' && s[3] <= '3')
11162                 {
11163                   regno = s[3] - '0';
11164                   s += 4;
11165                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
11166                   continue;
11167                 }
11168               else
11169                 as_bad (_("Invalid dsp/smartmips acc register"));
11170               break;
11171
11172             case '&': /* Four DSP accumulators in bits 13,14.  */
11173               gas_assert (!mips_opts.micromips);
11174               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11175                   s[3] >= '0' && s[3] <= '3')
11176                 {
11177                   regno = s[3] - '0';
11178                   s += 4;
11179                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
11180                   continue;
11181                 }
11182               else
11183                 as_bad (_("Invalid dsp/smartmips acc register"));
11184               break;
11185
11186             case '\\':          /* 3-bit bit position.  */
11187               {
11188                 unsigned long mask = (mips_opts.micromips
11189                                       ? MICROMIPSOP_MASK_3BITPOS
11190                                       : OP_MASK_3BITPOS);
11191
11192                 my_getExpression (&imm_expr, s);
11193                 check_absolute_expr (ip, &imm_expr);
11194                 if ((unsigned long) imm_expr.X_add_number > mask)
11195                   as_warn (_("Bit position for %s not in range 0..%lu (%lu)"),
11196                            ip->insn_mo->name,
11197                            mask, (unsigned long) imm_expr.X_add_number);
11198                 INSERT_OPERAND (mips_opts.micromips,
11199                                 3BITPOS, *ip, imm_expr.X_add_number);
11200                 imm_expr.X_op = O_absent;
11201                 s = expr_end;
11202               }
11203               continue;
11204
11205             case ',':
11206               ++argnum;
11207               if (*s++ == *args)
11208                 continue;
11209               s--;
11210               switch (*++args)
11211                 {
11212                 case 'r':
11213                 case 'v':
11214                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11215                   continue;
11216
11217                 case 'w':
11218                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11219                   continue;
11220
11221                 case 'W':
11222                   gas_assert (!mips_opts.micromips);
11223                   INSERT_OPERAND (0, FT, *ip, lastregno);
11224                   continue;
11225
11226                 case 'V':
11227                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11228                   continue;
11229                 }
11230               break;
11231
11232             case '(':
11233               /* Handle optional base register.
11234                  Either the base register is omitted or
11235                  we must have a left paren.  */
11236               /* This is dependent on the next operand specifier
11237                  is a base register specification.  */
11238               gas_assert (args[1] == 'b'
11239                           || (mips_opts.micromips
11240                               && args[1] == 'm'
11241                               && (args[2] == 'l' || args[2] == 'n'
11242                                   || args[2] == 's' || args[2] == 'a')));
11243               if (*s == '\0' && args[1] == 'b')
11244                 return;
11245               /* Fall through.  */
11246
11247             case ')':           /* These must match exactly.  */
11248               if (*s++ == *args)
11249                 continue;
11250               break;
11251
11252             case '+':           /* Opcode extension character.  */
11253               switch (*++args)
11254                 {
11255                 case '1':       /* UDI immediates.  */
11256                 case '2':
11257                 case '3':
11258                 case '4':
11259                   gas_assert (!mips_opts.micromips);
11260                   {
11261                     const struct mips_immed *imm = mips_immed;
11262
11263                     while (imm->type && imm->type != *args)
11264                       ++imm;
11265                     if (! imm->type)
11266                       abort ();
11267                     my_getExpression (&imm_expr, s);
11268                     check_absolute_expr (ip, &imm_expr);
11269                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11270                       {
11271                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11272                                  imm->desc ? imm->desc : ip->insn_mo->name,
11273                                  (unsigned long) imm_expr.X_add_number,
11274                                  (unsigned long) imm_expr.X_add_number);
11275                         imm_expr.X_add_number &= imm->mask;
11276                       }
11277                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11278                                         << imm->shift);
11279                     imm_expr.X_op = O_absent;
11280                     s = expr_end;
11281                   }
11282                   continue;
11283
11284                 case 'J':               /* 10-bit hypcall code.  */
11285                   gas_assert (!mips_opts.micromips);
11286                   {
11287                     unsigned long mask = OP_MASK_CODE10;
11288
11289                     my_getExpression (&imm_expr, s);
11290                     check_absolute_expr (ip, &imm_expr);
11291                     if ((unsigned long) imm_expr.X_add_number > mask)
11292                       as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11293                                ip->insn_mo->name,
11294                                mask, (unsigned long) imm_expr.X_add_number);
11295                     INSERT_OPERAND (0, CODE10, *ip, imm_expr.X_add_number);
11296                     imm_expr.X_op = O_absent;
11297                     s = expr_end;
11298                   }
11299                   continue;
11300
11301                 case 'A':               /* ins/ext position, becomes LSB.  */
11302                   limlo = 0;
11303                   limhi = 31;
11304                   goto do_lsb;
11305                 case 'E':
11306                   limlo = 32;
11307                   limhi = 63;
11308                   goto do_lsb;
11309                 do_lsb:
11310                   my_getExpression (&imm_expr, s);
11311                   check_absolute_expr (ip, &imm_expr);
11312                   if ((unsigned long) imm_expr.X_add_number < limlo
11313                       || (unsigned long) imm_expr.X_add_number > limhi)
11314                     {
11315                       as_bad (_("Improper position (%lu)"),
11316                               (unsigned long) imm_expr.X_add_number);
11317                       imm_expr.X_add_number = limlo;
11318                     }
11319                   lastpos = imm_expr.X_add_number;
11320                   INSERT_OPERAND (mips_opts.micromips,
11321                                   EXTLSB, *ip, imm_expr.X_add_number);
11322                   imm_expr.X_op = O_absent;
11323                   s = expr_end;
11324                   continue;
11325
11326                 case 'B':               /* ins size, becomes MSB.  */
11327                   limlo = 1;
11328                   limhi = 32;
11329                   goto do_msb;
11330                 case 'F':
11331                   limlo = 33;
11332                   limhi = 64;
11333                   goto do_msb;
11334                 do_msb:
11335                   my_getExpression (&imm_expr, s);
11336                   check_absolute_expr (ip, &imm_expr);
11337                   /* Check for negative input so that small negative numbers
11338                      will not succeed incorrectly.  The checks against
11339                      (pos+size) transitively check "size" itself,
11340                      assuming that "pos" is reasonable.  */
11341                   if ((long) imm_expr.X_add_number < 0
11342                       || ((unsigned long) imm_expr.X_add_number
11343                           + lastpos) < limlo
11344                       || ((unsigned long) imm_expr.X_add_number
11345                           + lastpos) > limhi)
11346                     {
11347                       as_bad (_("Improper insert size (%lu, position %lu)"),
11348                               (unsigned long) imm_expr.X_add_number,
11349                               (unsigned long) lastpos);
11350                       imm_expr.X_add_number = limlo - lastpos;
11351                     }
11352                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11353                                   lastpos + imm_expr.X_add_number - 1);
11354                   imm_expr.X_op = O_absent;
11355                   s = expr_end;
11356                   continue;
11357
11358                 case 'C':               /* ext size, becomes MSBD.  */
11359                   limlo = 1;
11360                   limhi = 32;
11361                   sizelo = 1;
11362                   goto do_msbd;
11363                 case 'G':
11364                   limlo = 33;
11365                   limhi = 64;
11366                   sizelo = 33;
11367                   goto do_msbd;
11368                 case 'H':
11369                   limlo = 33;
11370                   limhi = 64;
11371                   sizelo = 1;
11372                   goto do_msbd;
11373                 do_msbd:
11374                   my_getExpression (&imm_expr, s);
11375                   check_absolute_expr (ip, &imm_expr);
11376                   /* The checks against (pos+size) don't transitively check
11377                      "size" itself, assuming that "pos" is reasonable.
11378                      We also need to check the lower bound of "size".  */
11379                   if ((long) imm_expr.X_add_number < sizelo
11380                       || ((unsigned long) imm_expr.X_add_number
11381                           + lastpos) < limlo
11382                       || ((unsigned long) imm_expr.X_add_number
11383                           + lastpos) > limhi)
11384                     {
11385                       as_bad (_("Improper extract size (%lu, position %lu)"),
11386                               (unsigned long) imm_expr.X_add_number,
11387                               (unsigned long) lastpos);
11388                       imm_expr.X_add_number = limlo - lastpos;
11389                     }
11390                   INSERT_OPERAND (mips_opts.micromips,
11391                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11392                   imm_expr.X_op = O_absent;
11393                   s = expr_end;
11394                   continue;
11395
11396                 case 'I':
11397                   /* "+I" is like "I", except that imm2_expr is used.  */
11398                   my_getExpression (&imm2_expr, s);
11399                   if (imm2_expr.X_op != O_big
11400                       && imm2_expr.X_op != O_constant)
11401                   insn_error = _("absolute expression required");
11402                   if (HAVE_32BIT_GPRS)
11403                     normalize_constant_expr (&imm2_expr);
11404                   s = expr_end;
11405                   continue;
11406
11407                 case 't': /* Coprocessor register number.  */
11408                   gas_assert (!mips_opts.micromips);
11409                   if (s[0] == '$' && ISDIGIT (s[1]))
11410                     {
11411                       ++s;
11412                       regno = 0;
11413                       do
11414                         {
11415                           regno *= 10;
11416                           regno += *s - '0';
11417                           ++s;
11418                         }
11419                       while (ISDIGIT (*s));
11420                       if (regno > 31)
11421                         as_bad (_("Invalid register number (%d)"), regno);
11422                       else
11423                         {
11424                           INSERT_OPERAND (0, RT, *ip, regno);
11425                           continue;
11426                         }
11427                     }
11428                   else
11429                     as_bad (_("Invalid coprocessor 0 register number"));
11430                   break;
11431
11432                 case 'x':
11433                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11434                      is not in the valid range.  */
11435                   gas_assert (!mips_opts.micromips);
11436                   my_getExpression (&imm_expr, s);
11437                   check_absolute_expr (ip, &imm_expr);
11438                   if ((unsigned) imm_expr.X_add_number > 31)
11439                     {
11440                       as_bad (_("Improper bit index (%lu)"),
11441                               (unsigned long) imm_expr.X_add_number);
11442                       imm_expr.X_add_number = 0;
11443                     }
11444                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11445                   imm_expr.X_op = O_absent;
11446                   s = expr_end;
11447                   continue;
11448
11449                 case 'X':
11450                   /* bbit[01] bit index when bbit is used but we generate
11451                      bbit[01]32 because the index is over 32.  Move to the
11452                      next candidate if index is not in the valid range.  */
11453                   gas_assert (!mips_opts.micromips);
11454                   my_getExpression (&imm_expr, s);
11455                   check_absolute_expr (ip, &imm_expr);
11456                   if ((unsigned) imm_expr.X_add_number < 32
11457                       || (unsigned) imm_expr.X_add_number > 63)
11458                     break;
11459                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11460                   imm_expr.X_op = O_absent;
11461                   s = expr_end;
11462                   continue;
11463
11464                 case 'p':
11465                   /* cins, cins32, exts and exts32 position field.  Give error
11466                      if it's not in the valid range.  */
11467                   gas_assert (!mips_opts.micromips);
11468                   my_getExpression (&imm_expr, s);
11469                   check_absolute_expr (ip, &imm_expr);
11470                   if ((unsigned) imm_expr.X_add_number > 31)
11471                     {
11472                       as_bad (_("Improper position (%lu)"),
11473                               (unsigned long) imm_expr.X_add_number);
11474                       imm_expr.X_add_number = 0;
11475                     }
11476                   lastpos = imm_expr.X_add_number;
11477                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
11478                   imm_expr.X_op = O_absent;
11479                   s = expr_end;
11480                   continue;
11481
11482                 case 'P':
11483                   /* cins, cins32, exts and exts32 position field.  Move to
11484                      the next candidate if it's not in the valid range.  */
11485                   gas_assert (!mips_opts.micromips);
11486                   my_getExpression (&imm_expr, s);
11487                   check_absolute_expr (ip, &imm_expr);
11488                   if ((unsigned) imm_expr.X_add_number < 32
11489                       || (unsigned) imm_expr.X_add_number > 63)
11490                     break;
11491                   lastpos = imm_expr.X_add_number;
11492                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
11493                   imm_expr.X_op = O_absent;
11494                   s = expr_end;
11495                   continue;
11496
11497                 case 's':
11498                   /* cins32 and exts32 length-minus-one field.  */
11499                   gas_assert (!mips_opts.micromips);
11500                   my_getExpression (&imm_expr, s);
11501                   check_absolute_expr (ip, &imm_expr);
11502                   if ((unsigned long) imm_expr.X_add_number > 31
11503                       || (unsigned long) imm_expr.X_add_number + lastpos > 31)
11504                     {
11505                       as_bad (_("Improper size (%lu)"),
11506                               (unsigned long) imm_expr.X_add_number);
11507                       imm_expr.X_add_number = 0;
11508                     }
11509                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11510                   imm_expr.X_op = O_absent;
11511                   s = expr_end;
11512                   continue;
11513
11514                 case 'S':
11515                   /* cins/exts length-minus-one field.  */
11516                   gas_assert (!mips_opts.micromips);
11517                   my_getExpression (&imm_expr, s);
11518                   check_absolute_expr (ip, &imm_expr);
11519                   if ((unsigned long) imm_expr.X_add_number > 31
11520                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
11521                     {
11522                       as_bad (_("Improper size (%lu)"),
11523                               (unsigned long) imm_expr.X_add_number);
11524                       imm_expr.X_add_number = 0;
11525                     }
11526                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11527                   imm_expr.X_op = O_absent;
11528                   s = expr_end;
11529                   continue;
11530
11531                 case 'Q':
11532                   /* seqi/snei immediate field.  */
11533                   gas_assert (!mips_opts.micromips);
11534                   my_getExpression (&imm_expr, s);
11535                   check_absolute_expr (ip, &imm_expr);
11536                   if ((long) imm_expr.X_add_number < -512
11537                       || (long) imm_expr.X_add_number >= 512)
11538                     {
11539                       as_bad (_("Improper immediate (%ld)"),
11540                                (long) imm_expr.X_add_number);
11541                       imm_expr.X_add_number = 0;
11542                     }
11543                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
11544                   imm_expr.X_op = O_absent;
11545                   s = expr_end;
11546                   continue;
11547
11548                 case 'a': /* 8-bit signed offset in bit 6 */
11549                   gas_assert (!mips_opts.micromips);
11550                   my_getExpression (&imm_expr, s);
11551                   check_absolute_expr (ip, &imm_expr);
11552                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
11553                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
11554                   if (imm_expr.X_add_number < min_range
11555                       || imm_expr.X_add_number > max_range)
11556                     {
11557                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11558                               (long) min_range, (long) max_range,
11559                               (long) imm_expr.X_add_number);
11560                     }
11561                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
11562                   imm_expr.X_op = O_absent;
11563                   s = expr_end;
11564                   continue;
11565
11566                 case 'b': /* 8-bit signed offset in bit 3 */
11567                   gas_assert (!mips_opts.micromips);
11568                   my_getExpression (&imm_expr, s);
11569                   check_absolute_expr (ip, &imm_expr);
11570                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
11571                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
11572                   if (imm_expr.X_add_number < min_range
11573                       || imm_expr.X_add_number > max_range)
11574                     {
11575                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11576                               (long) min_range, (long) max_range,
11577                               (long) imm_expr.X_add_number);
11578                     }
11579                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
11580                   imm_expr.X_op = O_absent;
11581                   s = expr_end;
11582                   continue;
11583
11584                 case 'c': /* 9-bit signed offset in bit 6 */
11585                   gas_assert (!mips_opts.micromips);
11586                   my_getExpression (&imm_expr, s);
11587                   check_absolute_expr (ip, &imm_expr);
11588                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
11589                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
11590                   /* We check the offset range before adjusted.  */
11591                   min_range <<= 4;
11592                   max_range <<= 4;
11593                   if (imm_expr.X_add_number < min_range
11594                       || imm_expr.X_add_number > max_range)
11595                     {
11596                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11597                               (long) min_range, (long) max_range,
11598                               (long) imm_expr.X_add_number);
11599                     }
11600                   if (imm_expr.X_add_number & 0xf)
11601                     {
11602                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
11603                               (long) imm_expr.X_add_number);
11604                     }
11605                   /* Right shift 4 bits to adjust the offset operand.  */
11606                   INSERT_OPERAND (0, OFFSET_C, *ip,
11607                                   imm_expr.X_add_number >> 4);
11608                   imm_expr.X_op = O_absent;
11609                   s = expr_end;
11610                   continue;
11611
11612                 case 'z':
11613                   gas_assert (!mips_opts.micromips);
11614                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
11615                     break;
11616                   if (regno == AT && mips_opts.at)
11617                     {
11618                       if (mips_opts.at == ATREG)
11619                         as_warn (_("used $at without \".set noat\""));
11620                       else
11621                         as_warn (_("used $%u with \".set at=$%u\""),
11622                                  regno, mips_opts.at);
11623                     }
11624                   INSERT_OPERAND (0, RZ, *ip, regno);
11625                   continue;
11626
11627                 case 'Z':
11628                   gas_assert (!mips_opts.micromips);
11629                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
11630                     break;
11631                   INSERT_OPERAND (0, FZ, *ip, regno);
11632                   continue;
11633
11634                 case 'i':
11635                   goto jump;
11636
11637                 case 'j':
11638                   {
11639                     int shift = 8;
11640                     size_t i;
11641                     bfd_reloc_code_real_type r[3];
11642
11643                     /* Check whether there is only a single bracketed expression
11644                        left.  If so, it must be the base register and the
11645                        constant must be zero.  */
11646                     if (*s == '(' && strchr (s + 1, '(') == 0)
11647                       continue;
11648
11649                     /* If this value won't fit into the offset, then go find
11650                        a macro that will generate a 16- or 32-bit offset code
11651                        pattern.  */
11652                     i = my_getSmallExpression (&imm_expr, r, s);
11653                     if ((i == 0 && (imm_expr.X_op != O_constant
11654                                     || imm_expr.X_add_number >= 1 << shift
11655                                     || imm_expr.X_add_number < -1 << shift))
11656                         || i > 0)
11657                       {
11658                         imm_expr.X_op = O_absent;
11659                         break;
11660                       }
11661                     INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, *ip,
11662                                     imm_expr.X_add_number);
11663                     imm_expr.X_op = O_absent;
11664                     s = expr_end;
11665                   }
11666                   continue;
11667
11668                 default:
11669                   as_bad (_("Internal error: bad %s opcode "
11670                             "(unknown extension operand type `+%c'): %s %s"),
11671                           mips_opts.micromips ? "microMIPS" : "MIPS",
11672                           *args, insn->name, insn->args);
11673                   /* Further processing is fruitless.  */
11674                   return;
11675                 }
11676               break;
11677
11678             case '.':           /* 10-bit offset.  */
11679               gas_assert (mips_opts.micromips);
11680             case '~':           /* 12-bit offset.  */
11681               {
11682                 int shift = *args == '.' ? 9 : 11;
11683                 size_t i;
11684                 bfd_reloc_code_real_type r[3];
11685
11686                 /* Check whether there is only a single bracketed expression
11687                    left.  If so, it must be the base register and the
11688                    constant must be zero.  */
11689                 if (*s == '(' && strchr (s + 1, '(') == 0)
11690                   continue;
11691
11692                 /* If this value won't fit into the offset, then go find
11693                    a macro that will generate a 16- or 32-bit offset code
11694                    pattern.  */
11695                 i = my_getSmallExpression (&imm_expr, r, s);
11696                 if ((i == 0 && (imm_expr.X_op != O_constant
11697                                 || imm_expr.X_add_number >= 1 << shift
11698                                 || imm_expr.X_add_number < -1 << shift))
11699                     || i > 0)
11700                   {
11701                     imm_expr.X_op = O_absent;
11702                     break;
11703                   }
11704                 if (shift == 9)
11705                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
11706                 else
11707                   INSERT_OPERAND (mips_opts.micromips,
11708                                   OFFSET12, *ip, imm_expr.X_add_number);
11709                 imm_expr.X_op = O_absent;
11710                 s = expr_end;
11711               }
11712               continue;
11713
11714             case '<':           /* must be at least one digit */
11715               /*
11716                * According to the manual, if the shift amount is greater
11717                * than 31 or less than 0, then the shift amount should be
11718                * mod 32.  In reality the mips assembler issues an error.
11719                * We issue a warning and mask out all but the low 5 bits.
11720                */
11721               my_getExpression (&imm_expr, s);
11722               check_absolute_expr (ip, &imm_expr);
11723               if ((unsigned long) imm_expr.X_add_number > 31)
11724                 as_warn (_("Improper shift amount (%lu)"),
11725                          (unsigned long) imm_expr.X_add_number);
11726               INSERT_OPERAND (mips_opts.micromips,
11727                               SHAMT, *ip, imm_expr.X_add_number);
11728               imm_expr.X_op = O_absent;
11729               s = expr_end;
11730               continue;
11731
11732             case '>':           /* shift amount minus 32 */
11733               my_getExpression (&imm_expr, s);
11734               check_absolute_expr (ip, &imm_expr);
11735               if ((unsigned long) imm_expr.X_add_number < 32
11736                   || (unsigned long) imm_expr.X_add_number > 63)
11737                 break;
11738               INSERT_OPERAND (mips_opts.micromips,
11739                               SHAMT, *ip, imm_expr.X_add_number - 32);
11740               imm_expr.X_op = O_absent;
11741               s = expr_end;
11742               continue;
11743
11744             case 'k':           /* CACHE code.  */
11745             case 'h':           /* PREFX code.  */
11746             case '1':           /* SYNC type.  */
11747               my_getExpression (&imm_expr, s);
11748               check_absolute_expr (ip, &imm_expr);
11749               if ((unsigned long) imm_expr.X_add_number > 31)
11750                 as_warn (_("Invalid value for `%s' (%lu)"),
11751                          ip->insn_mo->name,
11752                          (unsigned long) imm_expr.X_add_number);
11753               switch (*args)
11754                 {
11755                 case 'k':
11756                   if (mips_fix_cn63xxp1
11757                       && !mips_opts.micromips
11758                       && strcmp ("pref", insn->name) == 0)
11759                     switch (imm_expr.X_add_number)
11760                       {
11761                       case 5:
11762                       case 25:
11763                       case 26:
11764                       case 27:
11765                       case 28:
11766                       case 29:
11767                       case 30:
11768                       case 31:  /* These are ok.  */
11769                         break;
11770
11771                       default:  /* The rest must be changed to 28.  */
11772                         imm_expr.X_add_number = 28;
11773                         break;
11774                       }
11775                   INSERT_OPERAND (mips_opts.micromips,
11776                                   CACHE, *ip, imm_expr.X_add_number);
11777                   break;
11778                 case 'h':
11779                   INSERT_OPERAND (mips_opts.micromips,
11780                                   PREFX, *ip, imm_expr.X_add_number);
11781                   break;
11782                 case '1':
11783                   INSERT_OPERAND (mips_opts.micromips,
11784                                   STYPE, *ip, imm_expr.X_add_number);
11785                   break;
11786                 }
11787               imm_expr.X_op = O_absent;
11788               s = expr_end;
11789               continue;
11790
11791             case 'c':           /* BREAK code.  */
11792               {
11793                 unsigned long mask = (mips_opts.micromips
11794                                       ? MICROMIPSOP_MASK_CODE
11795                                       : OP_MASK_CODE);
11796
11797                 my_getExpression (&imm_expr, s);
11798                 check_absolute_expr (ip, &imm_expr);
11799                 if ((unsigned long) imm_expr.X_add_number > mask)
11800                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11801                            ip->insn_mo->name,
11802                            mask, (unsigned long) imm_expr.X_add_number);
11803                 INSERT_OPERAND (mips_opts.micromips,
11804                                 CODE, *ip, imm_expr.X_add_number);
11805                 imm_expr.X_op = O_absent;
11806                 s = expr_end;
11807               }
11808               continue;
11809
11810             case 'q':           /* Lower BREAK code.  */
11811               {
11812                 unsigned long mask = (mips_opts.micromips
11813                                       ? MICROMIPSOP_MASK_CODE2
11814                                       : OP_MASK_CODE2);
11815
11816                 my_getExpression (&imm_expr, s);
11817                 check_absolute_expr (ip, &imm_expr);
11818                 if ((unsigned long) imm_expr.X_add_number > mask)
11819                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
11820                            ip->insn_mo->name,
11821                            mask, (unsigned long) imm_expr.X_add_number);
11822                 INSERT_OPERAND (mips_opts.micromips,
11823                                 CODE2, *ip, imm_expr.X_add_number);
11824                 imm_expr.X_op = O_absent;
11825                 s = expr_end;
11826               }
11827               continue;
11828
11829             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
11830               {
11831                 unsigned long mask = (mips_opts.micromips
11832                                       ? MICROMIPSOP_MASK_CODE10
11833                                       : OP_MASK_CODE20);
11834
11835                 my_getExpression (&imm_expr, s);
11836                 check_absolute_expr (ip, &imm_expr);
11837                 if ((unsigned long) imm_expr.X_add_number > mask)
11838                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11839                            ip->insn_mo->name,
11840                            mask, (unsigned long) imm_expr.X_add_number);
11841                 if (mips_opts.micromips)
11842                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
11843                 else
11844                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
11845                 imm_expr.X_op = O_absent;
11846                 s = expr_end;
11847               }
11848               continue;
11849
11850             case 'C':           /* 25- or 23-bit coprocessor code.  */
11851               {
11852                 unsigned long mask = (mips_opts.micromips
11853                                       ? MICROMIPSOP_MASK_COPZ
11854                                       : OP_MASK_COPZ);
11855
11856                 my_getExpression (&imm_expr, s);
11857                 check_absolute_expr (ip, &imm_expr);
11858                 if ((unsigned long) imm_expr.X_add_number > mask)
11859                   as_warn (_("Coproccesor code > %u bits (%lu)"),
11860                            mips_opts.micromips ? 23U : 25U,
11861                            (unsigned long) imm_expr.X_add_number);
11862                 INSERT_OPERAND (mips_opts.micromips,
11863                                 COPZ, *ip, imm_expr.X_add_number);
11864                 imm_expr.X_op = O_absent;
11865                 s = expr_end;
11866               }
11867               continue;
11868
11869             case 'J':           /* 19-bit WAIT code.  */
11870               gas_assert (!mips_opts.micromips);
11871               my_getExpression (&imm_expr, s);
11872               check_absolute_expr (ip, &imm_expr);
11873               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
11874                 {
11875                   as_warn (_("Illegal 19-bit code (%lu)"),
11876                            (unsigned long) imm_expr.X_add_number);
11877                   imm_expr.X_add_number &= OP_MASK_CODE19;
11878                 }
11879               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
11880               imm_expr.X_op = O_absent;
11881               s = expr_end;
11882               continue;
11883
11884             case 'P':           /* Performance register.  */
11885               gas_assert (!mips_opts.micromips);
11886               my_getExpression (&imm_expr, s);
11887               check_absolute_expr (ip, &imm_expr);
11888               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
11889                 as_warn (_("Invalid performance register (%lu)"),
11890                          (unsigned long) imm_expr.X_add_number);
11891               if (imm_expr.X_add_number != 0 && mips_opts.arch == CPU_R5900
11892                 && (!strcmp(insn->name,"mfps") || !strcmp(insn->name,"mtps")))
11893                 as_warn (_("Invalid performance register (%lu)"),
11894                   (unsigned long) imm_expr.X_add_number);
11895               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
11896               imm_expr.X_op = O_absent;
11897               s = expr_end;
11898               continue;
11899
11900             case 'G':           /* Coprocessor destination register.  */
11901               {
11902                 unsigned long opcode = ip->insn_opcode;
11903                 unsigned long mask;
11904                 unsigned int types;
11905                 int cop0;
11906
11907                 if (mips_opts.micromips)
11908                   {
11909                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
11910                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
11911                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
11912                     opcode &= mask;
11913                     switch (opcode)
11914                       {
11915                       case 0x000000fc:                          /* mfc0  */
11916                       case 0x000002fc:                          /* mtc0  */
11917                       case 0x580000fc:                          /* dmfc0 */
11918                       case 0x580002fc:                          /* dmtc0 */
11919                         cop0 = 1;
11920                         break;
11921                       default:
11922                         cop0 = 0;
11923                         break;
11924                       }
11925                   }
11926                 else
11927                   {
11928                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
11929                     cop0 = opcode == OP_OP_COP0;
11930                   }
11931                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
11932                 ok = reg_lookup (&s, types, &regno);
11933                 if (mips_opts.micromips)
11934                   INSERT_OPERAND (1, RS, *ip, regno);
11935                 else
11936                   INSERT_OPERAND (0, RD, *ip, regno);
11937                 if (ok)
11938                   {
11939                     lastregno = regno;
11940                     continue;
11941                   }
11942               }
11943               break;
11944
11945             case 'y':           /* ALNV.PS source register.  */
11946               gas_assert (mips_opts.micromips);
11947               goto do_reg;
11948             case 'x':           /* Ignore register name.  */
11949             case 'U':           /* Destination register (CLO/CLZ).  */
11950             case 'g':           /* Coprocessor destination register.  */
11951               gas_assert (!mips_opts.micromips);
11952             case 'b':           /* Base register.  */
11953             case 'd':           /* Destination register.  */
11954             case 's':           /* Source register.  */
11955             case 't':           /* Target register.  */
11956             case 'r':           /* Both target and source.  */
11957             case 'v':           /* Both dest and source.  */
11958             case 'w':           /* Both dest and target.  */
11959             case 'E':           /* Coprocessor target register.  */
11960             case 'K':           /* RDHWR destination register.  */
11961             case 'z':           /* Must be zero register.  */
11962             do_reg:
11963               s_reset = s;
11964               if (*args == 'E' || *args == 'K')
11965                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
11966               else
11967                 {
11968                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
11969                   if (regno == AT && mips_opts.at)
11970                     {
11971                       if (mips_opts.at == ATREG)
11972                         as_warn (_("Used $at without \".set noat\""));
11973                       else
11974                         as_warn (_("Used $%u with \".set at=$%u\""),
11975                                  regno, mips_opts.at);
11976                     }
11977                 }
11978               if (ok)
11979                 {
11980                   c = *args;
11981                   if (*s == ' ')
11982                     ++s;
11983                   if (args[1] != *s)
11984                     {
11985                       if (c == 'r' || c == 'v' || c == 'w')
11986                         {
11987                           regno = lastregno;
11988                           s = s_reset;
11989                           ++args;
11990                         }
11991                     }
11992                   /* 'z' only matches $0.  */
11993                   if (c == 'z' && regno != 0)
11994                     break;
11995
11996                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
11997                     {
11998                       if (regno == lastregno)
11999                         {
12000                           insn_error
12001                             = _("Source and destination must be different");
12002                           continue;
12003                         }
12004                       if (regno == 31 && lastregno == 0xffffffff)
12005                         {
12006                           insn_error
12007                             = _("A destination register must be supplied");
12008                           continue;
12009                         }
12010                     }
12011                   /* Now that we have assembled one operand, we use the args
12012                      string to figure out where it goes in the instruction.  */
12013                   switch (c)
12014                     {
12015                     case 'r':
12016                     case 's':
12017                     case 'v':
12018                     case 'b':
12019                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
12020                       break;
12021
12022                     case 'K':
12023                       if (mips_opts.micromips)
12024                         INSERT_OPERAND (1, RS, *ip, regno);
12025                       else
12026                         INSERT_OPERAND (0, RD, *ip, regno);
12027                       break;
12028
12029                     case 'd':
12030                     case 'g':
12031                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
12032                       break;
12033
12034                     case 'U':
12035                       gas_assert (!mips_opts.micromips);
12036                       INSERT_OPERAND (0, RD, *ip, regno);
12037                       INSERT_OPERAND (0, RT, *ip, regno);
12038                       break;
12039
12040                     case 'w':
12041                     case 't':
12042                     case 'E':
12043                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
12044                       break;
12045
12046                     case 'y':
12047                       gas_assert (mips_opts.micromips);
12048                       INSERT_OPERAND (1, RS3, *ip, regno);
12049                       break;
12050
12051                     case 'x':
12052                       /* This case exists because on the r3000 trunc
12053                          expands into a macro which requires a gp
12054                          register.  On the r6000 or r4000 it is
12055                          assembled into a single instruction which
12056                          ignores the register.  Thus the insn version
12057                          is MIPS_ISA2 and uses 'x', and the macro
12058                          version is MIPS_ISA1 and uses 't'.  */
12059                       break;
12060
12061                     case 'z':
12062                       /* This case is for the div instruction, which
12063                          acts differently if the destination argument
12064                          is $0.  This only matches $0, and is checked
12065                          outside the switch.  */
12066                       break;
12067                     }
12068                   lastregno = regno;
12069                   continue;
12070                 }
12071               switch (*args++)
12072                 {
12073                 case 'r':
12074                 case 'v':
12075                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
12076                   continue;
12077
12078                 case 'w':
12079                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
12080                   continue;
12081                 }
12082               break;
12083
12084             case 'O':           /* MDMX alignment immediate constant.  */
12085               gas_assert (!mips_opts.micromips);
12086               my_getExpression (&imm_expr, s);
12087               check_absolute_expr (ip, &imm_expr);
12088               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
12089                 as_warn (_("Improper align amount (%ld), using low bits"),
12090                          (long) imm_expr.X_add_number);
12091               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
12092               imm_expr.X_op = O_absent;
12093               s = expr_end;
12094               continue;
12095
12096             case 'Q':           /* MDMX vector, element sel, or const.  */
12097               if (s[0] != '$')
12098                 {
12099                   /* MDMX Immediate.  */
12100                   gas_assert (!mips_opts.micromips);
12101                   my_getExpression (&imm_expr, s);
12102                   check_absolute_expr (ip, &imm_expr);
12103                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
12104                     as_warn (_("Invalid MDMX Immediate (%ld)"),
12105                              (long) imm_expr.X_add_number);
12106                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
12107                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12108                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
12109                   else
12110                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
12111                   imm_expr.X_op = O_absent;
12112                   s = expr_end;
12113                   continue;
12114                 }
12115               /* Not MDMX Immediate.  Fall through.  */
12116             case 'X':           /* MDMX destination register.  */
12117             case 'Y':           /* MDMX source register.  */
12118             case 'Z':           /* MDMX target register.  */
12119               is_mdmx = !(insn->membership & INSN_5400);
12120             case 'W':
12121               gas_assert (!mips_opts.micromips);
12122             case 'D':           /* Floating point destination register.  */
12123             case 'S':           /* Floating point source register.  */
12124             case 'T':           /* Floating point target register.  */
12125             case 'R':           /* Floating point source register.  */
12126             case 'V':
12127               rtype = RTYPE_FPU;
12128               if (is_mdmx
12129                   || ((mips_opts.ase & ASE_MDMX)
12130                       && (ip->insn_mo->pinfo & FP_D)
12131                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
12132                                                 | INSN_COPROC_MEMORY_DELAY
12133                                                 | INSN_LOAD_COPROC_DELAY
12134                                                 | INSN_LOAD_MEMORY_DELAY
12135                                                 | INSN_STORE_MEMORY))))
12136                 rtype |= RTYPE_VEC;
12137               s_reset = s;
12138               if (reg_lookup (&s, rtype, &regno))
12139                 {
12140                   if ((regno & 1) != 0
12141                       && HAVE_32BIT_FPRS
12142                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
12143                     as_warn (_("Float register should be even, was %d"),
12144                              regno);
12145
12146                   c = *args;
12147                   if (*s == ' ')
12148                     ++s;
12149                   if (args[1] != *s)
12150                     {
12151                       if (c == 'V' || c == 'W')
12152                         {
12153                           regno = lastregno;
12154                           s = s_reset;
12155                           ++args;
12156                         }
12157                     }
12158                   switch (c)
12159                     {
12160                     case 'D':
12161                     case 'X':
12162                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
12163                       break;
12164
12165                     case 'V':
12166                     case 'S':
12167                     case 'Y':
12168                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
12169                       break;
12170
12171                     case 'Q':
12172                       /* This is like 'Z', but also needs to fix the MDMX
12173                          vector/scalar select bits.  Note that the
12174                          scalar immediate case is handled above.  */
12175                       if ((ip->insn_mo->membership & INSN_5400)
12176                           && strcmp (insn->name, "rzu.ob") == 0)
12177                         as_bad (_("Operand %d of `%s' must be an immediate"),
12178                                 argnum, ip->insn_mo->name);
12179
12180                       if (*s == '[')
12181                         {
12182                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
12183                           int max_el = (is_qh ? 3 : 7);
12184                           s++;
12185                           my_getExpression(&imm_expr, s);
12186                           check_absolute_expr (ip, &imm_expr);
12187                           s = expr_end;
12188                           if (imm_expr.X_add_number > max_el)
12189                             as_bad (_("Bad element selector %ld"),
12190                                     (long) imm_expr.X_add_number);
12191                           imm_expr.X_add_number &= max_el;
12192                           ip->insn_opcode |= (imm_expr.X_add_number
12193                                               << (OP_SH_VSEL +
12194                                                   (is_qh ? 2 : 1)));
12195                           imm_expr.X_op = O_absent;
12196                           if (*s != ']')
12197                             as_warn (_("Expecting ']' found '%s'"), s);
12198                           else
12199                             s++;
12200                         }
12201                       else
12202                         {
12203                           if ((ip->insn_mo->membership & INSN_5400)
12204                               && (strcmp (insn->name, "sll.ob") == 0
12205                                   || strcmp (insn->name, "srl.ob") == 0))
12206                             as_bad (_("Operand %d of `%s' must be scalar"),
12207                                     argnum, ip->insn_mo->name);
12208
12209                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12210                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
12211                                                 << OP_SH_VSEL);
12212                           else
12213                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
12214                                                 OP_SH_VSEL);
12215                         }
12216                       /* Fall through.  */
12217                     case 'W':
12218                     case 'T':
12219                     case 'Z':
12220                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
12221                       break;
12222
12223                     case 'R':
12224                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
12225                       break;
12226                     }
12227                   lastregno = regno;
12228                   continue;
12229                 }
12230
12231               switch (*args++)
12232                 {
12233                 case 'V':
12234                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
12235                   continue;
12236
12237                 case 'W':
12238                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
12239                   continue;
12240                 }
12241               break;
12242
12243             case 'I':
12244               my_getExpression (&imm_expr, s);
12245               if (imm_expr.X_op != O_big
12246                   && imm_expr.X_op != O_constant)
12247                 insn_error = _("absolute expression required");
12248               if (HAVE_32BIT_GPRS)
12249                 normalize_constant_expr (&imm_expr);
12250               s = expr_end;
12251               continue;
12252
12253             case 'A':
12254               my_getSmallExpression (&offset_expr, offset_reloc, s);
12255               if (offset_expr.X_op == O_register)
12256                 {
12257                   /* Assume that the offset has been elided and that what
12258                      we saw was a base register.  The match will fail later
12259                      if that assumption turns out to be wrong.  */
12260                   offset_expr.X_op = O_constant;
12261                   offset_expr.X_add_number = 0;
12262                 }
12263               else
12264                 {
12265                   normalize_address_expr (&offset_expr);
12266                   s = expr_end;
12267                 }
12268               continue;
12269
12270             case 'F':
12271             case 'L':
12272             case 'f':
12273             case 'l':
12274               {
12275                 int f64;
12276                 int using_gprs;
12277                 char *save_in;
12278                 char *err;
12279                 unsigned char temp[8];
12280                 int len;
12281                 unsigned int length;
12282                 segT seg;
12283                 subsegT subseg;
12284                 char *p;
12285
12286                 /* These only appear as the last operand in an
12287                    instruction, and every instruction that accepts
12288                    them in any variant accepts them in all variants.
12289                    This means we don't have to worry about backing out
12290                    any changes if the instruction does not match.
12291
12292                    The difference between them is the size of the
12293                    floating point constant and where it goes.  For 'F'
12294                    and 'L' the constant is 64 bits; for 'f' and 'l' it
12295                    is 32 bits.  Where the constant is placed is based
12296                    on how the MIPS assembler does things:
12297                     F -- .rdata
12298                     L -- .lit8
12299                     f -- immediate value
12300                     l -- .lit4
12301
12302                     The .lit4 and .lit8 sections are only used if
12303                     permitted by the -G argument.
12304
12305                     The code below needs to know whether the target register
12306                     is 32 or 64 bits wide.  It relies on the fact 'f' and
12307                     'F' are used with GPR-based instructions and 'l' and
12308                     'L' are used with FPR-based instructions.  */
12309
12310                 f64 = *args == 'F' || *args == 'L';
12311                 using_gprs = *args == 'F' || *args == 'f';
12312
12313                 save_in = input_line_pointer;
12314                 input_line_pointer = s;
12315                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12316                 length = len;
12317                 s = input_line_pointer;
12318                 input_line_pointer = save_in;
12319                 if (err != NULL && *err != '\0')
12320                   {
12321                     as_bad (_("Bad floating point constant: %s"), err);
12322                     memset (temp, '\0', sizeof temp);
12323                     length = f64 ? 8 : 4;
12324                   }
12325
12326                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12327
12328                 if (*args == 'f'
12329                     || (*args == 'l'
12330                         && (g_switch_value < 4
12331                             || (temp[0] == 0 && temp[1] == 0)
12332                             || (temp[2] == 0 && temp[3] == 0))))
12333                   {
12334                     imm_expr.X_op = O_constant;
12335                     if (!target_big_endian)
12336                       imm_expr.X_add_number = bfd_getl32 (temp);
12337                     else
12338                       imm_expr.X_add_number = bfd_getb32 (temp);
12339                   }
12340                 else if (length > 4
12341                          && !mips_disable_float_construction
12342                          /* Constants can only be constructed in GPRs and
12343                             copied to FPRs if the GPRs are at least as wide
12344                             as the FPRs.  Force the constant into memory if
12345                             we are using 64-bit FPRs but the GPRs are only
12346                             32 bits wide.  */
12347                          && (using_gprs
12348                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12349                          && ((temp[0] == 0 && temp[1] == 0)
12350                              || (temp[2] == 0 && temp[3] == 0))
12351                          && ((temp[4] == 0 && temp[5] == 0)
12352                              || (temp[6] == 0 && temp[7] == 0)))
12353                   {
12354                     /* The value is simple enough to load with a couple of
12355                        instructions.  If using 32-bit registers, set
12356                        imm_expr to the high order 32 bits and offset_expr to
12357                        the low order 32 bits.  Otherwise, set imm_expr to
12358                        the entire 64 bit constant.  */
12359                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12360                       {
12361                         imm_expr.X_op = O_constant;
12362                         offset_expr.X_op = O_constant;
12363                         if (!target_big_endian)
12364                           {
12365                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12366                             offset_expr.X_add_number = bfd_getl32 (temp);
12367                           }
12368                         else
12369                           {
12370                             imm_expr.X_add_number = bfd_getb32 (temp);
12371                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12372                           }
12373                         if (offset_expr.X_add_number == 0)
12374                           offset_expr.X_op = O_absent;
12375                       }
12376                     else
12377                       {
12378                         imm_expr.X_op = O_constant;
12379                         if (!target_big_endian)
12380                           imm_expr.X_add_number = bfd_getl64 (temp);
12381                         else
12382                           imm_expr.X_add_number = bfd_getb64 (temp);
12383                       }
12384                   }
12385                 else
12386                   {
12387                     const char *newname;
12388                     segT new_seg;
12389
12390                     /* Switch to the right section.  */
12391                     seg = now_seg;
12392                     subseg = now_subseg;
12393                     switch (*args)
12394                       {
12395                       default: /* unused default case avoids warnings.  */
12396                       case 'L':
12397                         newname = RDATA_SECTION_NAME;
12398                         if (g_switch_value >= 8)
12399                           newname = ".lit8";
12400                         break;
12401                       case 'F':
12402                         newname = RDATA_SECTION_NAME;
12403                         break;
12404                       case 'l':
12405                         gas_assert (g_switch_value >= 4);
12406                         newname = ".lit4";
12407                         break;
12408                       }
12409                     new_seg = subseg_new (newname, (subsegT) 0);
12410                     bfd_set_section_flags (stdoutput, new_seg,
12411                                            (SEC_ALLOC
12412                                             | SEC_LOAD
12413                                             | SEC_READONLY
12414                                             | SEC_DATA));
12415                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12416                     if (strncmp (TARGET_OS, "elf", 3) != 0)
12417                       record_alignment (new_seg, 4);
12418                     else
12419                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12420                     if (seg == now_seg)
12421                       as_bad (_("Can't use floating point insn in this section"));
12422
12423                     /* Set the argument to the current address in the
12424                        section.  */
12425                     offset_expr.X_op = O_symbol;
12426                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12427                     offset_expr.X_add_number = 0;
12428
12429                     /* Put the floating point number into the section.  */
12430                     p = frag_more ((int) length);
12431                     memcpy (p, temp, length);
12432
12433                     /* Switch back to the original section.  */
12434                     subseg_set (seg, subseg);
12435                   }
12436               }
12437               continue;
12438
12439             case 'i':           /* 16-bit unsigned immediate.  */
12440             case 'j':           /* 16-bit signed immediate.  */
12441               *offset_reloc = BFD_RELOC_LO16;
12442               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0)
12443                 {
12444                   int more;
12445                   offsetT minval, maxval;
12446
12447                   more = (insn + 1 < past
12448                           && strcmp (insn->name, insn[1].name) == 0);
12449
12450                   /* For compatibility with older assemblers, we accept
12451                      0x8000-0xffff as signed 16-bit numbers when only
12452                      signed numbers are allowed.  */
12453                   if (*args == 'i')
12454                     minval = 0, maxval = 0xffff;
12455                   else if (more)
12456                     minval = -0x8000, maxval = 0x7fff;
12457                   else
12458                     minval = -0x8000, maxval = 0xffff;
12459
12460                   if (offset_expr.X_op != O_constant
12461                       || offset_expr.X_add_number < minval
12462                       || offset_expr.X_add_number > maxval)
12463                     {
12464                       if (more)
12465                         break;
12466                       if (offset_expr.X_op == O_constant
12467                           || offset_expr.X_op == O_big)
12468                         as_bad (_("Expression out of range"));
12469                     }
12470                 }
12471               s = expr_end;
12472               continue;
12473
12474             case 'o':           /* 16-bit offset.  */
12475               offset_reloc[0] = BFD_RELOC_LO16;
12476               offset_reloc[1] = BFD_RELOC_UNUSED;
12477               offset_reloc[2] = BFD_RELOC_UNUSED;
12478
12479               /* Check whether there is only a single bracketed expression
12480                  left.  If so, it must be the base register and the
12481                  constant must be zero.  */
12482               if (*s == '(' && strchr (s + 1, '(') == 0)
12483                 {
12484                   offset_expr.X_op = O_constant;
12485                   offset_expr.X_add_number = 0;
12486                   continue;
12487                 }
12488
12489               /* If this value won't fit into a 16 bit offset, then go
12490                  find a macro that will generate the 32 bit offset
12491                  code pattern.  */
12492               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12493                   && (offset_expr.X_op != O_constant
12494                       || offset_expr.X_add_number >= 0x8000
12495                       || offset_expr.X_add_number < -0x8000))
12496                 break;
12497
12498               s = expr_end;
12499               continue;
12500
12501             case 'p':           /* PC-relative offset.  */
12502               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12503               my_getExpression (&offset_expr, s);
12504               s = expr_end;
12505               continue;
12506
12507             case 'u':           /* Upper 16 bits.  */
12508               *offset_reloc = BFD_RELOC_LO16;
12509               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12510                   && offset_expr.X_op == O_constant
12511                   && (offset_expr.X_add_number < 0
12512                       || offset_expr.X_add_number >= 0x10000))
12513                 as_bad (_("lui expression (%lu) not in range 0..65535"),
12514                         (unsigned long) offset_expr.X_add_number);
12515               s = expr_end;
12516               continue;
12517
12518             case 'a':           /* 26-bit address.  */
12519             jump:
12520               *offset_reloc = BFD_RELOC_MIPS_JMP;
12521               my_getExpression (&offset_expr, s);
12522               s = expr_end;
12523               continue;
12524
12525             case 'N':           /* 3-bit branch condition code.  */
12526             case 'M':           /* 3-bit compare condition code.  */
12527               rtype = RTYPE_CCC;
12528               if (ip->insn_mo->pinfo & (FP_D | FP_S))
12529                 rtype |= RTYPE_FCC;
12530               if (!reg_lookup (&s, rtype, &regno))
12531                 break;
12532               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
12533                    || strcmp (str + strlen (str) - 5, "any2f") == 0
12534                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
12535                   && (regno & 1) != 0)
12536                 as_warn (_("Condition code register should be even for %s, "
12537                            "was %d"),
12538                          str, regno);
12539               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
12540                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
12541                   && (regno & 3) != 0)
12542                 as_warn (_("Condition code register should be 0 or 4 for %s, "
12543                            "was %d"),
12544                          str, regno);
12545               if (*args == 'N')
12546                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
12547               else
12548                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
12549               continue;
12550
12551             case 'H':
12552               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
12553                 s += 2;
12554               if (ISDIGIT (*s))
12555                 {
12556                   c = 0;
12557                   do
12558                     {
12559                       c *= 10;
12560                       c += *s - '0';
12561                       ++s;
12562                     }
12563                   while (ISDIGIT (*s));
12564                 }
12565               else
12566                 c = 8; /* Invalid sel value.  */
12567
12568               if (c > 7)
12569                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
12570               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
12571               continue;
12572
12573             case 'e':
12574               gas_assert (!mips_opts.micromips);
12575               /* Must be at least one digit.  */
12576               my_getExpression (&imm_expr, s);
12577               check_absolute_expr (ip, &imm_expr);
12578
12579               if ((unsigned long) imm_expr.X_add_number
12580                   > (unsigned long) OP_MASK_VECBYTE)
12581                 {
12582                   as_bad (_("bad byte vector index (%ld)"),
12583                            (long) imm_expr.X_add_number);
12584                   imm_expr.X_add_number = 0;
12585                 }
12586
12587               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
12588               imm_expr.X_op = O_absent;
12589               s = expr_end;
12590               continue;
12591
12592             case '%':
12593               gas_assert (!mips_opts.micromips);
12594               my_getExpression (&imm_expr, s);
12595               check_absolute_expr (ip, &imm_expr);
12596
12597               if ((unsigned long) imm_expr.X_add_number
12598                   > (unsigned long) OP_MASK_VECALIGN)
12599                 {
12600                   as_bad (_("bad byte vector index (%ld)"),
12601                            (long) imm_expr.X_add_number);
12602                   imm_expr.X_add_number = 0;
12603                 }
12604
12605               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
12606               imm_expr.X_op = O_absent;
12607               s = expr_end;
12608               continue;
12609
12610             case 'm':           /* Opcode extension character.  */
12611               gas_assert (mips_opts.micromips);
12612               c = *++args;
12613               switch (c)
12614                 {
12615                 case 'r':
12616                   if (strncmp (s, "$pc", 3) == 0)
12617                     {
12618                       s += 3;
12619                       continue;
12620                     }
12621                   break;
12622
12623                 case 'a':
12624                 case 'b':
12625                 case 'c':
12626                 case 'd':
12627                 case 'e':
12628                 case 'f':
12629                 case 'g':
12630                 case 'h':
12631                 case 'j':
12632                 case 'l':
12633                 case 'm':
12634                 case 'n':
12635                 case 'p':
12636                 case 'q':
12637                 case 's':
12638                 case 't':
12639                 case 'x':
12640                 case 'y':
12641                 case 'z':
12642                   s_reset = s;
12643                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12644                   if (regno == AT && mips_opts.at)
12645                     {
12646                       if (mips_opts.at == ATREG)
12647                         as_warn (_("Used $at without \".set noat\""));
12648                       else
12649                         as_warn (_("Used $%u with \".set at=$%u\""),
12650                                  regno, mips_opts.at);
12651                     }
12652                   if (!ok)
12653                     {
12654                       if (c == 'c')
12655                         {
12656                           gas_assert (args[1] == ',');
12657                           regno = lastregno;
12658                           ++args;
12659                         }
12660                       else if (c == 't')
12661                         {
12662                           gas_assert (args[1] == ',');
12663                           ++args;
12664                           continue;                     /* Nothing to do.  */
12665                         }
12666                       else
12667                         break;
12668                     }
12669
12670                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
12671                     {
12672                       if (regno == lastregno)
12673                         {
12674                           insn_error
12675                             = _("Source and destination must be different");
12676                           continue;
12677                         }
12678                       if (regno == 31 && lastregno == 0xffffffff)
12679                         {
12680                           insn_error
12681                             = _("A destination register must be supplied");
12682                           continue;
12683                         }
12684                     }
12685
12686                   if (*s == ' ')
12687                     ++s;
12688                   if (args[1] != *s)
12689                     {
12690                       if (c == 'e')
12691                         {
12692                           gas_assert (args[1] == ',');
12693                           regno = lastregno;
12694                           s = s_reset;
12695                           ++args;
12696                         }
12697                       else if (c == 't')
12698                         {
12699                           gas_assert (args[1] == ',');
12700                           s = s_reset;
12701                           ++args;
12702                           continue;                     /* Nothing to do.  */
12703                         }
12704                     }
12705
12706                   /* Make sure regno is the same as lastregno.  */
12707                   if (c == 't' && regno != lastregno)
12708                     break;
12709
12710                   /* Make sure regno is the same as destregno.  */
12711                   if (c == 'x' && regno != destregno)
12712                     break;
12713
12714                   /* We need to save regno, before regno maps to the
12715                      microMIPS register encoding.  */
12716                   lastregno = regno;
12717
12718                   if (c == 'f')
12719                     destregno = regno;
12720
12721                   switch (c)
12722                     {
12723                       case 'a':
12724                         if (regno != GP)
12725                           regno = ILLEGAL_REG;
12726                         break;
12727
12728                       case 'b':
12729                         regno = mips32_to_micromips_reg_b_map[regno];
12730                         break;
12731
12732                       case 'c':
12733                         regno = mips32_to_micromips_reg_c_map[regno];
12734                         break;
12735
12736                       case 'd':
12737                         regno = mips32_to_micromips_reg_d_map[regno];
12738                         break;
12739
12740                       case 'e':
12741                         regno = mips32_to_micromips_reg_e_map[regno];
12742                         break;
12743
12744                       case 'f':
12745                         regno = mips32_to_micromips_reg_f_map[regno];
12746                         break;
12747
12748                       case 'g':
12749                         regno = mips32_to_micromips_reg_g_map[regno];
12750                         break;
12751
12752                       case 'h':
12753                         s += strspn (s, " \t");
12754                         if (*s != ',')
12755                           {
12756                             regno = ILLEGAL_REG;
12757                             break;
12758                           }
12759                         ++s;
12760                         s += strspn (s, " \t");
12761                         ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno2);
12762                         if (!ok)
12763                           {
12764                             regno = ILLEGAL_REG;
12765                             break;
12766                           }
12767                         if (regno2 == AT && mips_opts.at)
12768                           {
12769                             if (mips_opts.at == ATREG)
12770                               as_warn (_("Used $at without \".set noat\""));
12771                             else
12772                               as_warn (_("Used $%u with \".set at=$%u\""),
12773                                        regno2, mips_opts.at);
12774                           }
12775                         regno = (mips_lookup_reg_pair
12776                                  (regno, regno2,
12777                                   micromips_to_32_reg_h_map1,
12778                                   micromips_to_32_reg_h_map2, 8));
12779                         break;
12780
12781                       case 'l':
12782                         regno = mips32_to_micromips_reg_l_map[regno];
12783                         break;
12784
12785                       case 'm':
12786                         regno = mips32_to_micromips_reg_m_map[regno];
12787                         break;
12788
12789                       case 'n':
12790                         regno = mips32_to_micromips_reg_n_map[regno];
12791                         break;
12792
12793                       case 'q':
12794                         regno = mips32_to_micromips_reg_q_map[regno];
12795                         break;
12796
12797                       case 's':
12798                         if (regno != SP)
12799                           regno = ILLEGAL_REG;
12800                         break;
12801
12802                       case 'y':
12803                         if (regno != 31)
12804                           regno = ILLEGAL_REG;
12805                         break;
12806
12807                       case 'z':
12808                         if (regno != ZERO)
12809                           regno = ILLEGAL_REG;
12810                         break;
12811
12812                       case 'j': /* Do nothing.  */
12813                       case 'p':
12814                       case 't':
12815                       case 'x':
12816                         break;
12817
12818                       default:
12819                         abort ();
12820                     }
12821
12822                   if (regno == ILLEGAL_REG)
12823                     break;
12824
12825                   switch (c)
12826                     {
12827                       case 'b':
12828                         INSERT_OPERAND (1, MB, *ip, regno);
12829                         break;
12830
12831                       case 'c':
12832                         INSERT_OPERAND (1, MC, *ip, regno);
12833                         break;
12834
12835                       case 'd':
12836                         INSERT_OPERAND (1, MD, *ip, regno);
12837                         break;
12838
12839                       case 'e':
12840                         INSERT_OPERAND (1, ME, *ip, regno);
12841                         break;
12842
12843                       case 'f':
12844                         INSERT_OPERAND (1, MF, *ip, regno);
12845                         break;
12846
12847                       case 'g':
12848                         INSERT_OPERAND (1, MG, *ip, regno);
12849                         break;
12850
12851                       case 'h':
12852                         INSERT_OPERAND (1, MH, *ip, regno);
12853                         break;
12854
12855                       case 'j':
12856                         INSERT_OPERAND (1, MJ, *ip, regno);
12857                         break;
12858
12859                       case 'l':
12860                         INSERT_OPERAND (1, ML, *ip, regno);
12861                         break;
12862
12863                       case 'm':
12864                         INSERT_OPERAND (1, MM, *ip, regno);
12865                         break;
12866
12867                       case 'n':
12868                         INSERT_OPERAND (1, MN, *ip, regno);
12869                         break;
12870
12871                       case 'p':
12872                         INSERT_OPERAND (1, MP, *ip, regno);
12873                         break;
12874
12875                       case 'q':
12876                         INSERT_OPERAND (1, MQ, *ip, regno);
12877                         break;
12878
12879                       case 'a': /* Do nothing.  */
12880                       case 's': /* Do nothing.  */
12881                       case 't': /* Do nothing.  */
12882                       case 'x': /* Do nothing.  */
12883                       case 'y': /* Do nothing.  */
12884                       case 'z': /* Do nothing.  */
12885                         break;
12886
12887                       default:
12888                         abort ();
12889                     }
12890                   continue;
12891
12892                 case 'A':
12893                   {
12894                     bfd_reloc_code_real_type r[3];
12895                     expressionS ep;
12896                     int imm;
12897
12898                     /* Check whether there is only a single bracketed
12899                        expression left.  If so, it must be the base register
12900                        and the constant must be zero.  */
12901                     if (*s == '(' && strchr (s + 1, '(') == 0)
12902                       {
12903                         INSERT_OPERAND (1, IMMA, *ip, 0);
12904                         continue;
12905                       }
12906
12907                     if (my_getSmallExpression (&ep, r, s) > 0
12908                         || !expr_const_in_range (&ep, -64, 64, 2))
12909                       break;
12910
12911                     imm = ep.X_add_number >> 2;
12912                     INSERT_OPERAND (1, IMMA, *ip, imm);
12913                   }
12914                   s = expr_end;
12915                   continue;
12916
12917                 case 'B':
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                         || ep.X_op != O_constant)
12925                       break;
12926
12927                     for (imm = 0; imm < 8; imm++)
12928                       if (micromips_imm_b_map[imm] == ep.X_add_number)
12929                         break;
12930                     if (imm >= 8)
12931                       break;
12932
12933                     INSERT_OPERAND (1, IMMB, *ip, imm);
12934                   }
12935                   s = expr_end;
12936                   continue;
12937
12938                 case 'C':
12939                   {
12940                     bfd_reloc_code_real_type r[3];
12941                     expressionS ep;
12942                     int imm;
12943
12944                     if (my_getSmallExpression (&ep, r, s) > 0
12945                         || ep.X_op != O_constant)
12946                       break;
12947
12948                     for (imm = 0; imm < 16; imm++)
12949                       if (micromips_imm_c_map[imm] == ep.X_add_number)
12950                         break;
12951                     if (imm >= 16)
12952                       break;
12953
12954                     INSERT_OPERAND (1, IMMC, *ip, imm);
12955                   }
12956                   s = expr_end;
12957                   continue;
12958
12959                 case 'D':       /* pc relative offset */
12960                 case 'E':       /* pc relative offset */
12961                   my_getExpression (&offset_expr, s);
12962                   if (offset_expr.X_op == O_register)
12963                     break;
12964
12965                   if (!forced_insn_length)
12966                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12967                   else if (c == 'D')
12968                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12969                   else
12970                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12971                   s = expr_end;
12972                   continue;
12973
12974                 case 'F':
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, 0, 16, 0))
12982                       break;
12983
12984                     imm = ep.X_add_number;
12985                     INSERT_OPERAND (1, IMMF, *ip, imm);
12986                   }
12987                   s = expr_end;
12988                   continue;
12989
12990                 case 'G':
12991                   {
12992                     bfd_reloc_code_real_type r[3];
12993                     expressionS ep;
12994                     int imm;
12995
12996                     /* Check whether there is only a single bracketed
12997                        expression left.  If so, it must be the base register
12998                        and the constant must be zero.  */
12999                     if (*s == '(' && strchr (s + 1, '(') == 0)
13000                       {
13001                         INSERT_OPERAND (1, IMMG, *ip, 0);
13002                         continue;
13003                       }
13004
13005                     if (my_getSmallExpression (&ep, r, s) > 0
13006                         || !expr_const_in_range (&ep, -1, 15, 0))
13007                       break;
13008
13009                     imm = ep.X_add_number & 15;
13010                     INSERT_OPERAND (1, IMMG, *ip, imm);
13011                   }
13012                   s = expr_end;
13013                   continue;
13014
13015                 case 'H':
13016                   {
13017                     bfd_reloc_code_real_type r[3];
13018                     expressionS ep;
13019                     int imm;
13020
13021                     /* Check whether there is only a single bracketed
13022                        expression left.  If so, it must be the base register
13023                        and the constant must be zero.  */
13024                     if (*s == '(' && strchr (s + 1, '(') == 0)
13025                       {
13026                         INSERT_OPERAND (1, IMMH, *ip, 0);
13027                         continue;
13028                       }
13029
13030                     if (my_getSmallExpression (&ep, r, s) > 0
13031                         || !expr_const_in_range (&ep, 0, 16, 1))
13032                       break;
13033
13034                     imm = ep.X_add_number >> 1;
13035                     INSERT_OPERAND (1, IMMH, *ip, imm);
13036                   }
13037                   s = expr_end;
13038                   continue;
13039
13040                 case 'I':
13041                   {
13042                     bfd_reloc_code_real_type r[3];
13043                     expressionS ep;
13044                     int imm;
13045
13046                     if (my_getSmallExpression (&ep, r, s) > 0
13047                         || !expr_const_in_range (&ep, -1, 127, 0))
13048                       break;
13049
13050                     imm = ep.X_add_number & 127;
13051                     INSERT_OPERAND (1, IMMI, *ip, imm);
13052                   }
13053                   s = expr_end;
13054                   continue;
13055
13056                 case 'J':
13057                   {
13058                     bfd_reloc_code_real_type r[3];
13059                     expressionS ep;
13060                     int imm;
13061
13062                     /* Check whether there is only a single bracketed
13063                        expression left.  If so, it must be the base register
13064                        and the constant must be zero.  */
13065                     if (*s == '(' && strchr (s + 1, '(') == 0)
13066                       {
13067                         INSERT_OPERAND (1, IMMJ, *ip, 0);
13068                         continue;
13069                       }
13070
13071                     if (my_getSmallExpression (&ep, r, s) > 0
13072                         || !expr_const_in_range (&ep, 0, 16, 2))
13073                       break;
13074
13075                     imm = ep.X_add_number >> 2;
13076                     INSERT_OPERAND (1, IMMJ, *ip, imm);
13077                   }
13078                   s = expr_end;
13079                   continue;
13080
13081                 case 'L':
13082                   {
13083                     bfd_reloc_code_real_type r[3];
13084                     expressionS ep;
13085                     int imm;
13086
13087                     /* Check whether there is only a single bracketed
13088                        expression left.  If so, it must be the base register
13089                        and the constant must be zero.  */
13090                     if (*s == '(' && strchr (s + 1, '(') == 0)
13091                       {
13092                         INSERT_OPERAND (1, IMML, *ip, 0);
13093                         continue;
13094                       }
13095
13096                     if (my_getSmallExpression (&ep, r, s) > 0
13097                         || !expr_const_in_range (&ep, 0, 16, 0))
13098                       break;
13099
13100                     imm = ep.X_add_number;
13101                     INSERT_OPERAND (1, IMML, *ip, imm);
13102                   }
13103                   s = expr_end;
13104                   continue;
13105
13106                 case 'M':
13107                   {
13108                     bfd_reloc_code_real_type r[3];
13109                     expressionS ep;
13110                     int imm;
13111
13112                     if (my_getSmallExpression (&ep, r, s) > 0
13113                         || !expr_const_in_range (&ep, 1, 9, 0))
13114                       break;
13115
13116                     imm = ep.X_add_number & 7;
13117                     INSERT_OPERAND (1, IMMM, *ip, imm);
13118                   }
13119                   s = expr_end;
13120                   continue;
13121
13122                 case 'N':       /* Register list for lwm and swm.  */
13123                   {
13124                     /* A comma-separated list of registers and/or
13125                        dash-separated contiguous ranges including
13126                        both ra and a set of one or more registers
13127                        starting at s0 up to s3 which have to be
13128                        consecutive, e.g.:
13129
13130                        s0, ra
13131                        s0, s1, ra, s2, s3
13132                        s0-s2, ra
13133
13134                        and any permutations of these.  */
13135                     unsigned int reglist;
13136                     int imm;
13137
13138                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13139                       break;
13140
13141                     if ((reglist & 0xfff1ffff) != 0x80010000)
13142                       break;
13143
13144                     reglist = (reglist >> 17) & 7;
13145                     reglist += 1;
13146                     if ((reglist & -reglist) != reglist)
13147                       break;
13148
13149                     imm = ffs (reglist) - 1;
13150                     INSERT_OPERAND (1, IMMN, *ip, imm);
13151                   }
13152                   continue;
13153
13154                 case 'O':       /* sdbbp 4-bit code.  */
13155                   {
13156                     bfd_reloc_code_real_type r[3];
13157                     expressionS ep;
13158                     int imm;
13159
13160                     if (my_getSmallExpression (&ep, r, s) > 0
13161                         || !expr_const_in_range (&ep, 0, 16, 0))
13162                       break;
13163
13164                     imm = ep.X_add_number;
13165                     INSERT_OPERAND (1, IMMO, *ip, imm);
13166                   }
13167                   s = expr_end;
13168                   continue;
13169
13170                 case 'P':
13171                   {
13172                     bfd_reloc_code_real_type r[3];
13173                     expressionS ep;
13174                     int imm;
13175
13176                     if (my_getSmallExpression (&ep, r, s) > 0
13177                         || !expr_const_in_range (&ep, 0, 32, 2))
13178                       break;
13179
13180                     imm = ep.X_add_number >> 2;
13181                     INSERT_OPERAND (1, IMMP, *ip, imm);
13182                   }
13183                   s = expr_end;
13184                   continue;
13185
13186                 case 'Q':
13187                   {
13188                     bfd_reloc_code_real_type r[3];
13189                     expressionS ep;
13190                     int imm;
13191
13192                     if (my_getSmallExpression (&ep, r, s) > 0
13193                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
13194                       break;
13195
13196                     imm = ep.X_add_number >> 2;
13197                     INSERT_OPERAND (1, IMMQ, *ip, imm);
13198                   }
13199                   s = expr_end;
13200                   continue;
13201
13202                 case 'U':
13203                   {
13204                     bfd_reloc_code_real_type r[3];
13205                     expressionS ep;
13206                     int imm;
13207
13208                     /* Check whether there is only a single bracketed
13209                        expression left.  If so, it must be the base register
13210                        and the constant must be zero.  */
13211                     if (*s == '(' && strchr (s + 1, '(') == 0)
13212                       {
13213                         INSERT_OPERAND (1, IMMU, *ip, 0);
13214                         continue;
13215                       }
13216
13217                     if (my_getSmallExpression (&ep, r, s) > 0
13218                         || !expr_const_in_range (&ep, 0, 32, 2))
13219                       break;
13220
13221                     imm = ep.X_add_number >> 2;
13222                     INSERT_OPERAND (1, IMMU, *ip, imm);
13223                   }
13224                   s = expr_end;
13225                   continue;
13226
13227                 case 'W':
13228                   {
13229                     bfd_reloc_code_real_type r[3];
13230                     expressionS ep;
13231                     int imm;
13232
13233                     if (my_getSmallExpression (&ep, r, s) > 0
13234                         || !expr_const_in_range (&ep, 0, 64, 2))
13235                       break;
13236
13237                     imm = ep.X_add_number >> 2;
13238                     INSERT_OPERAND (1, IMMW, *ip, imm);
13239                   }
13240                   s = expr_end;
13241                   continue;
13242
13243                 case 'X':
13244                   {
13245                     bfd_reloc_code_real_type r[3];
13246                     expressionS ep;
13247                     int imm;
13248
13249                     if (my_getSmallExpression (&ep, r, s) > 0
13250                         || !expr_const_in_range (&ep, -8, 8, 0))
13251                       break;
13252
13253                     imm = ep.X_add_number;
13254                     INSERT_OPERAND (1, IMMX, *ip, imm);
13255                   }
13256                   s = expr_end;
13257                   continue;
13258
13259                 case 'Y':
13260                   {
13261                     bfd_reloc_code_real_type r[3];
13262                     expressionS ep;
13263                     int imm;
13264
13265                     if (my_getSmallExpression (&ep, r, s) > 0
13266                         || expr_const_in_range (&ep, -2, 2, 2)
13267                         || !expr_const_in_range (&ep, -258, 258, 2))
13268                       break;
13269
13270                     imm = ep.X_add_number >> 2;
13271                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
13272                     INSERT_OPERAND (1, IMMY, *ip, imm);
13273                   }
13274                   s = expr_end;
13275                   continue;
13276
13277                 case 'Z':
13278                   {
13279                     bfd_reloc_code_real_type r[3];
13280                     expressionS ep;
13281
13282                     if (my_getSmallExpression (&ep, r, s) > 0
13283                         || !expr_const_in_range (&ep, 0, 1, 0))
13284                       break;
13285                   }
13286                   s = expr_end;
13287                   continue;
13288
13289                 default:
13290                   as_bad (_("Internal error: bad microMIPS opcode "
13291                             "(unknown extension operand type `m%c'): %s %s"),
13292                           *args, insn->name, insn->args);
13293                   /* Further processing is fruitless.  */
13294                   return;
13295                 }
13296               break;
13297
13298             case 'n':           /* Register list for 32-bit lwm and swm.  */
13299               gas_assert (mips_opts.micromips);
13300               {
13301                 /* A comma-separated list of registers and/or
13302                    dash-separated contiguous ranges including
13303                    at least one of ra and a set of one or more
13304                    registers starting at s0 up to s7 and then
13305                    s8 which have to be consecutive, e.g.:
13306
13307                    ra
13308                    s0
13309                    ra, s0, s1, s2
13310                    s0-s8
13311                    s0-s5, ra
13312
13313                    and any permutations of these.  */
13314                 unsigned int reglist;
13315                 int imm;
13316                 int ra;
13317
13318                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13319                   break;
13320
13321                 if ((reglist & 0x3f00ffff) != 0)
13322                   break;
13323
13324                 ra = (reglist >> 27) & 0x10;
13325                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13326                 reglist += 1;
13327                 if ((reglist & -reglist) != reglist)
13328                   break;
13329
13330                 imm = (ffs (reglist) - 1) | ra;
13331                 INSERT_OPERAND (1, RT, *ip, imm);
13332                 imm_expr.X_op = O_absent;
13333               }
13334               continue;
13335
13336             case '|':           /* 4-bit trap code.  */
13337               gas_assert (mips_opts.micromips);
13338               my_getExpression (&imm_expr, s);
13339               check_absolute_expr (ip, &imm_expr);
13340               if ((unsigned long) imm_expr.X_add_number
13341                   > MICROMIPSOP_MASK_TRAP)
13342                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13343                         (unsigned long) imm_expr.X_add_number,
13344                         ip->insn_mo->name);
13345               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13346               imm_expr.X_op = O_absent;
13347               s = expr_end;
13348               continue;
13349
13350             default:
13351               as_bad (_("Bad char = '%c'\n"), *args);
13352               abort ();
13353             }
13354           break;
13355         }
13356       /* Args don't match.  */
13357       s = argsStart;
13358       insn_error = _("Illegal operands");
13359       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13360         {
13361           ++insn;
13362           continue;
13363         }
13364       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13365         {
13366           gas_assert (firstinsn);
13367           need_delay_slot_ok = FALSE;
13368           past = insn + 1;
13369           insn = firstinsn;
13370           continue;
13371         }
13372       return;
13373     }
13374 }
13375
13376 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13377
13378 /* As for mips_ip, but used when assembling MIPS16 code.
13379    Also set forced_insn_length to the resulting instruction size in
13380    bytes if the user explicitly requested a small or extended instruction.  */
13381
13382 static void
13383 mips16_ip (char *str, struct mips_cl_insn *ip)
13384 {
13385   char *s;
13386   const char *args;
13387   struct mips_opcode *insn;
13388   char *argsstart;
13389   unsigned int regno;
13390   unsigned int lastregno = 0;
13391   char *s_reset;
13392   size_t i;
13393
13394   insn_error = NULL;
13395
13396   forced_insn_length = 0;
13397
13398   for (s = str; ISLOWER (*s); ++s)
13399     ;
13400   switch (*s)
13401     {
13402     case '\0':
13403       break;
13404
13405     case ' ':
13406       *s++ = '\0';
13407       break;
13408
13409     case '.':
13410       if (s[1] == 't' && s[2] == ' ')
13411         {
13412           *s = '\0';
13413           forced_insn_length = 2;
13414           s += 3;
13415           break;
13416         }
13417       else if (s[1] == 'e' && s[2] == ' ')
13418         {
13419           *s = '\0';
13420           forced_insn_length = 4;
13421           s += 3;
13422           break;
13423         }
13424       /* Fall through.  */
13425     default:
13426       insn_error = _("unknown opcode");
13427       return;
13428     }
13429
13430   if (mips_opts.noautoextend && !forced_insn_length)
13431     forced_insn_length = 2;
13432
13433   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
13434     {
13435       insn_error = _("unrecognized opcode");
13436       return;
13437     }
13438
13439   argsstart = s;
13440   for (;;)
13441     {
13442       bfd_boolean ok;
13443       char relax_char;
13444
13445       gas_assert (strcmp (insn->name, str) == 0);
13446
13447       ok = is_opcode_valid_16 (insn);
13448       if (! ok)
13449         {
13450           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13451               && strcmp (insn->name, insn[1].name) == 0)
13452             {
13453               ++insn;
13454               continue;
13455             }
13456           else
13457             {
13458               if (!insn_error)
13459                 {
13460                   static char buf[100];
13461                   sprintf (buf,
13462                            _("Opcode not supported on this processor: %s (%s)"),
13463                            mips_cpu_info_from_arch (mips_opts.arch)->name,
13464                            mips_cpu_info_from_isa (mips_opts.isa)->name);
13465                   insn_error = buf;
13466                 }
13467               return;
13468             }
13469         }
13470
13471       create_insn (ip, insn);
13472       imm_expr.X_op = O_absent;
13473       imm2_expr.X_op = O_absent;
13474       offset_expr.X_op = O_absent;
13475       offset_reloc[0] = BFD_RELOC_UNUSED;
13476       offset_reloc[1] = BFD_RELOC_UNUSED;
13477       offset_reloc[2] = BFD_RELOC_UNUSED;
13478       relax_char = 0;
13479       for (args = insn->args; 1; ++args)
13480         {
13481           int c;
13482
13483           if (*s == ' ')
13484             ++s;
13485
13486           /* In this switch statement we call break if we did not find
13487              a match, continue if we did find a match, or return if we
13488              are done.  */
13489
13490           c = *args;
13491           switch (c)
13492             {
13493             case '\0':
13494               if (*s == '\0')
13495                 {
13496                   offsetT value;
13497
13498                   /* Stuff the immediate value in now, if we can.  */
13499                   if (insn->pinfo == INSN_MACRO)
13500                     {
13501                       gas_assert (relax_char == 0);
13502                       gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
13503                     }
13504                   else if (relax_char
13505                            && offset_expr.X_op == O_constant
13506                            && calculate_reloc (*offset_reloc,
13507                                                offset_expr.X_add_number,
13508                                                &value))
13509                     {
13510                       mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
13511                                     forced_insn_length, &ip->insn_opcode);
13512                       offset_expr.X_op = O_absent;
13513                       *offset_reloc = BFD_RELOC_UNUSED;
13514                     }
13515                   else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
13516                     {
13517                       if (forced_insn_length == 2)
13518                         as_bad (_("invalid unextended operand value"));
13519                       forced_insn_length = 4;
13520                       ip->insn_opcode |= MIPS16_EXTEND;
13521                     }
13522                   else if (relax_char)
13523                     *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
13524
13525                   return;
13526                 }
13527               break;
13528
13529             case ',':
13530               if (*s++ == c)
13531                 continue;
13532               s--;
13533               switch (*++args)
13534                 {
13535                 case 'v':
13536                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13537                   continue;
13538                 case 'w':
13539                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13540                   continue;
13541                 }
13542               break;
13543
13544             case '(':
13545             case ')':
13546               if (*s++ == c)
13547                 continue;
13548               break;
13549
13550             case 'v':
13551             case 'w':
13552               if (s[0] != '$')
13553                 {
13554                   if (c == 'v')
13555                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13556                   else
13557                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13558                   ++args;
13559                   continue;
13560                 }
13561               /* Fall through.  */
13562             case 'x':
13563             case 'y':
13564             case 'z':
13565             case 'Z':
13566             case '0':
13567             case 'S':
13568             case 'R':
13569             case 'X':
13570             case 'Y':
13571               s_reset = s;
13572               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
13573                 {
13574                   if (c == 'v' || c == 'w')
13575                     {
13576                       if (c == 'v')
13577                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13578                       else
13579                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13580                       ++args;
13581                       continue;
13582                     }
13583                   break;
13584                 }
13585
13586               if (*s == ' ')
13587                 ++s;
13588               if (args[1] != *s)
13589                 {
13590                   if (c == 'v' || c == 'w')
13591                     {
13592                       regno = mips16_to_32_reg_map[lastregno];
13593                       s = s_reset;
13594                       ++args;
13595                     }
13596                 }
13597
13598               switch (c)
13599                 {
13600                 case 'x':
13601                 case 'y':
13602                 case 'z':
13603                 case 'v':
13604                 case 'w':
13605                 case 'Z':
13606                   regno = mips32_to_16_reg_map[regno];
13607                   break;
13608
13609                 case '0':
13610                   if (regno != 0)
13611                     regno = ILLEGAL_REG;
13612                   break;
13613
13614                 case 'S':
13615                   if (regno != SP)
13616                     regno = ILLEGAL_REG;
13617                   break;
13618
13619                 case 'R':
13620                   if (regno != RA)
13621                     regno = ILLEGAL_REG;
13622                   break;
13623
13624                 case 'X':
13625                 case 'Y':
13626                   if (regno == AT && mips_opts.at)
13627                     {
13628                       if (mips_opts.at == ATREG)
13629                         as_warn (_("used $at without \".set noat\""));
13630                       else
13631                         as_warn (_("used $%u with \".set at=$%u\""),
13632                                  regno, mips_opts.at);
13633                     }
13634                   break;
13635
13636                 default:
13637                   abort ();
13638                 }
13639
13640               if (regno == ILLEGAL_REG)
13641                 break;
13642
13643               switch (c)
13644                 {
13645                 case 'x':
13646                 case 'v':
13647                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
13648                   break;
13649                 case 'y':
13650                 case 'w':
13651                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
13652                   break;
13653                 case 'z':
13654                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
13655                   break;
13656                 case 'Z':
13657                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
13658                 case '0':
13659                 case 'S':
13660                 case 'R':
13661                   break;
13662                 case 'X':
13663                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
13664                   break;
13665                 case 'Y':
13666                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
13667                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
13668                   break;
13669                 default:
13670                   abort ();
13671                 }
13672
13673               lastregno = regno;
13674               continue;
13675
13676             case 'P':
13677               if (strncmp (s, "$pc", 3) == 0)
13678                 {
13679                   s += 3;
13680                   continue;
13681                 }
13682               break;
13683
13684             case '5':
13685             case 'H':
13686             case 'W':
13687             case 'D':
13688             case 'j':
13689             case 'V':
13690             case 'C':
13691             case 'U':
13692             case 'k':
13693             case 'K':
13694               i = my_getSmallExpression (&offset_expr, offset_reloc, s);
13695               if (i > 0)
13696                 {
13697                   relax_char = c;
13698                   s = expr_end;
13699                   continue;
13700                 }
13701               *offset_reloc = BFD_RELOC_UNUSED;
13702               /* Fall through.  */
13703             case '<':
13704             case '>':
13705             case '[':
13706             case ']':
13707             case '4':
13708             case '8':
13709               my_getExpression (&offset_expr, s);
13710               if (offset_expr.X_op == O_register)
13711                 {
13712                   /* What we thought was an expression turned out to
13713                      be a register.  */
13714
13715                   if (s[0] == '(' && args[1] == '(')
13716                     {
13717                       /* It looks like the expression was omitted
13718                          before a register indirection, which means
13719                          that the expression is implicitly zero.  We
13720                          still set up offset_expr, so that we handle
13721                          explicit extensions correctly.  */
13722                       offset_expr.X_op = O_constant;
13723                       offset_expr.X_add_number = 0;
13724                       relax_char = c;
13725                       continue;
13726                     }
13727
13728                   break;
13729                 }
13730
13731               /* We need to relax this instruction.  */
13732               relax_char = c;
13733               s = expr_end;
13734               continue;
13735
13736             case 'p':
13737             case 'q':
13738             case 'A':
13739             case 'B':
13740             case 'E':
13741               /* We use offset_reloc rather than imm_reloc for the PC
13742                  relative operands.  This lets macros with both
13743                  immediate and address operands work correctly.  */
13744               my_getExpression (&offset_expr, s);
13745
13746               if (offset_expr.X_op == O_register)
13747                 break;
13748
13749               /* We need to relax this instruction.  */
13750               relax_char = c;
13751               s = expr_end;
13752               continue;
13753
13754             case '6':           /* break code */
13755               my_getExpression (&imm_expr, s);
13756               check_absolute_expr (ip, &imm_expr);
13757               if ((unsigned long) imm_expr.X_add_number > 63)
13758                 as_warn (_("Invalid value for `%s' (%lu)"),
13759                          ip->insn_mo->name,
13760                          (unsigned long) imm_expr.X_add_number);
13761               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
13762               imm_expr.X_op = O_absent;
13763               s = expr_end;
13764               continue;
13765
13766             case 'I':
13767               my_getExpression (&imm_expr, s);
13768               if (imm_expr.X_op != O_big
13769                   && imm_expr.X_op != O_constant)
13770                 insn_error = _("absolute expression required");
13771               if (HAVE_32BIT_GPRS)
13772                 normalize_constant_expr (&imm_expr);
13773               s = expr_end;
13774               continue;
13775
13776             case 'a':           /* 26 bit address */
13777             case 'i':
13778               my_getExpression (&offset_expr, s);
13779               s = expr_end;
13780               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13781               ip->insn_opcode <<= 16;
13782               continue;
13783
13784             case 'l':           /* register list for entry macro */
13785             case 'L':           /* register list for exit macro */
13786               {
13787                 int mask;
13788
13789                 if (c == 'l')
13790                   mask = 0;
13791                 else
13792                   mask = 7 << 3;
13793                 while (*s != '\0')
13794                   {
13795                     unsigned int freg, reg1, reg2;
13796
13797                     while (*s == ' ' || *s == ',')
13798                       ++s;
13799                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13800                       freg = 0;
13801                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
13802                       freg = 1;
13803                     else
13804                       {
13805                         as_bad (_("can't parse register list"));
13806                         break;
13807                       }
13808                     if (*s == ' ')
13809                       ++s;
13810                     if (*s != '-')
13811                       reg2 = reg1;
13812                     else
13813                       {
13814                         ++s;
13815                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
13816                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
13817                           {
13818                             as_bad (_("invalid register list"));
13819                             break;
13820                           }
13821                       }
13822                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
13823                       {
13824                         mask &= ~ (7 << 3);
13825                         mask |= 5 << 3;
13826                       }
13827                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
13828                       {
13829                         mask &= ~ (7 << 3);
13830                         mask |= 6 << 3;
13831                       }
13832                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
13833                       mask |= (reg2 - 3) << 3;
13834                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
13835                       mask |= (reg2 - 15) << 1;
13836                     else if (reg1 == RA && reg2 == RA)
13837                       mask |= 1;
13838                     else
13839                       {
13840                         as_bad (_("invalid register list"));
13841                         break;
13842                       }
13843                   }
13844                 /* The mask is filled in in the opcode table for the
13845                    benefit of the disassembler.  We remove it before
13846                    applying the actual mask.  */
13847                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
13848                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
13849               }
13850             continue;
13851
13852             case 'm':           /* Register list for save insn.  */
13853             case 'M':           /* Register list for restore insn.  */
13854               {
13855                 int opcode = ip->insn_opcode;
13856                 int framesz = 0, seen_framesz = 0;
13857                 int nargs = 0, statics = 0, sregs = 0;
13858
13859                 while (*s != '\0')
13860                   {
13861                     unsigned int reg1, reg2;
13862
13863                     SKIP_SPACE_TABS (s);
13864                     while (*s == ',')
13865                       ++s;
13866                     SKIP_SPACE_TABS (s);
13867
13868                     my_getExpression (&imm_expr, s);
13869                     if (imm_expr.X_op == O_constant)
13870                       {
13871                         /* Handle the frame size.  */
13872                         if (seen_framesz)
13873                           {
13874                             as_bad (_("more than one frame size in list"));
13875                             break;
13876                           }
13877                         seen_framesz = 1;
13878                         framesz = imm_expr.X_add_number;
13879                         imm_expr.X_op = O_absent;
13880                         s = expr_end;
13881                         continue;
13882                       }
13883
13884                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13885                       {
13886                         as_bad (_("can't parse register list"));
13887                         break;
13888                       }
13889
13890                     while (*s == ' ')
13891                       ++s;
13892
13893                     if (*s != '-')
13894                       reg2 = reg1;
13895                     else
13896                       {
13897                         ++s;
13898                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
13899                             || reg2 < reg1)
13900                           {
13901                             as_bad (_("can't parse register list"));
13902                             break;
13903                           }
13904                       }
13905
13906                     while (reg1 <= reg2)
13907                       {
13908                         if (reg1 >= 4 && reg1 <= 7)
13909                           {
13910                             if (!seen_framesz)
13911                                 /* args $a0-$a3 */
13912                                 nargs |= 1 << (reg1 - 4);
13913                             else
13914                                 /* statics $a0-$a3 */
13915                                 statics |= 1 << (reg1 - 4);
13916                           }
13917                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
13918                           {
13919                             /* $s0-$s8 */
13920                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
13921                           }
13922                         else if (reg1 == 31)
13923                           {
13924                             /* Add $ra to insn.  */
13925                             opcode |= 0x40;
13926                           }
13927                         else
13928                           {
13929                             as_bad (_("unexpected register in list"));
13930                             break;
13931                           }
13932                         if (++reg1 == 24)
13933                           reg1 = 30;
13934                       }
13935                   }
13936
13937                 /* Encode args/statics combination.  */
13938                 if (nargs & statics)
13939                   as_bad (_("arg/static registers overlap"));
13940                 else if (nargs == 0xf)
13941                   /* All $a0-$a3 are args.  */
13942                   opcode |= MIPS16_ALL_ARGS << 16;
13943                 else if (statics == 0xf)
13944                   /* All $a0-$a3 are statics.  */
13945                   opcode |= MIPS16_ALL_STATICS << 16;
13946                 else 
13947                   {
13948                     int narg = 0, nstat = 0;
13949
13950                     /* Count arg registers.  */
13951                     while (nargs & 0x1)
13952                       {
13953                         nargs >>= 1;
13954                         narg++;
13955                       }
13956                     if (nargs != 0)
13957                       as_bad (_("invalid arg register list"));
13958
13959                     /* Count static registers.  */
13960                     while (statics & 0x8)
13961                       {
13962                         statics = (statics << 1) & 0xf;
13963                         nstat++;
13964                       }
13965                     if (statics != 0) 
13966                       as_bad (_("invalid static register list"));
13967
13968                     /* Encode args/statics.  */
13969                     opcode |= ((narg << 2) | nstat) << 16;
13970                   }
13971
13972                 /* Encode $s0/$s1.  */
13973                 if (sregs & (1 << 0))           /* $s0 */
13974                   opcode |= 0x20;
13975                 if (sregs & (1 << 1))           /* $s1 */
13976                   opcode |= 0x10;
13977                 sregs >>= 2;
13978
13979                 if (sregs != 0)
13980                   {
13981                     /* Count regs $s2-$s8.  */
13982                     int nsreg = 0;
13983                     while (sregs & 1)
13984                       {
13985                         sregs >>= 1;
13986                         nsreg++;
13987                       }
13988                     if (sregs != 0)
13989                       as_bad (_("invalid static register list"));
13990                     /* Encode $s2-$s8. */
13991                     opcode |= nsreg << 24;
13992                   }
13993
13994                 /* Encode frame size.  */
13995                 if (!seen_framesz)
13996                   as_bad (_("missing frame size"));
13997                 else if ((framesz & 7) != 0 || framesz < 0
13998                          || framesz > 0xff * 8)
13999                   as_bad (_("invalid frame size"));
14000                 else if (framesz != 128 || (opcode >> 16) != 0)
14001                   {
14002                     framesz /= 8;
14003                     opcode |= (((framesz & 0xf0) << 16)
14004                              | (framesz & 0x0f));
14005                   }
14006
14007                 /* Finally build the instruction.  */
14008                 if ((opcode >> 16) != 0 || framesz == 0)
14009                   opcode |= MIPS16_EXTEND;
14010                 ip->insn_opcode = opcode;
14011               }
14012             continue;
14013
14014             case 'e':           /* extend code */
14015               my_getExpression (&imm_expr, s);
14016               check_absolute_expr (ip, &imm_expr);
14017               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
14018                 {
14019                   as_warn (_("Invalid value for `%s' (%lu)"),
14020                            ip->insn_mo->name,
14021                            (unsigned long) imm_expr.X_add_number);
14022                   imm_expr.X_add_number &= 0x7ff;
14023                 }
14024               ip->insn_opcode |= imm_expr.X_add_number;
14025               imm_expr.X_op = O_absent;
14026               s = expr_end;
14027               continue;
14028
14029             default:
14030               abort ();
14031             }
14032           break;
14033         }
14034
14035       /* Args don't match.  */
14036       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
14037           strcmp (insn->name, insn[1].name) == 0)
14038         {
14039           ++insn;
14040           s = argsstart;
14041           continue;
14042         }
14043
14044       insn_error = _("illegal operands");
14045
14046       return;
14047     }
14048 }
14049
14050 /* This structure holds information we know about a mips16 immediate
14051    argument type.  */
14052
14053 struct mips16_immed_operand
14054 {
14055   /* The type code used in the argument string in the opcode table.  */
14056   int type;
14057   /* The number of bits in the short form of the opcode.  */
14058   int nbits;
14059   /* The number of bits in the extended form of the opcode.  */
14060   int extbits;
14061   /* The amount by which the short form is shifted when it is used;
14062      for example, the sw instruction has a shift count of 2.  */
14063   int shift;
14064   /* The amount by which the short form is shifted when it is stored
14065      into the instruction code.  */
14066   int op_shift;
14067   /* Non-zero if the short form is unsigned.  */
14068   int unsp;
14069   /* Non-zero if the extended form is unsigned.  */
14070   int extu;
14071   /* Non-zero if the value is PC relative.  */
14072   int pcrel;
14073 };
14074
14075 /* The mips16 immediate operand types.  */
14076
14077 static const struct mips16_immed_operand mips16_immed_operands[] =
14078 {
14079   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14080   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14081   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14082   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14083   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
14084   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
14085   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
14086   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
14087   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
14088   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
14089   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
14090   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
14091   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
14092   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
14093   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
14094   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
14095   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14096   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14097   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
14098   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
14099   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
14100 };
14101
14102 #define MIPS16_NUM_IMMED \
14103   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
14104
14105 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14106    NBITS is the number of significant bits in VAL.  */
14107
14108 static unsigned long
14109 mips16_immed_extend (offsetT val, unsigned int nbits)
14110 {
14111   int extval;
14112   if (nbits == 16)
14113     {
14114       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14115       val &= 0x1f;
14116     }
14117   else if (nbits == 15)
14118     {
14119       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14120       val &= 0xf;
14121     }
14122   else
14123     {
14124       extval = ((val & 0x1f) << 6) | (val & 0x20);
14125       val = 0;
14126     }
14127   return (extval << 16) | val;
14128 }
14129
14130 /* Install immediate value VAL into MIPS16 instruction *INSN,
14131    extending it if necessary.  The instruction in *INSN may
14132    already be extended.
14133
14134    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14135    if none.  In the former case, VAL is a 16-bit number with no
14136    defined signedness.
14137
14138    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14139    is the length that the user requested, or 0 if none.  */
14140
14141 static void
14142 mips16_immed (char *file, unsigned int line, int type,
14143               bfd_reloc_code_real_type reloc, offsetT val,
14144               unsigned int user_insn_length, unsigned long *insn)
14145 {
14146   const struct mips16_immed_operand *op;
14147   int mintiny, maxtiny;
14148
14149   op = mips16_immed_operands;
14150   while (op->type != type)
14151     {
14152       ++op;
14153       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
14154     }
14155
14156   if (op->unsp)
14157     {
14158       if (type == '<' || type == '>' || type == '[' || type == ']')
14159         {
14160           mintiny = 1;
14161           maxtiny = 1 << op->nbits;
14162         }
14163       else
14164         {
14165           mintiny = 0;
14166           maxtiny = (1 << op->nbits) - 1;
14167         }
14168       if (reloc != BFD_RELOC_UNUSED)
14169         val &= 0xffff;
14170     }
14171   else
14172     {
14173       mintiny = - (1 << (op->nbits - 1));
14174       maxtiny = (1 << (op->nbits - 1)) - 1;
14175       if (reloc != BFD_RELOC_UNUSED)
14176         val = SEXT_16BIT (val);
14177     }
14178
14179   /* Branch offsets have an implicit 0 in the lowest bit.  */
14180   if (type == 'p' || type == 'q')
14181     val /= 2;
14182
14183   if ((val & ((1 << op->shift) - 1)) != 0
14184       || val < (mintiny << op->shift)
14185       || val > (maxtiny << op->shift))
14186     {
14187       /* We need an extended instruction.  */
14188       if (user_insn_length == 2)
14189         as_bad_where (file, line, _("invalid unextended operand value"));
14190       else
14191         *insn |= MIPS16_EXTEND;
14192     }
14193   else if (user_insn_length == 4)
14194     {
14195       /* The operand doesn't force an unextended instruction to be extended.
14196          Warn if the user wanted an extended instruction anyway.  */
14197       *insn |= MIPS16_EXTEND;
14198       as_warn_where (file, line,
14199                      _("extended operand requested but not required"));
14200     }
14201
14202   if (mips16_opcode_length (*insn) == 2)
14203     {
14204       int insnval;
14205
14206       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
14207       insnval <<= op->op_shift;
14208       *insn |= insnval;
14209     }
14210   else
14211     {
14212       long minext, maxext;
14213
14214       if (reloc == BFD_RELOC_UNUSED)
14215         {
14216           if (op->extu)
14217             {
14218               minext = 0;
14219               maxext = (1 << op->extbits) - 1;
14220             }
14221           else
14222             {
14223               minext = - (1 << (op->extbits - 1));
14224               maxext = (1 << (op->extbits - 1)) - 1;
14225             }
14226           if (val < minext || val > maxext)
14227             as_bad_where (file, line,
14228                           _("operand value out of range for instruction"));
14229         }
14230
14231       *insn |= mips16_immed_extend (val, op->extbits);
14232     }
14233 }
14234 \f
14235 struct percent_op_match
14236 {
14237   const char *str;
14238   bfd_reloc_code_real_type reloc;
14239 };
14240
14241 static const struct percent_op_match mips_percent_op[] =
14242 {
14243   {"%lo", BFD_RELOC_LO16},
14244   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14245   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14246   {"%call16", BFD_RELOC_MIPS_CALL16},
14247   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14248   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14249   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14250   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14251   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14252   {"%got", BFD_RELOC_MIPS_GOT16},
14253   {"%gp_rel", BFD_RELOC_GPREL16},
14254   {"%half", BFD_RELOC_16},
14255   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14256   {"%higher", BFD_RELOC_MIPS_HIGHER},
14257   {"%neg", BFD_RELOC_MIPS_SUB},
14258   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14259   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14260   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14261   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14262   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14263   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14264   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14265   {"%hi", BFD_RELOC_HI16_S}
14266 };
14267
14268 static const struct percent_op_match mips16_percent_op[] =
14269 {
14270   {"%lo", BFD_RELOC_MIPS16_LO16},
14271   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14272   {"%got", BFD_RELOC_MIPS16_GOT16},
14273   {"%call16", BFD_RELOC_MIPS16_CALL16},
14274   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14275   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14276   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14277   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14278   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14279   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14280   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14281   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14282 };
14283
14284
14285 /* Return true if *STR points to a relocation operator.  When returning true,
14286    move *STR over the operator and store its relocation code in *RELOC.
14287    Leave both *STR and *RELOC alone when returning false.  */
14288
14289 static bfd_boolean
14290 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14291 {
14292   const struct percent_op_match *percent_op;
14293   size_t limit, i;
14294
14295   if (mips_opts.mips16)
14296     {
14297       percent_op = mips16_percent_op;
14298       limit = ARRAY_SIZE (mips16_percent_op);
14299     }
14300   else
14301     {
14302       percent_op = mips_percent_op;
14303       limit = ARRAY_SIZE (mips_percent_op);
14304     }
14305
14306   for (i = 0; i < limit; i++)
14307     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14308       {
14309         int len = strlen (percent_op[i].str);
14310
14311         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14312           continue;
14313
14314         *str += strlen (percent_op[i].str);
14315         *reloc = percent_op[i].reloc;
14316
14317         /* Check whether the output BFD supports this relocation.
14318            If not, issue an error and fall back on something safe.  */
14319         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14320           {
14321             as_bad (_("relocation %s isn't supported by the current ABI"),
14322                     percent_op[i].str);
14323             *reloc = BFD_RELOC_UNUSED;
14324           }
14325         return TRUE;
14326       }
14327   return FALSE;
14328 }
14329
14330
14331 /* Parse string STR as a 16-bit relocatable operand.  Store the
14332    expression in *EP and the relocations in the array starting
14333    at RELOC.  Return the number of relocation operators used.
14334
14335    On exit, EXPR_END points to the first character after the expression.  */
14336
14337 static size_t
14338 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14339                        char *str)
14340 {
14341   bfd_reloc_code_real_type reversed_reloc[3];
14342   size_t reloc_index, i;
14343   int crux_depth, str_depth;
14344   char *crux;
14345
14346   /* Search for the start of the main expression, recoding relocations
14347      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14348      of the main expression and with CRUX_DEPTH containing the number
14349      of open brackets at that point.  */
14350   reloc_index = -1;
14351   str_depth = 0;
14352   do
14353     {
14354       reloc_index++;
14355       crux = str;
14356       crux_depth = str_depth;
14357
14358       /* Skip over whitespace and brackets, keeping count of the number
14359          of brackets.  */
14360       while (*str == ' ' || *str == '\t' || *str == '(')
14361         if (*str++ == '(')
14362           str_depth++;
14363     }
14364   while (*str == '%'
14365          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14366          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14367
14368   my_getExpression (ep, crux);
14369   str = expr_end;
14370
14371   /* Match every open bracket.  */
14372   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14373     if (*str++ == ')')
14374       crux_depth--;
14375
14376   if (crux_depth > 0)
14377     as_bad (_("unclosed '('"));
14378
14379   expr_end = str;
14380
14381   if (reloc_index != 0)
14382     {
14383       prev_reloc_op_frag = frag_now;
14384       for (i = 0; i < reloc_index; i++)
14385         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14386     }
14387
14388   return reloc_index;
14389 }
14390
14391 static void
14392 my_getExpression (expressionS *ep, char *str)
14393 {
14394   char *save_in;
14395
14396   save_in = input_line_pointer;
14397   input_line_pointer = str;
14398   expression (ep);
14399   expr_end = input_line_pointer;
14400   input_line_pointer = save_in;
14401 }
14402
14403 char *
14404 md_atof (int type, char *litP, int *sizeP)
14405 {
14406   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14407 }
14408
14409 void
14410 md_number_to_chars (char *buf, valueT val, int n)
14411 {
14412   if (target_big_endian)
14413     number_to_chars_bigendian (buf, val, n);
14414   else
14415     number_to_chars_littleendian (buf, val, n);
14416 }
14417 \f
14418 static int support_64bit_objects(void)
14419 {
14420   const char **list, **l;
14421   int yes;
14422
14423   list = bfd_target_list ();
14424   for (l = list; *l != NULL; l++)
14425     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14426         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14427       break;
14428   yes = (*l != NULL);
14429   free (list);
14430   return yes;
14431 }
14432
14433 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14434    NEW_VALUE.  Warn if another value was already specified.  Note:
14435    we have to defer parsing the -march and -mtune arguments in order
14436    to handle 'from-abi' correctly, since the ABI might be specified
14437    in a later argument.  */
14438
14439 static void
14440 mips_set_option_string (const char **string_ptr, const char *new_value)
14441 {
14442   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14443     as_warn (_("A different %s was already specified, is now %s"),
14444              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14445              new_value);
14446
14447   *string_ptr = new_value;
14448 }
14449
14450 int
14451 md_parse_option (int c, char *arg)
14452 {
14453   unsigned int i;
14454
14455   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14456     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14457       {
14458         file_ase_explicit |= mips_set_ase (&mips_ases[i],
14459                                            c == mips_ases[i].option_on);
14460         return 1;
14461       }
14462
14463   switch (c)
14464     {
14465     case OPTION_CONSTRUCT_FLOATS:
14466       mips_disable_float_construction = 0;
14467       break;
14468
14469     case OPTION_NO_CONSTRUCT_FLOATS:
14470       mips_disable_float_construction = 1;
14471       break;
14472
14473     case OPTION_TRAP:
14474       mips_trap = 1;
14475       break;
14476
14477     case OPTION_BREAK:
14478       mips_trap = 0;
14479       break;
14480
14481     case OPTION_EB:
14482       target_big_endian = 1;
14483       break;
14484
14485     case OPTION_EL:
14486       target_big_endian = 0;
14487       break;
14488
14489     case 'O':
14490       if (arg == NULL)
14491         mips_optimize = 1;
14492       else if (arg[0] == '0')
14493         mips_optimize = 0;
14494       else if (arg[0] == '1')
14495         mips_optimize = 1;
14496       else
14497         mips_optimize = 2;
14498       break;
14499
14500     case 'g':
14501       if (arg == NULL)
14502         mips_debug = 2;
14503       else
14504         mips_debug = atoi (arg);
14505       break;
14506
14507     case OPTION_MIPS1:
14508       file_mips_isa = ISA_MIPS1;
14509       break;
14510
14511     case OPTION_MIPS2:
14512       file_mips_isa = ISA_MIPS2;
14513       break;
14514
14515     case OPTION_MIPS3:
14516       file_mips_isa = ISA_MIPS3;
14517       break;
14518
14519     case OPTION_MIPS4:
14520       file_mips_isa = ISA_MIPS4;
14521       break;
14522
14523     case OPTION_MIPS5:
14524       file_mips_isa = ISA_MIPS5;
14525       break;
14526
14527     case OPTION_MIPS32:
14528       file_mips_isa = ISA_MIPS32;
14529       break;
14530
14531     case OPTION_MIPS32R2:
14532       file_mips_isa = ISA_MIPS32R2;
14533       break;
14534
14535     case OPTION_MIPS64R2:
14536       file_mips_isa = ISA_MIPS64R2;
14537       break;
14538
14539     case OPTION_MIPS64:
14540       file_mips_isa = ISA_MIPS64;
14541       break;
14542
14543     case OPTION_MTUNE:
14544       mips_set_option_string (&mips_tune_string, arg);
14545       break;
14546
14547     case OPTION_MARCH:
14548       mips_set_option_string (&mips_arch_string, arg);
14549       break;
14550
14551     case OPTION_M4650:
14552       mips_set_option_string (&mips_arch_string, "4650");
14553       mips_set_option_string (&mips_tune_string, "4650");
14554       break;
14555
14556     case OPTION_NO_M4650:
14557       break;
14558
14559     case OPTION_M4010:
14560       mips_set_option_string (&mips_arch_string, "4010");
14561       mips_set_option_string (&mips_tune_string, "4010");
14562       break;
14563
14564     case OPTION_NO_M4010:
14565       break;
14566
14567     case OPTION_M4100:
14568       mips_set_option_string (&mips_arch_string, "4100");
14569       mips_set_option_string (&mips_tune_string, "4100");
14570       break;
14571
14572     case OPTION_NO_M4100:
14573       break;
14574
14575     case OPTION_M3900:
14576       mips_set_option_string (&mips_arch_string, "3900");
14577       mips_set_option_string (&mips_tune_string, "3900");
14578       break;
14579
14580     case OPTION_NO_M3900:
14581       break;
14582
14583     case OPTION_MICROMIPS:
14584       if (mips_opts.mips16 == 1)
14585         {
14586           as_bad (_("-mmicromips cannot be used with -mips16"));
14587           return 0;
14588         }
14589       mips_opts.micromips = 1;
14590       mips_no_prev_insn ();
14591       break;
14592
14593     case OPTION_NO_MICROMIPS:
14594       mips_opts.micromips = 0;
14595       mips_no_prev_insn ();
14596       break;
14597
14598     case OPTION_MIPS16:
14599       if (mips_opts.micromips == 1)
14600         {
14601           as_bad (_("-mips16 cannot be used with -micromips"));
14602           return 0;
14603         }
14604       mips_opts.mips16 = 1;
14605       mips_no_prev_insn ();
14606       break;
14607
14608     case OPTION_NO_MIPS16:
14609       mips_opts.mips16 = 0;
14610       mips_no_prev_insn ();
14611       break;
14612
14613     case OPTION_FIX_24K:
14614       mips_fix_24k = 1;
14615       break;
14616
14617     case OPTION_NO_FIX_24K:
14618       mips_fix_24k = 0;
14619       break;
14620
14621     case OPTION_FIX_LOONGSON2F_JUMP:
14622       mips_fix_loongson2f_jump = TRUE;
14623       break;
14624
14625     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14626       mips_fix_loongson2f_jump = FALSE;
14627       break;
14628
14629     case OPTION_FIX_LOONGSON2F_NOP:
14630       mips_fix_loongson2f_nop = TRUE;
14631       break;
14632
14633     case OPTION_NO_FIX_LOONGSON2F_NOP:
14634       mips_fix_loongson2f_nop = FALSE;
14635       break;
14636
14637     case OPTION_FIX_VR4120:
14638       mips_fix_vr4120 = 1;
14639       break;
14640
14641     case OPTION_NO_FIX_VR4120:
14642       mips_fix_vr4120 = 0;
14643       break;
14644
14645     case OPTION_FIX_VR4130:
14646       mips_fix_vr4130 = 1;
14647       break;
14648
14649     case OPTION_NO_FIX_VR4130:
14650       mips_fix_vr4130 = 0;
14651       break;
14652
14653     case OPTION_FIX_CN63XXP1:
14654       mips_fix_cn63xxp1 = TRUE;
14655       break;
14656
14657     case OPTION_NO_FIX_CN63XXP1:
14658       mips_fix_cn63xxp1 = FALSE;
14659       break;
14660
14661     case OPTION_RELAX_BRANCH:
14662       mips_relax_branch = 1;
14663       break;
14664
14665     case OPTION_NO_RELAX_BRANCH:
14666       mips_relax_branch = 0;
14667       break;
14668
14669     case OPTION_INSN32:
14670       mips_opts.insn32 = TRUE;
14671       break;
14672
14673     case OPTION_NO_INSN32:
14674       mips_opts.insn32 = FALSE;
14675       break;
14676
14677     case OPTION_MSHARED:
14678       mips_in_shared = TRUE;
14679       break;
14680
14681     case OPTION_MNO_SHARED:
14682       mips_in_shared = FALSE;
14683       break;
14684
14685     case OPTION_MSYM32:
14686       mips_opts.sym32 = TRUE;
14687       break;
14688
14689     case OPTION_MNO_SYM32:
14690       mips_opts.sym32 = FALSE;
14691       break;
14692
14693       /* When generating ELF code, we permit -KPIC and -call_shared to
14694          select SVR4_PIC, and -non_shared to select no PIC.  This is
14695          intended to be compatible with Irix 5.  */
14696     case OPTION_CALL_SHARED:
14697       mips_pic = SVR4_PIC;
14698       mips_abicalls = TRUE;
14699       break;
14700
14701     case OPTION_CALL_NONPIC:
14702       mips_pic = NO_PIC;
14703       mips_abicalls = TRUE;
14704       break;
14705
14706     case OPTION_NON_SHARED:
14707       mips_pic = NO_PIC;
14708       mips_abicalls = FALSE;
14709       break;
14710
14711       /* The -xgot option tells the assembler to use 32 bit offsets
14712          when accessing the got in SVR4_PIC mode.  It is for Irix
14713          compatibility.  */
14714     case OPTION_XGOT:
14715       mips_big_got = 1;
14716       break;
14717
14718     case 'G':
14719       g_switch_value = atoi (arg);
14720       g_switch_seen = 1;
14721       break;
14722
14723       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14724          and -mabi=64.  */
14725     case OPTION_32:
14726       mips_abi = O32_ABI;
14727       break;
14728
14729     case OPTION_N32:
14730       mips_abi = N32_ABI;
14731       break;
14732
14733     case OPTION_64:
14734       mips_abi = N64_ABI;
14735       if (!support_64bit_objects())
14736         as_fatal (_("No compiled in support for 64 bit object file format"));
14737       break;
14738
14739     case OPTION_GP32:
14740       file_mips_gp32 = 1;
14741       break;
14742
14743     case OPTION_GP64:
14744       file_mips_gp32 = 0;
14745       break;
14746
14747     case OPTION_FP32:
14748       file_mips_fp32 = 1;
14749       break;
14750
14751     case OPTION_FP64:
14752       file_mips_fp32 = 0;
14753       break;
14754
14755     case OPTION_SINGLE_FLOAT:
14756       file_mips_single_float = 1;
14757       break;
14758
14759     case OPTION_DOUBLE_FLOAT:
14760       file_mips_single_float = 0;
14761       break;
14762
14763     case OPTION_SOFT_FLOAT:
14764       file_mips_soft_float = 1;
14765       break;
14766
14767     case OPTION_HARD_FLOAT:
14768       file_mips_soft_float = 0;
14769       break;
14770
14771     case OPTION_MABI:
14772       if (strcmp (arg, "32") == 0)
14773         mips_abi = O32_ABI;
14774       else if (strcmp (arg, "o64") == 0)
14775         mips_abi = O64_ABI;
14776       else if (strcmp (arg, "n32") == 0)
14777         mips_abi = N32_ABI;
14778       else if (strcmp (arg, "64") == 0)
14779         {
14780           mips_abi = N64_ABI;
14781           if (! support_64bit_objects())
14782             as_fatal (_("No compiled in support for 64 bit object file "
14783                         "format"));
14784         }
14785       else if (strcmp (arg, "eabi") == 0)
14786         mips_abi = EABI_ABI;
14787       else
14788         {
14789           as_fatal (_("invalid abi -mabi=%s"), arg);
14790           return 0;
14791         }
14792       break;
14793
14794     case OPTION_M7000_HILO_FIX:
14795       mips_7000_hilo_fix = TRUE;
14796       break;
14797
14798     case OPTION_MNO_7000_HILO_FIX:
14799       mips_7000_hilo_fix = FALSE;
14800       break;
14801
14802     case OPTION_MDEBUG:
14803       mips_flag_mdebug = TRUE;
14804       break;
14805
14806     case OPTION_NO_MDEBUG:
14807       mips_flag_mdebug = FALSE;
14808       break;
14809
14810     case OPTION_PDR:
14811       mips_flag_pdr = TRUE;
14812       break;
14813
14814     case OPTION_NO_PDR:
14815       mips_flag_pdr = FALSE;
14816       break;
14817
14818     case OPTION_MVXWORKS_PIC:
14819       mips_pic = VXWORKS_PIC;
14820       break;
14821
14822     case OPTION_NAN:
14823       if (strcmp (arg, "2008") == 0)
14824         mips_flag_nan2008 = TRUE;
14825       else if (strcmp (arg, "legacy") == 0)
14826         mips_flag_nan2008 = FALSE;
14827       else
14828         {
14829           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
14830           return 0;
14831         }
14832       break;
14833
14834     default:
14835       return 0;
14836     }
14837
14838     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14839
14840   return 1;
14841 }
14842 \f
14843 /* Set up globals to generate code for the ISA or processor
14844    described by INFO.  */
14845
14846 static void
14847 mips_set_architecture (const struct mips_cpu_info *info)
14848 {
14849   if (info != 0)
14850     {
14851       file_mips_arch = info->cpu;
14852       mips_opts.arch = info->cpu;
14853       mips_opts.isa = info->isa;
14854     }
14855 }
14856
14857
14858 /* Likewise for tuning.  */
14859
14860 static void
14861 mips_set_tune (const struct mips_cpu_info *info)
14862 {
14863   if (info != 0)
14864     mips_tune = info->cpu;
14865 }
14866
14867
14868 void
14869 mips_after_parse_args (void)
14870 {
14871   const struct mips_cpu_info *arch_info = 0;
14872   const struct mips_cpu_info *tune_info = 0;
14873
14874   /* GP relative stuff not working for PE */
14875   if (strncmp (TARGET_OS, "pe", 2) == 0)
14876     {
14877       if (g_switch_seen && g_switch_value != 0)
14878         as_bad (_("-G not supported in this configuration."));
14879       g_switch_value = 0;
14880     }
14881
14882   if (mips_abi == NO_ABI)
14883     mips_abi = MIPS_DEFAULT_ABI;
14884
14885   /* The following code determines the architecture and register size.
14886      Similar code was added to GCC 3.3 (see override_options() in
14887      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14888      as much as possible.  */
14889
14890   if (mips_arch_string != 0)
14891     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14892
14893   if (file_mips_isa != ISA_UNKNOWN)
14894     {
14895       /* Handle -mipsN.  At this point, file_mips_isa contains the
14896          ISA level specified by -mipsN, while arch_info->isa contains
14897          the -march selection (if any).  */
14898       if (arch_info != 0)
14899         {
14900           /* -march takes precedence over -mipsN, since it is more descriptive.
14901              There's no harm in specifying both as long as the ISA levels
14902              are the same.  */
14903           if (file_mips_isa != arch_info->isa)
14904             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
14905                     mips_cpu_info_from_isa (file_mips_isa)->name,
14906                     mips_cpu_info_from_isa (arch_info->isa)->name);
14907         }
14908       else
14909         arch_info = mips_cpu_info_from_isa (file_mips_isa);
14910     }
14911
14912   if (arch_info == 0)
14913     {
14914       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14915       gas_assert (arch_info);
14916     }
14917
14918   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14919     as_bad (_("-march=%s is not compatible with the selected ABI"),
14920             arch_info->name);
14921
14922   mips_set_architecture (arch_info);
14923
14924   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
14925   if (mips_tune_string != 0)
14926     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14927
14928   if (tune_info == 0)
14929     mips_set_tune (arch_info);
14930   else
14931     mips_set_tune (tune_info);
14932
14933   if (file_mips_gp32 >= 0)
14934     {
14935       /* The user specified the size of the integer registers.  Make sure
14936          it agrees with the ABI and ISA.  */
14937       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
14938         as_bad (_("-mgp64 used with a 32-bit processor"));
14939       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
14940         as_bad (_("-mgp32 used with a 64-bit ABI"));
14941       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
14942         as_bad (_("-mgp64 used with a 32-bit ABI"));
14943     }
14944   else
14945     {
14946       /* Infer the integer register size from the ABI and processor.
14947          Restrict ourselves to 32-bit registers if that's all the
14948          processor has, or if the ABI cannot handle 64-bit registers.  */
14949       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
14950                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
14951     }
14952
14953   switch (file_mips_fp32)
14954     {
14955     default:
14956     case -1:
14957       /* No user specified float register size.
14958          ??? GAS treats single-float processors as though they had 64-bit
14959          float registers (although it complains when double-precision
14960          instructions are used).  As things stand, saying they have 32-bit
14961          registers would lead to spurious "register must be even" messages.
14962          So here we assume float registers are never smaller than the
14963          integer ones.  */
14964       if (file_mips_gp32 == 0)
14965         /* 64-bit integer registers implies 64-bit float registers.  */
14966         file_mips_fp32 = 0;
14967       else if ((mips_opts.ase & FP64_ASES)
14968                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
14969         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
14970         file_mips_fp32 = 0;
14971       else
14972         /* 32-bit float registers.  */
14973         file_mips_fp32 = 1;
14974       break;
14975
14976     /* The user specified the size of the float registers.  Check if it
14977        agrees with the ABI and ISA.  */
14978     case 0:
14979       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14980         as_bad (_("-mfp64 used with a 32-bit fpu"));
14981       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
14982                && !ISA_HAS_MXHC1 (mips_opts.isa))
14983         as_warn (_("-mfp64 used with a 32-bit ABI"));
14984       break;
14985     case 1:
14986       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14987         as_warn (_("-mfp32 used with a 64-bit ABI"));
14988       break;
14989     }
14990
14991   /* End of GCC-shared inference code.  */
14992
14993   /* This flag is set when we have a 64-bit capable CPU but use only
14994      32-bit wide registers.  Note that EABI does not use it.  */
14995   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14996       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14997           || mips_abi == O32_ABI))
14998     mips_32bitmode = 1;
14999
15000   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
15001     as_bad (_("trap exception not supported at ISA 1"));
15002
15003   /* If the selected architecture includes support for ASEs, enable
15004      generation of code for them.  */
15005   if (mips_opts.mips16 == -1)
15006     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
15007   if (mips_opts.micromips == -1)
15008     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15009
15010   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
15011      ASEs from being selected implicitly.  */
15012   if (file_mips_fp32 == 1)
15013     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
15014
15015   /* If the user didn't explicitly select or deselect a particular ASE,
15016      use the default setting for the CPU.  */
15017   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
15018
15019   file_mips_isa = mips_opts.isa;
15020   file_ase = mips_opts.ase;
15021   mips_opts.gp32 = file_mips_gp32;
15022   mips_opts.fp32 = file_mips_fp32;
15023   mips_opts.soft_float = file_mips_soft_float;
15024   mips_opts.single_float = file_mips_single_float;
15025
15026   mips_check_isa_supports_ases ();
15027
15028   if (mips_flag_mdebug < 0)
15029     mips_flag_mdebug = 0;
15030 }
15031 \f
15032 void
15033 mips_init_after_args (void)
15034 {
15035   /* initialize opcodes */
15036   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15037   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15038 }
15039
15040 long
15041 md_pcrel_from (fixS *fixP)
15042 {
15043   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15044   switch (fixP->fx_r_type)
15045     {
15046     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15047     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15048       /* Return the address of the delay slot.  */
15049       return addr + 2;
15050
15051     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15052     case BFD_RELOC_MICROMIPS_JMP:
15053     case BFD_RELOC_16_PCREL_S2:
15054     case BFD_RELOC_MIPS_JMP:
15055       /* Return the address of the delay slot.  */
15056       return addr + 4;
15057
15058     case BFD_RELOC_32_PCREL:
15059       return addr;
15060
15061     default:
15062       /* We have no relocation type for PC relative MIPS16 instructions.  */
15063       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15064         as_bad_where (fixP->fx_file, fixP->fx_line,
15065                       _("PC relative MIPS16 instruction references a different section"));
15066       return addr;
15067     }
15068 }
15069
15070 /* This is called before the symbol table is processed.  In order to
15071    work with gcc when using mips-tfile, we must keep all local labels.
15072    However, in other cases, we want to discard them.  If we were
15073    called with -g, but we didn't see any debugging information, it may
15074    mean that gcc is smuggling debugging information through to
15075    mips-tfile, in which case we must generate all local labels.  */
15076
15077 void
15078 mips_frob_file_before_adjust (void)
15079 {
15080 #ifndef NO_ECOFF_DEBUGGING
15081   if (ECOFF_DEBUGGING
15082       && mips_debug != 0
15083       && ! ecoff_debugging_seen)
15084     flag_keep_locals = 1;
15085 #endif
15086 }
15087
15088 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15089    the corresponding LO16 reloc.  This is called before md_apply_fix and
15090    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15091    relocation operators.
15092
15093    For our purposes, a %lo() expression matches a %got() or %hi()
15094    expression if:
15095
15096       (a) it refers to the same symbol; and
15097       (b) the offset applied in the %lo() expression is no lower than
15098           the offset applied in the %got() or %hi().
15099
15100    (b) allows us to cope with code like:
15101
15102         lui     $4,%hi(foo)
15103         lh      $4,%lo(foo+2)($4)
15104
15105    ...which is legal on RELA targets, and has a well-defined behaviour
15106    if the user knows that adding 2 to "foo" will not induce a carry to
15107    the high 16 bits.
15108
15109    When several %lo()s match a particular %got() or %hi(), we use the
15110    following rules to distinguish them:
15111
15112      (1) %lo()s with smaller offsets are a better match than %lo()s with
15113          higher offsets.
15114
15115      (2) %lo()s with no matching %got() or %hi() are better than those
15116          that already have a matching %got() or %hi().
15117
15118      (3) later %lo()s are better than earlier %lo()s.
15119
15120    These rules are applied in order.
15121
15122    (1) means, among other things, that %lo()s with identical offsets are
15123    chosen if they exist.
15124
15125    (2) means that we won't associate several high-part relocations with
15126    the same low-part relocation unless there's no alternative.  Having
15127    several high parts for the same low part is a GNU extension; this rule
15128    allows careful users to avoid it.
15129
15130    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15131    with the last high-part relocation being at the front of the list.
15132    It therefore makes sense to choose the last matching low-part
15133    relocation, all other things being equal.  It's also easier
15134    to code that way.  */
15135
15136 void
15137 mips_frob_file (void)
15138 {
15139   struct mips_hi_fixup *l;
15140   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15141
15142   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15143     {
15144       segment_info_type *seginfo;
15145       bfd_boolean matched_lo_p;
15146       fixS **hi_pos, **lo_pos, **pos;
15147
15148       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15149
15150       /* If a GOT16 relocation turns out to be against a global symbol,
15151          there isn't supposed to be a matching LO.  Ignore %gots against
15152          constants; we'll report an error for those later.  */
15153       if (got16_reloc_p (l->fixp->fx_r_type)
15154           && !(l->fixp->fx_addsy
15155                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
15156         continue;
15157
15158       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15159       if (fixup_has_matching_lo_p (l->fixp))
15160         continue;
15161
15162       seginfo = seg_info (l->seg);
15163
15164       /* Set HI_POS to the position of this relocation in the chain.
15165          Set LO_POS to the position of the chosen low-part relocation.
15166          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15167          relocation that matches an immediately-preceding high-part
15168          relocation.  */
15169       hi_pos = NULL;
15170       lo_pos = NULL;
15171       matched_lo_p = FALSE;
15172       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15173
15174       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15175         {
15176           if (*pos == l->fixp)
15177             hi_pos = pos;
15178
15179           if ((*pos)->fx_r_type == looking_for_rtype
15180               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15181               && (*pos)->fx_offset >= l->fixp->fx_offset
15182               && (lo_pos == NULL
15183                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15184                   || (!matched_lo_p
15185                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15186             lo_pos = pos;
15187
15188           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15189                           && fixup_has_matching_lo_p (*pos));
15190         }
15191
15192       /* If we found a match, remove the high-part relocation from its
15193          current position and insert it before the low-part relocation.
15194          Make the offsets match so that fixup_has_matching_lo_p()
15195          will return true.
15196
15197          We don't warn about unmatched high-part relocations since some
15198          versions of gcc have been known to emit dead "lui ...%hi(...)"
15199          instructions.  */
15200       if (lo_pos != NULL)
15201         {
15202           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15203           if (l->fixp->fx_next != *lo_pos)
15204             {
15205               *hi_pos = l->fixp->fx_next;
15206               l->fixp->fx_next = *lo_pos;
15207               *lo_pos = l->fixp;
15208             }
15209         }
15210     }
15211 }
15212
15213 int
15214 mips_force_relocation (fixS *fixp)
15215 {
15216   if (generic_force_reloc (fixp))
15217     return 1;
15218
15219   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15220      so that the linker relaxation can update targets.  */
15221   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15222       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15223       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15224     return 1;
15225
15226   return 0;
15227 }
15228
15229 /* Read the instruction associated with RELOC from BUF.  */
15230
15231 static unsigned int
15232 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15233 {
15234   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15235     return read_compressed_insn (buf, 4);
15236   else
15237     return read_insn (buf);
15238 }
15239
15240 /* Write instruction INSN to BUF, given that it has been relocated
15241    by RELOC.  */
15242
15243 static void
15244 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15245                   unsigned long insn)
15246 {
15247   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15248     write_compressed_insn (buf, insn, 4);
15249   else
15250     write_insn (buf, insn);
15251 }
15252
15253 /* Apply a fixup to the object file.  */
15254
15255 void
15256 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15257 {
15258   char *buf;
15259   unsigned long insn;
15260   reloc_howto_type *howto;
15261
15262   /* We ignore generic BFD relocations we don't know about.  */
15263   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15264   if (! howto)
15265     return;
15266
15267   gas_assert (fixP->fx_size == 2
15268               || fixP->fx_size == 4
15269               || fixP->fx_r_type == BFD_RELOC_16
15270               || fixP->fx_r_type == BFD_RELOC_64
15271               || fixP->fx_r_type == BFD_RELOC_CTOR
15272               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15273               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15274               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15275               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15276               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15277
15278   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15279
15280   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15281               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15282               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15283               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
15284               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
15285
15286   /* Don't treat parts of a composite relocation as done.  There are two
15287      reasons for this:
15288
15289      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15290          should nevertheless be emitted if the first part is.
15291
15292      (2) In normal usage, composite relocations are never assembly-time
15293          constants.  The easiest way of dealing with the pathological
15294          exceptions is to generate a relocation against STN_UNDEF and
15295          leave everything up to the linker.  */
15296   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15297     fixP->fx_done = 1;
15298
15299   switch (fixP->fx_r_type)
15300     {
15301     case BFD_RELOC_MIPS_TLS_GD:
15302     case BFD_RELOC_MIPS_TLS_LDM:
15303     case BFD_RELOC_MIPS_TLS_DTPREL32:
15304     case BFD_RELOC_MIPS_TLS_DTPREL64:
15305     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15306     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15307     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15308     case BFD_RELOC_MIPS_TLS_TPREL32:
15309     case BFD_RELOC_MIPS_TLS_TPREL64:
15310     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15311     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15312     case BFD_RELOC_MICROMIPS_TLS_GD:
15313     case BFD_RELOC_MICROMIPS_TLS_LDM:
15314     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15315     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15316     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15317     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15318     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15319     case BFD_RELOC_MIPS16_TLS_GD:
15320     case BFD_RELOC_MIPS16_TLS_LDM:
15321     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15322     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15323     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15324     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15325     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15326       if (!fixP->fx_addsy)
15327         {
15328           as_bad_where (fixP->fx_file, fixP->fx_line,
15329                         _("TLS relocation against a constant"));
15330           break;
15331         }
15332       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15333       /* fall through */
15334
15335     case BFD_RELOC_MIPS_JMP:
15336     case BFD_RELOC_MIPS_SHIFT5:
15337     case BFD_RELOC_MIPS_SHIFT6:
15338     case BFD_RELOC_MIPS_GOT_DISP:
15339     case BFD_RELOC_MIPS_GOT_PAGE:
15340     case BFD_RELOC_MIPS_GOT_OFST:
15341     case BFD_RELOC_MIPS_SUB:
15342     case BFD_RELOC_MIPS_INSERT_A:
15343     case BFD_RELOC_MIPS_INSERT_B:
15344     case BFD_RELOC_MIPS_DELETE:
15345     case BFD_RELOC_MIPS_HIGHEST:
15346     case BFD_RELOC_MIPS_HIGHER:
15347     case BFD_RELOC_MIPS_SCN_DISP:
15348     case BFD_RELOC_MIPS_REL16:
15349     case BFD_RELOC_MIPS_RELGOT:
15350     case BFD_RELOC_MIPS_JALR:
15351     case BFD_RELOC_HI16:
15352     case BFD_RELOC_HI16_S:
15353     case BFD_RELOC_LO16:
15354     case BFD_RELOC_GPREL16:
15355     case BFD_RELOC_MIPS_LITERAL:
15356     case BFD_RELOC_MIPS_CALL16:
15357     case BFD_RELOC_MIPS_GOT16:
15358     case BFD_RELOC_GPREL32:
15359     case BFD_RELOC_MIPS_GOT_HI16:
15360     case BFD_RELOC_MIPS_GOT_LO16:
15361     case BFD_RELOC_MIPS_CALL_HI16:
15362     case BFD_RELOC_MIPS_CALL_LO16:
15363     case BFD_RELOC_MIPS16_GPREL:
15364     case BFD_RELOC_MIPS16_GOT16:
15365     case BFD_RELOC_MIPS16_CALL16:
15366     case BFD_RELOC_MIPS16_HI16:
15367     case BFD_RELOC_MIPS16_HI16_S:
15368     case BFD_RELOC_MIPS16_LO16:
15369     case BFD_RELOC_MIPS16_JMP:
15370     case BFD_RELOC_MICROMIPS_JMP:
15371     case BFD_RELOC_MICROMIPS_GOT_DISP:
15372     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15373     case BFD_RELOC_MICROMIPS_GOT_OFST:
15374     case BFD_RELOC_MICROMIPS_SUB:
15375     case BFD_RELOC_MICROMIPS_HIGHEST:
15376     case BFD_RELOC_MICROMIPS_HIGHER:
15377     case BFD_RELOC_MICROMIPS_SCN_DISP:
15378     case BFD_RELOC_MICROMIPS_JALR:
15379     case BFD_RELOC_MICROMIPS_HI16:
15380     case BFD_RELOC_MICROMIPS_HI16_S:
15381     case BFD_RELOC_MICROMIPS_LO16:
15382     case BFD_RELOC_MICROMIPS_GPREL16:
15383     case BFD_RELOC_MICROMIPS_LITERAL:
15384     case BFD_RELOC_MICROMIPS_CALL16:
15385     case BFD_RELOC_MICROMIPS_GOT16:
15386     case BFD_RELOC_MICROMIPS_GOT_HI16:
15387     case BFD_RELOC_MICROMIPS_GOT_LO16:
15388     case BFD_RELOC_MICROMIPS_CALL_HI16:
15389     case BFD_RELOC_MICROMIPS_CALL_LO16:
15390     case BFD_RELOC_MIPS_EH:
15391       if (fixP->fx_done)
15392         {
15393           offsetT value;
15394
15395           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15396             {
15397               insn = read_reloc_insn (buf, fixP->fx_r_type);
15398               if (mips16_reloc_p (fixP->fx_r_type))
15399                 insn |= mips16_immed_extend (value, 16);
15400               else
15401                 insn |= (value & 0xffff);
15402               write_reloc_insn (buf, fixP->fx_r_type, insn);
15403             }
15404           else
15405             as_bad_where (fixP->fx_file, fixP->fx_line,
15406                           _("Unsupported constant in relocation"));
15407         }
15408       break;
15409
15410     case BFD_RELOC_64:
15411       /* This is handled like BFD_RELOC_32, but we output a sign
15412          extended value if we are only 32 bits.  */
15413       if (fixP->fx_done)
15414         {
15415           if (8 <= sizeof (valueT))
15416             md_number_to_chars (buf, *valP, 8);
15417           else
15418             {
15419               valueT hiv;
15420
15421               if ((*valP & 0x80000000) != 0)
15422                 hiv = 0xffffffff;
15423               else
15424                 hiv = 0;
15425               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15426               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15427             }
15428         }
15429       break;
15430
15431     case BFD_RELOC_RVA:
15432     case BFD_RELOC_32:
15433     case BFD_RELOC_32_PCREL:
15434     case BFD_RELOC_16:
15435       /* If we are deleting this reloc entry, we must fill in the
15436          value now.  This can happen if we have a .word which is not
15437          resolved when it appears but is later defined.  */
15438       if (fixP->fx_done)
15439         md_number_to_chars (buf, *valP, fixP->fx_size);
15440       break;
15441
15442     case BFD_RELOC_16_PCREL_S2:
15443       if ((*valP & 0x3) != 0)
15444         as_bad_where (fixP->fx_file, fixP->fx_line,
15445                       _("Branch to misaligned address (%lx)"), (long) *valP);
15446
15447       /* We need to save the bits in the instruction since fixup_segment()
15448          might be deleting the relocation entry (i.e., a branch within
15449          the current segment).  */
15450       if (! fixP->fx_done)
15451         break;
15452
15453       /* Update old instruction data.  */
15454       insn = read_insn (buf);
15455
15456       if (*valP + 0x20000 <= 0x3ffff)
15457         {
15458           insn |= (*valP >> 2) & 0xffff;
15459           write_insn (buf, insn);
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           write_insn (buf, insn);
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       abort ();
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    This function used to have the comment:
15546
15547       The MIPS assembler also automatically adjusts any preceding label.
15548
15549    The implementation therefore applied the adjustment to a maximum of
15550    one label.  However, other label adjustments are applied to batches
15551    of labels, and adjusting just one caused problems when new labels
15552    were added for the sake of debugging or unwind information.
15553    We therefore adjust all preceding labels (given as LABELS) instead.  */
15554
15555 static void
15556 mips_align (int to, int *fill, struct insn_label_list *labels)
15557 {
15558   mips_emit_delays ();
15559   mips_record_compressed_mode ();
15560   if (fill == NULL && subseg_text_p (now_seg))
15561     frag_align_code (to, 0);
15562   else
15563     frag_align (to, fill ? *fill : 0, 0);
15564   record_alignment (now_seg, to);
15565   mips_move_labels (labels, FALSE);
15566 }
15567
15568 /* Align to a given power of two.  .align 0 turns off the automatic
15569    alignment used by the data creating pseudo-ops.  */
15570
15571 static void
15572 s_align (int x ATTRIBUTE_UNUSED)
15573 {
15574   int temp, fill_value, *fill_ptr;
15575   long max_alignment = 28;
15576
15577   /* o Note that the assembler pulls down any immediately preceding label
15578        to the aligned address.
15579      o It's not documented but auto alignment is reinstated by
15580        a .align pseudo instruction.
15581      o Note also that after auto alignment is turned off the mips assembler
15582        issues an error on attempt to assemble an improperly aligned data item.
15583        We don't.  */
15584
15585   temp = get_absolute_expression ();
15586   if (temp > max_alignment)
15587     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
15588   else if (temp < 0)
15589     {
15590       as_warn (_("Alignment negative: 0 assumed."));
15591       temp = 0;
15592     }
15593   if (*input_line_pointer == ',')
15594     {
15595       ++input_line_pointer;
15596       fill_value = get_absolute_expression ();
15597       fill_ptr = &fill_value;
15598     }
15599   else
15600     fill_ptr = 0;
15601   if (temp)
15602     {
15603       segment_info_type *si = seg_info (now_seg);
15604       struct insn_label_list *l = si->label_list;
15605       /* Auto alignment should be switched on by next section change.  */
15606       auto_align = 1;
15607       mips_align (temp, fill_ptr, l);
15608     }
15609   else
15610     {
15611       auto_align = 0;
15612     }
15613
15614   demand_empty_rest_of_line ();
15615 }
15616
15617 static void
15618 s_change_sec (int sec)
15619 {
15620   segT seg;
15621
15622   /* The ELF backend needs to know that we are changing sections, so
15623      that .previous works correctly.  We could do something like check
15624      for an obj_section_change_hook macro, but that might be confusing
15625      as it would not be appropriate to use it in the section changing
15626      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15627      This should be cleaner, somehow.  */
15628   obj_elf_section_change_hook ();
15629
15630   mips_emit_delays ();
15631
15632   switch (sec)
15633     {
15634     case 't':
15635       s_text (0);
15636       break;
15637     case 'd':
15638       s_data (0);
15639       break;
15640     case 'b':
15641       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15642       demand_empty_rest_of_line ();
15643       break;
15644
15645     case 'r':
15646       seg = subseg_new (RDATA_SECTION_NAME,
15647                         (subsegT) get_absolute_expression ());
15648       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15649                                               | SEC_READONLY | SEC_RELOC
15650                                               | SEC_DATA));
15651       if (strncmp (TARGET_OS, "elf", 3) != 0)
15652         record_alignment (seg, 4);
15653       demand_empty_rest_of_line ();
15654       break;
15655
15656     case 's':
15657       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15658       bfd_set_section_flags (stdoutput, seg,
15659                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15660       if (strncmp (TARGET_OS, "elf", 3) != 0)
15661         record_alignment (seg, 4);
15662       demand_empty_rest_of_line ();
15663       break;
15664
15665     case 'B':
15666       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15667       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15668       if (strncmp (TARGET_OS, "elf", 3) != 0)
15669         record_alignment (seg, 4);
15670       demand_empty_rest_of_line ();
15671       break;
15672     }
15673
15674   auto_align = 1;
15675 }
15676
15677 void
15678 s_change_section (int ignore ATTRIBUTE_UNUSED)
15679 {
15680   char *section_name;
15681   char c;
15682   char next_c = 0;
15683   int section_type;
15684   int section_flag;
15685   int section_entry_size;
15686   int section_alignment;
15687
15688   section_name = input_line_pointer;
15689   c = get_symbol_end ();
15690   if (c)
15691     next_c = *(input_line_pointer + 1);
15692
15693   /* Do we have .section Name<,"flags">?  */
15694   if (c != ',' || (c == ',' && next_c == '"'))
15695     {
15696       /* just after name is now '\0'.  */
15697       *input_line_pointer = c;
15698       input_line_pointer = section_name;
15699       obj_elf_section (ignore);
15700       return;
15701     }
15702   input_line_pointer++;
15703
15704   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15705   if (c == ',')
15706     section_type = get_absolute_expression ();
15707   else
15708     section_type = 0;
15709   if (*input_line_pointer++ == ',')
15710     section_flag = get_absolute_expression ();
15711   else
15712     section_flag = 0;
15713   if (*input_line_pointer++ == ',')
15714     section_entry_size = get_absolute_expression ();
15715   else
15716     section_entry_size = 0;
15717   if (*input_line_pointer++ == ',')
15718     section_alignment = get_absolute_expression ();
15719   else
15720     section_alignment = 0;
15721   /* FIXME: really ignore?  */
15722   (void) section_alignment;
15723
15724   section_name = xstrdup (section_name);
15725
15726   /* When using the generic form of .section (as implemented by obj-elf.c),
15727      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15728      traditionally had to fall back on the more common @progbits instead.
15729
15730      There's nothing really harmful in this, since bfd will correct
15731      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15732      means that, for backwards compatibility, the special_section entries
15733      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15734
15735      Even so, we shouldn't force users of the MIPS .section syntax to
15736      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15737      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15738      generic type-checking code.  */
15739   if (section_type == SHT_MIPS_DWARF)
15740     section_type = SHT_PROGBITS;
15741
15742   obj_elf_change_section (section_name, section_type, section_flag,
15743                           section_entry_size, 0, 0, 0);
15744
15745   if (now_seg->name != section_name)
15746     free (section_name);
15747 }
15748
15749 void
15750 mips_enable_auto_align (void)
15751 {
15752   auto_align = 1;
15753 }
15754
15755 static void
15756 s_cons (int log_size)
15757 {
15758   segment_info_type *si = seg_info (now_seg);
15759   struct insn_label_list *l = si->label_list;
15760
15761   mips_emit_delays ();
15762   if (log_size > 0 && auto_align)
15763     mips_align (log_size, 0, l);
15764   cons (1 << log_size);
15765   mips_clear_insn_labels ();
15766 }
15767
15768 static void
15769 s_float_cons (int type)
15770 {
15771   segment_info_type *si = seg_info (now_seg);
15772   struct insn_label_list *l = si->label_list;
15773
15774   mips_emit_delays ();
15775
15776   if (auto_align)
15777     {
15778       if (type == 'd')
15779         mips_align (3, 0, l);
15780       else
15781         mips_align (2, 0, l);
15782     }
15783
15784   float_cons (type);
15785   mips_clear_insn_labels ();
15786 }
15787
15788 /* Handle .globl.  We need to override it because on Irix 5 you are
15789    permitted to say
15790        .globl foo .text
15791    where foo is an undefined symbol, to mean that foo should be
15792    considered to be the address of a function.  */
15793
15794 static void
15795 s_mips_globl (int x ATTRIBUTE_UNUSED)
15796 {
15797   char *name;
15798   int c;
15799   symbolS *symbolP;
15800   flagword flag;
15801
15802   do
15803     {
15804       name = input_line_pointer;
15805       c = get_symbol_end ();
15806       symbolP = symbol_find_or_make (name);
15807       S_SET_EXTERNAL (symbolP);
15808
15809       *input_line_pointer = c;
15810       SKIP_WHITESPACE ();
15811
15812       /* On Irix 5, every global symbol that is not explicitly labelled as
15813          being a function is apparently labelled as being an object.  */
15814       flag = BSF_OBJECT;
15815
15816       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15817           && (*input_line_pointer != ','))
15818         {
15819           char *secname;
15820           asection *sec;
15821
15822           secname = input_line_pointer;
15823           c = get_symbol_end ();
15824           sec = bfd_get_section_by_name (stdoutput, secname);
15825           if (sec == NULL)
15826             as_bad (_("%s: no such section"), secname);
15827           *input_line_pointer = c;
15828
15829           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15830             flag = BSF_FUNCTION;
15831         }
15832
15833       symbol_get_bfdsym (symbolP)->flags |= flag;
15834
15835       c = *input_line_pointer;
15836       if (c == ',')
15837         {
15838           input_line_pointer++;
15839           SKIP_WHITESPACE ();
15840           if (is_end_of_line[(unsigned char) *input_line_pointer])
15841             c = '\n';
15842         }
15843     }
15844   while (c == ',');
15845
15846   demand_empty_rest_of_line ();
15847 }
15848
15849 static void
15850 s_option (int x ATTRIBUTE_UNUSED)
15851 {
15852   char *opt;
15853   char c;
15854
15855   opt = input_line_pointer;
15856   c = get_symbol_end ();
15857
15858   if (*opt == 'O')
15859     {
15860       /* FIXME: What does this mean?  */
15861     }
15862   else if (strncmp (opt, "pic", 3) == 0)
15863     {
15864       int i;
15865
15866       i = atoi (opt + 3);
15867       if (i == 0)
15868         mips_pic = NO_PIC;
15869       else if (i == 2)
15870         {
15871           mips_pic = SVR4_PIC;
15872           mips_abicalls = TRUE;
15873         }
15874       else
15875         as_bad (_(".option pic%d not supported"), i);
15876
15877       if (mips_pic == SVR4_PIC)
15878         {
15879           if (g_switch_seen && g_switch_value != 0)
15880             as_warn (_("-G may not be used with SVR4 PIC code"));
15881           g_switch_value = 0;
15882           bfd_set_gp_size (stdoutput, 0);
15883         }
15884     }
15885   else
15886     as_warn (_("Unrecognized option \"%s\""), opt);
15887
15888   *input_line_pointer = c;
15889   demand_empty_rest_of_line ();
15890 }
15891
15892 /* This structure is used to hold a stack of .set values.  */
15893
15894 struct mips_option_stack
15895 {
15896   struct mips_option_stack *next;
15897   struct mips_set_options options;
15898 };
15899
15900 static struct mips_option_stack *mips_opts_stack;
15901
15902 /* Handle the .set pseudo-op.  */
15903
15904 static void
15905 s_mipsset (int x ATTRIBUTE_UNUSED)
15906 {
15907   char *name = input_line_pointer, ch;
15908   const struct mips_ase *ase;
15909
15910   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15911     ++input_line_pointer;
15912   ch = *input_line_pointer;
15913   *input_line_pointer = '\0';
15914
15915   if (strcmp (name, "reorder") == 0)
15916     {
15917       if (mips_opts.noreorder)
15918         end_noreorder ();
15919     }
15920   else if (strcmp (name, "noreorder") == 0)
15921     {
15922       if (!mips_opts.noreorder)
15923         start_noreorder ();
15924     }
15925   else if (strncmp (name, "at=", 3) == 0)
15926     {
15927       char *s = name + 3;
15928
15929       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15930         as_bad (_("Unrecognized register name `%s'"), s);
15931     }
15932   else if (strcmp (name, "at") == 0)
15933     {
15934       mips_opts.at = ATREG;
15935     }
15936   else if (strcmp (name, "noat") == 0)
15937     {
15938       mips_opts.at = ZERO;
15939     }
15940   else if (strcmp (name, "macro") == 0)
15941     {
15942       mips_opts.warn_about_macros = 0;
15943     }
15944   else if (strcmp (name, "nomacro") == 0)
15945     {
15946       if (mips_opts.noreorder == 0)
15947         as_bad (_("`noreorder' must be set before `nomacro'"));
15948       mips_opts.warn_about_macros = 1;
15949     }
15950   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15951     {
15952       mips_opts.nomove = 0;
15953     }
15954   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15955     {
15956       mips_opts.nomove = 1;
15957     }
15958   else if (strcmp (name, "bopt") == 0)
15959     {
15960       mips_opts.nobopt = 0;
15961     }
15962   else if (strcmp (name, "nobopt") == 0)
15963     {
15964       mips_opts.nobopt = 1;
15965     }
15966   else if (strcmp (name, "gp=default") == 0)
15967     mips_opts.gp32 = file_mips_gp32;
15968   else if (strcmp (name, "gp=32") == 0)
15969     mips_opts.gp32 = 1;
15970   else if (strcmp (name, "gp=64") == 0)
15971     {
15972       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
15973         as_warn (_("%s isa does not support 64-bit registers"),
15974                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15975       mips_opts.gp32 = 0;
15976     }
15977   else if (strcmp (name, "fp=default") == 0)
15978     mips_opts.fp32 = file_mips_fp32;
15979   else if (strcmp (name, "fp=32") == 0)
15980     mips_opts.fp32 = 1;
15981   else if (strcmp (name, "fp=64") == 0)
15982     {
15983       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15984         as_warn (_("%s isa does not support 64-bit floating point registers"),
15985                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15986       mips_opts.fp32 = 0;
15987     }
15988   else if (strcmp (name, "softfloat") == 0)
15989     mips_opts.soft_float = 1;
15990   else if (strcmp (name, "hardfloat") == 0)
15991     mips_opts.soft_float = 0;
15992   else if (strcmp (name, "singlefloat") == 0)
15993     mips_opts.single_float = 1;
15994   else if (strcmp (name, "doublefloat") == 0)
15995     mips_opts.single_float = 0;
15996   else if (strcmp (name, "mips16") == 0
15997            || strcmp (name, "MIPS-16") == 0)
15998     {
15999       if (mips_opts.micromips == 1)
16000         as_fatal (_("`mips16' cannot be used with `micromips'"));
16001       mips_opts.mips16 = 1;
16002     }
16003   else if (strcmp (name, "nomips16") == 0
16004            || strcmp (name, "noMIPS-16") == 0)
16005     mips_opts.mips16 = 0;
16006   else if (strcmp (name, "micromips") == 0)
16007     {
16008       if (mips_opts.mips16 == 1)
16009         as_fatal (_("`micromips' cannot be used with `mips16'"));
16010       mips_opts.micromips = 1;
16011     }
16012   else if (strcmp (name, "nomicromips") == 0)
16013     mips_opts.micromips = 0;
16014   else if (name[0] == 'n'
16015            && name[1] == 'o'
16016            && (ase = mips_lookup_ase (name + 2)))
16017     mips_set_ase (ase, FALSE);
16018   else if ((ase = mips_lookup_ase (name)))
16019     mips_set_ase (ase, TRUE);
16020   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16021     {
16022       int reset = 0;
16023
16024       /* Permit the user to change the ISA and architecture on the fly.
16025          Needless to say, misuse can cause serious problems.  */
16026       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16027         {
16028           reset = 1;
16029           mips_opts.isa = file_mips_isa;
16030           mips_opts.arch = file_mips_arch;
16031         }
16032       else if (strncmp (name, "arch=", 5) == 0)
16033         {
16034           const struct mips_cpu_info *p;
16035
16036           p = mips_parse_cpu("internal use", name + 5);
16037           if (!p)
16038             as_bad (_("unknown architecture %s"), name + 5);
16039           else
16040             {
16041               mips_opts.arch = p->cpu;
16042               mips_opts.isa = p->isa;
16043             }
16044         }
16045       else if (strncmp (name, "mips", 4) == 0)
16046         {
16047           const struct mips_cpu_info *p;
16048
16049           p = mips_parse_cpu("internal use", name);
16050           if (!p)
16051             as_bad (_("unknown ISA level %s"), name + 4);
16052           else
16053             {
16054               mips_opts.arch = p->cpu;
16055               mips_opts.isa = p->isa;
16056             }
16057         }
16058       else
16059         as_bad (_("unknown ISA or architecture %s"), name);
16060
16061       switch (mips_opts.isa)
16062         {
16063         case  0:
16064           break;
16065         case ISA_MIPS1:
16066         case ISA_MIPS2:
16067         case ISA_MIPS32:
16068         case ISA_MIPS32R2:
16069           mips_opts.gp32 = 1;
16070           mips_opts.fp32 = 1;
16071           break;
16072         case ISA_MIPS3:
16073         case ISA_MIPS4:
16074         case ISA_MIPS5:
16075         case ISA_MIPS64:
16076         case ISA_MIPS64R2:
16077           mips_opts.gp32 = 0;
16078           if (mips_opts.arch == CPU_R5900)
16079             {
16080                 mips_opts.fp32 = 1;
16081             }
16082           else
16083             {
16084           mips_opts.fp32 = 0;
16085             }
16086           break;
16087         default:
16088           as_bad (_("unknown ISA level %s"), name + 4);
16089           break;
16090         }
16091       if (reset)
16092         {
16093           mips_opts.gp32 = file_mips_gp32;
16094           mips_opts.fp32 = file_mips_fp32;
16095         }
16096     }
16097   else if (strcmp (name, "autoextend") == 0)
16098     mips_opts.noautoextend = 0;
16099   else if (strcmp (name, "noautoextend") == 0)
16100     mips_opts.noautoextend = 1;
16101   else if (strcmp (name, "insn32") == 0)
16102     mips_opts.insn32 = TRUE;
16103   else if (strcmp (name, "noinsn32") == 0)
16104     mips_opts.insn32 = FALSE;
16105   else if (strcmp (name, "push") == 0)
16106     {
16107       struct mips_option_stack *s;
16108
16109       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16110       s->next = mips_opts_stack;
16111       s->options = mips_opts;
16112       mips_opts_stack = s;
16113     }
16114   else if (strcmp (name, "pop") == 0)
16115     {
16116       struct mips_option_stack *s;
16117
16118       s = mips_opts_stack;
16119       if (s == NULL)
16120         as_bad (_(".set pop with no .set push"));
16121       else
16122         {
16123           /* If we're changing the reorder mode we need to handle
16124              delay slots correctly.  */
16125           if (s->options.noreorder && ! mips_opts.noreorder)
16126             start_noreorder ();
16127           else if (! s->options.noreorder && mips_opts.noreorder)
16128             end_noreorder ();
16129
16130           mips_opts = s->options;
16131           mips_opts_stack = s->next;
16132           free (s);
16133         }
16134     }
16135   else if (strcmp (name, "sym32") == 0)
16136     mips_opts.sym32 = TRUE;
16137   else if (strcmp (name, "nosym32") == 0)
16138     mips_opts.sym32 = FALSE;
16139   else if (strchr (name, ','))
16140     {
16141       /* Generic ".set" directive; use the generic handler.  */
16142       *input_line_pointer = ch;
16143       input_line_pointer = name;
16144       s_set (0);
16145       return;
16146     }
16147   else
16148     {
16149       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16150     }
16151   mips_check_isa_supports_ases ();
16152   *input_line_pointer = ch;
16153   demand_empty_rest_of_line ();
16154 }
16155
16156 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16157    .option pic2.  It means to generate SVR4 PIC calls.  */
16158
16159 static void
16160 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16161 {
16162   mips_pic = SVR4_PIC;
16163   mips_abicalls = TRUE;
16164
16165   if (g_switch_seen && g_switch_value != 0)
16166     as_warn (_("-G may not be used with SVR4 PIC code"));
16167   g_switch_value = 0;
16168
16169   bfd_set_gp_size (stdoutput, 0);
16170   demand_empty_rest_of_line ();
16171 }
16172
16173 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16174    PIC code.  It sets the $gp register for the function based on the
16175    function address, which is in the register named in the argument.
16176    This uses a relocation against _gp_disp, which is handled specially
16177    by the linker.  The result is:
16178         lui     $gp,%hi(_gp_disp)
16179         addiu   $gp,$gp,%lo(_gp_disp)
16180         addu    $gp,$gp,.cpload argument
16181    The .cpload argument is normally $25 == $t9.
16182
16183    The -mno-shared option changes this to:
16184         lui     $gp,%hi(__gnu_local_gp)
16185         addiu   $gp,$gp,%lo(__gnu_local_gp)
16186    and the argument is ignored.  This saves an instruction, but the
16187    resulting code is not position independent; it uses an absolute
16188    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16189    can go into an ordinary executable, but not into a shared library.  */
16190
16191 static void
16192 s_cpload (int ignore ATTRIBUTE_UNUSED)
16193 {
16194   expressionS ex;
16195   int reg;
16196   int in_shared;
16197
16198   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16199      .cpload is ignored.  */
16200   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16201     {
16202       s_ignore (0);
16203       return;
16204     }
16205
16206   if (mips_opts.mips16)
16207     {
16208       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16209       ignore_rest_of_line ();
16210       return;
16211     }
16212
16213   /* .cpload should be in a .set noreorder section.  */
16214   if (mips_opts.noreorder == 0)
16215     as_warn (_(".cpload not in noreorder section"));
16216
16217   reg = tc_get_register (0);
16218
16219   /* If we need to produce a 64-bit address, we are better off using
16220      the default instruction sequence.  */
16221   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16222
16223   ex.X_op = O_symbol;
16224   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16225                                          "__gnu_local_gp");
16226   ex.X_op_symbol = NULL;
16227   ex.X_add_number = 0;
16228
16229   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16230   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16231
16232   mips_mark_labels ();
16233   mips_assembling_insn = TRUE;
16234
16235   macro_start ();
16236   macro_build_lui (&ex, mips_gp_register);
16237   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16238                mips_gp_register, BFD_RELOC_LO16);
16239   if (in_shared)
16240     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16241                  mips_gp_register, reg);
16242   macro_end ();
16243
16244   mips_assembling_insn = FALSE;
16245   demand_empty_rest_of_line ();
16246 }
16247
16248 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16249      .cpsetup $reg1, offset|$reg2, label
16250
16251    If offset is given, this results in:
16252      sd         $gp, offset($sp)
16253      lui        $gp, %hi(%neg(%gp_rel(label)))
16254      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16255      daddu      $gp, $gp, $reg1
16256
16257    If $reg2 is given, this results in:
16258      daddu      $reg2, $gp, $0
16259      lui        $gp, %hi(%neg(%gp_rel(label)))
16260      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16261      daddu      $gp, $gp, $reg1
16262    $reg1 is normally $25 == $t9.
16263
16264    The -mno-shared option replaces the last three instructions with
16265         lui     $gp,%hi(_gp)
16266         addiu   $gp,$gp,%lo(_gp)  */
16267
16268 static void
16269 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16270 {
16271   expressionS ex_off;
16272   expressionS ex_sym;
16273   int reg1;
16274
16275   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16276      We also need NewABI support.  */
16277   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16278     {
16279       s_ignore (0);
16280       return;
16281     }
16282
16283   if (mips_opts.mips16)
16284     {
16285       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16286       ignore_rest_of_line ();
16287       return;
16288     }
16289
16290   reg1 = tc_get_register (0);
16291   SKIP_WHITESPACE ();
16292   if (*input_line_pointer != ',')
16293     {
16294       as_bad (_("missing argument separator ',' for .cpsetup"));
16295       return;
16296     }
16297   else
16298     ++input_line_pointer;
16299   SKIP_WHITESPACE ();
16300   if (*input_line_pointer == '$')
16301     {
16302       mips_cpreturn_register = tc_get_register (0);
16303       mips_cpreturn_offset = -1;
16304     }
16305   else
16306     {
16307       mips_cpreturn_offset = get_absolute_expression ();
16308       mips_cpreturn_register = -1;
16309     }
16310   SKIP_WHITESPACE ();
16311   if (*input_line_pointer != ',')
16312     {
16313       as_bad (_("missing argument separator ',' for .cpsetup"));
16314       return;
16315     }
16316   else
16317     ++input_line_pointer;
16318   SKIP_WHITESPACE ();
16319   expression (&ex_sym);
16320
16321   mips_mark_labels ();
16322   mips_assembling_insn = TRUE;
16323
16324   macro_start ();
16325   if (mips_cpreturn_register == -1)
16326     {
16327       ex_off.X_op = O_constant;
16328       ex_off.X_add_symbol = NULL;
16329       ex_off.X_op_symbol = NULL;
16330       ex_off.X_add_number = mips_cpreturn_offset;
16331
16332       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16333                    BFD_RELOC_LO16, SP);
16334     }
16335   else
16336     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16337                  mips_gp_register, 0);
16338
16339   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16340     {
16341       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16342                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16343                    BFD_RELOC_HI16_S);
16344
16345       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16346                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16347                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16348
16349       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16350                    mips_gp_register, reg1);
16351     }
16352   else
16353     {
16354       expressionS ex;
16355
16356       ex.X_op = O_symbol;
16357       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16358       ex.X_op_symbol = NULL;
16359       ex.X_add_number = 0;
16360
16361       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16362       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16363
16364       macro_build_lui (&ex, mips_gp_register);
16365       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16366                    mips_gp_register, BFD_RELOC_LO16);
16367     }
16368
16369   macro_end ();
16370
16371   mips_assembling_insn = FALSE;
16372   demand_empty_rest_of_line ();
16373 }
16374
16375 static void
16376 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16377 {
16378   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16379      .cplocal is ignored.  */
16380   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16381     {
16382       s_ignore (0);
16383       return;
16384     }
16385
16386   if (mips_opts.mips16)
16387     {
16388       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16389       ignore_rest_of_line ();
16390       return;
16391     }
16392
16393   mips_gp_register = tc_get_register (0);
16394   demand_empty_rest_of_line ();
16395 }
16396
16397 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16398    offset from $sp.  The offset is remembered, and after making a PIC
16399    call $gp is restored from that location.  */
16400
16401 static void
16402 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16403 {
16404   expressionS ex;
16405
16406   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16407      .cprestore is ignored.  */
16408   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16409     {
16410       s_ignore (0);
16411       return;
16412     }
16413
16414   if (mips_opts.mips16)
16415     {
16416       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16417       ignore_rest_of_line ();
16418       return;
16419     }
16420
16421   mips_cprestore_offset = get_absolute_expression ();
16422   mips_cprestore_valid = 1;
16423
16424   ex.X_op = O_constant;
16425   ex.X_add_symbol = NULL;
16426   ex.X_op_symbol = NULL;
16427   ex.X_add_number = mips_cprestore_offset;
16428
16429   mips_mark_labels ();
16430   mips_assembling_insn = TRUE;
16431
16432   macro_start ();
16433   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16434                                 SP, HAVE_64BIT_ADDRESSES);
16435   macro_end ();
16436
16437   mips_assembling_insn = FALSE;
16438   demand_empty_rest_of_line ();
16439 }
16440
16441 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16442    was given in the preceding .cpsetup, it results in:
16443      ld         $gp, offset($sp)
16444
16445    If a register $reg2 was given there, it results in:
16446      daddu      $gp, $reg2, $0  */
16447
16448 static void
16449 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16450 {
16451   expressionS ex;
16452
16453   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16454      We also need NewABI support.  */
16455   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16456     {
16457       s_ignore (0);
16458       return;
16459     }
16460
16461   if (mips_opts.mips16)
16462     {
16463       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16464       ignore_rest_of_line ();
16465       return;
16466     }
16467
16468   mips_mark_labels ();
16469   mips_assembling_insn = TRUE;
16470
16471   macro_start ();
16472   if (mips_cpreturn_register == -1)
16473     {
16474       ex.X_op = O_constant;
16475       ex.X_add_symbol = NULL;
16476       ex.X_op_symbol = NULL;
16477       ex.X_add_number = mips_cpreturn_offset;
16478
16479       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16480     }
16481   else
16482     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
16483                  mips_cpreturn_register, 0);
16484   macro_end ();
16485
16486   mips_assembling_insn = FALSE;
16487   demand_empty_rest_of_line ();
16488 }
16489
16490 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16491    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16492    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16493    debug information or MIPS16 TLS.  */
16494
16495 static void
16496 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16497                      bfd_reloc_code_real_type rtype)
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"), dirstr);
16507       ignore_rest_of_line ();
16508     }
16509
16510   p = frag_more (bytes);
16511   md_number_to_chars (p, 0, bytes);
16512   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16513   demand_empty_rest_of_line ();
16514   mips_clear_insn_labels ();
16515 }
16516
16517 /* Handle .dtprelword.  */
16518
16519 static void
16520 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16521 {
16522   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16523 }
16524
16525 /* Handle .dtpreldword.  */
16526
16527 static void
16528 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16529 {
16530   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16531 }
16532
16533 /* Handle .tprelword.  */
16534
16535 static void
16536 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16537 {
16538   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16539 }
16540
16541 /* Handle .tpreldword.  */
16542
16543 static void
16544 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16545 {
16546   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16547 }
16548
16549 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16550    code.  It sets the offset to use in gp_rel relocations.  */
16551
16552 static void
16553 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16554 {
16555   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16556      We also need NewABI support.  */
16557   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16558     {
16559       s_ignore (0);
16560       return;
16561     }
16562
16563   mips_gprel_offset = get_absolute_expression ();
16564
16565   demand_empty_rest_of_line ();
16566 }
16567
16568 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16569    code.  It generates a 32 bit GP relative reloc.  */
16570
16571 static void
16572 s_gpword (int ignore ATTRIBUTE_UNUSED)
16573 {
16574   segment_info_type *si;
16575   struct insn_label_list *l;
16576   expressionS ex;
16577   char *p;
16578
16579   /* When not generating PIC code, this is treated as .word.  */
16580   if (mips_pic != SVR4_PIC)
16581     {
16582       s_cons (2);
16583       return;
16584     }
16585
16586   si = seg_info (now_seg);
16587   l = si->label_list;
16588   mips_emit_delays ();
16589   if (auto_align)
16590     mips_align (2, 0, l);
16591
16592   expression (&ex);
16593   mips_clear_insn_labels ();
16594
16595   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16596     {
16597       as_bad (_("Unsupported use of .gpword"));
16598       ignore_rest_of_line ();
16599     }
16600
16601   p = frag_more (4);
16602   md_number_to_chars (p, 0, 4);
16603   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16604                BFD_RELOC_GPREL32);
16605
16606   demand_empty_rest_of_line ();
16607 }
16608
16609 static void
16610 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16611 {
16612   segment_info_type *si;
16613   struct insn_label_list *l;
16614   expressionS ex;
16615   char *p;
16616
16617   /* When not generating PIC code, this is treated as .dword.  */
16618   if (mips_pic != SVR4_PIC)
16619     {
16620       s_cons (3);
16621       return;
16622     }
16623
16624   si = seg_info (now_seg);
16625   l = si->label_list;
16626   mips_emit_delays ();
16627   if (auto_align)
16628     mips_align (3, 0, l);
16629
16630   expression (&ex);
16631   mips_clear_insn_labels ();
16632
16633   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16634     {
16635       as_bad (_("Unsupported use of .gpdword"));
16636       ignore_rest_of_line ();
16637     }
16638
16639   p = frag_more (8);
16640   md_number_to_chars (p, 0, 8);
16641   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16642                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16643
16644   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16645   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16646            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16647
16648   demand_empty_rest_of_line ();
16649 }
16650
16651 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
16652    tables.  It generates a R_MIPS_EH reloc.  */
16653
16654 static void
16655 s_ehword (int ignore ATTRIBUTE_UNUSED)
16656 {
16657   expressionS ex;
16658   char *p;
16659
16660   mips_emit_delays ();
16661
16662   expression (&ex);
16663   mips_clear_insn_labels ();
16664
16665   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16666     {
16667       as_bad (_("Unsupported use of .ehword"));
16668       ignore_rest_of_line ();
16669     }
16670
16671   p = frag_more (4);
16672   md_number_to_chars (p, 0, 4);
16673   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16674                BFD_RELOC_MIPS_EH);
16675
16676   demand_empty_rest_of_line ();
16677 }
16678
16679 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16680    tables in SVR4 PIC code.  */
16681
16682 static void
16683 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16684 {
16685   int reg;
16686
16687   /* This is ignored when not generating SVR4 PIC code.  */
16688   if (mips_pic != SVR4_PIC)
16689     {
16690       s_ignore (0);
16691       return;
16692     }
16693
16694   mips_mark_labels ();
16695   mips_assembling_insn = TRUE;
16696
16697   /* Add $gp to the register named as an argument.  */
16698   macro_start ();
16699   reg = tc_get_register (0);
16700   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16701   macro_end ();
16702
16703   mips_assembling_insn = FALSE;
16704   demand_empty_rest_of_line ();
16705 }
16706
16707 /* Handle the .insn pseudo-op.  This marks instruction labels in
16708    mips16/micromips mode.  This permits the linker to handle them specially,
16709    such as generating jalx instructions when needed.  We also make
16710    them odd for the duration of the assembly, in order to generate the
16711    right sort of code.  We will make them even in the adjust_symtab
16712    routine, while leaving them marked.  This is convenient for the
16713    debugger and the disassembler.  The linker knows to make them odd
16714    again.  */
16715
16716 static void
16717 s_insn (int ignore ATTRIBUTE_UNUSED)
16718 {
16719   mips_mark_labels ();
16720
16721   demand_empty_rest_of_line ();
16722 }
16723
16724 /* Handle the .nan pseudo-op.  */
16725
16726 static void
16727 s_nan (int ignore ATTRIBUTE_UNUSED)
16728 {
16729   static const char str_legacy[] = "legacy";
16730   static const char str_2008[] = "2008";
16731   size_t i;
16732
16733   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16734
16735   if (i == sizeof (str_2008) - 1
16736       && memcmp (input_line_pointer, str_2008, i) == 0)
16737     mips_flag_nan2008 = TRUE;
16738   else if (i == sizeof (str_legacy) - 1
16739            && memcmp (input_line_pointer, str_legacy, i) == 0)
16740     mips_flag_nan2008 = FALSE;
16741   else
16742     as_bad (_("Bad .nan directive"));
16743
16744   input_line_pointer += i;
16745   demand_empty_rest_of_line ();
16746 }
16747
16748 /* Handle a .stab[snd] directive.  Ideally these directives would be
16749    implemented in a transparent way, so that removing them would not
16750    have any effect on the generated instructions.  However, s_stab
16751    internally changes the section, so in practice we need to decide
16752    now whether the preceding label marks compressed code.  We do not
16753    support changing the compression mode of a label after a .stab*
16754    directive, such as in:
16755
16756    foo:
16757         .stabs ...
16758         .set mips16
16759
16760    so the current mode wins.  */
16761
16762 static void
16763 s_mips_stab (int type)
16764 {
16765   mips_mark_labels ();
16766   s_stab (type);
16767 }
16768
16769 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16770
16771 static void
16772 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16773 {
16774   char *name;
16775   int c;
16776   symbolS *symbolP;
16777   expressionS exp;
16778
16779   name = input_line_pointer;
16780   c = get_symbol_end ();
16781   symbolP = symbol_find_or_make (name);
16782   S_SET_WEAK (symbolP);
16783   *input_line_pointer = c;
16784
16785   SKIP_WHITESPACE ();
16786
16787   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16788     {
16789       if (S_IS_DEFINED (symbolP))
16790         {
16791           as_bad (_("ignoring attempt to redefine symbol %s"),
16792                   S_GET_NAME (symbolP));
16793           ignore_rest_of_line ();
16794           return;
16795         }
16796
16797       if (*input_line_pointer == ',')
16798         {
16799           ++input_line_pointer;
16800           SKIP_WHITESPACE ();
16801         }
16802
16803       expression (&exp);
16804       if (exp.X_op != O_symbol)
16805         {
16806           as_bad (_("bad .weakext directive"));
16807           ignore_rest_of_line ();
16808           return;
16809         }
16810       symbol_set_value_expression (symbolP, &exp);
16811     }
16812
16813   demand_empty_rest_of_line ();
16814 }
16815
16816 /* Parse a register string into a number.  Called from the ECOFF code
16817    to parse .frame.  The argument is non-zero if this is the frame
16818    register, so that we can record it in mips_frame_reg.  */
16819
16820 int
16821 tc_get_register (int frame)
16822 {
16823   unsigned int reg;
16824
16825   SKIP_WHITESPACE ();
16826   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16827     reg = 0;
16828   if (frame)
16829     {
16830       mips_frame_reg = reg != 0 ? reg : SP;
16831       mips_frame_reg_valid = 1;
16832       mips_cprestore_valid = 0;
16833     }
16834   return reg;
16835 }
16836
16837 valueT
16838 md_section_align (asection *seg, valueT addr)
16839 {
16840   int align = bfd_get_section_alignment (stdoutput, seg);
16841
16842   /* We don't need to align ELF sections to the full alignment.
16843      However, Irix 5 may prefer that we align them at least to a 16
16844      byte boundary.  We don't bother to align the sections if we
16845      are targeted for an embedded system.  */
16846   if (strncmp (TARGET_OS, "elf", 3) == 0)
16847     return addr;
16848   if (align > 4)
16849     align = 4;
16850
16851   return ((addr + (1 << align) - 1) & (-1 << align));
16852 }
16853
16854 /* Utility routine, called from above as well.  If called while the
16855    input file is still being read, it's only an approximation.  (For
16856    example, a symbol may later become defined which appeared to be
16857    undefined earlier.)  */
16858
16859 static int
16860 nopic_need_relax (symbolS *sym, int before_relaxing)
16861 {
16862   if (sym == 0)
16863     return 0;
16864
16865   if (g_switch_value > 0)
16866     {
16867       const char *symname;
16868       int change;
16869
16870       /* Find out whether this symbol can be referenced off the $gp
16871          register.  It can be if it is smaller than the -G size or if
16872          it is in the .sdata or .sbss section.  Certain symbols can
16873          not be referenced off the $gp, although it appears as though
16874          they can.  */
16875       symname = S_GET_NAME (sym);
16876       if (symname != (const char *) NULL
16877           && (strcmp (symname, "eprol") == 0
16878               || strcmp (symname, "etext") == 0
16879               || strcmp (symname, "_gp") == 0
16880               || strcmp (symname, "edata") == 0
16881               || strcmp (symname, "_fbss") == 0
16882               || strcmp (symname, "_fdata") == 0
16883               || strcmp (symname, "_ftext") == 0
16884               || strcmp (symname, "end") == 0
16885               || strcmp (symname, "_gp_disp") == 0))
16886         change = 1;
16887       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16888                && (0
16889 #ifndef NO_ECOFF_DEBUGGING
16890                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16891                        && (symbol_get_obj (sym)->ecoff_extern_size
16892                            <= g_switch_value))
16893 #endif
16894                    /* We must defer this decision until after the whole
16895                       file has been read, since there might be a .extern
16896                       after the first use of this symbol.  */
16897                    || (before_relaxing
16898 #ifndef NO_ECOFF_DEBUGGING
16899                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16900 #endif
16901                        && S_GET_VALUE (sym) == 0)
16902                    || (S_GET_VALUE (sym) != 0
16903                        && S_GET_VALUE (sym) <= g_switch_value)))
16904         change = 0;
16905       else
16906         {
16907           const char *segname;
16908
16909           segname = segment_name (S_GET_SEGMENT (sym));
16910           gas_assert (strcmp (segname, ".lit8") != 0
16911                   && strcmp (segname, ".lit4") != 0);
16912           change = (strcmp (segname, ".sdata") != 0
16913                     && strcmp (segname, ".sbss") != 0
16914                     && strncmp (segname, ".sdata.", 7) != 0
16915                     && strncmp (segname, ".sbss.", 6) != 0
16916                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16917                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16918         }
16919       return change;
16920     }
16921   else
16922     /* We are not optimizing for the $gp register.  */
16923     return 1;
16924 }
16925
16926
16927 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16928
16929 static bfd_boolean
16930 pic_need_relax (symbolS *sym, asection *segtype)
16931 {
16932   asection *symsec;
16933
16934   /* Handle the case of a symbol equated to another symbol.  */
16935   while (symbol_equated_reloc_p (sym))
16936     {
16937       symbolS *n;
16938
16939       /* It's possible to get a loop here in a badly written program.  */
16940       n = symbol_get_value_expression (sym)->X_add_symbol;
16941       if (n == sym)
16942         break;
16943       sym = n;
16944     }
16945
16946   if (symbol_section_p (sym))
16947     return TRUE;
16948
16949   symsec = S_GET_SEGMENT (sym);
16950
16951   /* This must duplicate the test in adjust_reloc_syms.  */
16952   return (!bfd_is_und_section (symsec)
16953           && !bfd_is_abs_section (symsec)
16954           && !bfd_is_com_section (symsec)
16955           && !s_is_linkonce (sym, segtype)
16956           /* A global or weak symbol is treated as external.  */
16957           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16958 }
16959
16960
16961 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16962    extended opcode.  SEC is the section the frag is in.  */
16963
16964 static int
16965 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16966 {
16967   int type;
16968   const struct mips16_immed_operand *op;
16969   offsetT val;
16970   int mintiny, maxtiny;
16971   segT symsec;
16972   fragS *sym_frag;
16973
16974   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16975     return 0;
16976   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16977     return 1;
16978
16979   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16980   op = mips16_immed_operands;
16981   while (op->type != type)
16982     {
16983       ++op;
16984       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
16985     }
16986
16987   if (op->unsp)
16988     {
16989       if (type == '<' || type == '>' || type == '[' || type == ']')
16990         {
16991           mintiny = 1;
16992           maxtiny = 1 << op->nbits;
16993         }
16994       else
16995         {
16996           mintiny = 0;
16997           maxtiny = (1 << op->nbits) - 1;
16998         }
16999     }
17000   else
17001     {
17002       mintiny = - (1 << (op->nbits - 1));
17003       maxtiny = (1 << (op->nbits - 1)) - 1;
17004     }
17005
17006   sym_frag = symbol_get_frag (fragp->fr_symbol);
17007   val = S_GET_VALUE (fragp->fr_symbol);
17008   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17009
17010   if (op->pcrel)
17011     {
17012       addressT addr;
17013
17014       /* We won't have the section when we are called from
17015          mips_relax_frag.  However, we will always have been called
17016          from md_estimate_size_before_relax first.  If this is a
17017          branch to a different section, we mark it as such.  If SEC is
17018          NULL, and the frag is not marked, then it must be a branch to
17019          the same section.  */
17020       if (sec == NULL)
17021         {
17022           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17023             return 1;
17024         }
17025       else
17026         {
17027           /* Must have been called from md_estimate_size_before_relax.  */
17028           if (symsec != sec)
17029             {
17030               fragp->fr_subtype =
17031                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17032
17033               /* FIXME: We should support this, and let the linker
17034                  catch branches and loads that are out of range.  */
17035               as_bad_where (fragp->fr_file, fragp->fr_line,
17036                             _("unsupported PC relative reference to different section"));
17037
17038               return 1;
17039             }
17040           if (fragp != sym_frag && sym_frag->fr_address == 0)
17041             /* Assume non-extended on the first relaxation pass.
17042                The address we have calculated will be bogus if this is
17043                a forward branch to another frag, as the forward frag
17044                will have fr_address == 0.  */
17045             return 0;
17046         }
17047
17048       /* In this case, we know for sure that the symbol fragment is in
17049          the same section.  If the relax_marker of the symbol fragment
17050          differs from the relax_marker of this fragment, we have not
17051          yet adjusted the symbol fragment fr_address.  We want to add
17052          in STRETCH in order to get a better estimate of the address.
17053          This particularly matters because of the shift bits.  */
17054       if (stretch != 0
17055           && sym_frag->relax_marker != fragp->relax_marker)
17056         {
17057           fragS *f;
17058
17059           /* Adjust stretch for any alignment frag.  Note that if have
17060              been expanding the earlier code, the symbol may be
17061              defined in what appears to be an earlier frag.  FIXME:
17062              This doesn't handle the fr_subtype field, which specifies
17063              a maximum number of bytes to skip when doing an
17064              alignment.  */
17065           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17066             {
17067               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17068                 {
17069                   if (stretch < 0)
17070                     stretch = - ((- stretch)
17071                                  & ~ ((1 << (int) f->fr_offset) - 1));
17072                   else
17073                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17074                   if (stretch == 0)
17075                     break;
17076                 }
17077             }
17078           if (f != NULL)
17079             val += stretch;
17080         }
17081
17082       addr = fragp->fr_address + fragp->fr_fix;
17083
17084       /* The base address rules are complicated.  The base address of
17085          a branch is the following instruction.  The base address of a
17086          PC relative load or add is the instruction itself, but if it
17087          is in a delay slot (in which case it can not be extended) use
17088          the address of the instruction whose delay slot it is in.  */
17089       if (type == 'p' || type == 'q')
17090         {
17091           addr += 2;
17092
17093           /* If we are currently assuming that this frag should be
17094              extended, then, the current address is two bytes
17095              higher.  */
17096           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17097             addr += 2;
17098
17099           /* Ignore the low bit in the target, since it will be set
17100              for a text label.  */
17101           if ((val & 1) != 0)
17102             --val;
17103         }
17104       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17105         addr -= 4;
17106       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17107         addr -= 2;
17108
17109       val -= addr & ~ ((1 << op->shift) - 1);
17110
17111       /* Branch offsets have an implicit 0 in the lowest bit.  */
17112       if (type == 'p' || type == 'q')
17113         val /= 2;
17114
17115       /* If any of the shifted bits are set, we must use an extended
17116          opcode.  If the address depends on the size of this
17117          instruction, this can lead to a loop, so we arrange to always
17118          use an extended opcode.  We only check this when we are in
17119          the main relaxation loop, when SEC is NULL.  */
17120       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17121         {
17122           fragp->fr_subtype =
17123             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17124           return 1;
17125         }
17126
17127       /* If we are about to mark a frag as extended because the value
17128          is precisely maxtiny + 1, then there is a chance of an
17129          infinite loop as in the following code:
17130              la $4,foo
17131              .skip      1020
17132              .align     2
17133            foo:
17134          In this case when the la is extended, foo is 0x3fc bytes
17135          away, so the la can be shrunk, but then foo is 0x400 away, so
17136          the la must be extended.  To avoid this loop, we mark the
17137          frag as extended if it was small, and is about to become
17138          extended with a value of maxtiny + 1.  */
17139       if (val == ((maxtiny + 1) << op->shift)
17140           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17141           && sec == NULL)
17142         {
17143           fragp->fr_subtype =
17144             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17145           return 1;
17146         }
17147     }
17148   else if (symsec != absolute_section && sec != NULL)
17149     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17150
17151   if ((val & ((1 << op->shift) - 1)) != 0
17152       || val < (mintiny << op->shift)
17153       || val > (maxtiny << op->shift))
17154     return 1;
17155   else
17156     return 0;
17157 }
17158
17159 /* Compute the length of a branch sequence, and adjust the
17160    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17161    worst-case length is computed, with UPDATE being used to indicate
17162    whether an unconditional (-1), branch-likely (+1) or regular (0)
17163    branch is to be computed.  */
17164 static int
17165 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17166 {
17167   bfd_boolean toofar;
17168   int length;
17169
17170   if (fragp
17171       && S_IS_DEFINED (fragp->fr_symbol)
17172       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17173     {
17174       addressT addr;
17175       offsetT val;
17176
17177       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17178
17179       addr = fragp->fr_address + fragp->fr_fix + 4;
17180
17181       val -= addr;
17182
17183       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17184     }
17185   else if (fragp)
17186     /* If the symbol is not defined or it's in a different segment,
17187        assume the user knows what's going on and emit a short
17188        branch.  */
17189     toofar = FALSE;
17190   else
17191     toofar = TRUE;
17192
17193   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17194     fragp->fr_subtype
17195       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17196                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17197                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17198                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17199                              toofar);
17200
17201   length = 4;
17202   if (toofar)
17203     {
17204       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17205         length += 8;
17206
17207       if (mips_pic != NO_PIC)
17208         {
17209           /* Additional space for PIC loading of target address.  */
17210           length += 8;
17211           if (mips_opts.isa == ISA_MIPS1)
17212             /* Additional space for $at-stabilizing nop.  */
17213             length += 4;
17214         }
17215
17216       /* If branch is conditional.  */
17217       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17218         length += 8;
17219     }
17220
17221   return length;
17222 }
17223
17224 /* Compute the length of a branch sequence, and adjust the
17225    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17226    worst-case length is computed, with UPDATE being used to indicate
17227    whether an unconditional (-1), or regular (0) branch is to be
17228    computed.  */
17229
17230 static int
17231 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17232 {
17233   bfd_boolean toofar;
17234   int length;
17235
17236   if (fragp
17237       && S_IS_DEFINED (fragp->fr_symbol)
17238       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17239     {
17240       addressT addr;
17241       offsetT val;
17242
17243       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17244       /* Ignore the low bit in the target, since it will be set
17245          for a text label.  */
17246       if ((val & 1) != 0)
17247         --val;
17248
17249       addr = fragp->fr_address + fragp->fr_fix + 4;
17250
17251       val -= addr;
17252
17253       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17254     }
17255   else if (fragp)
17256     /* If the symbol is not defined or it's in a different segment,
17257        assume the user knows what's going on and emit a short
17258        branch.  */
17259     toofar = FALSE;
17260   else
17261     toofar = TRUE;
17262
17263   if (fragp && update
17264       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17265     fragp->fr_subtype = (toofar
17266                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17267                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17268
17269   length = 4;
17270   if (toofar)
17271     {
17272       bfd_boolean compact_known = fragp != NULL;
17273       bfd_boolean compact = FALSE;
17274       bfd_boolean uncond;
17275
17276       if (compact_known)
17277         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17278       if (fragp)
17279         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17280       else
17281         uncond = update < 0;
17282
17283       /* If label is out of range, we turn branch <br>:
17284
17285                 <br>    label                   # 4 bytes
17286             0:
17287
17288          into:
17289
17290                 j       label                   # 4 bytes
17291                 nop                             # 2 bytes if compact && !PIC
17292             0:
17293        */
17294       if (mips_pic == NO_PIC && (!compact_known || compact))
17295         length += 2;
17296
17297       /* If assembling PIC code, we further turn:
17298
17299                         j       label                   # 4 bytes
17300
17301          into:
17302
17303                         lw/ld   at, %got(label)(gp)     # 4 bytes
17304                         d/addiu at, %lo(label)          # 4 bytes
17305                         jr/c    at                      # 2 bytes
17306        */
17307       if (mips_pic != NO_PIC)
17308         length += 6;
17309
17310       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17311
17312                         <brneg> 0f                      # 4 bytes
17313                         nop                             # 2 bytes if !compact
17314        */
17315       if (!uncond)
17316         length += (compact_known && compact) ? 4 : 6;
17317     }
17318
17319   return length;
17320 }
17321
17322 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17323    bit accordingly.  */
17324
17325 static int
17326 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17327 {
17328   bfd_boolean toofar;
17329
17330   if (fragp
17331       && S_IS_DEFINED (fragp->fr_symbol)
17332       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17333     {
17334       addressT addr;
17335       offsetT val;
17336       int type;
17337
17338       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17339       /* Ignore the low bit in the target, since it will be set
17340          for a text label.  */
17341       if ((val & 1) != 0)
17342         --val;
17343
17344       /* Assume this is a 2-byte branch.  */
17345       addr = fragp->fr_address + fragp->fr_fix + 2;
17346
17347       /* We try to avoid the infinite loop by not adding 2 more bytes for
17348          long branches.  */
17349
17350       val -= addr;
17351
17352       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17353       if (type == 'D')
17354         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17355       else if (type == 'E')
17356         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17357       else
17358         abort ();
17359     }
17360   else
17361     /* If the symbol is not defined or it's in a different segment,
17362        we emit a normal 32-bit branch.  */
17363     toofar = TRUE;
17364
17365   if (fragp && update
17366       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17367     fragp->fr_subtype
17368       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17369                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17370
17371   if (toofar)
17372     return 4;
17373
17374   return 2;
17375 }
17376
17377 /* Estimate the size of a frag before relaxing.  Unless this is the
17378    mips16, we are not really relaxing here, and the final size is
17379    encoded in the subtype information.  For the mips16, we have to
17380    decide whether we are using an extended opcode or not.  */
17381
17382 int
17383 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17384 {
17385   int change;
17386
17387   if (RELAX_BRANCH_P (fragp->fr_subtype))
17388     {
17389
17390       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17391
17392       return fragp->fr_var;
17393     }
17394
17395   if (RELAX_MIPS16_P (fragp->fr_subtype))
17396     /* We don't want to modify the EXTENDED bit here; it might get us
17397        into infinite loops.  We change it only in mips_relax_frag().  */
17398     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17399
17400   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17401     {
17402       int length = 4;
17403
17404       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17405         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17406       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17407         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17408       fragp->fr_var = length;
17409
17410       return length;
17411     }
17412
17413   if (mips_pic == NO_PIC)
17414     change = nopic_need_relax (fragp->fr_symbol, 0);
17415   else if (mips_pic == SVR4_PIC)
17416     change = pic_need_relax (fragp->fr_symbol, segtype);
17417   else if (mips_pic == VXWORKS_PIC)
17418     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17419     change = 0;
17420   else
17421     abort ();
17422
17423   if (change)
17424     {
17425       fragp->fr_subtype |= RELAX_USE_SECOND;
17426       return -RELAX_FIRST (fragp->fr_subtype);
17427     }
17428   else
17429     return -RELAX_SECOND (fragp->fr_subtype);
17430 }
17431
17432 /* This is called to see whether a reloc against a defined symbol
17433    should be converted into a reloc against a section.  */
17434
17435 int
17436 mips_fix_adjustable (fixS *fixp)
17437 {
17438   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17439       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17440     return 0;
17441
17442   if (fixp->fx_addsy == NULL)
17443     return 1;
17444
17445   /* If symbol SYM is in a mergeable section, relocations of the form
17446      SYM + 0 can usually be made section-relative.  The mergeable data
17447      is then identified by the section offset rather than by the symbol.
17448
17449      However, if we're generating REL LO16 relocations, the offset is split
17450      between the LO16 and parterning high part relocation.  The linker will
17451      need to recalculate the complete offset in order to correctly identify
17452      the merge data.
17453
17454      The linker has traditionally not looked for the parterning high part
17455      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17456      placed anywhere.  Rather than break backwards compatibility by changing
17457      this, it seems better not to force the issue, and instead keep the
17458      original symbol.  This will work with either linker behavior.  */
17459   if ((lo16_reloc_p (fixp->fx_r_type)
17460        || reloc_needs_lo_p (fixp->fx_r_type))
17461       && HAVE_IN_PLACE_ADDENDS
17462       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17463     return 0;
17464
17465   /* There is no place to store an in-place offset for JALR relocations.
17466      Likewise an in-range offset of limited PC-relative relocations may
17467      overflow the in-place relocatable field if recalculated against the
17468      start address of the symbol's containing section.  */
17469   if (HAVE_IN_PLACE_ADDENDS
17470       && (limited_pcrel_reloc_p (fixp->fx_r_type)
17471           || jalr_reloc_p (fixp->fx_r_type)))
17472     return 0;
17473
17474   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17475      to a floating-point stub.  The same is true for non-R_MIPS16_26
17476      relocations against MIPS16 functions; in this case, the stub becomes
17477      the function's canonical address.
17478
17479      Floating-point stubs are stored in unique .mips16.call.* or
17480      .mips16.fn.* sections.  If a stub T for function F is in section S,
17481      the first relocation in section S must be against F; this is how the
17482      linker determines the target function.  All relocations that might
17483      resolve to T must also be against F.  We therefore have the following
17484      restrictions, which are given in an intentionally-redundant way:
17485
17486        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17487           symbols.
17488
17489        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17490           if that stub might be used.
17491
17492        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17493           symbols.
17494
17495        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17496           that stub might be used.
17497
17498      There is a further restriction:
17499
17500        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17501           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
17502           targets with in-place addends; the relocation field cannot
17503           encode the low bit.
17504
17505      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17506      against a MIPS16 symbol.  We deal with (5) by by not reducing any
17507      such relocations on REL targets.
17508
17509      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17510      relocation against some symbol R, no relocation against R may be
17511      reduced.  (Note that this deals with (2) as well as (1) because
17512      relocations against global symbols will never be reduced on ELF
17513      targets.)  This approach is a little simpler than trying to detect
17514      stub sections, and gives the "all or nothing" per-symbol consistency
17515      that we have for MIPS16 symbols.  */
17516   if (fixp->fx_subsy == NULL
17517       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17518           || *symbol_get_tc (fixp->fx_addsy)
17519           || (HAVE_IN_PLACE_ADDENDS
17520               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17521               && jmp_reloc_p (fixp->fx_r_type))))
17522     return 0;
17523
17524   return 1;
17525 }
17526
17527 /* Translate internal representation of relocation info to BFD target
17528    format.  */
17529
17530 arelent **
17531 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17532 {
17533   static arelent *retval[4];
17534   arelent *reloc;
17535   bfd_reloc_code_real_type code;
17536
17537   memset (retval, 0, sizeof(retval));
17538   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
17539   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
17540   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17541   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17542
17543   if (fixp->fx_pcrel)
17544     {
17545       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17546                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17547                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17548                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17549                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
17550
17551       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17552          Relocations want only the symbol offset.  */
17553       reloc->addend = fixp->fx_addnumber + reloc->address;
17554     }
17555   else
17556     reloc->addend = fixp->fx_addnumber;
17557
17558   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17559      entry to be used in the relocation's section offset.  */
17560   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17561     {
17562       reloc->address = reloc->addend;
17563       reloc->addend = 0;
17564     }
17565
17566   code = fixp->fx_r_type;
17567
17568   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17569   if (reloc->howto == NULL)
17570     {
17571       as_bad_where (fixp->fx_file, fixp->fx_line,
17572                     _("Can not represent %s relocation in this object file format"),
17573                     bfd_get_reloc_code_name (code));
17574       retval[0] = NULL;
17575     }
17576
17577   return retval;
17578 }
17579
17580 /* Relax a machine dependent frag.  This returns the amount by which
17581    the current size of the frag should change.  */
17582
17583 int
17584 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17585 {
17586   if (RELAX_BRANCH_P (fragp->fr_subtype))
17587     {
17588       offsetT old_var = fragp->fr_var;
17589
17590       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17591
17592       return fragp->fr_var - old_var;
17593     }
17594
17595   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17596     {
17597       offsetT old_var = fragp->fr_var;
17598       offsetT new_var = 4;
17599
17600       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17601         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17602       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17603         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17604       fragp->fr_var = new_var;
17605
17606       return new_var - old_var;
17607     }
17608
17609   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17610     return 0;
17611
17612   if (mips16_extended_frag (fragp, NULL, stretch))
17613     {
17614       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17615         return 0;
17616       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17617       return 2;
17618     }
17619   else
17620     {
17621       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17622         return 0;
17623       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17624       return -2;
17625     }
17626
17627   return 0;
17628 }
17629
17630 /* Convert a machine dependent frag.  */
17631
17632 void
17633 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17634 {
17635   if (RELAX_BRANCH_P (fragp->fr_subtype))
17636     {
17637       char *buf;
17638       unsigned long insn;
17639       expressionS exp;
17640       fixS *fixp;
17641
17642       buf = fragp->fr_literal + fragp->fr_fix;
17643       insn = read_insn (buf);
17644
17645       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17646         {
17647           /* We generate a fixup instead of applying it right now
17648              because, if there are linker relaxations, we're going to
17649              need the relocations.  */
17650           exp.X_op = O_symbol;
17651           exp.X_add_symbol = fragp->fr_symbol;
17652           exp.X_add_number = fragp->fr_offset;
17653
17654           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17655                               BFD_RELOC_16_PCREL_S2);
17656           fixp->fx_file = fragp->fr_file;
17657           fixp->fx_line = fragp->fr_line;
17658
17659           buf = write_insn (buf, insn);
17660         }
17661       else
17662         {
17663           int i;
17664
17665           as_warn_where (fragp->fr_file, fragp->fr_line,
17666                          _("Relaxed out-of-range branch into a jump"));
17667
17668           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17669             goto uncond;
17670
17671           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17672             {
17673               /* Reverse the branch.  */
17674               switch ((insn >> 28) & 0xf)
17675                 {
17676                 case 4:
17677                   /* bc[0-3][tf]l? instructions can have the condition
17678                      reversed by tweaking a single TF bit, and their
17679                      opcodes all have 0x4???????.  */
17680                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
17681                   insn ^= 0x00010000;
17682                   break;
17683
17684                 case 0:
17685                   /* bltz       0x04000000      bgez    0x04010000
17686                      bltzal     0x04100000      bgezal  0x04110000  */
17687                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17688                   insn ^= 0x00010000;
17689                   break;
17690
17691                 case 1:
17692                   /* beq        0x10000000      bne     0x14000000
17693                      blez       0x18000000      bgtz    0x1c000000  */
17694                   insn ^= 0x04000000;
17695                   break;
17696
17697                 default:
17698                   abort ();
17699                 }
17700             }
17701
17702           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17703             {
17704               /* Clear the and-link bit.  */
17705               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17706
17707               /* bltzal         0x04100000      bgezal  0x04110000
17708                  bltzall        0x04120000      bgezall 0x04130000  */
17709               insn &= ~0x00100000;
17710             }
17711
17712           /* Branch over the branch (if the branch was likely) or the
17713              full jump (not likely case).  Compute the offset from the
17714              current instruction to branch to.  */
17715           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17716             i = 16;
17717           else
17718             {
17719               /* How many bytes in instructions we've already emitted?  */
17720               i = buf - fragp->fr_literal - fragp->fr_fix;
17721               /* How many bytes in instructions from here to the end?  */
17722               i = fragp->fr_var - i;
17723             }
17724           /* Convert to instruction count.  */
17725           i >>= 2;
17726           /* Branch counts from the next instruction.  */
17727           i--;
17728           insn |= i;
17729           /* Branch over the jump.  */
17730           buf = write_insn (buf, insn);
17731
17732           /* nop */
17733           buf = write_insn (buf, 0);
17734
17735           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17736             {
17737               /* beql $0, $0, 2f */
17738               insn = 0x50000000;
17739               /* Compute the PC offset from the current instruction to
17740                  the end of the variable frag.  */
17741               /* How many bytes in instructions we've already emitted?  */
17742               i = buf - fragp->fr_literal - fragp->fr_fix;
17743               /* How many bytes in instructions from here to the end?  */
17744               i = fragp->fr_var - i;
17745               /* Convert to instruction count.  */
17746               i >>= 2;
17747               /* Don't decrement i, because we want to branch over the
17748                  delay slot.  */
17749               insn |= i;
17750
17751               buf = write_insn (buf, insn);
17752               buf = write_insn (buf, 0);
17753             }
17754
17755         uncond:
17756           if (mips_pic == NO_PIC)
17757             {
17758               /* j or jal.  */
17759               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17760                       ? 0x0c000000 : 0x08000000);
17761               exp.X_op = O_symbol;
17762               exp.X_add_symbol = fragp->fr_symbol;
17763               exp.X_add_number = fragp->fr_offset;
17764
17765               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17766                                   FALSE, BFD_RELOC_MIPS_JMP);
17767               fixp->fx_file = fragp->fr_file;
17768               fixp->fx_line = fragp->fr_line;
17769
17770               buf = write_insn (buf, insn);
17771             }
17772           else
17773             {
17774               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17775
17776               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17777               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17778               insn |= at << OP_SH_RT;
17779               exp.X_op = O_symbol;
17780               exp.X_add_symbol = fragp->fr_symbol;
17781               exp.X_add_number = fragp->fr_offset;
17782
17783               if (fragp->fr_offset)
17784                 {
17785                   exp.X_add_symbol = make_expr_symbol (&exp);
17786                   exp.X_add_number = 0;
17787                 }
17788
17789               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17790                                   FALSE, BFD_RELOC_MIPS_GOT16);
17791               fixp->fx_file = fragp->fr_file;
17792               fixp->fx_line = fragp->fr_line;
17793
17794               buf = write_insn (buf, insn);
17795
17796               if (mips_opts.isa == ISA_MIPS1)
17797                 /* nop */
17798                 buf = write_insn (buf, 0);
17799
17800               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17801               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17802               insn |= at << OP_SH_RS | at << OP_SH_RT;
17803
17804               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17805                                   FALSE, BFD_RELOC_LO16);
17806               fixp->fx_file = fragp->fr_file;
17807               fixp->fx_line = fragp->fr_line;
17808
17809               buf = write_insn (buf, insn);
17810
17811               /* j(al)r $at.  */
17812               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17813                 insn = 0x0000f809;
17814               else
17815                 insn = 0x00000008;
17816               insn |= at << OP_SH_RS;
17817
17818               buf = write_insn (buf, insn);
17819             }
17820         }
17821
17822       fragp->fr_fix += fragp->fr_var;
17823       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17824       return;
17825     }
17826
17827   /* Relax microMIPS branches.  */
17828   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17829     {
17830       char *buf = fragp->fr_literal + fragp->fr_fix;
17831       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17832       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17833       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17834       bfd_boolean short_ds;
17835       unsigned long insn;
17836       expressionS exp;
17837       fixS *fixp;
17838
17839       exp.X_op = O_symbol;
17840       exp.X_add_symbol = fragp->fr_symbol;
17841       exp.X_add_number = fragp->fr_offset;
17842
17843       fragp->fr_fix += fragp->fr_var;
17844
17845       /* Handle 16-bit branches that fit or are forced to fit.  */
17846       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (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           if (type == 'D')
17852             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17853                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17854           else if (type == 'E')
17855             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17856                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17857           else
17858             abort ();
17859
17860           fixp->fx_file = fragp->fr_file;
17861           fixp->fx_line = fragp->fr_line;
17862
17863           /* These relocations can have an addend that won't fit in
17864              2 octets.  */
17865           fixp->fx_no_overflow = 1;
17866
17867           return;
17868         }
17869
17870       /* Handle 32-bit branches that fit or are forced to fit.  */
17871       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17872           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17873         {
17874           /* We generate a fixup instead of applying it right now,
17875              because if there is linker relaxation, we're going to
17876              need the relocations.  */
17877           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17878                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
17879           fixp->fx_file = fragp->fr_file;
17880           fixp->fx_line = fragp->fr_line;
17881
17882           if (type == 0)
17883             return;
17884         }
17885
17886       /* Relax 16-bit branches to 32-bit branches.  */
17887       if (type != 0)
17888         {
17889           insn = read_compressed_insn (buf, 2);
17890
17891           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17892             insn = 0x94000000;                          /* beq  */
17893           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17894             {
17895               unsigned long regno;
17896
17897               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17898               regno = micromips_to_32_reg_d_map [regno];
17899               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17900               insn |= regno << MICROMIPSOP_SH_RS;
17901             }
17902           else
17903             abort ();
17904
17905           /* Nothing else to do, just write it out.  */
17906           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17907               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17908             {
17909               buf = write_compressed_insn (buf, insn, 4);
17910               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17911               return;
17912             }
17913         }
17914       else
17915         insn = read_compressed_insn (buf, 4);
17916
17917       /* Relax 32-bit branches to a sequence of instructions.  */
17918       as_warn_where (fragp->fr_file, fragp->fr_line,
17919                      _("Relaxed out-of-range branch into a jump"));
17920
17921       /* Set the short-delay-slot bit.  */
17922       short_ds = al && (insn & 0x02000000) != 0;
17923
17924       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17925         {
17926           symbolS *l;
17927
17928           /* Reverse the branch.  */
17929           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17930               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17931             insn ^= 0x20000000;
17932           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17933                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17934                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17935                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17936                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17937                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17938                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17939                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17940                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17941                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17942             insn ^= 0x00400000;
17943           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17944                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17945                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17946                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17947             insn ^= 0x00200000;
17948           else
17949             abort ();
17950
17951           if (al)
17952             {
17953               /* Clear the and-link and short-delay-slot bits.  */
17954               gas_assert ((insn & 0xfda00000) == 0x40200000);
17955
17956               /* bltzal  0x40200000     bgezal  0x40600000  */
17957               /* bltzals 0x42200000     bgezals 0x42600000  */
17958               insn &= ~0x02200000;
17959             }
17960
17961           /* Make a label at the end for use with the branch.  */
17962           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17963           micromips_label_inc ();
17964           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17965
17966           /* Refer to it.  */
17967           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17968                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17969           fixp->fx_file = fragp->fr_file;
17970           fixp->fx_line = fragp->fr_line;
17971
17972           /* Branch over the jump.  */
17973           buf = write_compressed_insn (buf, insn, 4);
17974           if (!compact)
17975             /* nop */
17976             buf = write_compressed_insn (buf, 0x0c00, 2);
17977         }
17978
17979       if (mips_pic == NO_PIC)
17980         {
17981           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17982
17983           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17984           insn = al ? jal : 0xd4000000;
17985
17986           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17987                               BFD_RELOC_MICROMIPS_JMP);
17988           fixp->fx_file = fragp->fr_file;
17989           fixp->fx_line = fragp->fr_line;
17990
17991           buf = write_compressed_insn (buf, insn, 4);
17992           if (compact)
17993             /* nop */
17994             buf = write_compressed_insn (buf, 0x0c00, 2);
17995         }
17996       else
17997         {
17998           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17999           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18000           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18001
18002           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18003           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18004           insn |= at << MICROMIPSOP_SH_RT;
18005
18006           if (exp.X_add_number)
18007             {
18008               exp.X_add_symbol = make_expr_symbol (&exp);
18009               exp.X_add_number = 0;
18010             }
18011
18012           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18013                               BFD_RELOC_MICROMIPS_GOT16);
18014           fixp->fx_file = fragp->fr_file;
18015           fixp->fx_line = fragp->fr_line;
18016
18017           buf = write_compressed_insn (buf, insn, 4);
18018
18019           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18020           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18021           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18022
18023           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18024                               BFD_RELOC_MICROMIPS_LO16);
18025           fixp->fx_file = fragp->fr_file;
18026           fixp->fx_line = fragp->fr_line;
18027
18028           buf = write_compressed_insn (buf, insn, 4);
18029
18030           /* jr/jrc/jalr/jalrs $at  */
18031           insn = al ? jalr : jr;
18032           insn |= at << MICROMIPSOP_SH_MJ;
18033
18034           buf = write_compressed_insn (buf, insn, 2);
18035         }
18036
18037       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18038       return;
18039     }
18040
18041   if (RELAX_MIPS16_P (fragp->fr_subtype))
18042     {
18043       int type;
18044       const struct mips16_immed_operand *op;
18045       offsetT val;
18046       char *buf;
18047       unsigned int user_length, length;
18048       unsigned long insn;
18049       bfd_boolean ext;
18050
18051       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18052       op = mips16_immed_operands;
18053       while (op->type != type)
18054         ++op;
18055
18056       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18057       val = resolve_symbol_value (fragp->fr_symbol);
18058       if (op->pcrel)
18059         {
18060           addressT addr;
18061
18062           addr = fragp->fr_address + fragp->fr_fix;
18063
18064           /* The rules for the base address of a PC relative reloc are
18065              complicated; see mips16_extended_frag.  */
18066           if (type == 'p' || type == 'q')
18067             {
18068               addr += 2;
18069               if (ext)
18070                 addr += 2;
18071               /* Ignore the low bit in the target, since it will be
18072                  set for a text label.  */
18073               if ((val & 1) != 0)
18074                 --val;
18075             }
18076           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18077             addr -= 4;
18078           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18079             addr -= 2;
18080
18081           addr &= ~ (addressT) ((1 << op->shift) - 1);
18082           val -= addr;
18083
18084           /* Make sure the section winds up with the alignment we have
18085              assumed.  */
18086           if (op->shift > 0)
18087             record_alignment (asec, op->shift);
18088         }
18089
18090       if (ext
18091           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18092               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18093         as_warn_where (fragp->fr_file, fragp->fr_line,
18094                        _("extended instruction in delay slot"));
18095
18096       buf = fragp->fr_literal + fragp->fr_fix;
18097
18098       insn = read_compressed_insn (buf, 2);
18099       if (ext)
18100         insn |= MIPS16_EXTEND;
18101
18102       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18103         user_length = 4;
18104       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18105         user_length = 2;
18106       else
18107         user_length = 0;
18108
18109       mips16_immed (fragp->fr_file, fragp->fr_line, type,
18110                     BFD_RELOC_UNUSED, val, user_length, &insn);
18111
18112       length = (ext ? 4 : 2);
18113       gas_assert (mips16_opcode_length (insn) == length);
18114       write_compressed_insn (buf, insn, length);
18115       fragp->fr_fix += length;
18116     }
18117   else
18118     {
18119       relax_substateT subtype = fragp->fr_subtype;
18120       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18121       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18122       int first, second;
18123       fixS *fixp;
18124
18125       first = RELAX_FIRST (subtype);
18126       second = RELAX_SECOND (subtype);
18127       fixp = (fixS *) fragp->fr_opcode;
18128
18129       /* If the delay slot chosen does not match the size of the instruction,
18130          then emit a warning.  */
18131       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18132            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18133         {
18134           relax_substateT s;
18135           const char *msg;
18136
18137           s = subtype & (RELAX_DELAY_SLOT_16BIT
18138                          | RELAX_DELAY_SLOT_SIZE_FIRST
18139                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18140           msg = macro_warning (s);
18141           if (msg != NULL)
18142             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18143           subtype &= ~s;
18144         }
18145
18146       /* Possibly emit a warning if we've chosen the longer option.  */
18147       if (use_second == second_longer)
18148         {
18149           relax_substateT s;
18150           const char *msg;
18151
18152           s = (subtype
18153                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18154           msg = macro_warning (s);
18155           if (msg != NULL)
18156             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18157           subtype &= ~s;
18158         }
18159
18160       /* Go through all the fixups for the first sequence.  Disable them
18161          (by marking them as done) if we're going to use the second
18162          sequence instead.  */
18163       while (fixp
18164              && fixp->fx_frag == fragp
18165              && fixp->fx_where < fragp->fr_fix - second)
18166         {
18167           if (subtype & RELAX_USE_SECOND)
18168             fixp->fx_done = 1;
18169           fixp = fixp->fx_next;
18170         }
18171
18172       /* Go through the fixups for the second sequence.  Disable them if
18173          we're going to use the first sequence, otherwise adjust their
18174          addresses to account for the relaxation.  */
18175       while (fixp && fixp->fx_frag == fragp)
18176         {
18177           if (subtype & RELAX_USE_SECOND)
18178             fixp->fx_where -= first;
18179           else
18180             fixp->fx_done = 1;
18181           fixp = fixp->fx_next;
18182         }
18183
18184       /* Now modify the frag contents.  */
18185       if (subtype & RELAX_USE_SECOND)
18186         {
18187           char *start;
18188
18189           start = fragp->fr_literal + fragp->fr_fix - first - second;
18190           memmove (start, start + first, second);
18191           fragp->fr_fix -= first;
18192         }
18193       else
18194         fragp->fr_fix -= second;
18195     }
18196 }
18197
18198 /* This function is called after the relocs have been generated.
18199    We've been storing mips16 text labels as odd.  Here we convert them
18200    back to even for the convenience of the debugger.  */
18201
18202 void
18203 mips_frob_file_after_relocs (void)
18204 {
18205   asymbol **syms;
18206   unsigned int count, i;
18207
18208   syms = bfd_get_outsymbols (stdoutput);
18209   count = bfd_get_symcount (stdoutput);
18210   for (i = 0; i < count; i++, syms++)
18211     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18212         && ((*syms)->value & 1) != 0)
18213       {
18214         (*syms)->value &= ~1;
18215         /* If the symbol has an odd size, it was probably computed
18216            incorrectly, so adjust that as well.  */
18217         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18218           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18219       }
18220 }
18221
18222 /* This function is called whenever a label is defined, including fake
18223    labels instantiated off the dot special symbol.  It is used when
18224    handling branch delays; if a branch has a label, we assume we cannot
18225    move it.  This also bumps the value of the symbol by 1 in compressed
18226    code.  */
18227
18228 static void
18229 mips_record_label (symbolS *sym)
18230 {
18231   segment_info_type *si = seg_info (now_seg);
18232   struct insn_label_list *l;
18233
18234   if (free_insn_labels == NULL)
18235     l = (struct insn_label_list *) xmalloc (sizeof *l);
18236   else
18237     {
18238       l = free_insn_labels;
18239       free_insn_labels = l->next;
18240     }
18241
18242   l->label = sym;
18243   l->next = si->label_list;
18244   si->label_list = l;
18245 }
18246
18247 /* This function is called as tc_frob_label() whenever a label is defined
18248    and adds a DWARF-2 record we only want for true labels.  */
18249
18250 void
18251 mips_define_label (symbolS *sym)
18252 {
18253   mips_record_label (sym);
18254   dwarf2_emit_label (sym);
18255 }
18256
18257 /* This function is called by tc_new_dot_label whenever a new dot symbol
18258    is defined.  */
18259
18260 void
18261 mips_add_dot_label (symbolS *sym)
18262 {
18263   mips_record_label (sym);
18264   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18265     mips_compressed_mark_label (sym);
18266 }
18267 \f
18268 /* Some special processing for a MIPS ELF file.  */
18269
18270 void
18271 mips_elf_final_processing (void)
18272 {
18273   /* Write out the register information.  */
18274   if (mips_abi != N64_ABI)
18275     {
18276       Elf32_RegInfo s;
18277
18278       s.ri_gprmask = mips_gprmask;
18279       s.ri_cprmask[0] = mips_cprmask[0];
18280       s.ri_cprmask[1] = mips_cprmask[1];
18281       s.ri_cprmask[2] = mips_cprmask[2];
18282       s.ri_cprmask[3] = mips_cprmask[3];
18283       /* The gp_value field is set by the MIPS ELF backend.  */
18284
18285       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18286                                        ((Elf32_External_RegInfo *)
18287                                         mips_regmask_frag));
18288     }
18289   else
18290     {
18291       Elf64_Internal_RegInfo s;
18292
18293       s.ri_gprmask = mips_gprmask;
18294       s.ri_pad = 0;
18295       s.ri_cprmask[0] = mips_cprmask[0];
18296       s.ri_cprmask[1] = mips_cprmask[1];
18297       s.ri_cprmask[2] = mips_cprmask[2];
18298       s.ri_cprmask[3] = mips_cprmask[3];
18299       /* The gp_value field is set by the MIPS ELF backend.  */
18300
18301       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18302                                        ((Elf64_External_RegInfo *)
18303                                         mips_regmask_frag));
18304     }
18305
18306   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18307      sort of BFD interface for this.  */
18308   if (mips_any_noreorder)
18309     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18310   if (mips_pic != NO_PIC)
18311     {
18312       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18313       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18314     }
18315   if (mips_abicalls)
18316     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18317
18318   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
18319      defined at present; this might need to change in future.  */
18320   if (file_ase_mips16)
18321     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18322   if (file_ase_micromips)
18323     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18324   if (file_ase & ASE_MDMX)
18325     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18326
18327   /* Set the MIPS ELF ABI flags.  */
18328   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18329     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18330   else if (mips_abi == O64_ABI)
18331     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18332   else if (mips_abi == EABI_ABI)
18333     {
18334       if (!file_mips_gp32)
18335         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18336       else
18337         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18338     }
18339   else if (mips_abi == N32_ABI)
18340     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18341
18342   /* Nothing to do for N64_ABI.  */
18343
18344   if (mips_32bitmode)
18345     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18346
18347   if (mips_flag_nan2008)
18348     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
18349
18350 #if 0 /* XXX FIXME */
18351   /* 32 bit code with 64 bit FP registers.  */
18352   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18353     elf_elfheader (stdoutput)->e_flags |= ???;
18354 #endif
18355 }
18356 \f
18357 typedef struct proc {
18358   symbolS *func_sym;
18359   symbolS *func_end_sym;
18360   unsigned long reg_mask;
18361   unsigned long reg_offset;
18362   unsigned long fpreg_mask;
18363   unsigned long fpreg_offset;
18364   unsigned long frame_offset;
18365   unsigned long frame_reg;
18366   unsigned long pc_reg;
18367 } procS;
18368
18369 static procS cur_proc;
18370 static procS *cur_proc_ptr;
18371 static int numprocs;
18372
18373 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18374    as "2", and a normal nop as "0".  */
18375
18376 #define NOP_OPCODE_MIPS         0
18377 #define NOP_OPCODE_MIPS16       1
18378 #define NOP_OPCODE_MICROMIPS    2
18379
18380 char
18381 mips_nop_opcode (void)
18382 {
18383   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18384     return NOP_OPCODE_MICROMIPS;
18385   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18386     return NOP_OPCODE_MIPS16;
18387   else
18388     return NOP_OPCODE_MIPS;
18389 }
18390
18391 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18392    32-bit microMIPS NOPs here (if applicable).  */
18393
18394 void
18395 mips_handle_align (fragS *fragp)
18396 {
18397   char nop_opcode;
18398   char *p;
18399   int bytes, size, excess;
18400   valueT opcode;
18401
18402   if (fragp->fr_type != rs_align_code)
18403     return;
18404
18405   p = fragp->fr_literal + fragp->fr_fix;
18406   nop_opcode = *p;
18407   switch (nop_opcode)
18408     {
18409     case NOP_OPCODE_MICROMIPS:
18410       opcode = micromips_nop32_insn.insn_opcode;
18411       size = 4;
18412       break;
18413     case NOP_OPCODE_MIPS16:
18414       opcode = mips16_nop_insn.insn_opcode;
18415       size = 2;
18416       break;
18417     case NOP_OPCODE_MIPS:
18418     default:
18419       opcode = nop_insn.insn_opcode;
18420       size = 4;
18421       break;
18422     }
18423
18424   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18425   excess = bytes % size;
18426
18427   /* Handle the leading part if we're not inserting a whole number of
18428      instructions, and make it the end of the fixed part of the frag.
18429      Try to fit in a short microMIPS NOP if applicable and possible,
18430      and use zeroes otherwise.  */
18431   gas_assert (excess < 4);
18432   fragp->fr_fix += excess;
18433   switch (excess)
18434     {
18435     case 3:
18436       *p++ = '\0';
18437       /* Fall through.  */
18438     case 2:
18439       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
18440         {
18441           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
18442           break;
18443         }
18444       *p++ = '\0';
18445       /* Fall through.  */
18446     case 1:
18447       *p++ = '\0';
18448       /* Fall through.  */
18449     case 0:
18450       break;
18451     }
18452
18453   md_number_to_chars (p, opcode, size);
18454   fragp->fr_var = size;
18455 }
18456
18457 static void
18458 md_obj_begin (void)
18459 {
18460 }
18461
18462 static void
18463 md_obj_end (void)
18464 {
18465   /* Check for premature end, nesting errors, etc.  */
18466   if (cur_proc_ptr)
18467     as_warn (_("missing .end at end of assembly"));
18468 }
18469
18470 static long
18471 get_number (void)
18472 {
18473   int negative = 0;
18474   long val = 0;
18475
18476   if (*input_line_pointer == '-')
18477     {
18478       ++input_line_pointer;
18479       negative = 1;
18480     }
18481   if (!ISDIGIT (*input_line_pointer))
18482     as_bad (_("expected simple number"));
18483   if (input_line_pointer[0] == '0')
18484     {
18485       if (input_line_pointer[1] == 'x')
18486         {
18487           input_line_pointer += 2;
18488           while (ISXDIGIT (*input_line_pointer))
18489             {
18490               val <<= 4;
18491               val |= hex_value (*input_line_pointer++);
18492             }
18493           return negative ? -val : val;
18494         }
18495       else
18496         {
18497           ++input_line_pointer;
18498           while (ISDIGIT (*input_line_pointer))
18499             {
18500               val <<= 3;
18501               val |= *input_line_pointer++ - '0';
18502             }
18503           return negative ? -val : val;
18504         }
18505     }
18506   if (!ISDIGIT (*input_line_pointer))
18507     {
18508       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18509               *input_line_pointer, *input_line_pointer);
18510       as_warn (_("invalid number"));
18511       return -1;
18512     }
18513   while (ISDIGIT (*input_line_pointer))
18514     {
18515       val *= 10;
18516       val += *input_line_pointer++ - '0';
18517     }
18518   return negative ? -val : val;
18519 }
18520
18521 /* The .file directive; just like the usual .file directive, but there
18522    is an initial number which is the ECOFF file index.  In the non-ECOFF
18523    case .file implies DWARF-2.  */
18524
18525 static void
18526 s_mips_file (int x ATTRIBUTE_UNUSED)
18527 {
18528   static int first_file_directive = 0;
18529
18530   if (ECOFF_DEBUGGING)
18531     {
18532       get_number ();
18533       s_app_file (0);
18534     }
18535   else
18536     {
18537       char *filename;
18538
18539       filename = dwarf2_directive_file (0);
18540
18541       /* Versions of GCC up to 3.1 start files with a ".file"
18542          directive even for stabs output.  Make sure that this
18543          ".file" is handled.  Note that you need a version of GCC
18544          after 3.1 in order to support DWARF-2 on MIPS.  */
18545       if (filename != NULL && ! first_file_directive)
18546         {
18547           (void) new_logical_line (filename, -1);
18548           s_app_file_string (filename, 0);
18549         }
18550       first_file_directive = 1;
18551     }
18552 }
18553
18554 /* The .loc directive, implying DWARF-2.  */
18555
18556 static void
18557 s_mips_loc (int x ATTRIBUTE_UNUSED)
18558 {
18559   if (!ECOFF_DEBUGGING)
18560     dwarf2_directive_loc (0);
18561 }
18562
18563 /* The .end directive.  */
18564
18565 static void
18566 s_mips_end (int x ATTRIBUTE_UNUSED)
18567 {
18568   symbolS *p;
18569
18570   /* Following functions need their own .frame and .cprestore directives.  */
18571   mips_frame_reg_valid = 0;
18572   mips_cprestore_valid = 0;
18573
18574   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18575     {
18576       p = get_symbol ();
18577       demand_empty_rest_of_line ();
18578     }
18579   else
18580     p = NULL;
18581
18582   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18583     as_warn (_(".end not in text section"));
18584
18585   if (!cur_proc_ptr)
18586     {
18587       as_warn (_(".end directive without a preceding .ent directive."));
18588       demand_empty_rest_of_line ();
18589       return;
18590     }
18591
18592   if (p != NULL)
18593     {
18594       gas_assert (S_GET_NAME (p));
18595       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18596         as_warn (_(".end symbol does not match .ent symbol."));
18597
18598       if (debug_type == DEBUG_STABS)
18599         stabs_generate_asm_endfunc (S_GET_NAME (p),
18600                                     S_GET_NAME (p));
18601     }
18602   else
18603     as_warn (_(".end directive missing or unknown symbol"));
18604
18605   /* Create an expression to calculate the size of the function.  */
18606   if (p && cur_proc_ptr)
18607     {
18608       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18609       expressionS *exp = xmalloc (sizeof (expressionS));
18610
18611       obj->size = exp;
18612       exp->X_op = O_subtract;
18613       exp->X_add_symbol = symbol_temp_new_now ();
18614       exp->X_op_symbol = p;
18615       exp->X_add_number = 0;
18616
18617       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18618     }
18619
18620   /* Generate a .pdr section.  */
18621   if (!ECOFF_DEBUGGING && mips_flag_pdr)
18622     {
18623       segT saved_seg = now_seg;
18624       subsegT saved_subseg = now_subseg;
18625       expressionS exp;
18626       char *fragp;
18627
18628 #ifdef md_flush_pending_output
18629       md_flush_pending_output ();
18630 #endif
18631
18632       gas_assert (pdr_seg);
18633       subseg_set (pdr_seg, 0);
18634
18635       /* Write the symbol.  */
18636       exp.X_op = O_symbol;
18637       exp.X_add_symbol = p;
18638       exp.X_add_number = 0;
18639       emit_expr (&exp, 4);
18640
18641       fragp = frag_more (7 * 4);
18642
18643       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18644       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18645       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18646       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18647       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18648       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18649       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18650
18651       subseg_set (saved_seg, saved_subseg);
18652     }
18653
18654   cur_proc_ptr = NULL;
18655 }
18656
18657 /* The .aent and .ent directives.  */
18658
18659 static void
18660 s_mips_ent (int aent)
18661 {
18662   symbolS *symbolP;
18663
18664   symbolP = get_symbol ();
18665   if (*input_line_pointer == ',')
18666     ++input_line_pointer;
18667   SKIP_WHITESPACE ();
18668   if (ISDIGIT (*input_line_pointer)
18669       || *input_line_pointer == '-')
18670     get_number ();
18671
18672   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18673     as_warn (_(".ent or .aent not in text section."));
18674
18675   if (!aent && cur_proc_ptr)
18676     as_warn (_("missing .end"));
18677
18678   if (!aent)
18679     {
18680       /* This function needs its own .frame and .cprestore directives.  */
18681       mips_frame_reg_valid = 0;
18682       mips_cprestore_valid = 0;
18683
18684       cur_proc_ptr = &cur_proc;
18685       memset (cur_proc_ptr, '\0', sizeof (procS));
18686
18687       cur_proc_ptr->func_sym = symbolP;
18688
18689       ++numprocs;
18690
18691       if (debug_type == DEBUG_STABS)
18692         stabs_generate_asm_func (S_GET_NAME (symbolP),
18693                                  S_GET_NAME (symbolP));
18694     }
18695
18696   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18697
18698   demand_empty_rest_of_line ();
18699 }
18700
18701 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18702    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18703    s_mips_frame is used so that we can set the PDR information correctly.
18704    We can't use the ecoff routines because they make reference to the ecoff
18705    symbol table (in the mdebug section).  */
18706
18707 static void
18708 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18709 {
18710   if (ECOFF_DEBUGGING)
18711     s_ignore (ignore);
18712   else
18713     {
18714       long val;
18715
18716       if (cur_proc_ptr == (procS *) NULL)
18717         {
18718           as_warn (_(".frame outside of .ent"));
18719           demand_empty_rest_of_line ();
18720           return;
18721         }
18722
18723       cur_proc_ptr->frame_reg = tc_get_register (1);
18724
18725       SKIP_WHITESPACE ();
18726       if (*input_line_pointer++ != ','
18727           || get_absolute_expression_and_terminator (&val) != ',')
18728         {
18729           as_warn (_("Bad .frame directive"));
18730           --input_line_pointer;
18731           demand_empty_rest_of_line ();
18732           return;
18733         }
18734
18735       cur_proc_ptr->frame_offset = val;
18736       cur_proc_ptr->pc_reg = tc_get_register (0);
18737
18738       demand_empty_rest_of_line ();
18739     }
18740 }
18741
18742 /* The .fmask and .mask directives. If the mdebug section is present
18743    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18744    embedded targets, s_mips_mask is used so that we can set the PDR
18745    information correctly. We can't use the ecoff routines because they
18746    make reference to the ecoff symbol table (in the mdebug section).  */
18747
18748 static void
18749 s_mips_mask (int reg_type)
18750 {
18751   if (ECOFF_DEBUGGING)
18752     s_ignore (reg_type);
18753   else
18754     {
18755       long mask, off;
18756
18757       if (cur_proc_ptr == (procS *) NULL)
18758         {
18759           as_warn (_(".mask/.fmask outside of .ent"));
18760           demand_empty_rest_of_line ();
18761           return;
18762         }
18763
18764       if (get_absolute_expression_and_terminator (&mask) != ',')
18765         {
18766           as_warn (_("Bad .mask/.fmask directive"));
18767           --input_line_pointer;
18768           demand_empty_rest_of_line ();
18769           return;
18770         }
18771
18772       off = get_absolute_expression ();
18773
18774       if (reg_type == 'F')
18775         {
18776           cur_proc_ptr->fpreg_mask = mask;
18777           cur_proc_ptr->fpreg_offset = off;
18778         }
18779       else
18780         {
18781           cur_proc_ptr->reg_mask = mask;
18782           cur_proc_ptr->reg_offset = off;
18783         }
18784
18785       demand_empty_rest_of_line ();
18786     }
18787 }
18788
18789 /* A table describing all the processors gas knows about.  Names are
18790    matched in the order listed.
18791
18792    To ease comparison, please keep this table in the same order as
18793    gcc's mips_cpu_info_table[].  */
18794 static const struct mips_cpu_info mips_cpu_info_table[] =
18795 {
18796   /* Entries for generic ISAs */
18797   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
18798   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
18799   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
18800   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
18801   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
18802   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
18803   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
18804   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
18805   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
18806
18807   /* MIPS I */
18808   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18809   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18810   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
18811
18812   /* MIPS II */
18813   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
18814
18815   /* MIPS III */
18816   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
18817   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
18818   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
18819   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18820   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18821   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18822   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18823   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
18824   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
18825   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
18826   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
18827   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
18828   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
18829   /* ST Microelectronics Loongson 2E and 2F cores */
18830   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
18831   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
18832
18833   /* MIPS IV */
18834   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
18835   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
18836   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
18837   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
18838   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
18839   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18840   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
18841   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
18842   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18843   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18844   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18845   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18846   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
18847   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
18848   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
18849
18850   /* MIPS 32 */
18851   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18852   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18853   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
18854   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
18855
18856   /* MIPS 32 Release 2 */
18857   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18858   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18859   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18860   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
18861   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18862   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18863   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
18864   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
18865   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
18866                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
18867   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
18868                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
18869   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18870   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18871   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18872   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18873   /* Deprecated forms of the above.  */
18874   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18875   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
18876   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
18877   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18878   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18879   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18880   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18881   /* Deprecated forms of the above.  */
18882   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18883   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
18884   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
18885   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18886   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18887   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18888   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18889   /* Deprecated forms of the above.  */
18890   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18891   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18892   /* 34Kn is a 34kc without DSP.  */
18893   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
18894   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
18895   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18896   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18897   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18898   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18899   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18900   /* Deprecated forms of the above.  */
18901   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18902   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
18903   /* 1004K cores are multiprocessor versions of the 34K.  */
18904   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18905   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18906   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18907   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18908
18909   /* MIPS 64 */
18910   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18911   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18912   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18913   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18914
18915   /* Broadcom SB-1 CPU core */
18916   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18917   /* Broadcom SB-1A CPU core */
18918   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18919   
18920   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
18921
18922   /* MIPS 64 Release 2 */
18923
18924   /* Cavium Networks Octeon CPU core */
18925   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
18926   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
18927   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
18928
18929   /* RMI Xlr */
18930   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
18931
18932   /* Broadcom XLP.
18933      XLP is mostly like XLR, with the prominent exception that it is
18934      MIPS64R2 rather than MIPS64.  */
18935   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
18936
18937   /* End marker */
18938   { NULL, 0, 0, 0, 0 }
18939 };
18940
18941
18942 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
18943    with a final "000" replaced by "k".  Ignore case.
18944
18945    Note: this function is shared between GCC and GAS.  */
18946
18947 static bfd_boolean
18948 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
18949 {
18950   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
18951     given++, canonical++;
18952
18953   return ((*given == 0 && *canonical == 0)
18954           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
18955 }
18956
18957
18958 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
18959    CPU name.  We've traditionally allowed a lot of variation here.
18960
18961    Note: this function is shared between GCC and GAS.  */
18962
18963 static bfd_boolean
18964 mips_matching_cpu_name_p (const char *canonical, const char *given)
18965 {
18966   /* First see if the name matches exactly, or with a final "000"
18967      turned into "k".  */
18968   if (mips_strict_matching_cpu_name_p (canonical, given))
18969     return TRUE;
18970
18971   /* If not, try comparing based on numerical designation alone.
18972      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
18973   if (TOLOWER (*given) == 'r')
18974     given++;
18975   if (!ISDIGIT (*given))
18976     return FALSE;
18977
18978   /* Skip over some well-known prefixes in the canonical name,
18979      hoping to find a number there too.  */
18980   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
18981     canonical += 2;
18982   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
18983     canonical += 2;
18984   else if (TOLOWER (canonical[0]) == 'r')
18985     canonical += 1;
18986
18987   return mips_strict_matching_cpu_name_p (canonical, given);
18988 }
18989
18990
18991 /* Parse an option that takes the name of a processor as its argument.
18992    OPTION is the name of the option and CPU_STRING is the argument.
18993    Return the corresponding processor enumeration if the CPU_STRING is
18994    recognized, otherwise report an error and return null.
18995
18996    A similar function exists in GCC.  */
18997
18998 static const struct mips_cpu_info *
18999 mips_parse_cpu (const char *option, const char *cpu_string)
19000 {
19001   const struct mips_cpu_info *p;
19002
19003   /* 'from-abi' selects the most compatible architecture for the given
19004      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19005      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19006      version.  Look first at the -mgp options, if given, otherwise base
19007      the choice on MIPS_DEFAULT_64BIT.
19008
19009      Treat NO_ABI like the EABIs.  One reason to do this is that the
19010      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19011      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19012      'mips64', just as we did in the days before 'from-abi'.  */
19013   if (strcasecmp (cpu_string, "from-abi") == 0)
19014     {
19015       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19016         return mips_cpu_info_from_isa (ISA_MIPS1);
19017
19018       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19019         return mips_cpu_info_from_isa (ISA_MIPS3);
19020
19021       if (file_mips_gp32 >= 0)
19022         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19023
19024       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19025                                      ? ISA_MIPS3
19026                                      : ISA_MIPS1);
19027     }
19028
19029   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19030   if (strcasecmp (cpu_string, "default") == 0)
19031     return 0;
19032
19033   for (p = mips_cpu_info_table; p->name != 0; p++)
19034     if (mips_matching_cpu_name_p (p->name, cpu_string))
19035       return p;
19036
19037   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19038   return 0;
19039 }
19040
19041 /* Return the canonical processor information for ISA (a member of the
19042    ISA_MIPS* enumeration).  */
19043
19044 static const struct mips_cpu_info *
19045 mips_cpu_info_from_isa (int isa)
19046 {
19047   int i;
19048
19049   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19050     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19051         && isa == mips_cpu_info_table[i].isa)
19052       return (&mips_cpu_info_table[i]);
19053
19054   return NULL;
19055 }
19056
19057 static const struct mips_cpu_info *
19058 mips_cpu_info_from_arch (int arch)
19059 {
19060   int i;
19061
19062   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19063     if (arch == mips_cpu_info_table[i].cpu)
19064       return (&mips_cpu_info_table[i]);
19065
19066   return NULL;
19067 }
19068 \f
19069 static void
19070 show (FILE *stream, const char *string, int *col_p, int *first_p)
19071 {
19072   if (*first_p)
19073     {
19074       fprintf (stream, "%24s", "");
19075       *col_p = 24;
19076     }
19077   else
19078     {
19079       fprintf (stream, ", ");
19080       *col_p += 2;
19081     }
19082
19083   if (*col_p + strlen (string) > 72)
19084     {
19085       fprintf (stream, "\n%24s", "");
19086       *col_p = 24;
19087     }
19088
19089   fprintf (stream, "%s", string);
19090   *col_p += strlen (string);
19091
19092   *first_p = 0;
19093 }
19094
19095 void
19096 md_show_usage (FILE *stream)
19097 {
19098   int column, first;
19099   size_t i;
19100
19101   fprintf (stream, _("\
19102 MIPS options:\n\
19103 -EB                     generate big endian output\n\
19104 -EL                     generate little endian output\n\
19105 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19106 -G NUM                  allow referencing objects up to NUM bytes\n\
19107                         implicitly with the gp register [default 8]\n"));
19108   fprintf (stream, _("\
19109 -mips1                  generate MIPS ISA I instructions\n\
19110 -mips2                  generate MIPS ISA II instructions\n\
19111 -mips3                  generate MIPS ISA III instructions\n\
19112 -mips4                  generate MIPS ISA IV instructions\n\
19113 -mips5                  generate MIPS ISA V instructions\n\
19114 -mips32                 generate MIPS32 ISA instructions\n\
19115 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19116 -mips64                 generate MIPS64 ISA instructions\n\
19117 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19118 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19119
19120   first = 1;
19121
19122   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19123     show (stream, mips_cpu_info_table[i].name, &column, &first);
19124   show (stream, "from-abi", &column, &first);
19125   fputc ('\n', stream);
19126
19127   fprintf (stream, _("\
19128 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19129 -no-mCPU                don't generate code specific to CPU.\n\
19130                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19131
19132   first = 1;
19133
19134   show (stream, "3900", &column, &first);
19135   show (stream, "4010", &column, &first);
19136   show (stream, "4100", &column, &first);
19137   show (stream, "4650", &column, &first);
19138   fputc ('\n', stream);
19139
19140   fprintf (stream, _("\
19141 -mips16                 generate mips16 instructions\n\
19142 -no-mips16              do not generate mips16 instructions\n"));
19143   fprintf (stream, _("\
19144 -mmicromips             generate microMIPS instructions\n\
19145 -mno-micromips          do not generate microMIPS instructions\n"));
19146   fprintf (stream, _("\
19147 -msmartmips             generate smartmips instructions\n\
19148 -mno-smartmips          do not generate smartmips instructions\n"));  
19149   fprintf (stream, _("\
19150 -mdsp                   generate DSP instructions\n\
19151 -mno-dsp                do not generate DSP instructions\n"));
19152   fprintf (stream, _("\
19153 -mdspr2                 generate DSP R2 instructions\n\
19154 -mno-dspr2              do not generate DSP R2 instructions\n"));
19155   fprintf (stream, _("\
19156 -mmt                    generate MT instructions\n\
19157 -mno-mt                 do not generate MT instructions\n"));
19158   fprintf (stream, _("\
19159 -mmcu                   generate MCU instructions\n\
19160 -mno-mcu                do not generate MCU instructions\n"));
19161   fprintf (stream, _("\
19162 -mvirt                  generate Virtualization instructions\n\
19163 -mno-virt               do not generate Virtualization instructions\n"));
19164   fprintf (stream, _("\
19165 -minsn32                only generate 32-bit microMIPS instructions\n\
19166 -mno-insn32             generate all microMIPS instructions\n"));
19167   fprintf (stream, _("\
19168 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19169 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19170 -mfix-vr4120            work around certain VR4120 errata\n\
19171 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19172 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19173 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19174 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19175 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19176 -msym32                 assume all symbols have 32-bit values\n\
19177 -O0                     remove unneeded NOPs, do not swap branches\n\
19178 -O                      remove unneeded NOPs and swap branches\n\
19179 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19180 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19181   fprintf (stream, _("\
19182 -mhard-float            allow floating-point instructions\n\
19183 -msoft-float            do not allow floating-point instructions\n\
19184 -msingle-float          only allow 32-bit floating-point operations\n\
19185 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19186 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19187 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19188 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19189
19190   first = 1;
19191
19192   show (stream, "legacy", &column, &first);
19193   show (stream, "2008", &column, &first);
19194
19195   fputc ('\n', stream);
19196
19197   fprintf (stream, _("\
19198 -KPIC, -call_shared     generate SVR4 position independent code\n\
19199 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19200 -mvxworks-pic           generate VxWorks position independent code\n\
19201 -non_shared             do not generate code that can operate with DSOs\n\
19202 -xgot                   assume a 32 bit GOT\n\
19203 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19204 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19205                         position dependent (non shared) code\n\
19206 -mabi=ABI               create ABI conformant object file for:\n"));
19207
19208   first = 1;
19209
19210   show (stream, "32", &column, &first);
19211   show (stream, "o64", &column, &first);
19212   show (stream, "n32", &column, &first);
19213   show (stream, "64", &column, &first);
19214   show (stream, "eabi", &column, &first);
19215
19216   fputc ('\n', stream);
19217
19218   fprintf (stream, _("\
19219 -32                     create o32 ABI object file (default)\n\
19220 -n32                    create n32 ABI object file\n\
19221 -64                     create 64 ABI object file\n"));
19222 }
19223
19224 #ifdef TE_IRIX
19225 enum dwarf2_format
19226 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19227 {
19228   if (HAVE_64BIT_SYMBOLS)
19229     return dwarf2_format_64bit_irix;
19230   else
19231     return dwarf2_format_32bit;
19232 }
19233 #endif
19234
19235 int
19236 mips_dwarf2_addr_size (void)
19237 {
19238   if (HAVE_64BIT_OBJECTS)
19239     return 8;
19240   else
19241     return 4;
19242 }
19243
19244 /* Standard calling conventions leave the CFA at SP on entry.  */
19245 void
19246 mips_cfi_frame_initial_instructions (void)
19247 {
19248   cfi_add_CFA_def_cfa_register (SP);
19249 }
19250
19251 int
19252 tc_mips_regname_to_dw2regnum (char *regname)
19253 {
19254   unsigned int regnum = -1;
19255   unsigned int reg;
19256
19257   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19258     regnum = reg;
19259
19260   return regnum;
19261 }