include/opcode/
[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 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92
93 #define ZERO 0
94 #define ATREG 1
95 #define S0  16
96 #define S7  23
97 #define TREG 24
98 #define PIC_CALL_REG 25
99 #define KT0 26
100 #define KT1 27
101 #define GP  28
102 #define SP  29
103 #define FP  30
104 #define RA  31
105
106 #define ILLEGAL_REG (32)
107
108 #define AT  mips_opts.at
109
110 extern int target_big_endian;
111
112 /* The name of the readonly data section.  */
113 #define RDATA_SECTION_NAME ".rodata"
114
115 /* Ways in which an instruction can be "appended" to the output.  */
116 enum append_method {
117   /* Just add it normally.  */
118   APPEND_ADD,
119
120   /* Add it normally and then add a nop.  */
121   APPEND_ADD_WITH_NOP,
122
123   /* Turn an instruction with a delay slot into a "compact" version.  */
124   APPEND_ADD_COMPACT,
125
126   /* Insert the instruction before the last one.  */
127   APPEND_SWAP
128 };
129
130 /* Information about an instruction, including its format, operands
131    and fixups.  */
132 struct mips_cl_insn
133 {
134   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
135   const struct mips_opcode *insn_mo;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  If we have
139      decided to use an extended MIPS16 instruction, this includes the
140      extension.  */
141   unsigned long insn_opcode;
142
143   /* The frag that contains the instruction.  */
144   struct frag *frag;
145
146   /* The offset into FRAG of the first instruction byte.  */
147   long where;
148
149   /* The relocs associated with the instruction, if any.  */
150   fixS *fixp[3];
151
152   /* True if this entry cannot be moved from its current position.  */
153   unsigned int fixed_p : 1;
154
155   /* True if this instruction occurred in a .set noreorder block.  */
156   unsigned int noreorder_p : 1;
157
158   /* True for mips16 instructions that jump to an absolute address.  */
159   unsigned int mips16_absolute_jump_p : 1;
160
161   /* True if this instruction is complete.  */
162   unsigned int complete_p : 1;
163
164   /* True if this instruction is cleared from history by unconditional
165      branch.  */
166   unsigned int cleared_p : 1;
167 };
168
169 /* The ABI to use.  */
170 enum mips_abi_level
171 {
172   NO_ABI = 0,
173   O32_ABI,
174   O64_ABI,
175   N32_ABI,
176   N64_ABI,
177   EABI_ABI
178 };
179
180 /* MIPS ABI we are using for this output file.  */
181 static enum mips_abi_level mips_abi = NO_ABI;
182
183 /* Whether or not we have code that can call pic code.  */
184 int mips_abicalls = FALSE;
185
186 /* Whether or not we have code which can be put into a shared
187    library.  */
188 static bfd_boolean mips_in_shared = TRUE;
189
190 /* This is the set of options which may be modified by the .set
191    pseudo-op.  We use a struct so that .set push and .set pop are more
192    reliable.  */
193
194 struct mips_set_options
195 {
196   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
197      if it has not been initialized.  Changed by `.set mipsN', and the
198      -mipsN command line option, and the default CPU.  */
199   int isa;
200   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
201      <asename>', by command line options, and based on the default
202      architecture.  */
203   int ase;
204   /* Whether we are assembling for the mips16 processor.  0 if we are
205      not, 1 if we are, and -1 if the value has not been initialized.
206      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
207      -nomips16 command line options, and the default CPU.  */
208   int mips16;
209   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
210      1 if we are, and -1 if the value has not been initialized.  Changed
211      by `.set micromips' and `.set nomicromips', and the -mmicromips
212      and -mno-micromips command line options, and the default CPU.  */
213   int micromips;
214   /* Non-zero if we should not reorder instructions.  Changed by `.set
215      reorder' and `.set noreorder'.  */
216   int noreorder;
217   /* Non-zero if we should not permit the register designated "assembler
218      temporary" to be used in instructions.  The value is the register
219      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
220      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
221   unsigned int at;
222   /* Non-zero if we should warn when a macro instruction expands into
223      more than one machine instruction.  Changed by `.set nomacro' and
224      `.set macro'.  */
225   int warn_about_macros;
226   /* Non-zero if we should not move instructions.  Changed by `.set
227      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
228   int nomove;
229   /* Non-zero if we should not optimize branches by moving the target
230      of the branch into the delay slot.  Actually, we don't perform
231      this optimization anyhow.  Changed by `.set bopt' and `.set
232      nobopt'.  */
233   int nobopt;
234   /* Non-zero if we should not autoextend mips16 instructions.
235      Changed by `.set autoextend' and `.set noautoextend'.  */
236   int noautoextend;
237   /* True if we should only emit 32-bit microMIPS instructions.
238      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
239      and -mno-insn32 command line options.  */
240   bfd_boolean insn32;
241   /* Restrict general purpose registers and floating point registers
242      to 32 bit.  This is initially determined when -mgp32 or -mfp32
243      is passed but can changed if the assembler code uses .set mipsN.  */
244   int gp32;
245   int fp32;
246   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
247      command line option, and the default CPU.  */
248   int arch;
249   /* True if ".set sym32" is in effect.  */
250   bfd_boolean sym32;
251   /* True if floating-point operations are not allowed.  Changed by .set
252      softfloat or .set hardfloat, by command line options -msoft-float or
253      -mhard-float.  The default is false.  */
254   bfd_boolean soft_float;
255
256   /* True if only single-precision floating-point operations are allowed.
257      Changed by .set singlefloat or .set doublefloat, command-line options
258      -msingle-float or -mdouble-float.  The default is false.  */
259   bfd_boolean single_float;
260 };
261
262 /* This is the struct we use to hold the current set of options.  Note
263    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
264    -1 to indicate that they have not been initialized.  */
265
266 /* True if -mgp32 was passed.  */
267 static int file_mips_gp32 = -1;
268
269 /* True if -mfp32 was passed.  */
270 static int file_mips_fp32 = -1;
271
272 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
273 static int file_mips_soft_float = 0;
274
275 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
276 static int file_mips_single_float = 0;
277
278 /* True if -mnan=2008, false if -mnan=legacy.  */
279 static bfd_boolean mips_flag_nan2008 = FALSE;
280
281 static struct mips_set_options mips_opts =
282 {
283   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
284   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
285   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
286   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
287   /* soft_float */ FALSE, /* single_float */ FALSE
288 };
289
290 /* The set of ASEs that were selected on the command line, either
291    explicitly via ASE options or implicitly through things like -march.  */
292 static unsigned int file_ase;
293
294 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
295 static unsigned int file_ase_explicit;
296
297 /* These variables are filled in with the masks of registers used.
298    The object format code reads them and puts them in the appropriate
299    place.  */
300 unsigned long mips_gprmask;
301 unsigned long mips_cprmask[4];
302
303 /* MIPS ISA we are using for this output file.  */
304 static int file_mips_isa = ISA_UNKNOWN;
305
306 /* True if any MIPS16 code was produced.  */
307 static int file_ase_mips16;
308
309 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
310                               || mips_opts.isa == ISA_MIPS32R2          \
311                               || mips_opts.isa == ISA_MIPS64            \
312                               || mips_opts.isa == ISA_MIPS64R2)
313
314 /* True if any microMIPS code was produced.  */
315 static int file_ase_micromips;
316
317 /* True if we want to create R_MIPS_JALR for jalr $25.  */
318 #ifdef TE_IRIX
319 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
320 #else
321 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
322    because there's no place for any addend, the only acceptable
323    expression is a bare symbol.  */
324 #define MIPS_JALR_HINT_P(EXPR) \
325   (!HAVE_IN_PLACE_ADDENDS \
326    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
327 #endif
328
329 /* The argument of the -march= flag.  The architecture we are assembling.  */
330 static int file_mips_arch = CPU_UNKNOWN;
331 static const char *mips_arch_string;
332
333 /* The argument of the -mtune= flag.  The architecture for which we
334    are optimizing.  */
335 static int mips_tune = CPU_UNKNOWN;
336 static const char *mips_tune_string;
337
338 /* True when generating 32-bit code for a 64-bit processor.  */
339 static int mips_32bitmode = 0;
340
341 /* True if the given ABI requires 32-bit registers.  */
342 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
343
344 /* Likewise 64-bit registers.  */
345 #define ABI_NEEDS_64BIT_REGS(ABI)       \
346   ((ABI) == N32_ABI                     \
347    || (ABI) == N64_ABI                  \
348    || (ABI) == O64_ABI)
349
350 /*  Return true if ISA supports 64 bit wide gp registers.  */
351 #define ISA_HAS_64BIT_REGS(ISA)         \
352   ((ISA) == ISA_MIPS3                   \
353    || (ISA) == ISA_MIPS4                \
354    || (ISA) == ISA_MIPS5                \
355    || (ISA) == ISA_MIPS64               \
356    || (ISA) == ISA_MIPS64R2)
357
358 /*  Return true if ISA supports 64 bit wide float registers.  */
359 #define ISA_HAS_64BIT_FPRS(ISA)         \
360   ((ISA) == ISA_MIPS3                   \
361    || (ISA) == ISA_MIPS4                \
362    || (ISA) == ISA_MIPS5                \
363    || (ISA) == ISA_MIPS32R2             \
364    || (ISA) == ISA_MIPS64               \
365    || (ISA) == ISA_MIPS64R2)
366
367 /* Return true if ISA supports 64-bit right rotate (dror et al.)
368    instructions.  */
369 #define ISA_HAS_DROR(ISA)               \
370   ((ISA) == ISA_MIPS64R2                \
371    || (mips_opts.micromips              \
372        && ISA_HAS_64BIT_REGS (ISA))     \
373    )
374
375 /* Return true if ISA supports 32-bit right rotate (ror et al.)
376    instructions.  */
377 #define ISA_HAS_ROR(ISA)                \
378   ((ISA) == ISA_MIPS32R2                \
379    || (ISA) == ISA_MIPS64R2             \
380    || (mips_opts.ase & ASE_SMARTMIPS)   \
381    || mips_opts.micromips               \
382    )
383
384 /* Return true if ISA supports single-precision floats in odd registers.  */
385 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
386   ((ISA) == ISA_MIPS32                  \
387    || (ISA) == ISA_MIPS32R2             \
388    || (ISA) == ISA_MIPS64               \
389    || (ISA) == ISA_MIPS64R2)
390
391 /* Return true if ISA supports move to/from high part of a 64-bit
392    floating-point register. */
393 #define ISA_HAS_MXHC1(ISA)              \
394   ((ISA) == ISA_MIPS32R2                \
395    || (ISA) == ISA_MIPS64R2)
396
397 #define HAVE_32BIT_GPRS                            \
398     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
399
400 #define HAVE_32BIT_FPRS                            \
401     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
402
403 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
404 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
405
406 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
407
408 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
409
410 /* True if relocations are stored in-place.  */
411 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
412
413 /* The ABI-derived address size.  */
414 #define HAVE_64BIT_ADDRESSES \
415   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
416 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
417
418 /* The size of symbolic constants (i.e., expressions of the form
419    "SYMBOL" or "SYMBOL + OFFSET").  */
420 #define HAVE_32BIT_SYMBOLS \
421   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
422 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
423
424 /* Addresses are loaded in different ways, depending on the address size
425    in use.  The n32 ABI Documentation also mandates the use of additions
426    with overflow checking, but existing implementations don't follow it.  */
427 #define ADDRESS_ADD_INSN                                                \
428    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
429
430 #define ADDRESS_ADDI_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
432
433 #define ADDRESS_LOAD_INSN                                               \
434    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
435
436 #define ADDRESS_STORE_INSN                                              \
437    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
438
439 /* Return true if the given CPU supports the MIPS16 ASE.  */
440 #define CPU_HAS_MIPS16(cpu)                                             \
441    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
442     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
443
444 /* Return true if the given CPU supports the microMIPS ASE.  */
445 #define CPU_HAS_MICROMIPS(cpu)  0
446
447 /* True if CPU has a dror instruction.  */
448 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
449
450 /* True if CPU has a ror instruction.  */
451 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
452
453 /* True if CPU is in the Octeon family */
454 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
455
456 /* True if CPU has seq/sne and seqi/snei instructions.  */
457 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
458
459 /* True, if CPU has support for ldc1 and sdc1. */
460 #define CPU_HAS_LDC1_SDC1(CPU)  \
461    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
462
463 /* True if mflo and mfhi can be immediately followed by instructions
464    which write to the HI and LO registers.
465
466    According to MIPS specifications, MIPS ISAs I, II, and III need
467    (at least) two instructions between the reads of HI/LO and
468    instructions which write them, and later ISAs do not.  Contradicting
469    the MIPS specifications, some MIPS IV processor user manuals (e.g.
470    the UM for the NEC Vr5000) document needing the instructions between
471    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
472    MIPS64 and later ISAs to have the interlocks, plus any specific
473    earlier-ISA CPUs for which CPU documentation declares that the
474    instructions are really interlocked.  */
475 #define hilo_interlocks \
476   (mips_opts.isa == ISA_MIPS32                        \
477    || mips_opts.isa == ISA_MIPS32R2                   \
478    || mips_opts.isa == ISA_MIPS64                     \
479    || mips_opts.isa == ISA_MIPS64R2                   \
480    || mips_opts.arch == CPU_R4010                     \
481    || mips_opts.arch == CPU_R5900                     \
482    || mips_opts.arch == CPU_R10000                    \
483    || mips_opts.arch == CPU_R12000                    \
484    || mips_opts.arch == CPU_R14000                    \
485    || mips_opts.arch == CPU_R16000                    \
486    || mips_opts.arch == CPU_RM7000                    \
487    || mips_opts.arch == CPU_VR5500                    \
488    || mips_opts.micromips                             \
489    )
490
491 /* Whether the processor uses hardware interlocks to protect reads
492    from the GPRs after they are loaded from memory, and thus does not
493    require nops to be inserted.  This applies to instructions marked
494    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
495    level I and microMIPS mode instructions are always interlocked.  */
496 #define gpr_interlocks                                \
497   (mips_opts.isa != ISA_MIPS1                         \
498    || mips_opts.arch == CPU_R3900                     \
499    || mips_opts.arch == CPU_R5900                     \
500    || mips_opts.micromips                             \
501    )
502
503 /* Whether the processor uses hardware interlocks to avoid delays
504    required by coprocessor instructions, and thus does not require
505    nops to be inserted.  This applies to instructions marked
506    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
507    between instructions marked INSN_WRITE_COND_CODE and ones marked
508    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
509    levels I, II, and III and microMIPS mode instructions are always
510    interlocked.  */
511 /* Itbl support may require additional care here.  */
512 #define cop_interlocks                                \
513   ((mips_opts.isa != ISA_MIPS1                        \
514     && mips_opts.isa != ISA_MIPS2                     \
515     && mips_opts.isa != ISA_MIPS3)                    \
516    || mips_opts.arch == CPU_R4300                     \
517    || mips_opts.micromips                             \
518    )
519
520 /* Whether the processor uses hardware interlocks to protect reads
521    from coprocessor registers after they are loaded from memory, and
522    thus does not require nops to be inserted.  This applies to
523    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
524    requires at MIPS ISA level I and microMIPS mode instructions are
525    always interlocked.  */
526 #define cop_mem_interlocks                            \
527   (mips_opts.isa != ISA_MIPS1                         \
528    || mips_opts.micromips                             \
529    )
530
531 /* Is this a mfhi or mflo instruction?  */
532 #define MF_HILO_INSN(PINFO) \
533   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
534
535 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
536    has been selected.  This implies, in particular, that addresses of text
537    labels have their LSB set.  */
538 #define HAVE_CODE_COMPRESSION                                           \
539   ((mips_opts.mips16 | mips_opts.micromips) != 0)
540
541 /* The minimum and maximum signed values that can be stored in a GPR.  */
542 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
543 #define GPR_SMIN (-GPR_SMAX - 1)
544
545 /* MIPS PIC level.  */
546
547 enum mips_pic_level mips_pic;
548
549 /* 1 if we should generate 32 bit offsets from the $gp register in
550    SVR4_PIC mode.  Currently has no meaning in other modes.  */
551 static int mips_big_got = 0;
552
553 /* 1 if trap instructions should used for overflow rather than break
554    instructions.  */
555 static int mips_trap = 0;
556
557 /* 1 if double width floating point constants should not be constructed
558    by assembling two single width halves into two single width floating
559    point registers which just happen to alias the double width destination
560    register.  On some architectures this aliasing can be disabled by a bit
561    in the status register, and the setting of this bit cannot be determined
562    automatically at assemble time.  */
563 static int mips_disable_float_construction;
564
565 /* Non-zero if any .set noreorder directives were used.  */
566
567 static int mips_any_noreorder;
568
569 /* Non-zero if nops should be inserted when the register referenced in
570    an mfhi/mflo instruction is read in the next two instructions.  */
571 static int mips_7000_hilo_fix;
572
573 /* The size of objects in the small data section.  */
574 static unsigned int g_switch_value = 8;
575 /* Whether the -G option was used.  */
576 static int g_switch_seen = 0;
577
578 #define N_RMASK 0xc4
579 #define N_VFP   0xd4
580
581 /* If we can determine in advance that GP optimization won't be
582    possible, we can skip the relaxation stuff that tries to produce
583    GP-relative references.  This makes delay slot optimization work
584    better.
585
586    This function can only provide a guess, but it seems to work for
587    gcc output.  It needs to guess right for gcc, otherwise gcc
588    will put what it thinks is a GP-relative instruction in a branch
589    delay slot.
590
591    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
592    fixed it for the non-PIC mode.  KR 95/04/07  */
593 static int nopic_need_relax (symbolS *, int);
594
595 /* handle of the OPCODE hash table */
596 static struct hash_control *op_hash = NULL;
597
598 /* The opcode hash table we use for the mips16.  */
599 static struct hash_control *mips16_op_hash = NULL;
600
601 /* The opcode hash table we use for the microMIPS ASE.  */
602 static struct hash_control *micromips_op_hash = NULL;
603
604 /* This array holds the chars that always start a comment.  If the
605     pre-processor is disabled, these aren't very useful */
606 const char comment_chars[] = "#";
607
608 /* This array holds the chars that only start a comment at the beginning of
609    a line.  If the line seems to have the form '# 123 filename'
610    .line and .file directives will appear in the pre-processed output */
611 /* Note that input_file.c hand checks for '#' at the beginning of the
612    first line of the input file.  This is because the compiler outputs
613    #NO_APP at the beginning of its output.  */
614 /* Also note that C style comments are always supported.  */
615 const char line_comment_chars[] = "#";
616
617 /* This array holds machine specific line separator characters.  */
618 const char line_separator_chars[] = ";";
619
620 /* Chars that can be used to separate mant from exp in floating point nums */
621 const char EXP_CHARS[] = "eE";
622
623 /* Chars that mean this number is a floating point constant */
624 /* As in 0f12.456 */
625 /* or    0d1.2345e12 */
626 const char FLT_CHARS[] = "rRsSfFdDxXpP";
627
628 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
629    changed in read.c .  Ideally it shouldn't have to know about it at all,
630    but nothing is ideal around here.
631  */
632
633 /* Types of printf format used for instruction-related error messages.
634    "I" means int ("%d") and "S" means string ("%s"). */
635 enum mips_insn_error_format {
636   ERR_FMT_PLAIN,
637   ERR_FMT_I,
638   ERR_FMT_SS,
639 };
640
641 /* Information about an error that was found while assembling the current
642    instruction.  */
643 struct mips_insn_error {
644   /* We sometimes need to match an instruction against more than one
645      opcode table entry.  Errors found during this matching are reported
646      against a particular syntactic argument rather than against the
647      instruction as a whole.  We grade these messages so that errors
648      against argument N have a greater priority than an error against
649      any argument < N, since the former implies that arguments up to N
650      were acceptable and that the opcode entry was therefore a closer match.
651      If several matches report an error against the same argument,
652      we only use that error if it is the same in all cases.
653
654      min_argnum is the minimum argument number for which an error message
655      should be accepted.  It is 0 if MSG is against the instruction as
656      a whole.  */
657   int min_argnum;
658
659   /* The printf()-style message, including its format and arguments.  */
660   enum mips_insn_error_format format;
661   const char *msg;
662   union {
663     int i;
664     const char *ss[2];
665   } u;
666 };
667
668 /* The error that should be reported for the current instruction.  */
669 static struct mips_insn_error insn_error;
670
671 static int auto_align = 1;
672
673 /* When outputting SVR4 PIC code, the assembler needs to know the
674    offset in the stack frame from which to restore the $gp register.
675    This is set by the .cprestore pseudo-op, and saved in this
676    variable.  */
677 static offsetT mips_cprestore_offset = -1;
678
679 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
680    more optimizations, it can use a register value instead of a memory-saved
681    offset and even an other register than $gp as global pointer.  */
682 static offsetT mips_cpreturn_offset = -1;
683 static int mips_cpreturn_register = -1;
684 static int mips_gp_register = GP;
685 static int mips_gprel_offset = 0;
686
687 /* Whether mips_cprestore_offset has been set in the current function
688    (or whether it has already been warned about, if not).  */
689 static int mips_cprestore_valid = 0;
690
691 /* This is the register which holds the stack frame, as set by the
692    .frame pseudo-op.  This is needed to implement .cprestore.  */
693 static int mips_frame_reg = SP;
694
695 /* Whether mips_frame_reg has been set in the current function
696    (or whether it has already been warned about, if not).  */
697 static int mips_frame_reg_valid = 0;
698
699 /* To output NOP instructions correctly, we need to keep information
700    about the previous two instructions.  */
701
702 /* Whether we are optimizing.  The default value of 2 means to remove
703    unneeded NOPs and swap branch instructions when possible.  A value
704    of 1 means to not swap branches.  A value of 0 means to always
705    insert NOPs.  */
706 static int mips_optimize = 2;
707
708 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
709    equivalent to seeing no -g option at all.  */
710 static int mips_debug = 0;
711
712 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
713 #define MAX_VR4130_NOPS 4
714
715 /* The maximum number of NOPs needed to fill delay slots.  */
716 #define MAX_DELAY_NOPS 2
717
718 /* The maximum number of NOPs needed for any purpose.  */
719 #define MAX_NOPS 4
720
721 /* A list of previous instructions, with index 0 being the most recent.
722    We need to look back MAX_NOPS instructions when filling delay slots
723    or working around processor errata.  We need to look back one
724    instruction further if we're thinking about using history[0] to
725    fill a branch delay slot.  */
726 static struct mips_cl_insn history[1 + MAX_NOPS];
727
728 /* Arrays of operands for each instruction.  */
729 #define MAX_OPERANDS 6
730 struct mips_operand_array {
731   const struct mips_operand *operand[MAX_OPERANDS];
732 };
733 static struct mips_operand_array *mips_operands;
734 static struct mips_operand_array *mips16_operands;
735 static struct mips_operand_array *micromips_operands;
736
737 /* Nop instructions used by emit_nop.  */
738 static struct mips_cl_insn nop_insn;
739 static struct mips_cl_insn mips16_nop_insn;
740 static struct mips_cl_insn micromips_nop16_insn;
741 static struct mips_cl_insn micromips_nop32_insn;
742
743 /* The appropriate nop for the current mode.  */
744 #define NOP_INSN (mips_opts.mips16                                      \
745                   ? &mips16_nop_insn                                    \
746                   : (mips_opts.micromips                                \
747                      ? (mips_opts.insn32                                \
748                         ? &micromips_nop32_insn                         \
749                         : &micromips_nop16_insn)                        \
750                      : &nop_insn))
751
752 /* The size of NOP_INSN in bytes.  */
753 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
754                         || (mips_opts.micromips && !mips_opts.insn32))  \
755                        ? 2 : 4)
756
757 /* If this is set, it points to a frag holding nop instructions which
758    were inserted before the start of a noreorder section.  If those
759    nops turn out to be unnecessary, the size of the frag can be
760    decreased.  */
761 static fragS *prev_nop_frag;
762
763 /* The number of nop instructions we created in prev_nop_frag.  */
764 static int prev_nop_frag_holds;
765
766 /* The number of nop instructions that we know we need in
767    prev_nop_frag.  */
768 static int prev_nop_frag_required;
769
770 /* The number of instructions we've seen since prev_nop_frag.  */
771 static int prev_nop_frag_since;
772
773 /* Relocations against symbols are sometimes done in two parts, with a HI
774    relocation and a LO relocation.  Each relocation has only 16 bits of
775    space to store an addend.  This means that in order for the linker to
776    handle carries correctly, it must be able to locate both the HI and
777    the LO relocation.  This means that the relocations must appear in
778    order in the relocation table.
779
780    In order to implement this, we keep track of each unmatched HI
781    relocation.  We then sort them so that they immediately precede the
782    corresponding LO relocation.  */
783
784 struct mips_hi_fixup
785 {
786   /* Next HI fixup.  */
787   struct mips_hi_fixup *next;
788   /* This fixup.  */
789   fixS *fixp;
790   /* The section this fixup is in.  */
791   segT seg;
792 };
793
794 /* The list of unmatched HI relocs.  */
795
796 static struct mips_hi_fixup *mips_hi_fixup_list;
797
798 /* The frag containing the last explicit relocation operator.
799    Null if explicit relocations have not been used.  */
800
801 static fragS *prev_reloc_op_frag;
802
803 /* Map mips16 register numbers to normal MIPS register numbers.  */
804
805 static const unsigned int mips16_to_32_reg_map[] =
806 {
807   16, 17, 2, 3, 4, 5, 6, 7
808 };
809
810 /* Map microMIPS register numbers to normal MIPS register numbers.  */
811
812 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
813
814 /* The microMIPS registers with type h.  */
815 static const unsigned int micromips_to_32_reg_h_map1[] =
816 {
817   5, 5, 6, 4, 4, 4, 4, 4
818 };
819 static const unsigned int micromips_to_32_reg_h_map2[] =
820 {
821   6, 7, 7, 21, 22, 5, 6, 7
822 };
823
824 /* The microMIPS registers with type m.  */
825 static const unsigned int micromips_to_32_reg_m_map[] =
826 {
827   0, 17, 2, 3, 16, 18, 19, 20
828 };
829
830 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
831
832 /* Classifies the kind of instructions we're interested in when
833    implementing -mfix-vr4120.  */
834 enum fix_vr4120_class
835 {
836   FIX_VR4120_MACC,
837   FIX_VR4120_DMACC,
838   FIX_VR4120_MULT,
839   FIX_VR4120_DMULT,
840   FIX_VR4120_DIV,
841   FIX_VR4120_MTHILO,
842   NUM_FIX_VR4120_CLASSES
843 };
844
845 /* ...likewise -mfix-loongson2f-jump.  */
846 static bfd_boolean mips_fix_loongson2f_jump;
847
848 /* ...likewise -mfix-loongson2f-nop.  */
849 static bfd_boolean mips_fix_loongson2f_nop;
850
851 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
852 static bfd_boolean mips_fix_loongson2f;
853
854 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
855    there must be at least one other instruction between an instruction
856    of type X and an instruction of type Y.  */
857 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
858
859 /* True if -mfix-vr4120 is in force.  */
860 static int mips_fix_vr4120;
861
862 /* ...likewise -mfix-vr4130.  */
863 static int mips_fix_vr4130;
864
865 /* ...likewise -mfix-24k.  */
866 static int mips_fix_24k;
867
868 /* ...likewise -mfix-cn63xxp1 */
869 static bfd_boolean mips_fix_cn63xxp1;
870
871 /* We don't relax branches by default, since this causes us to expand
872    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
873    fail to compute the offset before expanding the macro to the most
874    efficient expansion.  */
875
876 static int mips_relax_branch;
877 \f
878 /* The expansion of many macros depends on the type of symbol that
879    they refer to.  For example, when generating position-dependent code,
880    a macro that refers to a symbol may have two different expansions,
881    one which uses GP-relative addresses and one which uses absolute
882    addresses.  When generating SVR4-style PIC, a macro may have
883    different expansions for local and global symbols.
884
885    We handle these situations by generating both sequences and putting
886    them in variant frags.  In position-dependent code, the first sequence
887    will be the GP-relative one and the second sequence will be the
888    absolute one.  In SVR4 PIC, the first sequence will be for global
889    symbols and the second will be for local symbols.
890
891    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
892    SECOND are the lengths of the two sequences in bytes.  These fields
893    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
894    the subtype has the following flags:
895
896    RELAX_USE_SECOND
897         Set if it has been decided that we should use the second
898         sequence instead of the first.
899
900    RELAX_SECOND_LONGER
901         Set in the first variant frag if the macro's second implementation
902         is longer than its first.  This refers to the macro as a whole,
903         not an individual relaxation.
904
905    RELAX_NOMACRO
906         Set in the first variant frag if the macro appeared in a .set nomacro
907         block and if one alternative requires a warning but the other does not.
908
909    RELAX_DELAY_SLOT
910         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
911         delay slot.
912
913    RELAX_DELAY_SLOT_16BIT
914         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
915         16-bit instruction.
916
917    RELAX_DELAY_SLOT_SIZE_FIRST
918         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
919         the macro is of the wrong size for the branch delay slot.
920
921    RELAX_DELAY_SLOT_SIZE_SECOND
922         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
923         the macro is of the wrong size for the branch delay slot.
924
925    The frag's "opcode" points to the first fixup for relaxable code.
926
927    Relaxable macros are generated using a sequence such as:
928
929       relax_start (SYMBOL);
930       ... generate first expansion ...
931       relax_switch ();
932       ... generate second expansion ...
933       relax_end ();
934
935    The code and fixups for the unwanted alternative are discarded
936    by md_convert_frag.  */
937 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
938
939 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
940 #define RELAX_SECOND(X) ((X) & 0xff)
941 #define RELAX_USE_SECOND 0x10000
942 #define RELAX_SECOND_LONGER 0x20000
943 #define RELAX_NOMACRO 0x40000
944 #define RELAX_DELAY_SLOT 0x80000
945 #define RELAX_DELAY_SLOT_16BIT 0x100000
946 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
947 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
948
949 /* Branch without likely bit.  If label is out of range, we turn:
950
951         beq reg1, reg2, label
952         delay slot
953
954    into
955
956         bne reg1, reg2, 0f
957         nop
958         j label
959      0: delay slot
960
961    with the following opcode replacements:
962
963         beq <-> bne
964         blez <-> bgtz
965         bltz <-> bgez
966         bc1f <-> bc1t
967
968         bltzal <-> bgezal  (with jal label instead of j label)
969
970    Even though keeping the delay slot instruction in the delay slot of
971    the branch would be more efficient, it would be very tricky to do
972    correctly, because we'd have to introduce a variable frag *after*
973    the delay slot instruction, and expand that instead.  Let's do it
974    the easy way for now, even if the branch-not-taken case now costs
975    one additional instruction.  Out-of-range branches are not supposed
976    to be common, anyway.
977
978    Branch likely.  If label is out of range, we turn:
979
980         beql reg1, reg2, label
981         delay slot (annulled if branch not taken)
982
983    into
984
985         beql reg1, reg2, 1f
986         nop
987         beql $0, $0, 2f
988         nop
989      1: j[al] label
990         delay slot (executed only if branch taken)
991      2:
992
993    It would be possible to generate a shorter sequence by losing the
994    likely bit, generating something like:
995
996         bne reg1, reg2, 0f
997         nop
998         j[al] label
999         delay slot (executed only if branch taken)
1000      0:
1001
1002         beql -> bne
1003         bnel -> beq
1004         blezl -> bgtz
1005         bgtzl -> blez
1006         bltzl -> bgez
1007         bgezl -> bltz
1008         bc1fl -> bc1t
1009         bc1tl -> bc1f
1010
1011         bltzall -> bgezal  (with jal label instead of j label)
1012         bgezall -> bltzal  (ditto)
1013
1014
1015    but it's not clear that it would actually improve performance.  */
1016 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1017   ((relax_substateT)                                            \
1018    (0xc0000000                                                  \
1019     | ((at) & 0x1f)                                             \
1020     | ((toofar) ? 0x20 : 0)                                     \
1021     | ((link) ? 0x40 : 0)                                       \
1022     | ((likely) ? 0x80 : 0)                                     \
1023     | ((uncond) ? 0x100 : 0)))
1024 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1025 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1026 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1027 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1028 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1029 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1030
1031 /* For mips16 code, we use an entirely different form of relaxation.
1032    mips16 supports two versions of most instructions which take
1033    immediate values: a small one which takes some small value, and a
1034    larger one which takes a 16 bit value.  Since branches also follow
1035    this pattern, relaxing these values is required.
1036
1037    We can assemble both mips16 and normal MIPS code in a single
1038    object.  Therefore, we need to support this type of relaxation at
1039    the same time that we support the relaxation described above.  We
1040    use the high bit of the subtype field to distinguish these cases.
1041
1042    The information we store for this type of relaxation is the
1043    argument code found in the opcode file for this relocation, whether
1044    the user explicitly requested a small or extended form, and whether
1045    the relocation is in a jump or jal delay slot.  That tells us the
1046    size of the value, and how it should be stored.  We also store
1047    whether the fragment is considered to be extended or not.  We also
1048    store whether this is known to be a branch to a different section,
1049    whether we have tried to relax this frag yet, and whether we have
1050    ever extended a PC relative fragment because of a shift count.  */
1051 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1052   (0x80000000                                                   \
1053    | ((type) & 0xff)                                            \
1054    | ((small) ? 0x100 : 0)                                      \
1055    | ((ext) ? 0x200 : 0)                                        \
1056    | ((dslot) ? 0x400 : 0)                                      \
1057    | ((jal_dslot) ? 0x800 : 0))
1058 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1059 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1060 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1061 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1062 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1063 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1064 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1065 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1066 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1067 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1068 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1069 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1070
1071 /* For microMIPS code, we use relaxation similar to one we use for
1072    MIPS16 code.  Some instructions that take immediate values support
1073    two encodings: a small one which takes some small value, and a
1074    larger one which takes a 16 bit value.  As some branches also follow
1075    this pattern, relaxing these values is required.
1076
1077    We can assemble both microMIPS and normal MIPS code in a single
1078    object.  Therefore, we need to support this type of relaxation at
1079    the same time that we support the relaxation described above.  We
1080    use one of the high bits of the subtype field to distinguish these
1081    cases.
1082
1083    The information we store for this type of relaxation is the argument
1084    code found in the opcode file for this relocation, the register
1085    selected as the assembler temporary, whether the branch is
1086    unconditional, whether it is compact, whether it stores the link
1087    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1088    branches to a sequence of instructions is enabled, and whether the
1089    displacement of a branch is too large to fit as an immediate argument
1090    of a 16-bit and a 32-bit branch, respectively.  */
1091 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1092                                relax32, toofar16, toofar32)     \
1093   (0x40000000                                                   \
1094    | ((type) & 0xff)                                            \
1095    | (((at) & 0x1f) << 8)                                       \
1096    | ((uncond) ? 0x2000 : 0)                                    \
1097    | ((compact) ? 0x4000 : 0)                                   \
1098    | ((link) ? 0x8000 : 0)                                      \
1099    | ((relax32) ? 0x10000 : 0)                                  \
1100    | ((toofar16) ? 0x20000 : 0)                                 \
1101    | ((toofar32) ? 0x40000 : 0))
1102 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1103 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1104 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1105 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1106 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1107 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1108 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1109
1110 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1111 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1112 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1113 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1114 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1115 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1116
1117 /* Sign-extend 16-bit value X.  */
1118 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1119
1120 /* Is the given value a sign-extended 32-bit value?  */
1121 #define IS_SEXT_32BIT_NUM(x)                                            \
1122   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1123    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1124
1125 /* Is the given value a sign-extended 16-bit value?  */
1126 #define IS_SEXT_16BIT_NUM(x)                                            \
1127   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1128    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1129
1130 /* Is the given value a sign-extended 12-bit value?  */
1131 #define IS_SEXT_12BIT_NUM(x)                                            \
1132   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1133
1134 /* Is the given value a sign-extended 9-bit value?  */
1135 #define IS_SEXT_9BIT_NUM(x)                                             \
1136   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1137
1138 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1139 #define IS_ZEXT_32BIT_NUM(x)                                            \
1140   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1141    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1142
1143 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1144    SHIFT places.  */
1145 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1146   (((STRUCT) >> (SHIFT)) & (MASK))
1147
1148 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1149 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1150   (!(MICROMIPS) \
1151    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1152    : EXTRACT_BITS ((INSN).insn_opcode, \
1153                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1154 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1155   EXTRACT_BITS ((INSN).insn_opcode, \
1156                 MIPS16OP_MASK_##FIELD, \
1157                 MIPS16OP_SH_##FIELD)
1158
1159 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1160 #define MIPS16_EXTEND (0xf000U << 16)
1161 \f
1162 /* Whether or not we are emitting a branch-likely macro.  */
1163 static bfd_boolean emit_branch_likely_macro = FALSE;
1164
1165 /* Global variables used when generating relaxable macros.  See the
1166    comment above RELAX_ENCODE for more details about how relaxation
1167    is used.  */
1168 static struct {
1169   /* 0 if we're not emitting a relaxable macro.
1170      1 if we're emitting the first of the two relaxation alternatives.
1171      2 if we're emitting the second alternative.  */
1172   int sequence;
1173
1174   /* The first relaxable fixup in the current frag.  (In other words,
1175      the first fixup that refers to relaxable code.)  */
1176   fixS *first_fixup;
1177
1178   /* sizes[0] says how many bytes of the first alternative are stored in
1179      the current frag.  Likewise sizes[1] for the second alternative.  */
1180   unsigned int sizes[2];
1181
1182   /* The symbol on which the choice of sequence depends.  */
1183   symbolS *symbol;
1184 } mips_relax;
1185 \f
1186 /* Global variables used to decide whether a macro needs a warning.  */
1187 static struct {
1188   /* True if the macro is in a branch delay slot.  */
1189   bfd_boolean delay_slot_p;
1190
1191   /* Set to the length in bytes required if the macro is in a delay slot
1192      that requires a specific length of instruction, otherwise zero.  */
1193   unsigned int delay_slot_length;
1194
1195   /* For relaxable macros, sizes[0] is the length of the first alternative
1196      in bytes and sizes[1] is the length of the second alternative.
1197      For non-relaxable macros, both elements give the length of the
1198      macro in bytes.  */
1199   unsigned int sizes[2];
1200
1201   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1202      instruction of the first alternative in bytes and first_insn_sizes[1]
1203      is the length of the first instruction of the second alternative.
1204      For non-relaxable macros, both elements give the length of the first
1205      instruction in bytes.
1206
1207      Set to zero if we haven't yet seen the first instruction.  */
1208   unsigned int first_insn_sizes[2];
1209
1210   /* For relaxable macros, insns[0] is the number of instructions for the
1211      first alternative and insns[1] is the number of instructions for the
1212      second alternative.
1213
1214      For non-relaxable macros, both elements give the number of
1215      instructions for the macro.  */
1216   unsigned int insns[2];
1217
1218   /* The first variant frag for this macro.  */
1219   fragS *first_frag;
1220 } mips_macro_warning;
1221 \f
1222 /* Prototypes for static functions.  */
1223
1224 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1225
1226 static void append_insn
1227   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1228    bfd_boolean expansionp);
1229 static void mips_no_prev_insn (void);
1230 static void macro_build (expressionS *, const char *, const char *, ...);
1231 static void mips16_macro_build
1232   (expressionS *, const char *, const char *, va_list *);
1233 static void load_register (int, expressionS *, int);
1234 static void macro_start (void);
1235 static void macro_end (void);
1236 static void macro (struct mips_cl_insn *ip, char *str);
1237 static void mips16_macro (struct mips_cl_insn * ip);
1238 static void mips_ip (char *str, struct mips_cl_insn * ip);
1239 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1240 static void mips16_immed
1241   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1242    unsigned int, unsigned long *);
1243 static size_t my_getSmallExpression
1244   (expressionS *, bfd_reloc_code_real_type *, char *);
1245 static void my_getExpression (expressionS *, char *);
1246 static void s_align (int);
1247 static void s_change_sec (int);
1248 static void s_change_section (int);
1249 static void s_cons (int);
1250 static void s_float_cons (int);
1251 static void s_mips_globl (int);
1252 static void s_option (int);
1253 static void s_mipsset (int);
1254 static void s_abicalls (int);
1255 static void s_cpload (int);
1256 static void s_cpsetup (int);
1257 static void s_cplocal (int);
1258 static void s_cprestore (int);
1259 static void s_cpreturn (int);
1260 static void s_dtprelword (int);
1261 static void s_dtpreldword (int);
1262 static void s_tprelword (int);
1263 static void s_tpreldword (int);
1264 static void s_gpvalue (int);
1265 static void s_gpword (int);
1266 static void s_gpdword (int);
1267 static void s_ehword (int);
1268 static void s_cpadd (int);
1269 static void s_insn (int);
1270 static void s_nan (int);
1271 static void md_obj_begin (void);
1272 static void md_obj_end (void);
1273 static void s_mips_ent (int);
1274 static void s_mips_end (int);
1275 static void s_mips_frame (int);
1276 static void s_mips_mask (int reg_type);
1277 static void s_mips_stab (int);
1278 static void s_mips_weakext (int);
1279 static void s_mips_file (int);
1280 static void s_mips_loc (int);
1281 static bfd_boolean pic_need_relax (symbolS *, asection *);
1282 static int relaxed_branch_length (fragS *, asection *, int);
1283 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1284 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1285
1286 /* Table and functions used to map between CPU/ISA names, and
1287    ISA levels, and CPU numbers.  */
1288
1289 struct mips_cpu_info
1290 {
1291   const char *name;           /* CPU or ISA name.  */
1292   int flags;                  /* MIPS_CPU_* flags.  */
1293   int ase;                    /* Set of ASEs implemented by the CPU.  */
1294   int isa;                    /* ISA level.  */
1295   int cpu;                    /* CPU number (default CPU if ISA).  */
1296 };
1297
1298 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1299
1300 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1301 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1302 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1303 \f
1304 /* Command-line options.  */
1305 const char *md_shortopts = "O::g::G:";
1306
1307 enum options
1308   {
1309     OPTION_MARCH = OPTION_MD_BASE,
1310     OPTION_MTUNE,
1311     OPTION_MIPS1,
1312     OPTION_MIPS2,
1313     OPTION_MIPS3,
1314     OPTION_MIPS4,
1315     OPTION_MIPS5,
1316     OPTION_MIPS32,
1317     OPTION_MIPS64,
1318     OPTION_MIPS32R2,
1319     OPTION_MIPS64R2,
1320     OPTION_MIPS16,
1321     OPTION_NO_MIPS16,
1322     OPTION_MIPS3D,
1323     OPTION_NO_MIPS3D,
1324     OPTION_MDMX,
1325     OPTION_NO_MDMX,
1326     OPTION_DSP,
1327     OPTION_NO_DSP,
1328     OPTION_MT,
1329     OPTION_NO_MT,
1330     OPTION_VIRT,
1331     OPTION_NO_VIRT,
1332     OPTION_SMARTMIPS,
1333     OPTION_NO_SMARTMIPS,
1334     OPTION_DSPR2,
1335     OPTION_NO_DSPR2,
1336     OPTION_EVA,
1337     OPTION_NO_EVA,
1338     OPTION_MICROMIPS,
1339     OPTION_NO_MICROMIPS,
1340     OPTION_MCU,
1341     OPTION_NO_MCU,
1342     OPTION_COMPAT_ARCH_BASE,
1343     OPTION_M4650,
1344     OPTION_NO_M4650,
1345     OPTION_M4010,
1346     OPTION_NO_M4010,
1347     OPTION_M4100,
1348     OPTION_NO_M4100,
1349     OPTION_M3900,
1350     OPTION_NO_M3900,
1351     OPTION_M7000_HILO_FIX,
1352     OPTION_MNO_7000_HILO_FIX,
1353     OPTION_FIX_24K,
1354     OPTION_NO_FIX_24K,
1355     OPTION_FIX_LOONGSON2F_JUMP,
1356     OPTION_NO_FIX_LOONGSON2F_JUMP,
1357     OPTION_FIX_LOONGSON2F_NOP,
1358     OPTION_NO_FIX_LOONGSON2F_NOP,
1359     OPTION_FIX_VR4120,
1360     OPTION_NO_FIX_VR4120,
1361     OPTION_FIX_VR4130,
1362     OPTION_NO_FIX_VR4130,
1363     OPTION_FIX_CN63XXP1,
1364     OPTION_NO_FIX_CN63XXP1,
1365     OPTION_TRAP,
1366     OPTION_BREAK,
1367     OPTION_EB,
1368     OPTION_EL,
1369     OPTION_FP32,
1370     OPTION_GP32,
1371     OPTION_CONSTRUCT_FLOATS,
1372     OPTION_NO_CONSTRUCT_FLOATS,
1373     OPTION_FP64,
1374     OPTION_GP64,
1375     OPTION_RELAX_BRANCH,
1376     OPTION_NO_RELAX_BRANCH,
1377     OPTION_INSN32,
1378     OPTION_NO_INSN32,
1379     OPTION_MSHARED,
1380     OPTION_MNO_SHARED,
1381     OPTION_MSYM32,
1382     OPTION_MNO_SYM32,
1383     OPTION_SOFT_FLOAT,
1384     OPTION_HARD_FLOAT,
1385     OPTION_SINGLE_FLOAT,
1386     OPTION_DOUBLE_FLOAT,
1387     OPTION_32,
1388     OPTION_CALL_SHARED,
1389     OPTION_CALL_NONPIC,
1390     OPTION_NON_SHARED,
1391     OPTION_XGOT,
1392     OPTION_MABI,
1393     OPTION_N32,
1394     OPTION_64,
1395     OPTION_MDEBUG,
1396     OPTION_NO_MDEBUG,
1397     OPTION_PDR,
1398     OPTION_NO_PDR,
1399     OPTION_MVXWORKS_PIC,
1400     OPTION_NAN,
1401     OPTION_END_OF_ENUM
1402   };
1403
1404 struct option md_longopts[] =
1405 {
1406   /* Options which specify architecture.  */
1407   {"march", required_argument, NULL, OPTION_MARCH},
1408   {"mtune", required_argument, NULL, OPTION_MTUNE},
1409   {"mips0", no_argument, NULL, OPTION_MIPS1},
1410   {"mips1", no_argument, NULL, OPTION_MIPS1},
1411   {"mips2", no_argument, NULL, OPTION_MIPS2},
1412   {"mips3", no_argument, NULL, OPTION_MIPS3},
1413   {"mips4", no_argument, NULL, OPTION_MIPS4},
1414   {"mips5", no_argument, NULL, OPTION_MIPS5},
1415   {"mips32", no_argument, NULL, OPTION_MIPS32},
1416   {"mips64", no_argument, NULL, OPTION_MIPS64},
1417   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1418   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1419
1420   /* Options which specify Application Specific Extensions (ASEs).  */
1421   {"mips16", no_argument, NULL, OPTION_MIPS16},
1422   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1423   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1424   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1425   {"mdmx", no_argument, NULL, OPTION_MDMX},
1426   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1427   {"mdsp", no_argument, NULL, OPTION_DSP},
1428   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1429   {"mmt", no_argument, NULL, OPTION_MT},
1430   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1431   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1432   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1433   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1434   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1435   {"meva", no_argument, NULL, OPTION_EVA},
1436   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1437   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1438   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1439   {"mmcu", no_argument, NULL, OPTION_MCU},
1440   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1441   {"mvirt", no_argument, NULL, OPTION_VIRT},
1442   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1443
1444   /* Old-style architecture options.  Don't add more of these.  */
1445   {"m4650", no_argument, NULL, OPTION_M4650},
1446   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1447   {"m4010", no_argument, NULL, OPTION_M4010},
1448   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1449   {"m4100", no_argument, NULL, OPTION_M4100},
1450   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1451   {"m3900", no_argument, NULL, OPTION_M3900},
1452   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1453
1454   /* Options which enable bug fixes.  */
1455   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1456   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1457   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1458   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1459   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1460   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1461   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1462   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1463   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1464   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1465   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1466   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1467   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1468   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1469   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1470
1471   /* Miscellaneous options.  */
1472   {"trap", no_argument, NULL, OPTION_TRAP},
1473   {"no-break", no_argument, NULL, OPTION_TRAP},
1474   {"break", no_argument, NULL, OPTION_BREAK},
1475   {"no-trap", no_argument, NULL, OPTION_BREAK},
1476   {"EB", no_argument, NULL, OPTION_EB},
1477   {"EL", no_argument, NULL, OPTION_EL},
1478   {"mfp32", no_argument, NULL, OPTION_FP32},
1479   {"mgp32", no_argument, NULL, OPTION_GP32},
1480   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1481   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1482   {"mfp64", no_argument, NULL, OPTION_FP64},
1483   {"mgp64", no_argument, NULL, OPTION_GP64},
1484   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1485   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1486   {"minsn32", no_argument, NULL, OPTION_INSN32},
1487   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1488   {"mshared", no_argument, NULL, OPTION_MSHARED},
1489   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1490   {"msym32", no_argument, NULL, OPTION_MSYM32},
1491   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1492   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1493   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1494   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1495   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1496
1497   /* Strictly speaking this next option is ELF specific,
1498      but we allow it for other ports as well in order to
1499      make testing easier.  */
1500   {"32", no_argument, NULL, OPTION_32},
1501
1502   /* ELF-specific options.  */
1503   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1504   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1505   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1506   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1507   {"xgot", no_argument, NULL, OPTION_XGOT},
1508   {"mabi", required_argument, NULL, OPTION_MABI},
1509   {"n32", no_argument, NULL, OPTION_N32},
1510   {"64", no_argument, NULL, OPTION_64},
1511   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1512   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1513   {"mpdr", no_argument, NULL, OPTION_PDR},
1514   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1515   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1516   {"mnan", required_argument, NULL, OPTION_NAN},
1517
1518   {NULL, no_argument, NULL, 0}
1519 };
1520 size_t md_longopts_size = sizeof (md_longopts);
1521 \f
1522 /* Information about either an Application Specific Extension or an
1523    optional architecture feature that, for simplicity, we treat in the
1524    same way as an ASE.  */
1525 struct mips_ase
1526 {
1527   /* The name of the ASE, used in both the command-line and .set options.  */
1528   const char *name;
1529
1530   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1531      and 64-bit architectures, the flags here refer to the subset that
1532      is available on both.  */
1533   unsigned int flags;
1534
1535   /* The ASE_* flag used for instructions that are available on 64-bit
1536      architectures but that are not included in FLAGS.  */
1537   unsigned int flags64;
1538
1539   /* The command-line options that turn the ASE on and off.  */
1540   int option_on;
1541   int option_off;
1542
1543   /* The minimum required architecture revisions for MIPS32, MIPS64,
1544      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1545   int mips32_rev;
1546   int mips64_rev;
1547   int micromips32_rev;
1548   int micromips64_rev;
1549 };
1550
1551 /* A table of all supported ASEs.  */
1552 static const struct mips_ase mips_ases[] = {
1553   { "dsp", ASE_DSP, ASE_DSP64,
1554     OPTION_DSP, OPTION_NO_DSP,
1555     2, 2, 2, 2 },
1556
1557   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1558     OPTION_DSPR2, OPTION_NO_DSPR2,
1559     2, 2, 2, 2 },
1560
1561   { "eva", ASE_EVA, 0,
1562     OPTION_EVA, OPTION_NO_EVA,
1563     2, 2, 2, 2 },
1564
1565   { "mcu", ASE_MCU, 0,
1566     OPTION_MCU, OPTION_NO_MCU,
1567     2, 2, 2, 2 },
1568
1569   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1570   { "mdmx", ASE_MDMX, 0,
1571     OPTION_MDMX, OPTION_NO_MDMX,
1572     -1, 1, -1, -1 },
1573
1574   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1575   { "mips3d", ASE_MIPS3D, 0,
1576     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1577     2, 1, -1, -1 },
1578
1579   { "mt", ASE_MT, 0,
1580     OPTION_MT, OPTION_NO_MT,
1581     2, 2, -1, -1 },
1582
1583   { "smartmips", ASE_SMARTMIPS, 0,
1584     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1585     1, -1, -1, -1 },
1586
1587   { "virt", ASE_VIRT, ASE_VIRT64,
1588     OPTION_VIRT, OPTION_NO_VIRT,
1589     2, 2, 2, 2 }
1590 };
1591
1592 /* The set of ASEs that require -mfp64.  */
1593 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1594
1595 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1596 static const unsigned int mips_ase_groups[] = {
1597   ASE_DSP | ASE_DSPR2
1598 };
1599 \f
1600 /* Pseudo-op table.
1601
1602    The following pseudo-ops from the Kane and Heinrich MIPS book
1603    should be defined here, but are currently unsupported: .alias,
1604    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1605
1606    The following pseudo-ops from the Kane and Heinrich MIPS book are
1607    specific to the type of debugging information being generated, and
1608    should be defined by the object format: .aent, .begin, .bend,
1609    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1610    .vreg.
1611
1612    The following pseudo-ops from the Kane and Heinrich MIPS book are
1613    not MIPS CPU specific, but are also not specific to the object file
1614    format.  This file is probably the best place to define them, but
1615    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1616
1617 static const pseudo_typeS mips_pseudo_table[] =
1618 {
1619   /* MIPS specific pseudo-ops.  */
1620   {"option", s_option, 0},
1621   {"set", s_mipsset, 0},
1622   {"rdata", s_change_sec, 'r'},
1623   {"sdata", s_change_sec, 's'},
1624   {"livereg", s_ignore, 0},
1625   {"abicalls", s_abicalls, 0},
1626   {"cpload", s_cpload, 0},
1627   {"cpsetup", s_cpsetup, 0},
1628   {"cplocal", s_cplocal, 0},
1629   {"cprestore", s_cprestore, 0},
1630   {"cpreturn", s_cpreturn, 0},
1631   {"dtprelword", s_dtprelword, 0},
1632   {"dtpreldword", s_dtpreldword, 0},
1633   {"tprelword", s_tprelword, 0},
1634   {"tpreldword", s_tpreldword, 0},
1635   {"gpvalue", s_gpvalue, 0},
1636   {"gpword", s_gpword, 0},
1637   {"gpdword", s_gpdword, 0},
1638   {"ehword", s_ehword, 0},
1639   {"cpadd", s_cpadd, 0},
1640   {"insn", s_insn, 0},
1641   {"nan", s_nan, 0},
1642
1643   /* Relatively generic pseudo-ops that happen to be used on MIPS
1644      chips.  */
1645   {"asciiz", stringer, 8 + 1},
1646   {"bss", s_change_sec, 'b'},
1647   {"err", s_err, 0},
1648   {"half", s_cons, 1},
1649   {"dword", s_cons, 3},
1650   {"weakext", s_mips_weakext, 0},
1651   {"origin", s_org, 0},
1652   {"repeat", s_rept, 0},
1653
1654   /* For MIPS this is non-standard, but we define it for consistency.  */
1655   {"sbss", s_change_sec, 'B'},
1656
1657   /* These pseudo-ops are defined in read.c, but must be overridden
1658      here for one reason or another.  */
1659   {"align", s_align, 0},
1660   {"byte", s_cons, 0},
1661   {"data", s_change_sec, 'd'},
1662   {"double", s_float_cons, 'd'},
1663   {"float", s_float_cons, 'f'},
1664   {"globl", s_mips_globl, 0},
1665   {"global", s_mips_globl, 0},
1666   {"hword", s_cons, 1},
1667   {"int", s_cons, 2},
1668   {"long", s_cons, 2},
1669   {"octa", s_cons, 4},
1670   {"quad", s_cons, 3},
1671   {"section", s_change_section, 0},
1672   {"short", s_cons, 1},
1673   {"single", s_float_cons, 'f'},
1674   {"stabd", s_mips_stab, 'd'},
1675   {"stabn", s_mips_stab, 'n'},
1676   {"stabs", s_mips_stab, 's'},
1677   {"text", s_change_sec, 't'},
1678   {"word", s_cons, 2},
1679
1680   { "extern", ecoff_directive_extern, 0},
1681
1682   { NULL, NULL, 0 },
1683 };
1684
1685 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1686 {
1687   /* These pseudo-ops should be defined by the object file format.
1688      However, a.out doesn't support them, so we have versions here.  */
1689   {"aent", s_mips_ent, 1},
1690   {"bgnb", s_ignore, 0},
1691   {"end", s_mips_end, 0},
1692   {"endb", s_ignore, 0},
1693   {"ent", s_mips_ent, 0},
1694   {"file", s_mips_file, 0},
1695   {"fmask", s_mips_mask, 'F'},
1696   {"frame", s_mips_frame, 0},
1697   {"loc", s_mips_loc, 0},
1698   {"mask", s_mips_mask, 'R'},
1699   {"verstamp", s_ignore, 0},
1700   { NULL, NULL, 0 },
1701 };
1702
1703 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1704    purpose of the `.dc.a' internal pseudo-op.  */
1705
1706 int
1707 mips_address_bytes (void)
1708 {
1709   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1710 }
1711
1712 extern void pop_insert (const pseudo_typeS *);
1713
1714 void
1715 mips_pop_insert (void)
1716 {
1717   pop_insert (mips_pseudo_table);
1718   if (! ECOFF_DEBUGGING)
1719     pop_insert (mips_nonecoff_pseudo_table);
1720 }
1721 \f
1722 /* Symbols labelling the current insn.  */
1723
1724 struct insn_label_list
1725 {
1726   struct insn_label_list *next;
1727   symbolS *label;
1728 };
1729
1730 static struct insn_label_list *free_insn_labels;
1731 #define label_list tc_segment_info_data.labels
1732
1733 static void mips_clear_insn_labels (void);
1734 static void mips_mark_labels (void);
1735 static void mips_compressed_mark_labels (void);
1736
1737 static inline void
1738 mips_clear_insn_labels (void)
1739 {
1740   register struct insn_label_list **pl;
1741   segment_info_type *si;
1742
1743   if (now_seg)
1744     {
1745       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1746         ;
1747       
1748       si = seg_info (now_seg);
1749       *pl = si->label_list;
1750       si->label_list = NULL;
1751     }
1752 }
1753
1754 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1755
1756 static inline void
1757 mips_mark_labels (void)
1758 {
1759   if (HAVE_CODE_COMPRESSION)
1760     mips_compressed_mark_labels ();
1761 }
1762 \f
1763 static char *expr_end;
1764
1765 /* Expressions which appear in macro instructions.  These are set by
1766    mips_ip and read by macro.  */
1767
1768 static expressionS imm_expr;
1769 static expressionS imm2_expr;
1770
1771 /* The relocatable field in an instruction and the relocs associated
1772    with it.  These variables are used for instructions like LUI and
1773    JAL as well as true offsets.  They are also used for address
1774    operands in macros.  */
1775
1776 static expressionS offset_expr;
1777 static bfd_reloc_code_real_type offset_reloc[3]
1778   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1779
1780 /* This is set to the resulting size of the instruction to be produced
1781    by mips16_ip if an explicit extension is used or by mips_ip if an
1782    explicit size is supplied.  */
1783
1784 static unsigned int forced_insn_length;
1785
1786 /* True if we are assembling an instruction.  All dot symbols defined during
1787    this time should be treated as code labels.  */
1788
1789 static bfd_boolean mips_assembling_insn;
1790
1791 /* The pdr segment for per procedure frame/regmask info.  Not used for
1792    ECOFF debugging.  */
1793
1794 static segT pdr_seg;
1795
1796 /* The default target format to use.  */
1797
1798 #if defined (TE_FreeBSD)
1799 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1800 #elif defined (TE_TMIPS)
1801 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1802 #else
1803 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1804 #endif
1805
1806 const char *
1807 mips_target_format (void)
1808 {
1809   switch (OUTPUT_FLAVOR)
1810     {
1811     case bfd_target_elf_flavour:
1812 #ifdef TE_VXWORKS
1813       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1814         return (target_big_endian
1815                 ? "elf32-bigmips-vxworks"
1816                 : "elf32-littlemips-vxworks");
1817 #endif
1818       return (target_big_endian
1819               ? (HAVE_64BIT_OBJECTS
1820                  ? ELF_TARGET ("elf64-", "big")
1821                  : (HAVE_NEWABI
1822                     ? ELF_TARGET ("elf32-n", "big")
1823                     : ELF_TARGET ("elf32-", "big")))
1824               : (HAVE_64BIT_OBJECTS
1825                  ? ELF_TARGET ("elf64-", "little")
1826                  : (HAVE_NEWABI
1827                     ? ELF_TARGET ("elf32-n", "little")
1828                     : ELF_TARGET ("elf32-", "little"))));
1829     default:
1830       abort ();
1831       return NULL;
1832     }
1833 }
1834
1835 /* Return the ISA revision that is currently in use, or 0 if we are
1836    generating code for MIPS V or below.  */
1837
1838 static int
1839 mips_isa_rev (void)
1840 {
1841   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1842     return 2;
1843
1844   /* microMIPS implies revision 2 or above.  */
1845   if (mips_opts.micromips)
1846     return 2;
1847
1848   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1849     return 1;
1850
1851   return 0;
1852 }
1853
1854 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1855
1856 static unsigned int
1857 mips_ase_mask (unsigned int flags)
1858 {
1859   unsigned int i;
1860
1861   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1862     if (flags & mips_ase_groups[i])
1863       flags |= mips_ase_groups[i];
1864   return flags;
1865 }
1866
1867 /* Check whether the current ISA supports ASE.  Issue a warning if
1868    appropriate.  */
1869
1870 static void
1871 mips_check_isa_supports_ase (const struct mips_ase *ase)
1872 {
1873   const char *base;
1874   int min_rev, size;
1875   static unsigned int warned_isa;
1876   static unsigned int warned_fp32;
1877
1878   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1879     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1880   else
1881     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1882   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1883       && (warned_isa & ase->flags) != ase->flags)
1884     {
1885       warned_isa |= ase->flags;
1886       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1887       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1888       if (min_rev < 0)
1889         as_warn (_("The %d-bit %s architecture does not support the"
1890                    " `%s' extension"), size, base, ase->name);
1891       else
1892         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1893                  ase->name, base, size, min_rev);
1894     }
1895   if ((ase->flags & FP64_ASES)
1896       && mips_opts.fp32
1897       && (warned_fp32 & ase->flags) != ase->flags)
1898     {
1899       warned_fp32 |= ase->flags;
1900       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1901     }
1902 }
1903
1904 /* Check all enabled ASEs to see whether they are supported by the
1905    chosen architecture.  */
1906
1907 static void
1908 mips_check_isa_supports_ases (void)
1909 {
1910   unsigned int i, mask;
1911
1912   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1913     {
1914       mask = mips_ase_mask (mips_ases[i].flags);
1915       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1916         mips_check_isa_supports_ase (&mips_ases[i]);
1917     }
1918 }
1919
1920 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1921    that were affected.  */
1922
1923 static unsigned int
1924 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1925 {
1926   unsigned int mask;
1927
1928   mask = mips_ase_mask (ase->flags);
1929   mips_opts.ase &= ~mask;
1930   if (enabled_p)
1931     mips_opts.ase |= ase->flags;
1932   return mask;
1933 }
1934
1935 /* Return the ASE called NAME, or null if none.  */
1936
1937 static const struct mips_ase *
1938 mips_lookup_ase (const char *name)
1939 {
1940   unsigned int i;
1941
1942   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1943     if (strcmp (name, mips_ases[i].name) == 0)
1944       return &mips_ases[i];
1945   return NULL;
1946 }
1947
1948 /* Return the length of a microMIPS instruction in bytes.  If bits of
1949    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1950    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1951    major opcode) will require further modifications to the opcode
1952    table.  */
1953
1954 static inline unsigned int
1955 micromips_insn_length (const struct mips_opcode *mo)
1956 {
1957   return (mo->mask >> 16) == 0 ? 2 : 4;
1958 }
1959
1960 /* Return the length of MIPS16 instruction OPCODE.  */
1961
1962 static inline unsigned int
1963 mips16_opcode_length (unsigned long opcode)
1964 {
1965   return (opcode >> 16) == 0 ? 2 : 4;
1966 }
1967
1968 /* Return the length of instruction INSN.  */
1969
1970 static inline unsigned int
1971 insn_length (const struct mips_cl_insn *insn)
1972 {
1973   if (mips_opts.micromips)
1974     return micromips_insn_length (insn->insn_mo);
1975   else if (mips_opts.mips16)
1976     return mips16_opcode_length (insn->insn_opcode);
1977   else
1978     return 4;
1979 }
1980
1981 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1982
1983 static void
1984 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1985 {
1986   size_t i;
1987
1988   insn->insn_mo = mo;
1989   insn->insn_opcode = mo->match;
1990   insn->frag = NULL;
1991   insn->where = 0;
1992   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1993     insn->fixp[i] = NULL;
1994   insn->fixed_p = (mips_opts.noreorder > 0);
1995   insn->noreorder_p = (mips_opts.noreorder > 0);
1996   insn->mips16_absolute_jump_p = 0;
1997   insn->complete_p = 0;
1998   insn->cleared_p = 0;
1999 }
2000
2001 /* Get a list of all the operands in INSN.  */
2002
2003 static const struct mips_operand_array *
2004 insn_operands (const struct mips_cl_insn *insn)
2005 {
2006   if (insn->insn_mo >= &mips_opcodes[0]
2007       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2008     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2009
2010   if (insn->insn_mo >= &mips16_opcodes[0]
2011       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2012     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2013
2014   if (insn->insn_mo >= &micromips_opcodes[0]
2015       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2016     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2017
2018   abort ();
2019 }
2020
2021 /* Get a description of operand OPNO of INSN.  */
2022
2023 static const struct mips_operand *
2024 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2025 {
2026   const struct mips_operand_array *operands;
2027
2028   operands = insn_operands (insn);
2029   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2030     abort ();
2031   return operands->operand[opno];
2032 }
2033
2034 /* Install UVAL as the value of OPERAND in INSN.  */
2035
2036 static inline void
2037 insn_insert_operand (struct mips_cl_insn *insn,
2038                      const struct mips_operand *operand, unsigned int uval)
2039 {
2040   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2041 }
2042
2043 /* Extract the value of OPERAND from INSN.  */
2044
2045 static inline unsigned
2046 insn_extract_operand (const struct mips_cl_insn *insn,
2047                       const struct mips_operand *operand)
2048 {
2049   return mips_extract_operand (operand, insn->insn_opcode);
2050 }
2051
2052 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2053
2054 static void
2055 mips_record_compressed_mode (void)
2056 {
2057   segment_info_type *si;
2058
2059   si = seg_info (now_seg);
2060   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2061     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2062   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2063     si->tc_segment_info_data.micromips = mips_opts.micromips;
2064 }
2065
2066 /* Read a standard MIPS instruction from BUF.  */
2067
2068 static unsigned long
2069 read_insn (char *buf)
2070 {
2071   if (target_big_endian)
2072     return bfd_getb32 ((bfd_byte *) buf);
2073   else
2074     return bfd_getl32 ((bfd_byte *) buf);
2075 }
2076
2077 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2078    the next byte.  */
2079
2080 static char *
2081 write_insn (char *buf, unsigned int insn)
2082 {
2083   md_number_to_chars (buf, insn, 4);
2084   return buf + 4;
2085 }
2086
2087 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2088    has length LENGTH.  */
2089
2090 static unsigned long
2091 read_compressed_insn (char *buf, unsigned int length)
2092 {
2093   unsigned long insn;
2094   unsigned int i;
2095
2096   insn = 0;
2097   for (i = 0; i < length; i += 2)
2098     {
2099       insn <<= 16;
2100       if (target_big_endian)
2101         insn |= bfd_getb16 ((char *) buf);
2102       else
2103         insn |= bfd_getl16 ((char *) buf);
2104       buf += 2;
2105     }
2106   return insn;
2107 }
2108
2109 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2110    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2111
2112 static char *
2113 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2114 {
2115   unsigned int i;
2116
2117   for (i = 0; i < length; i += 2)
2118     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2119   return buf + length;
2120 }
2121
2122 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2123
2124 static void
2125 install_insn (const struct mips_cl_insn *insn)
2126 {
2127   char *f = insn->frag->fr_literal + insn->where;
2128   if (HAVE_CODE_COMPRESSION)
2129     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2130   else
2131     write_insn (f, insn->insn_opcode);
2132   mips_record_compressed_mode ();
2133 }
2134
2135 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2136    and install the opcode in the new location.  */
2137
2138 static void
2139 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2140 {
2141   size_t i;
2142
2143   insn->frag = frag;
2144   insn->where = where;
2145   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2146     if (insn->fixp[i] != NULL)
2147       {
2148         insn->fixp[i]->fx_frag = frag;
2149         insn->fixp[i]->fx_where = where;
2150       }
2151   install_insn (insn);
2152 }
2153
2154 /* Add INSN to the end of the output.  */
2155
2156 static void
2157 add_fixed_insn (struct mips_cl_insn *insn)
2158 {
2159   char *f = frag_more (insn_length (insn));
2160   move_insn (insn, frag_now, f - frag_now->fr_literal);
2161 }
2162
2163 /* Start a variant frag and move INSN to the start of the variant part,
2164    marking it as fixed.  The other arguments are as for frag_var.  */
2165
2166 static void
2167 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2168                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2169 {
2170   frag_grow (max_chars);
2171   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2172   insn->fixed_p = 1;
2173   frag_var (rs_machine_dependent, max_chars, var,
2174             subtype, symbol, offset, NULL);
2175 }
2176
2177 /* Insert N copies of INSN into the history buffer, starting at
2178    position FIRST.  Neither FIRST nor N need to be clipped.  */
2179
2180 static void
2181 insert_into_history (unsigned int first, unsigned int n,
2182                      const struct mips_cl_insn *insn)
2183 {
2184   if (mips_relax.sequence != 2)
2185     {
2186       unsigned int i;
2187
2188       for (i = ARRAY_SIZE (history); i-- > first;)
2189         if (i >= first + n)
2190           history[i] = history[i - n];
2191         else
2192           history[i] = *insn;
2193     }
2194 }
2195
2196 /* Clear the error in insn_error.  */
2197
2198 static void
2199 clear_insn_error (void)
2200 {
2201   memset (&insn_error, 0, sizeof (insn_error));
2202 }
2203
2204 /* Possibly record error message MSG for the current instruction.
2205    If the error is about a particular argument, ARGNUM is the 1-based
2206    number of that argument, otherwise it is 0.  FORMAT is the format
2207    of MSG.  Return true if MSG was used, false if the current message
2208    was kept.  */
2209
2210 static bfd_boolean
2211 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2212                        const char *msg)
2213 {
2214   if (argnum == 0)
2215     {
2216       /* Give priority to errors against specific arguments, and to
2217          the first whole-instruction message.  */
2218       if (insn_error.msg)
2219         return FALSE;
2220     }
2221   else
2222     {
2223       /* Keep insn_error if it is against a later argument.  */
2224       if (argnum < insn_error.min_argnum)
2225         return FALSE;
2226
2227       /* If both errors are against the same argument but are different,
2228          give up on reporting a specific error for this argument.
2229          See the comment about mips_insn_error for details.  */
2230       if (argnum == insn_error.min_argnum
2231           && insn_error.msg
2232           && strcmp (insn_error.msg, msg) != 0)
2233         {
2234           insn_error.msg = 0;
2235           insn_error.min_argnum += 1;
2236           return FALSE;
2237         }
2238     }
2239   insn_error.min_argnum = argnum;
2240   insn_error.format = format;
2241   insn_error.msg = msg;
2242   return TRUE;
2243 }
2244
2245 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2246    as for set_insn_error_format.  */
2247
2248 static void
2249 set_insn_error (int argnum, const char *msg)
2250 {
2251   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2252 }
2253
2254 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2255    as for set_insn_error_format.  */
2256
2257 static void
2258 set_insn_error_i (int argnum, const char *msg, int i)
2259 {
2260   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2261     insn_error.u.i = i;
2262 }
2263
2264 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2265    are as for set_insn_error_format.  */
2266
2267 static void
2268 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2269 {
2270   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2271     {
2272       insn_error.u.ss[0] = s1;
2273       insn_error.u.ss[1] = s2;
2274     }
2275 }
2276
2277 /* Report the error in insn_error, which is against assembly code STR.  */
2278
2279 static void
2280 report_insn_error (const char *str)
2281 {
2282   const char *msg;
2283
2284   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2285   switch (insn_error.format)
2286     {
2287     case ERR_FMT_PLAIN:
2288       as_bad (msg, str);
2289       break;
2290
2291     case ERR_FMT_I:
2292       as_bad (msg, insn_error.u.i, str);
2293       break;
2294
2295     case ERR_FMT_SS:
2296       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2297       break;
2298     }
2299 }
2300
2301 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2302    the idea is to make it obvious at a glance that each errata is
2303    included.  */
2304
2305 static void
2306 init_vr4120_conflicts (void)
2307 {
2308 #define CONFLICT(FIRST, SECOND) \
2309     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2310
2311   /* Errata 21 - [D]DIV[U] after [D]MACC */
2312   CONFLICT (MACC, DIV);
2313   CONFLICT (DMACC, DIV);
2314
2315   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2316   CONFLICT (DMULT, DMULT);
2317   CONFLICT (DMULT, DMACC);
2318   CONFLICT (DMACC, DMULT);
2319   CONFLICT (DMACC, DMACC);
2320
2321   /* Errata 24 - MT{LO,HI} after [D]MACC */
2322   CONFLICT (MACC, MTHILO);
2323   CONFLICT (DMACC, MTHILO);
2324
2325   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2326      instruction is executed immediately after a MACC or DMACC
2327      instruction, the result of [either instruction] is incorrect."  */
2328   CONFLICT (MACC, MULT);
2329   CONFLICT (MACC, DMULT);
2330   CONFLICT (DMACC, MULT);
2331   CONFLICT (DMACC, DMULT);
2332
2333   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2334      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2335      DDIV or DDIVU instruction, the result of the MACC or
2336      DMACC instruction is incorrect.".  */
2337   CONFLICT (DMULT, MACC);
2338   CONFLICT (DMULT, DMACC);
2339   CONFLICT (DIV, MACC);
2340   CONFLICT (DIV, DMACC);
2341
2342 #undef CONFLICT
2343 }
2344
2345 struct regname {
2346   const char *name;
2347   unsigned int num;
2348 };
2349
2350 #define RNUM_MASK       0x00000ff
2351 #define RTYPE_MASK      0x0efff00
2352 #define RTYPE_NUM       0x0000100
2353 #define RTYPE_FPU       0x0000200
2354 #define RTYPE_FCC       0x0000400
2355 #define RTYPE_VEC       0x0000800
2356 #define RTYPE_GP        0x0001000
2357 #define RTYPE_CP0       0x0002000
2358 #define RTYPE_PC        0x0004000
2359 #define RTYPE_ACC       0x0008000
2360 #define RTYPE_CCC       0x0010000
2361 #define RTYPE_VI        0x0020000
2362 #define RTYPE_VF        0x0040000
2363 #define RTYPE_R5900_I   0x0080000
2364 #define RTYPE_R5900_Q   0x0100000
2365 #define RTYPE_R5900_R   0x0200000
2366 #define RTYPE_R5900_ACC 0x0400000
2367 #define RWARN           0x8000000
2368
2369 #define GENERIC_REGISTER_NUMBERS \
2370     {"$0",      RTYPE_NUM | 0},  \
2371     {"$1",      RTYPE_NUM | 1},  \
2372     {"$2",      RTYPE_NUM | 2},  \
2373     {"$3",      RTYPE_NUM | 3},  \
2374     {"$4",      RTYPE_NUM | 4},  \
2375     {"$5",      RTYPE_NUM | 5},  \
2376     {"$6",      RTYPE_NUM | 6},  \
2377     {"$7",      RTYPE_NUM | 7},  \
2378     {"$8",      RTYPE_NUM | 8},  \
2379     {"$9",      RTYPE_NUM | 9},  \
2380     {"$10",     RTYPE_NUM | 10}, \
2381     {"$11",     RTYPE_NUM | 11}, \
2382     {"$12",     RTYPE_NUM | 12}, \
2383     {"$13",     RTYPE_NUM | 13}, \
2384     {"$14",     RTYPE_NUM | 14}, \
2385     {"$15",     RTYPE_NUM | 15}, \
2386     {"$16",     RTYPE_NUM | 16}, \
2387     {"$17",     RTYPE_NUM | 17}, \
2388     {"$18",     RTYPE_NUM | 18}, \
2389     {"$19",     RTYPE_NUM | 19}, \
2390     {"$20",     RTYPE_NUM | 20}, \
2391     {"$21",     RTYPE_NUM | 21}, \
2392     {"$22",     RTYPE_NUM | 22}, \
2393     {"$23",     RTYPE_NUM | 23}, \
2394     {"$24",     RTYPE_NUM | 24}, \
2395     {"$25",     RTYPE_NUM | 25}, \
2396     {"$26",     RTYPE_NUM | 26}, \
2397     {"$27",     RTYPE_NUM | 27}, \
2398     {"$28",     RTYPE_NUM | 28}, \
2399     {"$29",     RTYPE_NUM | 29}, \
2400     {"$30",     RTYPE_NUM | 30}, \
2401     {"$31",     RTYPE_NUM | 31} 
2402
2403 #define FPU_REGISTER_NAMES       \
2404     {"$f0",     RTYPE_FPU | 0},  \
2405     {"$f1",     RTYPE_FPU | 1},  \
2406     {"$f2",     RTYPE_FPU | 2},  \
2407     {"$f3",     RTYPE_FPU | 3},  \
2408     {"$f4",     RTYPE_FPU | 4},  \
2409     {"$f5",     RTYPE_FPU | 5},  \
2410     {"$f6",     RTYPE_FPU | 6},  \
2411     {"$f7",     RTYPE_FPU | 7},  \
2412     {"$f8",     RTYPE_FPU | 8},  \
2413     {"$f9",     RTYPE_FPU | 9},  \
2414     {"$f10",    RTYPE_FPU | 10}, \
2415     {"$f11",    RTYPE_FPU | 11}, \
2416     {"$f12",    RTYPE_FPU | 12}, \
2417     {"$f13",    RTYPE_FPU | 13}, \
2418     {"$f14",    RTYPE_FPU | 14}, \
2419     {"$f15",    RTYPE_FPU | 15}, \
2420     {"$f16",    RTYPE_FPU | 16}, \
2421     {"$f17",    RTYPE_FPU | 17}, \
2422     {"$f18",    RTYPE_FPU | 18}, \
2423     {"$f19",    RTYPE_FPU | 19}, \
2424     {"$f20",    RTYPE_FPU | 20}, \
2425     {"$f21",    RTYPE_FPU | 21}, \
2426     {"$f22",    RTYPE_FPU | 22}, \
2427     {"$f23",    RTYPE_FPU | 23}, \
2428     {"$f24",    RTYPE_FPU | 24}, \
2429     {"$f25",    RTYPE_FPU | 25}, \
2430     {"$f26",    RTYPE_FPU | 26}, \
2431     {"$f27",    RTYPE_FPU | 27}, \
2432     {"$f28",    RTYPE_FPU | 28}, \
2433     {"$f29",    RTYPE_FPU | 29}, \
2434     {"$f30",    RTYPE_FPU | 30}, \
2435     {"$f31",    RTYPE_FPU | 31}
2436
2437 #define FPU_CONDITION_CODE_NAMES \
2438     {"$fcc0",   RTYPE_FCC | 0},  \
2439     {"$fcc1",   RTYPE_FCC | 1},  \
2440     {"$fcc2",   RTYPE_FCC | 2},  \
2441     {"$fcc3",   RTYPE_FCC | 3},  \
2442     {"$fcc4",   RTYPE_FCC | 4},  \
2443     {"$fcc5",   RTYPE_FCC | 5},  \
2444     {"$fcc6",   RTYPE_FCC | 6},  \
2445     {"$fcc7",   RTYPE_FCC | 7}
2446
2447 #define COPROC_CONDITION_CODE_NAMES         \
2448     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2449     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2450     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2451     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2452     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2453     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2454     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2455     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2456
2457 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2458     {"$a4",     RTYPE_GP | 8},  \
2459     {"$a5",     RTYPE_GP | 9},  \
2460     {"$a6",     RTYPE_GP | 10}, \
2461     {"$a7",     RTYPE_GP | 11}, \
2462     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2463     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2464     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2465     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2466     {"$t0",     RTYPE_GP | 12}, \
2467     {"$t1",     RTYPE_GP | 13}, \
2468     {"$t2",     RTYPE_GP | 14}, \
2469     {"$t3",     RTYPE_GP | 15}
2470
2471 #define O32_SYMBOLIC_REGISTER_NAMES \
2472     {"$t0",     RTYPE_GP | 8},  \
2473     {"$t1",     RTYPE_GP | 9},  \
2474     {"$t2",     RTYPE_GP | 10}, \
2475     {"$t3",     RTYPE_GP | 11}, \
2476     {"$t4",     RTYPE_GP | 12}, \
2477     {"$t5",     RTYPE_GP | 13}, \
2478     {"$t6",     RTYPE_GP | 14}, \
2479     {"$t7",     RTYPE_GP | 15}, \
2480     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2481     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2482     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2483     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2484
2485 /* Remaining symbolic register names */
2486 #define SYMBOLIC_REGISTER_NAMES \
2487     {"$zero",   RTYPE_GP | 0},  \
2488     {"$at",     RTYPE_GP | 1},  \
2489     {"$AT",     RTYPE_GP | 1},  \
2490     {"$v0",     RTYPE_GP | 2},  \
2491     {"$v1",     RTYPE_GP | 3},  \
2492     {"$a0",     RTYPE_GP | 4},  \
2493     {"$a1",     RTYPE_GP | 5},  \
2494     {"$a2",     RTYPE_GP | 6},  \
2495     {"$a3",     RTYPE_GP | 7},  \
2496     {"$s0",     RTYPE_GP | 16}, \
2497     {"$s1",     RTYPE_GP | 17}, \
2498     {"$s2",     RTYPE_GP | 18}, \
2499     {"$s3",     RTYPE_GP | 19}, \
2500     {"$s4",     RTYPE_GP | 20}, \
2501     {"$s5",     RTYPE_GP | 21}, \
2502     {"$s6",     RTYPE_GP | 22}, \
2503     {"$s7",     RTYPE_GP | 23}, \
2504     {"$t8",     RTYPE_GP | 24}, \
2505     {"$t9",     RTYPE_GP | 25}, \
2506     {"$k0",     RTYPE_GP | 26}, \
2507     {"$kt0",    RTYPE_GP | 26}, \
2508     {"$k1",     RTYPE_GP | 27}, \
2509     {"$kt1",    RTYPE_GP | 27}, \
2510     {"$gp",     RTYPE_GP | 28}, \
2511     {"$sp",     RTYPE_GP | 29}, \
2512     {"$s8",     RTYPE_GP | 30}, \
2513     {"$fp",     RTYPE_GP | 30}, \
2514     {"$ra",     RTYPE_GP | 31}
2515
2516 #define MIPS16_SPECIAL_REGISTER_NAMES \
2517     {"$pc",     RTYPE_PC | 0}
2518
2519 #define MDMX_VECTOR_REGISTER_NAMES \
2520     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2521     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2522     {"$v2",     RTYPE_VEC | 2},  \
2523     {"$v3",     RTYPE_VEC | 3},  \
2524     {"$v4",     RTYPE_VEC | 4},  \
2525     {"$v5",     RTYPE_VEC | 5},  \
2526     {"$v6",     RTYPE_VEC | 6},  \
2527     {"$v7",     RTYPE_VEC | 7},  \
2528     {"$v8",     RTYPE_VEC | 8},  \
2529     {"$v9",     RTYPE_VEC | 9},  \
2530     {"$v10",    RTYPE_VEC | 10}, \
2531     {"$v11",    RTYPE_VEC | 11}, \
2532     {"$v12",    RTYPE_VEC | 12}, \
2533     {"$v13",    RTYPE_VEC | 13}, \
2534     {"$v14",    RTYPE_VEC | 14}, \
2535     {"$v15",    RTYPE_VEC | 15}, \
2536     {"$v16",    RTYPE_VEC | 16}, \
2537     {"$v17",    RTYPE_VEC | 17}, \
2538     {"$v18",    RTYPE_VEC | 18}, \
2539     {"$v19",    RTYPE_VEC | 19}, \
2540     {"$v20",    RTYPE_VEC | 20}, \
2541     {"$v21",    RTYPE_VEC | 21}, \
2542     {"$v22",    RTYPE_VEC | 22}, \
2543     {"$v23",    RTYPE_VEC | 23}, \
2544     {"$v24",    RTYPE_VEC | 24}, \
2545     {"$v25",    RTYPE_VEC | 25}, \
2546     {"$v26",    RTYPE_VEC | 26}, \
2547     {"$v27",    RTYPE_VEC | 27}, \
2548     {"$v28",    RTYPE_VEC | 28}, \
2549     {"$v29",    RTYPE_VEC | 29}, \
2550     {"$v30",    RTYPE_VEC | 30}, \
2551     {"$v31",    RTYPE_VEC | 31}
2552
2553 #define R5900_I_NAMES \
2554     {"$I",      RTYPE_R5900_I | 0}
2555
2556 #define R5900_Q_NAMES \
2557     {"$Q",      RTYPE_R5900_Q | 0}
2558
2559 #define R5900_R_NAMES \
2560     {"$R",      RTYPE_R5900_R | 0}
2561
2562 #define R5900_ACC_NAMES \
2563     {"$ACC",    RTYPE_R5900_ACC | 0 }
2564
2565 #define MIPS_DSP_ACCUMULATOR_NAMES \
2566     {"$ac0",    RTYPE_ACC | 0}, \
2567     {"$ac1",    RTYPE_ACC | 1}, \
2568     {"$ac2",    RTYPE_ACC | 2}, \
2569     {"$ac3",    RTYPE_ACC | 3}
2570
2571 static const struct regname reg_names[] = {
2572   GENERIC_REGISTER_NUMBERS,
2573   FPU_REGISTER_NAMES,
2574   FPU_CONDITION_CODE_NAMES,
2575   COPROC_CONDITION_CODE_NAMES,
2576
2577   /* The $txx registers depends on the abi,
2578      these will be added later into the symbol table from
2579      one of the tables below once mips_abi is set after 
2580      parsing of arguments from the command line. */
2581   SYMBOLIC_REGISTER_NAMES,
2582
2583   MIPS16_SPECIAL_REGISTER_NAMES,
2584   MDMX_VECTOR_REGISTER_NAMES,
2585   R5900_I_NAMES,
2586   R5900_Q_NAMES,
2587   R5900_R_NAMES,
2588   R5900_ACC_NAMES,
2589   MIPS_DSP_ACCUMULATOR_NAMES,
2590   {0, 0}
2591 };
2592
2593 static const struct regname reg_names_o32[] = {
2594   O32_SYMBOLIC_REGISTER_NAMES,
2595   {0, 0}
2596 };
2597
2598 static const struct regname reg_names_n32n64[] = {
2599   N32N64_SYMBOLIC_REGISTER_NAMES,
2600   {0, 0}
2601 };
2602
2603 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2604    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2605    of these register symbols, return the associated vector register,
2606    otherwise return SYMVAL itself.  */
2607
2608 static unsigned int
2609 mips_prefer_vec_regno (unsigned int symval)
2610 {
2611   if ((symval & -2) == (RTYPE_GP | 2))
2612     return RTYPE_VEC | (symval & 1);
2613   return symval;
2614 }
2615
2616 /* Return true if string [S, E) is a valid register name, storing its
2617    symbol value in *SYMVAL_PTR if so.  */
2618
2619 static bfd_boolean
2620 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2621 {
2622   char save_c;
2623   symbolS *symbol;
2624
2625   /* Terminate name.  */
2626   save_c = *e;
2627   *e = '\0';
2628
2629   /* Look up the name.  */
2630   symbol = symbol_find (s);
2631   *e = save_c;
2632
2633   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2634     return FALSE;
2635
2636   *symval_ptr = S_GET_VALUE (symbol);
2637   return TRUE;
2638 }
2639
2640 /* Return true if the string at *SPTR is a valid register name.  Allow it
2641    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2642    is nonnull.
2643
2644    When returning true, move *SPTR past the register, store the
2645    register's symbol value in *SYMVAL_PTR and the channel mask in
2646    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2647    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2648    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2649
2650 static bfd_boolean
2651 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2652                      unsigned int *channels_ptr)
2653 {
2654   char *s, *e, *m;
2655   const char *q;
2656   unsigned int channels, symval, bit;
2657
2658   /* Find end of name.  */
2659   s = e = *sptr;
2660   if (is_name_beginner (*e))
2661     ++e;
2662   while (is_part_of_name (*e))
2663     ++e;
2664
2665   channels = 0;
2666   if (!mips_parse_register_1 (s, e, &symval))
2667     {
2668       if (!channels_ptr)
2669         return FALSE;
2670
2671       /* Eat characters from the end of the string that are valid
2672          channel suffixes.  The preceding register must be $ACC or
2673          end with a digit, so there is no ambiguity.  */
2674       bit = 1;
2675       m = e;
2676       for (q = "wzyx"; *q; q++, bit <<= 1)
2677         if (m > s && m[-1] == *q)
2678           {
2679             --m;
2680             channels |= bit;
2681           }
2682
2683       if (channels == 0
2684           || !mips_parse_register_1 (s, m, &symval)
2685           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2686         return FALSE;
2687     }
2688
2689   *sptr = e;
2690   *symval_ptr = symval;
2691   if (channels_ptr)
2692     *channels_ptr = channels;
2693   return TRUE;
2694 }
2695
2696 /* Check if SPTR points at a valid register specifier according to TYPES.
2697    If so, then return 1, advance S to consume the specifier and store
2698    the register's number in REGNOP, otherwise return 0.  */
2699
2700 static int
2701 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2702 {
2703   unsigned int regno;
2704
2705   if (mips_parse_register (s, &regno, NULL))
2706     {
2707       if (types & RTYPE_VEC)
2708         regno = mips_prefer_vec_regno (regno);
2709       if (regno & types)
2710         regno &= RNUM_MASK;
2711       else
2712         regno = ~0;
2713     }
2714   else
2715     {
2716       if (types & RWARN)
2717         as_warn (_("Unrecognized register name `%s'"), *s);
2718       regno = ~0;
2719     }
2720   if (regnop)
2721     *regnop = regno;
2722   return regno <= RNUM_MASK;
2723 }
2724
2725 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2726    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2727
2728 static char *
2729 mips_parse_vu0_channels (char *s, unsigned int *channels)
2730 {
2731   unsigned int i;
2732
2733   *channels = 0;
2734   for (i = 0; i < 4; i++)
2735     if (*s == "xyzw"[i])
2736       {
2737         *channels |= 1 << (3 - i);
2738         ++s;
2739       }
2740   return s;
2741 }
2742
2743 /* Token types for parsed operand lists.  */
2744 enum mips_operand_token_type {
2745   /* A plain register, e.g. $f2.  */
2746   OT_REG,
2747
2748   /* A 4-bit XYZW channel mask.  */
2749   OT_CHANNELS,
2750
2751   /* An element of a vector, e.g. $v0[1].  */
2752   OT_REG_ELEMENT,
2753
2754   /* A continuous range of registers, e.g. $s0-$s4.  */
2755   OT_REG_RANGE,
2756
2757   /* A (possibly relocated) expression.  */
2758   OT_INTEGER,
2759
2760   /* A floating-point value.  */
2761   OT_FLOAT,
2762
2763   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2764      before OT_REGs.  */
2765   OT_CHAR,
2766
2767   /* A doubled character, either "--" or "++".  */
2768   OT_DOUBLE_CHAR,
2769
2770   /* The end of the operand list.  */
2771   OT_END
2772 };
2773
2774 /* A parsed operand token.  */
2775 struct mips_operand_token
2776 {
2777   /* The type of token.  */
2778   enum mips_operand_token_type type;
2779   union
2780   {
2781     /* The register symbol value for an OT_REG.  */
2782     unsigned int regno;
2783
2784     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2785     unsigned int channels;
2786
2787     /* The register symbol value and index for an OT_REG_ELEMENT.  */
2788     struct {
2789       unsigned int regno;
2790       addressT index;
2791     } reg_element;
2792
2793     /* The two register symbol values involved in an OT_REG_RANGE.  */
2794     struct {
2795       unsigned int regno1;
2796       unsigned int regno2;
2797     } reg_range;
2798
2799     /* The value of an OT_INTEGER.  The value is represented as an
2800        expression and the relocation operators that were applied to
2801        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2802        relocation operators were used.  */
2803     struct {
2804       expressionS value;
2805       bfd_reloc_code_real_type relocs[3];
2806     } integer;
2807
2808     /* The binary data for an OT_FLOAT constant, and the number of bytes
2809        in the constant.  */
2810     struct {
2811       unsigned char data[8];
2812       int length;
2813     } flt;
2814
2815     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2816     char ch;
2817   } u;
2818 };
2819
2820 /* An obstack used to construct lists of mips_operand_tokens.  */
2821 static struct obstack mips_operand_tokens;
2822
2823 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2824
2825 static void
2826 mips_add_token (struct mips_operand_token *token,
2827                 enum mips_operand_token_type type)
2828 {
2829   token->type = type;
2830   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2831 }
2832
2833 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2834    and OT_REG tokens for them if so, and return a pointer to the first
2835    unconsumed character.  Return null otherwise.  */
2836
2837 static char *
2838 mips_parse_base_start (char *s)
2839 {
2840   struct mips_operand_token token;
2841   unsigned int regno, channels;
2842   bfd_boolean decrement_p;
2843
2844   if (*s != '(')
2845     return 0;
2846
2847   ++s;
2848   SKIP_SPACE_TABS (s);
2849
2850   /* Only match "--" as part of a base expression.  In other contexts "--X"
2851      is a double negative.  */
2852   decrement_p = (s[0] == '-' && s[1] == '-');
2853   if (decrement_p)
2854     {
2855       s += 2;
2856       SKIP_SPACE_TABS (s);
2857     }
2858
2859   /* Allow a channel specifier because that leads to better error messages
2860      than treating something like "$vf0x++" as an expression.  */
2861   if (!mips_parse_register (&s, &regno, &channels))
2862     return 0;
2863
2864   token.u.ch = '(';
2865   mips_add_token (&token, OT_CHAR);
2866
2867   if (decrement_p)
2868     {
2869       token.u.ch = '-';
2870       mips_add_token (&token, OT_DOUBLE_CHAR);
2871     }
2872
2873   token.u.regno = regno;
2874   mips_add_token (&token, OT_REG);
2875
2876   if (channels)
2877     {
2878       token.u.channels = channels;
2879       mips_add_token (&token, OT_CHANNELS);
2880     }
2881
2882   /* For consistency, only match "++" as part of base expressions too.  */
2883   SKIP_SPACE_TABS (s);
2884   if (s[0] == '+' && s[1] == '+')
2885     {
2886       s += 2;
2887       token.u.ch = '+';
2888       mips_add_token (&token, OT_DOUBLE_CHAR);
2889     }
2890
2891   return s;
2892 }
2893
2894 /* Parse one or more tokens from S.  Return a pointer to the first
2895    unconsumed character on success.  Return null if an error was found
2896    and store the error text in insn_error.  FLOAT_FORMAT is as for
2897    mips_parse_arguments.  */
2898
2899 static char *
2900 mips_parse_argument_token (char *s, char float_format)
2901 {
2902   char *end, *save_in, *err;
2903   unsigned int regno1, regno2, channels;
2904   struct mips_operand_token token;
2905
2906   /* First look for "($reg", since we want to treat that as an
2907      OT_CHAR and OT_REG rather than an expression.  */
2908   end = mips_parse_base_start (s);
2909   if (end)
2910     return end;
2911
2912   /* Handle other characters that end up as OT_CHARs.  */
2913   if (*s == ')' || *s == ',')
2914     {
2915       token.u.ch = *s;
2916       mips_add_token (&token, OT_CHAR);
2917       ++s;
2918       return s;
2919     }
2920
2921   /* Handle tokens that start with a register.  */
2922   if (mips_parse_register (&s, &regno1, &channels))
2923     {
2924       if (channels)
2925         {
2926           /* A register and a VU0 channel suffix.  */
2927           token.u.regno = regno1;
2928           mips_add_token (&token, OT_REG);
2929
2930           token.u.channels = channels;
2931           mips_add_token (&token, OT_CHANNELS);
2932           return s;
2933         }
2934
2935       SKIP_SPACE_TABS (s);
2936       if (*s == '-')
2937         {
2938           /* A register range.  */
2939           ++s;
2940           SKIP_SPACE_TABS (s);
2941           if (!mips_parse_register (&s, &regno2, NULL))
2942             {
2943               set_insn_error (0, _("Invalid register range"));
2944               return 0;
2945             }
2946
2947           token.u.reg_range.regno1 = regno1;
2948           token.u.reg_range.regno2 = regno2;
2949           mips_add_token (&token, OT_REG_RANGE);
2950           return s;
2951         }
2952       else if (*s == '[')
2953         {
2954           /* A vector element.  */
2955           expressionS element;
2956
2957           ++s;
2958           SKIP_SPACE_TABS (s);
2959           my_getExpression (&element, s);
2960           if (element.X_op != O_constant)
2961             {
2962               set_insn_error (0, _("Vector element must be constant"));
2963               return 0;
2964             }
2965           s = expr_end;
2966           SKIP_SPACE_TABS (s);
2967           if (*s != ']')
2968             {
2969               set_insn_error (0, _("Missing `]'"));
2970               return 0;
2971             }
2972           ++s;
2973
2974           token.u.reg_element.regno = regno1;
2975           token.u.reg_element.index = element.X_add_number;
2976           mips_add_token (&token, OT_REG_ELEMENT);
2977           return s;
2978         }
2979
2980       /* Looks like just a plain register.  */
2981       token.u.regno = regno1;
2982       mips_add_token (&token, OT_REG);
2983       return s;
2984     }
2985
2986   if (float_format)
2987     {
2988       /* First try to treat expressions as floats.  */
2989       save_in = input_line_pointer;
2990       input_line_pointer = s;
2991       err = md_atof (float_format, (char *) token.u.flt.data,
2992                      &token.u.flt.length);
2993       end = input_line_pointer;
2994       input_line_pointer = save_in;
2995       if (err && *err)
2996         {
2997           set_insn_error (0, err);
2998           return 0;
2999         }
3000       if (s != end)
3001         {
3002           mips_add_token (&token, OT_FLOAT);
3003           return end;
3004         }
3005     }
3006
3007   /* Treat everything else as an integer expression.  */
3008   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3009   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3010   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3011   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3012   s = expr_end;
3013   mips_add_token (&token, OT_INTEGER);
3014   return s;
3015 }
3016
3017 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3018    if expressions should be treated as 32-bit floating-point constants,
3019    'd' if they should be treated as 64-bit floating-point constants,
3020    or 0 if they should be treated as integer expressions (the usual case).
3021
3022    Return a list of tokens on success, otherwise return 0.  The caller
3023    must obstack_free the list after use.  */
3024
3025 static struct mips_operand_token *
3026 mips_parse_arguments (char *s, char float_format)
3027 {
3028   struct mips_operand_token token;
3029
3030   SKIP_SPACE_TABS (s);
3031   while (*s)
3032     {
3033       s = mips_parse_argument_token (s, float_format);
3034       if (!s)
3035         {
3036           obstack_free (&mips_operand_tokens,
3037                         obstack_finish (&mips_operand_tokens));
3038           return 0;
3039         }
3040       SKIP_SPACE_TABS (s);
3041     }
3042   mips_add_token (&token, OT_END);
3043   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3044 }
3045
3046 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3047    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3048
3049 static bfd_boolean
3050 is_opcode_valid (const struct mips_opcode *mo)
3051 {
3052   int isa = mips_opts.isa;
3053   int ase = mips_opts.ase;
3054   int fp_s, fp_d;
3055   unsigned int i;
3056
3057   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3058     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3059       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3060         ase |= mips_ases[i].flags64;
3061
3062   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3063     return FALSE;
3064
3065   /* Check whether the instruction or macro requires single-precision or
3066      double-precision floating-point support.  Note that this information is
3067      stored differently in the opcode table for insns and macros.  */
3068   if (mo->pinfo == INSN_MACRO)
3069     {
3070       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3071       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3072     }
3073   else
3074     {
3075       fp_s = mo->pinfo & FP_S;
3076       fp_d = mo->pinfo & FP_D;
3077     }
3078
3079   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3080     return FALSE;
3081
3082   if (fp_s && mips_opts.soft_float)
3083     return FALSE;
3084
3085   return TRUE;
3086 }
3087
3088 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3089    selected ISA and architecture.  */
3090
3091 static bfd_boolean
3092 is_opcode_valid_16 (const struct mips_opcode *mo)
3093 {
3094   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3095 }
3096
3097 /* Return TRUE if the size of the microMIPS opcode MO matches one
3098    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3099
3100 static bfd_boolean
3101 is_size_valid (const struct mips_opcode *mo)
3102 {
3103   if (!mips_opts.micromips)
3104     return TRUE;
3105
3106   if (mips_opts.insn32)
3107     {
3108       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3109         return FALSE;
3110       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3111         return FALSE;
3112     }
3113   if (!forced_insn_length)
3114     return TRUE;
3115   if (mo->pinfo == INSN_MACRO)
3116     return FALSE;
3117   return forced_insn_length == micromips_insn_length (mo);
3118 }
3119
3120 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3121    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3122
3123    We don't accept macros in 16-bit delay slots to avoid a case where
3124    a macro expansion fails because it relies on a preceding 32-bit real
3125    instruction to have matched and does not handle the operands correctly.
3126    The only macros that may expand to 16-bit instructions are JAL that
3127    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3128    and BGT (that likewise cannot be placed in a delay slot) that decay to
3129    a NOP.  In all these cases the macros precede any corresponding real
3130    instruction definitions in the opcode table, so they will match in the
3131    second pass where the size of the delay slot is ignored and therefore
3132    produce correct code.  */
3133
3134 static bfd_boolean
3135 is_delay_slot_valid (const struct mips_opcode *mo)
3136 {
3137   if (!mips_opts.micromips)
3138     return TRUE;
3139
3140   if (mo->pinfo == INSN_MACRO)
3141     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3142   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3143       && micromips_insn_length (mo) != 4)
3144     return FALSE;
3145   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3146       && micromips_insn_length (mo) != 2)
3147     return FALSE;
3148
3149   return TRUE;
3150 }
3151
3152 /* For consistency checking, verify that all bits of OPCODE are specified
3153    either by the match/mask part of the instruction definition, or by the
3154    operand list.  Also build up a list of operands in OPERANDS.
3155
3156    INSN_BITS says which bits of the instruction are significant.
3157    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3158    provides the mips_operand description of each operand.  DECODE_OPERAND
3159    is null for MIPS16 instructions.  */
3160
3161 static int
3162 validate_mips_insn (const struct mips_opcode *opcode,
3163                     unsigned long insn_bits,
3164                     const struct mips_operand *(*decode_operand) (const char *),
3165                     struct mips_operand_array *operands)
3166 {
3167   const char *s;
3168   unsigned long used_bits, doubled, undefined, opno, mask;
3169   const struct mips_operand *operand;
3170
3171   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3172   if ((mask & opcode->match) != opcode->match)
3173     {
3174       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3175               opcode->name, opcode->args);
3176       return 0;
3177     }
3178   used_bits = 0;
3179   opno = 0;
3180   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3181     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3182   for (s = opcode->args; *s; ++s)
3183     switch (*s)
3184       {
3185       case ',':
3186       case '(':
3187       case ')':
3188         break;
3189
3190       case '#':
3191         s++;
3192         break;
3193
3194       default:
3195         if (!decode_operand)
3196           operand = decode_mips16_operand (*s, FALSE);
3197         else
3198           operand = decode_operand (s);
3199         if (!operand && opcode->pinfo != INSN_MACRO)
3200           {
3201             as_bad (_("internal: unknown operand type: %s %s"),
3202                     opcode->name, opcode->args);
3203             return 0;
3204           }
3205         gas_assert (opno < MAX_OPERANDS);
3206         operands->operand[opno] = operand;
3207         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3208           {
3209             used_bits = mips_insert_operand (operand, used_bits, -1);
3210             if (operand->type == OP_MDMX_IMM_REG)
3211               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3212                  has separate entries for each format.  */
3213               used_bits &= ~(1 << (operand->lsb + 5));
3214             if (operand->type == OP_ENTRY_EXIT_LIST)
3215               used_bits &= ~(mask & 0x700);
3216           }
3217         /* Skip prefix characters.  */
3218         if (decode_operand && (*s == '+' || *s == 'm'))
3219           ++s;
3220         opno += 1;
3221         break;
3222       }
3223   doubled = used_bits & mask & insn_bits;
3224   if (doubled)
3225     {
3226       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3227                 " %s %s"), doubled, opcode->name, opcode->args);
3228       return 0;
3229     }
3230   used_bits |= mask;
3231   undefined = ~used_bits & insn_bits;
3232   if (opcode->pinfo != INSN_MACRO && undefined)
3233     {
3234       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3235               undefined, opcode->name, opcode->args);
3236       return 0;
3237     }
3238   used_bits &= ~insn_bits;
3239   if (used_bits)
3240     {
3241       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3242               used_bits, opcode->name, opcode->args);
3243       return 0;
3244     }
3245   return 1;
3246 }
3247
3248 /* The MIPS16 version of validate_mips_insn.  */
3249
3250 static int
3251 validate_mips16_insn (const struct mips_opcode *opcode,
3252                       struct mips_operand_array *operands)
3253 {
3254   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3255     {
3256       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3257          instruction.  Use TMP to describe the full instruction.  */
3258       struct mips_opcode tmp;
3259
3260       tmp = *opcode;
3261       tmp.match <<= 16;
3262       tmp.mask <<= 16;
3263       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3264     }
3265   return validate_mips_insn (opcode, 0xffff, 0, operands);
3266 }
3267
3268 /* The microMIPS version of validate_mips_insn.  */
3269
3270 static int
3271 validate_micromips_insn (const struct mips_opcode *opc,
3272                          struct mips_operand_array *operands)
3273 {
3274   unsigned long insn_bits;
3275   unsigned long major;
3276   unsigned int length;
3277
3278   if (opc->pinfo == INSN_MACRO)
3279     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3280                                operands);
3281
3282   length = micromips_insn_length (opc);
3283   if (length != 2 && length != 4)
3284     {
3285       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
3286                 "%s %s"), length, opc->name, opc->args);
3287       return 0;
3288     }
3289   major = opc->match >> (10 + 8 * (length - 2));
3290   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3291       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3292     {
3293       as_bad (_("Internal error: bad microMIPS opcode "
3294                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3295       return 0;
3296     }
3297
3298   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3299   insn_bits = 1 << 4 * length;
3300   insn_bits <<= 4 * length;
3301   insn_bits -= 1;
3302   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3303                              operands);
3304 }
3305
3306 /* This function is called once, at assembler startup time.  It should set up
3307    all the tables, etc. that the MD part of the assembler will need.  */
3308
3309 void
3310 md_begin (void)
3311 {
3312   const char *retval = NULL;
3313   int i = 0;
3314   int broken = 0;
3315
3316   if (mips_pic != NO_PIC)
3317     {
3318       if (g_switch_seen && g_switch_value != 0)
3319         as_bad (_("-G may not be used in position-independent code"));
3320       g_switch_value = 0;
3321     }
3322
3323   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3324     as_warn (_("Could not set architecture and machine"));
3325
3326   op_hash = hash_new ();
3327
3328   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3329   for (i = 0; i < NUMOPCODES;)
3330     {
3331       const char *name = mips_opcodes[i].name;
3332
3333       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3334       if (retval != NULL)
3335         {
3336           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3337                    mips_opcodes[i].name, retval);
3338           /* Probably a memory allocation problem?  Give up now.  */
3339           as_fatal (_("Broken assembler.  No assembly attempted."));
3340         }
3341       do
3342         {
3343           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3344                                    decode_mips_operand, &mips_operands[i]))
3345             broken = 1;
3346           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3347             {
3348               create_insn (&nop_insn, mips_opcodes + i);
3349               if (mips_fix_loongson2f_nop)
3350                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3351               nop_insn.fixed_p = 1;
3352             }
3353           ++i;
3354         }
3355       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3356     }
3357
3358   mips16_op_hash = hash_new ();
3359   mips16_operands = XCNEWVEC (struct mips_operand_array,
3360                               bfd_mips16_num_opcodes);
3361
3362   i = 0;
3363   while (i < bfd_mips16_num_opcodes)
3364     {
3365       const char *name = mips16_opcodes[i].name;
3366
3367       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3368       if (retval != NULL)
3369         as_fatal (_("internal: can't hash `%s': %s"),
3370                   mips16_opcodes[i].name, retval);
3371       do
3372         {
3373           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3374             broken = 1;
3375           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3376             {
3377               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3378               mips16_nop_insn.fixed_p = 1;
3379             }
3380           ++i;
3381         }
3382       while (i < bfd_mips16_num_opcodes
3383              && strcmp (mips16_opcodes[i].name, name) == 0);
3384     }
3385
3386   micromips_op_hash = hash_new ();
3387   micromips_operands = XCNEWVEC (struct mips_operand_array,
3388                                  bfd_micromips_num_opcodes);
3389
3390   i = 0;
3391   while (i < bfd_micromips_num_opcodes)
3392     {
3393       const char *name = micromips_opcodes[i].name;
3394
3395       retval = hash_insert (micromips_op_hash, name,
3396                             (void *) &micromips_opcodes[i]);
3397       if (retval != NULL)
3398         as_fatal (_("internal: can't hash `%s': %s"),
3399                   micromips_opcodes[i].name, retval);
3400       do
3401         {
3402           struct mips_cl_insn *micromips_nop_insn;
3403
3404           if (!validate_micromips_insn (&micromips_opcodes[i],
3405                                         &micromips_operands[i]))
3406             broken = 1;
3407
3408           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3409             {
3410               if (micromips_insn_length (micromips_opcodes + i) == 2)
3411                 micromips_nop_insn = &micromips_nop16_insn;
3412               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3413                 micromips_nop_insn = &micromips_nop32_insn;
3414               else
3415                 continue;
3416
3417               if (micromips_nop_insn->insn_mo == NULL
3418                   && strcmp (name, "nop") == 0)
3419                 {
3420                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3421                   micromips_nop_insn->fixed_p = 1;
3422                 }
3423             }
3424         }
3425       while (++i < bfd_micromips_num_opcodes
3426              && strcmp (micromips_opcodes[i].name, name) == 0);
3427     }
3428
3429   if (broken)
3430     as_fatal (_("Broken assembler.  No assembly attempted."));
3431
3432   /* We add all the general register names to the symbol table.  This
3433      helps us detect invalid uses of them.  */
3434   for (i = 0; reg_names[i].name; i++) 
3435     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3436                                      reg_names[i].num, /* & RNUM_MASK, */
3437                                      &zero_address_frag));
3438   if (HAVE_NEWABI)
3439     for (i = 0; reg_names_n32n64[i].name; i++) 
3440       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3441                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3442                                        &zero_address_frag));
3443   else
3444     for (i = 0; reg_names_o32[i].name; i++) 
3445       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3446                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3447                                        &zero_address_frag));
3448
3449   for (i = 0; i < 32; i++)
3450     {
3451       char regname[7];
3452
3453       /* R5900 VU0 floating-point register.  */
3454       regname[sizeof (rename) - 1] = 0;
3455       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3456       symbol_table_insert (symbol_new (regname, reg_section,
3457                                        RTYPE_VF | i, &zero_address_frag));
3458
3459       /* R5900 VU0 integer register.  */
3460       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3461       symbol_table_insert (symbol_new (regname, reg_section,
3462                                        RTYPE_VI | i, &zero_address_frag));
3463
3464     }
3465
3466   obstack_init (&mips_operand_tokens);
3467
3468   mips_no_prev_insn ();
3469
3470   mips_gprmask = 0;
3471   mips_cprmask[0] = 0;
3472   mips_cprmask[1] = 0;
3473   mips_cprmask[2] = 0;
3474   mips_cprmask[3] = 0;
3475
3476   /* set the default alignment for the text section (2**2) */
3477   record_alignment (text_section, 2);
3478
3479   bfd_set_gp_size (stdoutput, g_switch_value);
3480
3481   /* On a native system other than VxWorks, sections must be aligned
3482      to 16 byte boundaries.  When configured for an embedded ELF
3483      target, we don't bother.  */
3484   if (strncmp (TARGET_OS, "elf", 3) != 0
3485       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3486     {
3487       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3488       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3489       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3490     }
3491
3492   /* Create a .reginfo section for register masks and a .mdebug
3493      section for debugging information.  */
3494   {
3495     segT seg;
3496     subsegT subseg;
3497     flagword flags;
3498     segT sec;
3499
3500     seg = now_seg;
3501     subseg = now_subseg;
3502
3503     /* The ABI says this section should be loaded so that the
3504        running program can access it.  However, we don't load it
3505        if we are configured for an embedded target */
3506     flags = SEC_READONLY | SEC_DATA;
3507     if (strncmp (TARGET_OS, "elf", 3) != 0)
3508       flags |= SEC_ALLOC | SEC_LOAD;
3509
3510     if (mips_abi != N64_ABI)
3511       {
3512         sec = subseg_new (".reginfo", (subsegT) 0);
3513
3514         bfd_set_section_flags (stdoutput, sec, flags);
3515         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3516
3517         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3518       }
3519     else
3520       {
3521         /* The 64-bit ABI uses a .MIPS.options section rather than
3522            .reginfo section.  */
3523         sec = subseg_new (".MIPS.options", (subsegT) 0);
3524         bfd_set_section_flags (stdoutput, sec, flags);
3525         bfd_set_section_alignment (stdoutput, sec, 3);
3526
3527         /* Set up the option header.  */
3528         {
3529           Elf_Internal_Options opthdr;
3530           char *f;
3531
3532           opthdr.kind = ODK_REGINFO;
3533           opthdr.size = (sizeof (Elf_External_Options)
3534                          + sizeof (Elf64_External_RegInfo));
3535           opthdr.section = 0;
3536           opthdr.info = 0;
3537           f = frag_more (sizeof (Elf_External_Options));
3538           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3539                                          (Elf_External_Options *) f);
3540
3541           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3542         }
3543       }
3544
3545     if (ECOFF_DEBUGGING)
3546       {
3547         sec = subseg_new (".mdebug", (subsegT) 0);
3548         (void) bfd_set_section_flags (stdoutput, sec,
3549                                       SEC_HAS_CONTENTS | SEC_READONLY);
3550         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3551       }
3552     else if (mips_flag_pdr)
3553       {
3554         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3555         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3556                                       SEC_READONLY | SEC_RELOC
3557                                       | SEC_DEBUGGING);
3558         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3559       }
3560
3561     subseg_set (seg, subseg);
3562   }
3563
3564   if (! ECOFF_DEBUGGING)
3565     md_obj_begin ();
3566
3567   if (mips_fix_vr4120)
3568     init_vr4120_conflicts ();
3569 }
3570
3571 void
3572 md_mips_end (void)
3573 {
3574   mips_emit_delays ();
3575   if (! ECOFF_DEBUGGING)
3576     md_obj_end ();
3577 }
3578
3579 void
3580 md_assemble (char *str)
3581 {
3582   struct mips_cl_insn insn;
3583   bfd_reloc_code_real_type unused_reloc[3]
3584     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3585
3586   imm_expr.X_op = O_absent;
3587   imm2_expr.X_op = O_absent;
3588   offset_expr.X_op = O_absent;
3589   offset_reloc[0] = BFD_RELOC_UNUSED;
3590   offset_reloc[1] = BFD_RELOC_UNUSED;
3591   offset_reloc[2] = BFD_RELOC_UNUSED;
3592
3593   mips_mark_labels ();
3594   mips_assembling_insn = TRUE;
3595   clear_insn_error ();
3596
3597   if (mips_opts.mips16)
3598     mips16_ip (str, &insn);
3599   else
3600     {
3601       mips_ip (str, &insn);
3602       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3603             str, insn.insn_opcode));
3604     }
3605
3606   if (insn_error.msg)
3607     report_insn_error (str);
3608   else if (insn.insn_mo->pinfo == INSN_MACRO)
3609     {
3610       macro_start ();
3611       if (mips_opts.mips16)
3612         mips16_macro (&insn);
3613       else
3614         macro (&insn, str);
3615       macro_end ();
3616     }
3617   else
3618     {
3619       if (offset_expr.X_op != O_absent)
3620         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3621       else
3622         append_insn (&insn, NULL, unused_reloc, FALSE);
3623     }
3624
3625   mips_assembling_insn = FALSE;
3626 }
3627
3628 /* Convenience functions for abstracting away the differences between
3629    MIPS16 and non-MIPS16 relocations.  */
3630
3631 static inline bfd_boolean
3632 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3633 {
3634   switch (reloc)
3635     {
3636     case BFD_RELOC_MIPS16_JMP:
3637     case BFD_RELOC_MIPS16_GPREL:
3638     case BFD_RELOC_MIPS16_GOT16:
3639     case BFD_RELOC_MIPS16_CALL16:
3640     case BFD_RELOC_MIPS16_HI16_S:
3641     case BFD_RELOC_MIPS16_HI16:
3642     case BFD_RELOC_MIPS16_LO16:
3643       return TRUE;
3644
3645     default:
3646       return FALSE;
3647     }
3648 }
3649
3650 static inline bfd_boolean
3651 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3652 {
3653   switch (reloc)
3654     {
3655     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3656     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3657     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3658     case BFD_RELOC_MICROMIPS_GPREL16:
3659     case BFD_RELOC_MICROMIPS_JMP:
3660     case BFD_RELOC_MICROMIPS_HI16:
3661     case BFD_RELOC_MICROMIPS_HI16_S:
3662     case BFD_RELOC_MICROMIPS_LO16:
3663     case BFD_RELOC_MICROMIPS_LITERAL:
3664     case BFD_RELOC_MICROMIPS_GOT16:
3665     case BFD_RELOC_MICROMIPS_CALL16:
3666     case BFD_RELOC_MICROMIPS_GOT_HI16:
3667     case BFD_RELOC_MICROMIPS_GOT_LO16:
3668     case BFD_RELOC_MICROMIPS_CALL_HI16:
3669     case BFD_RELOC_MICROMIPS_CALL_LO16:
3670     case BFD_RELOC_MICROMIPS_SUB:
3671     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3672     case BFD_RELOC_MICROMIPS_GOT_OFST:
3673     case BFD_RELOC_MICROMIPS_GOT_DISP:
3674     case BFD_RELOC_MICROMIPS_HIGHEST:
3675     case BFD_RELOC_MICROMIPS_HIGHER:
3676     case BFD_RELOC_MICROMIPS_SCN_DISP:
3677     case BFD_RELOC_MICROMIPS_JALR:
3678       return TRUE;
3679
3680     default:
3681       return FALSE;
3682     }
3683 }
3684
3685 static inline bfd_boolean
3686 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3687 {
3688   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3689 }
3690
3691 static inline bfd_boolean
3692 got16_reloc_p (bfd_reloc_code_real_type reloc)
3693 {
3694   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3695           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3696 }
3697
3698 static inline bfd_boolean
3699 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3700 {
3701   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3702           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3703 }
3704
3705 static inline bfd_boolean
3706 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3707 {
3708   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3709           || reloc == BFD_RELOC_MICROMIPS_LO16);
3710 }
3711
3712 static inline bfd_boolean
3713 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3714 {
3715   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3716 }
3717
3718 static inline bfd_boolean
3719 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3720 {
3721   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3722           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3723 }
3724
3725 /* Return true if RELOC is a PC-relative relocation that does not have
3726    full address range.  */
3727
3728 static inline bfd_boolean
3729 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3730 {
3731   switch (reloc)
3732     {
3733     case BFD_RELOC_16_PCREL_S2:
3734     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3735     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3736     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3737       return TRUE;
3738
3739     case BFD_RELOC_32_PCREL:
3740       return HAVE_64BIT_ADDRESSES;
3741
3742     default:
3743       return FALSE;
3744     }
3745 }
3746
3747 /* Return true if the given relocation might need a matching %lo().
3748    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3749    need a matching %lo() when applied to local symbols.  */
3750
3751 static inline bfd_boolean
3752 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3753 {
3754   return (HAVE_IN_PLACE_ADDENDS
3755           && (hi16_reloc_p (reloc)
3756               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3757                  all GOT16 relocations evaluate to "G".  */
3758               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3759 }
3760
3761 /* Return the type of %lo() reloc needed by RELOC, given that
3762    reloc_needs_lo_p.  */
3763
3764 static inline bfd_reloc_code_real_type
3765 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3766 {
3767   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3768           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3769              : BFD_RELOC_LO16));
3770 }
3771
3772 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3773    relocation.  */
3774
3775 static inline bfd_boolean
3776 fixup_has_matching_lo_p (fixS *fixp)
3777 {
3778   return (fixp->fx_next != NULL
3779           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3780           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3781           && fixp->fx_offset == fixp->fx_next->fx_offset);
3782 }
3783
3784 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3785    says whether the labels refer to text or data.  */
3786
3787 static void
3788 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3789 {
3790   struct insn_label_list *l;
3791   valueT val;
3792
3793   for (l = labels; l != NULL; l = l->next)
3794     {
3795       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3796       symbol_set_frag (l->label, frag_now);
3797       val = (valueT) frag_now_fix ();
3798       /* MIPS16/microMIPS text labels are stored as odd.  */
3799       if (text_p && HAVE_CODE_COMPRESSION)
3800         ++val;
3801       S_SET_VALUE (l->label, val);
3802     }
3803 }
3804
3805 /* Move all labels in insn_labels to the current insertion point
3806    and treat them as text labels.  */
3807
3808 static void
3809 mips_move_text_labels (void)
3810 {
3811   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3812 }
3813
3814 static bfd_boolean
3815 s_is_linkonce (symbolS *sym, segT from_seg)
3816 {
3817   bfd_boolean linkonce = FALSE;
3818   segT symseg = S_GET_SEGMENT (sym);
3819
3820   if (symseg != from_seg && !S_IS_LOCAL (sym))
3821     {
3822       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3823         linkonce = TRUE;
3824       /* The GNU toolchain uses an extension for ELF: a section
3825          beginning with the magic string .gnu.linkonce is a
3826          linkonce section.  */
3827       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3828                    sizeof ".gnu.linkonce" - 1) == 0)
3829         linkonce = TRUE;
3830     }
3831   return linkonce;
3832 }
3833
3834 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3835    linker to handle them specially, such as generating jalx instructions
3836    when needed.  We also make them odd for the duration of the assembly,
3837    in order to generate the right sort of code.  We will make them even
3838    in the adjust_symtab routine, while leaving them marked.  This is
3839    convenient for the debugger and the disassembler.  The linker knows
3840    to make them odd again.  */
3841
3842 static void
3843 mips_compressed_mark_label (symbolS *label)
3844 {
3845   gas_assert (HAVE_CODE_COMPRESSION);
3846
3847   if (mips_opts.mips16)
3848     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3849   else
3850     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3851   if ((S_GET_VALUE (label) & 1) == 0
3852       /* Don't adjust the address if the label is global or weak, or
3853          in a link-once section, since we'll be emitting symbol reloc
3854          references to it which will be patched up by the linker, and
3855          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3856       && !S_IS_WEAK (label)
3857       && !S_IS_EXTERNAL (label)
3858       && !s_is_linkonce (label, now_seg))
3859     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3860 }
3861
3862 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3863
3864 static void
3865 mips_compressed_mark_labels (void)
3866 {
3867   struct insn_label_list *l;
3868
3869   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3870     mips_compressed_mark_label (l->label);
3871 }
3872
3873 /* End the current frag.  Make it a variant frag and record the
3874    relaxation info.  */
3875
3876 static void
3877 relax_close_frag (void)
3878 {
3879   mips_macro_warning.first_frag = frag_now;
3880   frag_var (rs_machine_dependent, 0, 0,
3881             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3882             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3883
3884   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3885   mips_relax.first_fixup = 0;
3886 }
3887
3888 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3889    See the comment above RELAX_ENCODE for more details.  */
3890
3891 static void
3892 relax_start (symbolS *symbol)
3893 {
3894   gas_assert (mips_relax.sequence == 0);
3895   mips_relax.sequence = 1;
3896   mips_relax.symbol = symbol;
3897 }
3898
3899 /* Start generating the second version of a relaxable sequence.
3900    See the comment above RELAX_ENCODE for more details.  */
3901
3902 static void
3903 relax_switch (void)
3904 {
3905   gas_assert (mips_relax.sequence == 1);
3906   mips_relax.sequence = 2;
3907 }
3908
3909 /* End the current relaxable sequence.  */
3910
3911 static void
3912 relax_end (void)
3913 {
3914   gas_assert (mips_relax.sequence == 2);
3915   relax_close_frag ();
3916   mips_relax.sequence = 0;
3917 }
3918
3919 /* Return true if IP is a delayed branch or jump.  */
3920
3921 static inline bfd_boolean
3922 delayed_branch_p (const struct mips_cl_insn *ip)
3923 {
3924   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3925                                 | INSN_COND_BRANCH_DELAY
3926                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3927 }
3928
3929 /* Return true if IP is a compact branch or jump.  */
3930
3931 static inline bfd_boolean
3932 compact_branch_p (const struct mips_cl_insn *ip)
3933 {
3934   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3935                                  | INSN2_COND_BRANCH)) != 0;
3936 }
3937
3938 /* Return true if IP is an unconditional branch or jump.  */
3939
3940 static inline bfd_boolean
3941 uncond_branch_p (const struct mips_cl_insn *ip)
3942 {
3943   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3944           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3945 }
3946
3947 /* Return true if IP is a branch-likely instruction.  */
3948
3949 static inline bfd_boolean
3950 branch_likely_p (const struct mips_cl_insn *ip)
3951 {
3952   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3953 }
3954
3955 /* Return the type of nop that should be used to fill the delay slot
3956    of delayed branch IP.  */
3957
3958 static struct mips_cl_insn *
3959 get_delay_slot_nop (const struct mips_cl_insn *ip)
3960 {
3961   if (mips_opts.micromips
3962       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3963     return &micromips_nop32_insn;
3964   return NOP_INSN;
3965 }
3966
3967 /* Return a mask that has bit N set if OPCODE reads the register(s)
3968    in operand N.  */
3969
3970 static unsigned int
3971 insn_read_mask (const struct mips_opcode *opcode)
3972 {
3973   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3974 }
3975
3976 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3977    in operand N.  */
3978
3979 static unsigned int
3980 insn_write_mask (const struct mips_opcode *opcode)
3981 {
3982   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
3983 }
3984
3985 /* Return a mask of the registers specified by operand OPERAND of INSN.
3986    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
3987    is set.  */
3988
3989 static unsigned int
3990 operand_reg_mask (const struct mips_cl_insn *insn,
3991                   const struct mips_operand *operand,
3992                   unsigned int type_mask)
3993 {
3994   unsigned int uval, vsel;
3995
3996   switch (operand->type)
3997     {
3998     case OP_INT:
3999     case OP_MAPPED_INT:
4000     case OP_MSB:
4001     case OP_PCREL:
4002     case OP_PERF_REG:
4003     case OP_ADDIUSP_INT:
4004     case OP_ENTRY_EXIT_LIST:
4005     case OP_REPEAT_DEST_REG:
4006     case OP_REPEAT_PREV_REG:
4007     case OP_PC:
4008     case OP_VU0_SUFFIX:
4009     case OP_VU0_MATCH_SUFFIX:
4010       abort ();
4011
4012     case OP_REG:
4013     case OP_OPTIONAL_REG:
4014       {
4015         const struct mips_reg_operand *reg_op;
4016
4017         reg_op = (const struct mips_reg_operand *) operand;
4018         if (!(type_mask & (1 << reg_op->reg_type)))
4019           return 0;
4020         uval = insn_extract_operand (insn, operand);
4021         return 1 << mips_decode_reg_operand (reg_op, uval);
4022       }
4023
4024     case OP_REG_PAIR:
4025       {
4026         const struct mips_reg_pair_operand *pair_op;
4027
4028         pair_op = (const struct mips_reg_pair_operand *) operand;
4029         if (!(type_mask & (1 << pair_op->reg_type)))
4030           return 0;
4031         uval = insn_extract_operand (insn, operand);
4032         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4033       }
4034
4035     case OP_CLO_CLZ_DEST:
4036       if (!(type_mask & (1 << OP_REG_GP)))
4037         return 0;
4038       uval = insn_extract_operand (insn, operand);
4039       return (1 << (uval & 31)) | (1 << (uval >> 5));
4040
4041     case OP_LWM_SWM_LIST:
4042       abort ();
4043
4044     case OP_SAVE_RESTORE_LIST:
4045       abort ();
4046
4047     case OP_MDMX_IMM_REG:
4048       if (!(type_mask & (1 << OP_REG_VEC)))
4049         return 0;
4050       uval = insn_extract_operand (insn, operand);
4051       vsel = uval >> 5;
4052       if ((vsel & 0x18) == 0x18)
4053         return 0;
4054       return 1 << (uval & 31);
4055     }
4056   abort ();
4057 }
4058
4059 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4060    where bit N of OPNO_MASK is set if operand N should be included.
4061    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4062    is set.  */
4063
4064 static unsigned int
4065 insn_reg_mask (const struct mips_cl_insn *insn,
4066                unsigned int type_mask, unsigned int opno_mask)
4067 {
4068   unsigned int opno, reg_mask;
4069
4070   opno = 0;
4071   reg_mask = 0;
4072   while (opno_mask != 0)
4073     {
4074       if (opno_mask & 1)
4075         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4076       opno_mask >>= 1;
4077       opno += 1;
4078     }
4079   return reg_mask;
4080 }
4081
4082 /* Return the mask of core registers that IP reads.  */
4083
4084 static unsigned int
4085 gpr_read_mask (const struct mips_cl_insn *ip)
4086 {
4087   unsigned long pinfo, pinfo2;
4088   unsigned int mask;
4089
4090   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4091   pinfo = ip->insn_mo->pinfo;
4092   pinfo2 = ip->insn_mo->pinfo2;
4093   if (pinfo & INSN_UDI)
4094     {
4095       /* UDI instructions have traditionally been assumed to read RS
4096          and RT.  */
4097       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4098       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4099     }
4100   if (pinfo & INSN_READ_GPR_24)
4101     mask |= 1 << 24;
4102   if (pinfo2 & INSN2_READ_GPR_16)
4103     mask |= 1 << 16;
4104   if (pinfo2 & INSN2_READ_SP)
4105     mask |= 1 << SP;
4106   if (pinfo2 & INSN2_READ_GPR_31)
4107     mask |= 1 << 31;
4108   /* Don't include register 0.  */
4109   return mask & ~1;
4110 }
4111
4112 /* Return the mask of core registers that IP writes.  */
4113
4114 static unsigned int
4115 gpr_write_mask (const struct mips_cl_insn *ip)
4116 {
4117   unsigned long pinfo, pinfo2;
4118   unsigned int mask;
4119
4120   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4121   pinfo = ip->insn_mo->pinfo;
4122   pinfo2 = ip->insn_mo->pinfo2;
4123   if (pinfo & INSN_WRITE_GPR_24)
4124     mask |= 1 << 24;
4125   if (pinfo & INSN_WRITE_GPR_31)
4126     mask |= 1 << 31;
4127   if (pinfo & INSN_UDI)
4128     /* UDI instructions have traditionally been assumed to write to RD.  */
4129     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4130   if (pinfo2 & INSN2_WRITE_SP)
4131     mask |= 1 << SP;
4132   /* Don't include register 0.  */
4133   return mask & ~1;
4134 }
4135
4136 /* Return the mask of floating-point registers that IP reads.  */
4137
4138 static unsigned int
4139 fpr_read_mask (const struct mips_cl_insn *ip)
4140 {
4141   unsigned long pinfo;
4142   unsigned int mask;
4143
4144   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4145                         insn_read_mask (ip->insn_mo));
4146   pinfo = ip->insn_mo->pinfo;
4147   /* Conservatively treat all operands to an FP_D instruction are doubles.
4148      (This is overly pessimistic for things like cvt.d.s.)  */
4149   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4150     mask |= mask << 1;
4151   return mask;
4152 }
4153
4154 /* Return the mask of floating-point registers that IP writes.  */
4155
4156 static unsigned int
4157 fpr_write_mask (const struct mips_cl_insn *ip)
4158 {
4159   unsigned long pinfo;
4160   unsigned int mask;
4161
4162   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4163                         insn_write_mask (ip->insn_mo));
4164   pinfo = ip->insn_mo->pinfo;
4165   /* Conservatively treat all operands to an FP_D instruction are doubles.
4166      (This is overly pessimistic for things like cvt.s.d.)  */
4167   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4168     mask |= mask << 1;
4169   return mask;
4170 }
4171
4172 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4173    Check whether that is allowed.  */
4174
4175 static bfd_boolean
4176 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4177 {
4178   const char *s = insn->name;
4179
4180   if (insn->pinfo == INSN_MACRO)
4181     /* Let a macro pass, we'll catch it later when it is expanded.  */
4182     return TRUE;
4183
4184   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4185     {
4186       /* Allow odd registers for single-precision ops.  */
4187       switch (insn->pinfo & (FP_S | FP_D))
4188         {
4189         case FP_S:
4190         case 0:
4191           return TRUE;
4192         case FP_D:
4193           return FALSE;
4194         default:
4195           break;
4196         }
4197
4198       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4199       s = strchr (insn->name, '.');
4200       if (s != NULL && opnum == 2)
4201         s = strchr (s + 1, '.');
4202       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4203     }
4204
4205   /* Single-precision coprocessor loads and moves are OK too.  */
4206   if ((insn->pinfo & FP_S)
4207       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4208                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4209     return TRUE;
4210
4211   return FALSE;
4212 }
4213
4214 /* Information about an instruction argument that we're trying to match.  */
4215 struct mips_arg_info
4216 {
4217   /* The instruction so far.  */
4218   struct mips_cl_insn *insn;
4219
4220   /* The first unconsumed operand token.  */
4221   struct mips_operand_token *token;
4222
4223   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4224   int opnum;
4225
4226   /* The 1-based argument number, for error reporting.  This does not
4227      count elided optional registers, etc..  */
4228   int argnum;
4229
4230   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4231   unsigned int last_regno;
4232
4233   /* If the first operand was an OP_REG, this is the register that it
4234      specified, otherwise it is ILLEGAL_REG.  */
4235   unsigned int dest_regno;
4236
4237   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4238      where it gives the lsb position.  */
4239   unsigned int last_op_int;
4240
4241   /* If true, match routines should assume that no later instruction
4242      alternative matches and should therefore be as accomodating as
4243      possible.  Match routines should not report errors if something
4244      is only invalid for !LAX_MATCH.  */
4245   bfd_boolean lax_match;
4246
4247   /* True if a reference to the current AT register was seen.  */
4248   bfd_boolean seen_at;
4249 };
4250
4251 /* Record that the argument is out of range.  */
4252
4253 static void
4254 match_out_of_range (struct mips_arg_info *arg)
4255 {
4256   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4257 }
4258
4259 /* Record that the argument isn't constant but needs to be.  */
4260
4261 static void
4262 match_not_constant (struct mips_arg_info *arg)
4263 {
4264   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4265                     arg->argnum);
4266 }
4267
4268 /* Try to match an OT_CHAR token for character CH.  Consume the token
4269    and return true on success, otherwise return false.  */
4270
4271 static bfd_boolean
4272 match_char (struct mips_arg_info *arg, char ch)
4273 {
4274   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4275     {
4276       ++arg->token;
4277       if (ch == ',')
4278         arg->argnum += 1;
4279       return TRUE;
4280     }
4281   return FALSE;
4282 }
4283
4284 /* Try to get an expression from the next tokens in ARG.  Consume the
4285    tokens and return true on success, storing the expression value in
4286    VALUE and relocation types in R.  */
4287
4288 static bfd_boolean
4289 match_expression (struct mips_arg_info *arg, expressionS *value,
4290                   bfd_reloc_code_real_type *r)
4291 {
4292   /* If the next token is a '(' that was parsed as being part of a base
4293      expression, assume we have an elided offset.  The later match will fail
4294      if this turns out to be wrong.  */
4295   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4296     {
4297       value->X_op = O_constant;
4298       value->X_add_number = 0;
4299       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4300       return TRUE;
4301     }
4302
4303   /* Reject register-based expressions such as "0+$2" and "(($2))".
4304      For plain registers the default error seems more appropriate.  */
4305   if (arg->token->type == OT_INTEGER
4306       && arg->token->u.integer.value.X_op == O_register)
4307     {
4308       set_insn_error (arg->argnum, _("register value used as expression"));
4309       return FALSE;
4310     }
4311
4312   if (arg->token->type == OT_INTEGER)
4313     {
4314       *value = arg->token->u.integer.value;
4315       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4316       ++arg->token;
4317       return TRUE;
4318     }
4319
4320   set_insn_error_i
4321     (arg->argnum, _("operand %d must be an immediate expression"),
4322      arg->argnum);
4323   return FALSE;
4324 }
4325
4326 /* Try to get a constant expression from the next tokens in ARG.  Consume
4327    the tokens and return return true on success, storing the constant value
4328    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4329    error.  */
4330
4331 static bfd_boolean
4332 match_const_int (struct mips_arg_info *arg, offsetT *value)
4333 {
4334   expressionS ex;
4335   bfd_reloc_code_real_type r[3];
4336
4337   if (!match_expression (arg, &ex, r))
4338     return FALSE;
4339
4340   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4341     *value = ex.X_add_number;
4342   else
4343     {
4344       match_not_constant (arg);
4345       return FALSE;
4346     }
4347   return TRUE;
4348 }
4349
4350 /* Return the RTYPE_* flags for a register operand of type TYPE that
4351    appears in instruction OPCODE.  */
4352
4353 static unsigned int
4354 convert_reg_type (const struct mips_opcode *opcode,
4355                   enum mips_reg_operand_type type)
4356 {
4357   switch (type)
4358     {
4359     case OP_REG_GP:
4360       return RTYPE_NUM | RTYPE_GP;
4361
4362     case OP_REG_FP:
4363       /* Allow vector register names for MDMX if the instruction is a 64-bit
4364          FPR load, store or move (including moves to and from GPRs).  */
4365       if ((mips_opts.ase & ASE_MDMX)
4366           && (opcode->pinfo & FP_D)
4367           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4368                                | INSN_COPROC_MEMORY_DELAY
4369                                | INSN_LOAD_COPROC_DELAY
4370                                | INSN_LOAD_MEMORY_DELAY
4371                                | INSN_STORE_MEMORY)))
4372         return RTYPE_FPU | RTYPE_VEC;
4373       return RTYPE_FPU;
4374
4375     case OP_REG_CCC:
4376       if (opcode->pinfo & (FP_D | FP_S))
4377         return RTYPE_CCC | RTYPE_FCC;
4378       return RTYPE_CCC;
4379
4380     case OP_REG_VEC:
4381       if (opcode->membership & INSN_5400)
4382         return RTYPE_FPU;
4383       return RTYPE_FPU | RTYPE_VEC;
4384
4385     case OP_REG_ACC:
4386       return RTYPE_ACC;
4387
4388     case OP_REG_COPRO:
4389       if (opcode->name[strlen (opcode->name) - 1] == '0')
4390         return RTYPE_NUM | RTYPE_CP0;
4391       return RTYPE_NUM;
4392
4393     case OP_REG_HW:
4394       return RTYPE_NUM;
4395
4396     case OP_REG_VI:
4397       return RTYPE_NUM | RTYPE_VI;
4398
4399     case OP_REG_VF:
4400       return RTYPE_NUM | RTYPE_VF;
4401
4402     case OP_REG_R5900_I:
4403       return RTYPE_R5900_I;
4404
4405     case OP_REG_R5900_Q:
4406       return RTYPE_R5900_Q;
4407
4408     case OP_REG_R5900_R:
4409       return RTYPE_R5900_R;
4410
4411     case OP_REG_R5900_ACC:
4412       return RTYPE_R5900_ACC;
4413     }
4414   abort ();
4415 }
4416
4417 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4418
4419 static void
4420 check_regno (struct mips_arg_info *arg,
4421              enum mips_reg_operand_type type, unsigned int regno)
4422 {
4423   if (AT && type == OP_REG_GP && regno == AT)
4424     arg->seen_at = TRUE;
4425
4426   if (type == OP_REG_FP
4427       && (regno & 1) != 0
4428       && HAVE_32BIT_FPRS
4429       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4430     as_warn (_("Float register should be even, was %d"), regno);
4431
4432   if (type == OP_REG_CCC)
4433     {
4434       const char *name;
4435       size_t length;
4436
4437       name = arg->insn->insn_mo->name;
4438       length = strlen (name);
4439       if ((regno & 1) != 0
4440           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4441               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4442         as_warn (_("Condition code register should be even for %s, was %d"),
4443                  name, regno);
4444
4445       if ((regno & 3) != 0
4446           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4447         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
4448                  name, regno);
4449     }
4450 }
4451
4452 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4453    a register of type TYPE.  Return true on success, storing the register
4454    number in *REGNO and warning about any dubious uses.  */
4455
4456 static bfd_boolean
4457 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4458              unsigned int symval, unsigned int *regno)
4459 {
4460   if (type == OP_REG_VEC)
4461     symval = mips_prefer_vec_regno (symval);
4462   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4463     return FALSE;
4464
4465   *regno = symval & RNUM_MASK;
4466   check_regno (arg, type, *regno);
4467   return TRUE;
4468 }
4469
4470 /* Try to interpret the next token in ARG as a register of type TYPE.
4471    Consume the token and return true on success, storing the register
4472    number in *REGNO.  Return false on failure.  */
4473
4474 static bfd_boolean
4475 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4476            unsigned int *regno)
4477 {
4478   if (arg->token->type == OT_REG
4479       && match_regno (arg, type, arg->token->u.regno, regno))
4480     {
4481       ++arg->token;
4482       return TRUE;
4483     }
4484   return FALSE;
4485 }
4486
4487 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4488    Consume the token and return true on success, storing the register numbers
4489    in *REGNO1 and *REGNO2.  Return false on failure.  */
4490
4491 static bfd_boolean
4492 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4493                  unsigned int *regno1, unsigned int *regno2)
4494 {
4495   if (match_reg (arg, type, regno1))
4496     {
4497       *regno2 = *regno1;
4498       return TRUE;
4499     }
4500   if (arg->token->type == OT_REG_RANGE
4501       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4502       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4503       && *regno1 <= *regno2)
4504     {
4505       ++arg->token;
4506       return TRUE;
4507     }
4508   return FALSE;
4509 }
4510
4511 /* OP_INT matcher.  */
4512
4513 static bfd_boolean
4514 match_int_operand (struct mips_arg_info *arg,
4515                    const struct mips_operand *operand_base)
4516 {
4517   const struct mips_int_operand *operand;
4518   unsigned int uval;
4519   int min_val, max_val, factor;
4520   offsetT sval;
4521
4522   operand = (const struct mips_int_operand *) operand_base;
4523   factor = 1 << operand->shift;
4524   min_val = mips_int_operand_min (operand);
4525   max_val = mips_int_operand_max (operand);
4526
4527   if (operand_base->lsb == 0
4528       && operand_base->size == 16
4529       && operand->shift == 0
4530       && operand->bias == 0
4531       && (operand->max_val == 32767 || operand->max_val == 65535))
4532     {
4533       /* The operand can be relocated.  */
4534       if (!match_expression (arg, &offset_expr, offset_reloc))
4535         return FALSE;
4536
4537       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4538         /* Relocation operators were used.  Accept the arguent and
4539            leave the relocation value in offset_expr and offset_relocs
4540            for the caller to process.  */
4541         return TRUE;
4542
4543       if (offset_expr.X_op != O_constant)
4544         {
4545           /* Accept non-constant operands if no later alternative matches,
4546              leaving it for the caller to process.  */
4547           if (!arg->lax_match)
4548             return FALSE;
4549           offset_reloc[0] = BFD_RELOC_LO16;
4550           return TRUE;
4551         }
4552
4553       /* Clear the global state; we're going to install the operand
4554          ourselves.  */
4555       sval = offset_expr.X_add_number;
4556       offset_expr.X_op = O_absent;
4557
4558       /* For compatibility with older assemblers, we accept
4559          0x8000-0xffff as signed 16-bit numbers when only
4560          signed numbers are allowed.  */
4561       if (sval > max_val)
4562         {
4563           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4564           if (!arg->lax_match && sval <= max_val)
4565             return FALSE;
4566         }
4567     }
4568   else
4569     {
4570       if (!match_const_int (arg, &sval))
4571         return FALSE;
4572     }
4573
4574   arg->last_op_int = sval;
4575
4576   if (sval < min_val || sval > max_val || sval % factor)
4577     {
4578       match_out_of_range (arg);
4579       return FALSE;
4580     }
4581
4582   uval = (unsigned int) sval >> operand->shift;
4583   uval -= operand->bias;
4584
4585   /* Handle -mfix-cn63xxp1.  */
4586   if (arg->opnum == 1
4587       && mips_fix_cn63xxp1
4588       && !mips_opts.micromips
4589       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4590     switch (uval)
4591       {
4592       case 5:
4593       case 25:
4594       case 26:
4595       case 27:
4596       case 28:
4597       case 29:
4598       case 30:
4599       case 31:
4600         /* These are ok.  */
4601         break;
4602
4603       default:
4604         /* The rest must be changed to 28.  */
4605         uval = 28;
4606         break;
4607       }
4608
4609   insn_insert_operand (arg->insn, operand_base, uval);
4610   return TRUE;
4611 }
4612
4613 /* OP_MAPPED_INT matcher.  */
4614
4615 static bfd_boolean
4616 match_mapped_int_operand (struct mips_arg_info *arg,
4617                           const struct mips_operand *operand_base)
4618 {
4619   const struct mips_mapped_int_operand *operand;
4620   unsigned int uval, num_vals;
4621   offsetT sval;
4622
4623   operand = (const struct mips_mapped_int_operand *) operand_base;
4624   if (!match_const_int (arg, &sval))
4625     return FALSE;
4626
4627   num_vals = 1 << operand_base->size;
4628   for (uval = 0; uval < num_vals; uval++)
4629     if (operand->int_map[uval] == sval)
4630       break;
4631   if (uval == num_vals)
4632     {
4633       match_out_of_range (arg);
4634       return FALSE;
4635     }
4636
4637   insn_insert_operand (arg->insn, operand_base, uval);
4638   return TRUE;
4639 }
4640
4641 /* OP_MSB matcher.  */
4642
4643 static bfd_boolean
4644 match_msb_operand (struct mips_arg_info *arg,
4645                    const struct mips_operand *operand_base)
4646 {
4647   const struct mips_msb_operand *operand;
4648   int min_val, max_val, max_high;
4649   offsetT size, sval, high;
4650
4651   operand = (const struct mips_msb_operand *) operand_base;
4652   min_val = operand->bias;
4653   max_val = min_val + (1 << operand_base->size) - 1;
4654   max_high = operand->opsize;
4655
4656   if (!match_const_int (arg, &size))
4657     return FALSE;
4658
4659   high = size + arg->last_op_int;
4660   sval = operand->add_lsb ? high : size;
4661
4662   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4663     {
4664       match_out_of_range (arg);
4665       return FALSE;
4666     }
4667   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4668   return TRUE;
4669 }
4670
4671 /* OP_REG matcher.  */
4672
4673 static bfd_boolean
4674 match_reg_operand (struct mips_arg_info *arg,
4675                    const struct mips_operand *operand_base)
4676 {
4677   const struct mips_reg_operand *operand;
4678   unsigned int regno, uval, num_vals;
4679
4680   operand = (const struct mips_reg_operand *) operand_base;
4681   if (!match_reg (arg, operand->reg_type, &regno))
4682     return FALSE;
4683
4684   if (operand->reg_map)
4685     {
4686       num_vals = 1 << operand->root.size;
4687       for (uval = 0; uval < num_vals; uval++)
4688         if (operand->reg_map[uval] == regno)
4689           break;
4690       if (num_vals == uval)
4691         return FALSE;
4692     }
4693   else
4694     uval = regno;
4695
4696   arg->last_regno = regno;
4697   if (arg->opnum == 1)
4698     arg->dest_regno = regno;
4699   insn_insert_operand (arg->insn, operand_base, uval);
4700   return TRUE;
4701 }
4702
4703 /* OP_REG_PAIR matcher.  */
4704
4705 static bfd_boolean
4706 match_reg_pair_operand (struct mips_arg_info *arg,
4707                         const struct mips_operand *operand_base)
4708 {
4709   const struct mips_reg_pair_operand *operand;
4710   unsigned int regno1, regno2, uval, num_vals;
4711
4712   operand = (const struct mips_reg_pair_operand *) operand_base;
4713   if (!match_reg (arg, operand->reg_type, &regno1)
4714       || !match_char (arg, ',')
4715       || !match_reg (arg, operand->reg_type, &regno2))
4716     return FALSE;
4717
4718   num_vals = 1 << operand_base->size;
4719   for (uval = 0; uval < num_vals; uval++)
4720     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4721       break;
4722   if (uval == num_vals)
4723     return FALSE;
4724
4725   insn_insert_operand (arg->insn, operand_base, uval);
4726   return TRUE;
4727 }
4728
4729 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4730
4731 static bfd_boolean
4732 match_pcrel_operand (struct mips_arg_info *arg)
4733 {
4734   bfd_reloc_code_real_type r[3];
4735
4736   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4737 }
4738
4739 /* OP_PERF_REG matcher.  */
4740
4741 static bfd_boolean
4742 match_perf_reg_operand (struct mips_arg_info *arg,
4743                         const struct mips_operand *operand)
4744 {
4745   offsetT sval;
4746
4747   if (!match_const_int (arg, &sval))
4748     return FALSE;
4749
4750   if (sval != 0
4751       && (sval != 1
4752           || (mips_opts.arch == CPU_R5900
4753               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4754                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4755     {
4756       set_insn_error (arg->argnum, _("invalid performance register"));
4757       return FALSE;
4758     }
4759
4760   insn_insert_operand (arg->insn, operand, sval);
4761   return TRUE;
4762 }
4763
4764 /* OP_ADDIUSP matcher.  */
4765
4766 static bfd_boolean
4767 match_addiusp_operand (struct mips_arg_info *arg,
4768                        const struct mips_operand *operand)
4769 {
4770   offsetT sval;
4771   unsigned int uval;
4772
4773   if (!match_const_int (arg, &sval))
4774     return FALSE;
4775
4776   if (sval % 4)
4777     {
4778       match_out_of_range (arg);
4779       return FALSE;
4780     }
4781
4782   sval /= 4;
4783   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4784     {
4785       match_out_of_range (arg);
4786       return FALSE;
4787     }
4788
4789   uval = (unsigned int) sval;
4790   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4791   insn_insert_operand (arg->insn, operand, uval);
4792   return TRUE;
4793 }
4794
4795 /* OP_CLO_CLZ_DEST matcher.  */
4796
4797 static bfd_boolean
4798 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4799                             const struct mips_operand *operand)
4800 {
4801   unsigned int regno;
4802
4803   if (!match_reg (arg, OP_REG_GP, &regno))
4804     return FALSE;
4805
4806   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4807   return TRUE;
4808 }
4809
4810 /* OP_LWM_SWM_LIST matcher.  */
4811
4812 static bfd_boolean
4813 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4814                             const struct mips_operand *operand)
4815 {
4816   unsigned int reglist, sregs, ra, regno1, regno2;
4817   struct mips_arg_info reset;
4818
4819   reglist = 0;
4820   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4821     return FALSE;
4822   do
4823     {
4824       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4825         {
4826           reglist |= 1 << FP;
4827           regno2 = S7;
4828         }
4829       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4830       reset = *arg;
4831     }
4832   while (match_char (arg, ',')
4833          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4834   *arg = reset;
4835
4836   if (operand->size == 2)
4837     {
4838       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4839
4840          s0, ra
4841          s0, s1, ra, s2, s3
4842          s0-s2, ra
4843
4844          and any permutations of these.  */
4845       if ((reglist & 0xfff1ffff) != 0x80010000)
4846         return FALSE;
4847
4848       sregs = (reglist >> 17) & 7;
4849       ra = 0;
4850     }
4851   else
4852     {
4853       /* The list must include at least one of ra and s0-sN,
4854          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4855          which are $23 and $30 respectively.)  E.g.:
4856
4857          ra
4858          s0
4859          ra, s0, s1, s2
4860          s0-s8
4861          s0-s5, ra
4862
4863          and any permutations of these.  */
4864       if ((reglist & 0x3f00ffff) != 0)
4865         return FALSE;
4866
4867       ra = (reglist >> 27) & 0x10;
4868       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4869     }
4870   sregs += 1;
4871   if ((sregs & -sregs) != sregs)
4872     return FALSE;
4873
4874   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4875   return TRUE;
4876 }
4877
4878 /* OP_ENTRY_EXIT_LIST matcher.  */
4879
4880 static unsigned int
4881 match_entry_exit_operand (struct mips_arg_info *arg,
4882                           const struct mips_operand *operand)
4883 {
4884   unsigned int mask;
4885   bfd_boolean is_exit;
4886
4887   /* The format is the same for both ENTRY and EXIT, but the constraints
4888      are different.  */
4889   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4890   mask = (is_exit ? 7 << 3 : 0);
4891   do
4892     {
4893       unsigned int regno1, regno2;
4894       bfd_boolean is_freg;
4895
4896       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4897         is_freg = FALSE;
4898       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4899         is_freg = TRUE;
4900       else
4901         return FALSE;
4902
4903       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4904         {
4905           mask &= ~(7 << 3);
4906           mask |= (5 + regno2) << 3;
4907         }
4908       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4909         mask |= (regno2 - 3) << 3;
4910       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4911         mask |= (regno2 - 15) << 1;
4912       else if (regno1 == RA && regno2 == RA)
4913         mask |= 1;
4914       else
4915         return FALSE;
4916     }
4917   while (match_char (arg, ','));
4918
4919   insn_insert_operand (arg->insn, operand, mask);
4920   return TRUE;
4921 }
4922
4923 /* OP_SAVE_RESTORE_LIST matcher.  */
4924
4925 static bfd_boolean
4926 match_save_restore_list_operand (struct mips_arg_info *arg)
4927 {
4928   unsigned int opcode, args, statics, sregs;
4929   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4930   offsetT frame_size;
4931
4932   opcode = arg->insn->insn_opcode;
4933   frame_size = 0;
4934   num_frame_sizes = 0;
4935   args = 0;
4936   statics = 0;
4937   sregs = 0;
4938   do
4939     {
4940       unsigned int regno1, regno2;
4941
4942       if (arg->token->type == OT_INTEGER)
4943         {
4944           /* Handle the frame size.  */
4945           if (!match_const_int (arg, &frame_size))
4946             return FALSE;
4947           num_frame_sizes += 1;
4948         }
4949       else
4950         {
4951           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4952             return FALSE;
4953
4954           while (regno1 <= regno2)
4955             {
4956               if (regno1 >= 4 && regno1 <= 7)
4957                 {
4958                   if (num_frame_sizes == 0)
4959                     /* args $a0-$a3 */
4960                     args |= 1 << (regno1 - 4);
4961                   else
4962                     /* statics $a0-$a3 */
4963                     statics |= 1 << (regno1 - 4);
4964                 }
4965               else if (regno1 >= 16 && regno1 <= 23)
4966                 /* $s0-$s7 */
4967                 sregs |= 1 << (regno1 - 16);
4968               else if (regno1 == 30)
4969                 /* $s8 */
4970                 sregs |= 1 << 8;
4971               else if (regno1 == 31)
4972                 /* Add $ra to insn.  */
4973                 opcode |= 0x40;
4974               else
4975                 return FALSE;
4976               regno1 += 1;
4977               if (regno1 == 24)
4978                 regno1 = 30;
4979             }
4980         }
4981     }
4982   while (match_char (arg, ','));
4983
4984   /* Encode args/statics combination.  */
4985   if (args & statics)
4986     return FALSE;
4987   else if (args == 0xf)
4988     /* All $a0-$a3 are args.  */
4989     opcode |= MIPS16_ALL_ARGS << 16;
4990   else if (statics == 0xf)
4991     /* All $a0-$a3 are statics.  */
4992     opcode |= MIPS16_ALL_STATICS << 16;
4993   else
4994     {
4995       /* Count arg registers.  */
4996       num_args = 0;
4997       while (args & 0x1)
4998         {
4999           args >>= 1;
5000           num_args += 1;
5001         }
5002       if (args != 0)
5003         return FALSE;
5004
5005       /* Count static registers.  */
5006       num_statics = 0;
5007       while (statics & 0x8)
5008         {
5009           statics = (statics << 1) & 0xf;
5010           num_statics += 1;
5011         }
5012       if (statics != 0)
5013         return FALSE;
5014
5015       /* Encode args/statics.  */
5016       opcode |= ((num_args << 2) | num_statics) << 16;
5017     }
5018
5019   /* Encode $s0/$s1.  */
5020   if (sregs & (1 << 0))         /* $s0 */
5021     opcode |= 0x20;
5022   if (sregs & (1 << 1))         /* $s1 */
5023     opcode |= 0x10;
5024   sregs >>= 2;
5025
5026   /* Encode $s2-$s8. */
5027   num_sregs = 0;
5028   while (sregs & 1)
5029     {
5030       sregs >>= 1;
5031       num_sregs += 1;
5032     }
5033   if (sregs != 0)
5034     return FALSE;
5035   opcode |= num_sregs << 24;
5036
5037   /* Encode frame size.  */
5038   if (num_frame_sizes == 0)
5039     {
5040       set_insn_error (arg->argnum, _("missing frame size"));
5041       return FALSE;
5042     }
5043   if (num_frame_sizes > 1)
5044     {
5045       set_insn_error (arg->argnum, _("frame size specified twice"));
5046       return FALSE;
5047     }
5048   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5049     {
5050       set_insn_error (arg->argnum, _("invalid frame size"));
5051       return FALSE;
5052     }
5053   if (frame_size != 128 || (opcode >> 16) != 0)
5054     {
5055       frame_size /= 8;
5056       opcode |= (((frame_size & 0xf0) << 16)
5057                  | (frame_size & 0x0f));
5058     }
5059
5060   /* Finally build the instruction.  */
5061   if ((opcode >> 16) != 0 || frame_size == 0)
5062     opcode |= MIPS16_EXTEND;
5063   arg->insn->insn_opcode = opcode;
5064   return TRUE;
5065 }
5066
5067 /* OP_MDMX_IMM_REG matcher.  */
5068
5069 static bfd_boolean
5070 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5071                             const struct mips_operand *operand)
5072 {
5073   unsigned int regno, uval;
5074   bfd_boolean is_qh;
5075   const struct mips_opcode *opcode;
5076
5077   /* The mips_opcode records whether this is an octobyte or quadhalf
5078      instruction.  Start out with that bit in place.  */
5079   opcode = arg->insn->insn_mo;
5080   uval = mips_extract_operand (operand, opcode->match);
5081   is_qh = (uval != 0);
5082
5083   if (arg->token->type == OT_REG || arg->token->type == OT_REG_ELEMENT)
5084     {
5085       if ((opcode->membership & INSN_5400)
5086           && strcmp (opcode->name, "rzu.ob") == 0)
5087         {
5088           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5089                             arg->argnum);
5090           return FALSE;
5091         }
5092
5093       /* Check whether this is a vector register or a broadcast of
5094          a single element.  */
5095       if (arg->token->type == OT_REG_ELEMENT)
5096         {
5097           if (!match_regno (arg, OP_REG_VEC, arg->token->u.reg_element.regno,
5098                             &regno))
5099             return FALSE;
5100           if (arg->token->u.reg_element.index > (is_qh ? 3 : 7))
5101             {
5102               set_insn_error (arg->argnum, _("invalid element selector"));
5103               return FALSE;
5104             }
5105           else
5106             uval |= arg->token->u.reg_element.index << (is_qh ? 2 : 1) << 5;
5107         }
5108       else
5109         {
5110           /* A full vector.  */
5111           if ((opcode->membership & INSN_5400)
5112               && (strcmp (opcode->name, "sll.ob") == 0
5113                   || strcmp (opcode->name, "srl.ob") == 0))
5114             {
5115               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5116                                 arg->argnum);
5117               return FALSE;
5118             }
5119
5120           if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5121             return FALSE;
5122           if (is_qh)
5123             uval |= MDMX_FMTSEL_VEC_QH << 5;
5124           else
5125             uval |= MDMX_FMTSEL_VEC_OB << 5;
5126         }
5127       uval |= regno;
5128       ++arg->token;
5129     }
5130   else
5131     {
5132       offsetT sval;
5133
5134       if (!match_const_int (arg, &sval))
5135         return FALSE;
5136       if (sval < 0 || sval > 31)
5137         {
5138           match_out_of_range (arg);
5139           return FALSE;
5140         }
5141       uval |= (sval & 31);
5142       if (is_qh)
5143         uval |= MDMX_FMTSEL_IMM_QH << 5;
5144       else
5145         uval |= MDMX_FMTSEL_IMM_OB << 5;
5146     }
5147   insn_insert_operand (arg->insn, operand, uval);
5148   return TRUE;
5149 }
5150
5151 /* OP_PC matcher.  */
5152
5153 static bfd_boolean
5154 match_pc_operand (struct mips_arg_info *arg)
5155 {
5156   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5157     {
5158       ++arg->token;
5159       return TRUE;
5160     }
5161   return FALSE;
5162 }
5163
5164 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5165    register that we need to match.  */
5166
5167 static bfd_boolean
5168 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5169 {
5170   unsigned int regno;
5171
5172   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5173 }
5174
5175 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5176    the length of the value in bytes (4 for float, 8 for double) and
5177    USING_GPRS says whether the destination is a GPR rather than an FPR.
5178
5179    Return the constant in IMM and OFFSET as follows:
5180
5181    - If the constant should be loaded via memory, set IMM to O_absent and
5182      OFFSET to the memory address.
5183
5184    - Otherwise, if the constant should be loaded into two 32-bit registers,
5185      set IMM to the O_constant to load into the high register and OFFSET
5186      to the corresponding value for the low register.
5187
5188    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5189
5190    These constants only appear as the last operand in an instruction,
5191    and every instruction that accepts them in any variant accepts them
5192    in all variants.  This means we don't have to worry about backing out
5193    any changes if the instruction does not match.  We just match
5194    unconditionally and report an error if the constant is invalid.  */
5195
5196 static bfd_boolean
5197 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5198                       expressionS *offset, int length, bfd_boolean using_gprs)
5199 {
5200   char *p;
5201   segT seg, new_seg;
5202   subsegT subseg;
5203   const char *newname;
5204   unsigned char *data;
5205
5206   /* Where the constant is placed is based on how the MIPS assembler
5207      does things:
5208
5209      length == 4 && using_gprs  -- immediate value only
5210      length == 8 && using_gprs  -- .rdata or immediate value
5211      length == 4 && !using_gprs -- .lit4 or immediate value
5212      length == 8 && !using_gprs -- .lit8 or immediate value
5213
5214      The .lit4 and .lit8 sections are only used if permitted by the
5215      -G argument.  */
5216   if (arg->token->type != OT_FLOAT)
5217     {
5218       set_insn_error (arg->argnum, _("floating-point expression required"));
5219       return FALSE;
5220     }
5221
5222   gas_assert (arg->token->u.flt.length == length);
5223   data = arg->token->u.flt.data;
5224   ++arg->token;
5225
5226   /* Handle 32-bit constants for which an immediate value is best.  */
5227   if (length == 4
5228       && (using_gprs
5229           || g_switch_value < 4
5230           || (data[0] == 0 && data[1] == 0)
5231           || (data[2] == 0 && data[3] == 0)))
5232     {
5233       imm->X_op = O_constant;
5234       if (!target_big_endian)
5235         imm->X_add_number = bfd_getl32 (data);
5236       else
5237         imm->X_add_number = bfd_getb32 (data);
5238       offset->X_op = O_absent;
5239       return TRUE;
5240     }
5241
5242   /* Handle 64-bit constants for which an immediate value is best.  */
5243   if (length == 8
5244       && !mips_disable_float_construction
5245       /* Constants can only be constructed in GPRs and copied
5246          to FPRs if the GPRs are at least as wide as the FPRs.
5247          Force the constant into memory if we are using 64-bit FPRs
5248          but the GPRs are only 32 bits wide.  */
5249       /* ??? No longer true with the addition of MTHC1, but this
5250          is legacy code...  */
5251       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5252       && ((data[0] == 0 && data[1] == 0)
5253           || (data[2] == 0 && data[3] == 0))
5254       && ((data[4] == 0 && data[5] == 0)
5255           || (data[6] == 0 && data[7] == 0)))
5256     {
5257       /* The value is simple enough to load with a couple of instructions.
5258          If using 32-bit registers, set IMM to the high order 32 bits and
5259          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5260          64 bit constant.  */
5261       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5262         {
5263           imm->X_op = O_constant;
5264           offset->X_op = O_constant;
5265           if (!target_big_endian)
5266             {
5267               imm->X_add_number = bfd_getl32 (data + 4);
5268               offset->X_add_number = bfd_getl32 (data);
5269             }
5270           else
5271             {
5272               imm->X_add_number = bfd_getb32 (data);
5273               offset->X_add_number = bfd_getb32 (data + 4);
5274             }
5275           if (offset->X_add_number == 0)
5276             offset->X_op = O_absent;
5277         }
5278       else
5279         {
5280           imm->X_op = O_constant;
5281           if (!target_big_endian)
5282             imm->X_add_number = bfd_getl64 (data);
5283           else
5284             imm->X_add_number = bfd_getb64 (data);
5285           offset->X_op = O_absent;
5286         }
5287       return TRUE;
5288     }
5289
5290   /* Switch to the right section.  */
5291   seg = now_seg;
5292   subseg = now_subseg;
5293   if (length == 4)
5294     {
5295       gas_assert (!using_gprs && g_switch_value >= 4);
5296       newname = ".lit4";
5297     }
5298   else
5299     {
5300       if (using_gprs || g_switch_value < 8)
5301         newname = RDATA_SECTION_NAME;
5302       else
5303         newname = ".lit8";
5304     }
5305
5306   new_seg = subseg_new (newname, (subsegT) 0);
5307   bfd_set_section_flags (stdoutput, new_seg,
5308                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5309   frag_align (length == 4 ? 2 : 3, 0, 0);
5310   if (strncmp (TARGET_OS, "elf", 3) != 0)
5311     record_alignment (new_seg, 4);
5312   else
5313     record_alignment (new_seg, length == 4 ? 2 : 3);
5314   if (seg == now_seg)
5315     as_bad (_("Can't use floating point insn in this section"));
5316
5317   /* Set the argument to the current address in the section.  */
5318   imm->X_op = O_absent;
5319   offset->X_op = O_symbol;
5320   offset->X_add_symbol = symbol_temp_new_now ();
5321   offset->X_add_number = 0;
5322
5323   /* Put the floating point number into the section.  */
5324   p = frag_more (length);
5325   memcpy (p, data, length);
5326
5327   /* Switch back to the original section.  */
5328   subseg_set (seg, subseg);
5329   return TRUE;
5330 }
5331
5332 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5333    them.  */
5334
5335 static bfd_boolean
5336 match_vu0_suffix_operand (struct mips_arg_info *arg,
5337                           const struct mips_operand *operand,
5338                           bfd_boolean match_p)
5339 {
5340   unsigned int uval;
5341
5342   /* The operand can be an XYZW mask or a single 2-bit channel index
5343      (with X being 0).  */
5344   gas_assert (operand->size == 2 || operand->size == 4);
5345
5346   /* The suffix can be omitted when it is already part of the opcode.  */
5347   if (arg->token->type != OT_CHANNELS)
5348     return match_p;
5349
5350   uval = arg->token->u.channels;
5351   if (operand->size == 2)
5352     {
5353       /* Check that a single bit is set and convert it into a 2-bit index.  */
5354       if ((uval & -uval) != uval)
5355         return FALSE;
5356       uval = 4 - ffs (uval);
5357     }
5358
5359   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5360     return FALSE;
5361
5362   ++arg->token;
5363   if (!match_p)
5364     insn_insert_operand (arg->insn, operand, uval);
5365   return TRUE;
5366 }
5367
5368 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5369    of the argument text if the match is successful, otherwise return null.  */
5370
5371 static bfd_boolean
5372 match_operand (struct mips_arg_info *arg,
5373                const struct mips_operand *operand)
5374 {
5375   switch (operand->type)
5376     {
5377     case OP_INT:
5378       return match_int_operand (arg, operand);
5379
5380     case OP_MAPPED_INT:
5381       return match_mapped_int_operand (arg, operand);
5382
5383     case OP_MSB:
5384       return match_msb_operand (arg, operand);
5385
5386     case OP_REG:
5387     case OP_OPTIONAL_REG:
5388       return match_reg_operand (arg, operand);
5389
5390     case OP_REG_PAIR:
5391       return match_reg_pair_operand (arg, operand);
5392
5393     case OP_PCREL:
5394       return match_pcrel_operand (arg);
5395
5396     case OP_PERF_REG:
5397       return match_perf_reg_operand (arg, operand);
5398
5399     case OP_ADDIUSP_INT:
5400       return match_addiusp_operand (arg, operand);
5401
5402     case OP_CLO_CLZ_DEST:
5403       return match_clo_clz_dest_operand (arg, operand);
5404
5405     case OP_LWM_SWM_LIST:
5406       return match_lwm_swm_list_operand (arg, operand);
5407
5408     case OP_ENTRY_EXIT_LIST:
5409       return match_entry_exit_operand (arg, operand);
5410
5411     case OP_SAVE_RESTORE_LIST:
5412       return match_save_restore_list_operand (arg);
5413
5414     case OP_MDMX_IMM_REG:
5415       return match_mdmx_imm_reg_operand (arg, operand);
5416
5417     case OP_REPEAT_DEST_REG:
5418       return match_tied_reg_operand (arg, arg->dest_regno);
5419
5420     case OP_REPEAT_PREV_REG:
5421       return match_tied_reg_operand (arg, arg->last_regno);
5422
5423     case OP_PC:
5424       return match_pc_operand (arg);
5425
5426     case OP_VU0_SUFFIX:
5427       return match_vu0_suffix_operand (arg, operand, FALSE);
5428
5429     case OP_VU0_MATCH_SUFFIX:
5430       return match_vu0_suffix_operand (arg, operand, TRUE);
5431     }
5432   abort ();
5433 }
5434
5435 /* ARG is the state after successfully matching an instruction.
5436    Issue any queued-up warnings.  */
5437
5438 static void
5439 check_completed_insn (struct mips_arg_info *arg)
5440 {
5441   if (arg->seen_at)
5442     {
5443       if (AT == ATREG)
5444         as_warn (_("Used $at without \".set noat\""));
5445       else
5446         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
5447     }
5448 }
5449
5450 /* Return true if modifying general-purpose register REG needs a delay.  */
5451
5452 static bfd_boolean
5453 reg_needs_delay (unsigned int reg)
5454 {
5455   unsigned long prev_pinfo;
5456
5457   prev_pinfo = history[0].insn_mo->pinfo;
5458   if (!mips_opts.noreorder
5459       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY) && !gpr_interlocks)
5460           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5461       && (gpr_write_mask (&history[0]) & (1 << reg)))
5462     return TRUE;
5463
5464   return FALSE;
5465 }
5466
5467 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5468    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5469    by VR4120 errata.  */
5470
5471 static unsigned int
5472 classify_vr4120_insn (const char *name)
5473 {
5474   if (strncmp (name, "macc", 4) == 0)
5475     return FIX_VR4120_MACC;
5476   if (strncmp (name, "dmacc", 5) == 0)
5477     return FIX_VR4120_DMACC;
5478   if (strncmp (name, "mult", 4) == 0)
5479     return FIX_VR4120_MULT;
5480   if (strncmp (name, "dmult", 5) == 0)
5481     return FIX_VR4120_DMULT;
5482   if (strstr (name, "div"))
5483     return FIX_VR4120_DIV;
5484   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5485     return FIX_VR4120_MTHILO;
5486   return NUM_FIX_VR4120_CLASSES;
5487 }
5488
5489 #define INSN_ERET  0x42000018
5490 #define INSN_DERET 0x4200001f
5491
5492 /* Return the number of instructions that must separate INSN1 and INSN2,
5493    where INSN1 is the earlier instruction.  Return the worst-case value
5494    for any INSN2 if INSN2 is null.  */
5495
5496 static unsigned int
5497 insns_between (const struct mips_cl_insn *insn1,
5498                const struct mips_cl_insn *insn2)
5499 {
5500   unsigned long pinfo1, pinfo2;
5501   unsigned int mask;
5502
5503   /* If INFO2 is null, pessimistically assume that all flags are set for
5504      the second instruction.  */
5505   pinfo1 = insn1->insn_mo->pinfo;
5506   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5507
5508   /* For most targets, write-after-read dependencies on the HI and LO
5509      registers must be separated by at least two instructions.  */
5510   if (!hilo_interlocks)
5511     {
5512       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5513         return 2;
5514       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5515         return 2;
5516     }
5517
5518   /* If we're working around r7000 errata, there must be two instructions
5519      between an mfhi or mflo and any instruction that uses the result.  */
5520   if (mips_7000_hilo_fix
5521       && !mips_opts.micromips
5522       && MF_HILO_INSN (pinfo1)
5523       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5524     return 2;
5525
5526   /* If we're working around 24K errata, one instruction is required
5527      if an ERET or DERET is followed by a branch instruction.  */
5528   if (mips_fix_24k && !mips_opts.micromips)
5529     {
5530       if (insn1->insn_opcode == INSN_ERET
5531           || insn1->insn_opcode == INSN_DERET)
5532         {
5533           if (insn2 == NULL
5534               || insn2->insn_opcode == INSN_ERET
5535               || insn2->insn_opcode == INSN_DERET
5536               || delayed_branch_p (insn2))
5537             return 1;
5538         }
5539     }
5540
5541   /* If working around VR4120 errata, check for combinations that need
5542      a single intervening instruction.  */
5543   if (mips_fix_vr4120 && !mips_opts.micromips)
5544     {
5545       unsigned int class1, class2;
5546
5547       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5548       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5549         {
5550           if (insn2 == NULL)
5551             return 1;
5552           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5553           if (vr4120_conflicts[class1] & (1 << class2))
5554             return 1;
5555         }
5556     }
5557
5558   if (!HAVE_CODE_COMPRESSION)
5559     {
5560       /* Check for GPR or coprocessor load delays.  All such delays
5561          are on the RT register.  */
5562       /* Itbl support may require additional care here.  */
5563       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
5564           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5565         {
5566           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5567             return 1;
5568         }
5569
5570       /* Check for generic coprocessor hazards.
5571
5572          This case is not handled very well.  There is no special
5573          knowledge of CP0 handling, and the coprocessors other than
5574          the floating point unit are not distinguished at all.  */
5575       /* Itbl support may require additional care here. FIXME!
5576          Need to modify this to include knowledge about
5577          user specified delays!  */
5578       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5579                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5580         {
5581           /* Handle cases where INSN1 writes to a known general coprocessor
5582              register.  There must be a one instruction delay before INSN2
5583              if INSN2 reads that register, otherwise no delay is needed.  */
5584           mask = fpr_write_mask (insn1);
5585           if (mask != 0)
5586             {
5587               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5588                 return 1;
5589             }
5590           else
5591             {
5592               /* Read-after-write dependencies on the control registers
5593                  require a two-instruction gap.  */
5594               if ((pinfo1 & INSN_WRITE_COND_CODE)
5595                   && (pinfo2 & INSN_READ_COND_CODE))
5596                 return 2;
5597
5598               /* We don't know exactly what INSN1 does.  If INSN2 is
5599                  also a coprocessor instruction, assume there must be
5600                  a one instruction gap.  */
5601               if (pinfo2 & INSN_COP)
5602                 return 1;
5603             }
5604         }
5605
5606       /* Check for read-after-write dependencies on the coprocessor
5607          control registers in cases where INSN1 does not need a general
5608          coprocessor delay.  This means that INSN1 is a floating point
5609          comparison instruction.  */
5610       /* Itbl support may require additional care here.  */
5611       else if (!cop_interlocks
5612                && (pinfo1 & INSN_WRITE_COND_CODE)
5613                && (pinfo2 & INSN_READ_COND_CODE))
5614         return 1;
5615     }
5616
5617   return 0;
5618 }
5619
5620 /* Return the number of nops that would be needed to work around the
5621    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5622    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5623    that are contained within the first IGNORE instructions of HIST.  */
5624
5625 static int
5626 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5627                  const struct mips_cl_insn *insn)
5628 {
5629   int i, j;
5630   unsigned int mask;
5631
5632   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5633      are not affected by the errata.  */
5634   if (insn != 0
5635       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5636           || strcmp (insn->insn_mo->name, "mtlo") == 0
5637           || strcmp (insn->insn_mo->name, "mthi") == 0))
5638     return 0;
5639
5640   /* Search for the first MFLO or MFHI.  */
5641   for (i = 0; i < MAX_VR4130_NOPS; i++)
5642     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5643       {
5644         /* Extract the destination register.  */
5645         mask = gpr_write_mask (&hist[i]);
5646
5647         /* No nops are needed if INSN reads that register.  */
5648         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5649           return 0;
5650
5651         /* ...or if any of the intervening instructions do.  */
5652         for (j = 0; j < i; j++)
5653           if (gpr_read_mask (&hist[j]) & mask)
5654             return 0;
5655
5656         if (i >= ignore)
5657           return MAX_VR4130_NOPS - i;
5658       }
5659   return 0;
5660 }
5661
5662 #define BASE_REG_EQ(INSN1, INSN2)       \
5663   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5664       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5665
5666 /* Return the minimum alignment for this store instruction.  */
5667
5668 static int
5669 fix_24k_align_to (const struct mips_opcode *mo)
5670 {
5671   if (strcmp (mo->name, "sh") == 0)
5672     return 2;
5673
5674   if (strcmp (mo->name, "swc1") == 0
5675       || strcmp (mo->name, "swc2") == 0
5676       || strcmp (mo->name, "sw") == 0
5677       || strcmp (mo->name, "sc") == 0
5678       || strcmp (mo->name, "s.s") == 0)
5679     return 4;
5680
5681   if (strcmp (mo->name, "sdc1") == 0
5682       || strcmp (mo->name, "sdc2") == 0
5683       || strcmp (mo->name, "s.d") == 0)
5684     return 8;
5685
5686   /* sb, swl, swr */
5687   return 1;
5688 }
5689
5690 struct fix_24k_store_info
5691   {
5692     /* Immediate offset, if any, for this store instruction.  */
5693     short off;
5694     /* Alignment required by this store instruction.  */
5695     int align_to;
5696     /* True for register offsets.  */
5697     int register_offset;
5698   };
5699
5700 /* Comparison function used by qsort.  */
5701
5702 static int
5703 fix_24k_sort (const void *a, const void *b)
5704 {
5705   const struct fix_24k_store_info *pos1 = a;
5706   const struct fix_24k_store_info *pos2 = b;
5707
5708   return (pos1->off - pos2->off);
5709 }
5710
5711 /* INSN is a store instruction.  Try to record the store information
5712    in STINFO.  Return false if the information isn't known.  */
5713
5714 static bfd_boolean
5715 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5716                            const struct mips_cl_insn *insn)
5717 {
5718   /* The instruction must have a known offset.  */
5719   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5720     return FALSE;
5721
5722   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5723   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5724   return TRUE;
5725 }
5726
5727 /* Return the number of nops that would be needed to work around the 24k
5728    "lost data on stores during refill" errata if instruction INSN
5729    immediately followed the 2 instructions described by HIST.
5730    Ignore hazards that are contained within the first IGNORE
5731    instructions of HIST.
5732
5733    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5734    for the data cache refills and store data. The following describes
5735    the scenario where the store data could be lost.
5736
5737    * A data cache miss, due to either a load or a store, causing fill
5738      data to be supplied by the memory subsystem
5739    * The first three doublewords of fill data are returned and written
5740      into the cache
5741    * A sequence of four stores occurs in consecutive cycles around the
5742      final doubleword of the fill:
5743    * Store A
5744    * Store B
5745    * Store C
5746    * Zero, One or more instructions
5747    * Store D
5748
5749    The four stores A-D must be to different doublewords of the line that
5750    is being filled. The fourth instruction in the sequence above permits
5751    the fill of the final doubleword to be transferred from the FSB into
5752    the cache. In the sequence above, the stores may be either integer
5753    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5754    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5755    different doublewords on the line. If the floating point unit is
5756    running in 1:2 mode, it is not possible to create the sequence above
5757    using only floating point store instructions.
5758
5759    In this case, the cache line being filled is incorrectly marked
5760    invalid, thereby losing the data from any store to the line that
5761    occurs between the original miss and the completion of the five
5762    cycle sequence shown above.
5763
5764    The workarounds are:
5765
5766    * Run the data cache in write-through mode.
5767    * Insert a non-store instruction between
5768      Store A and Store B or Store B and Store C.  */
5769   
5770 static int
5771 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5772               const struct mips_cl_insn *insn)
5773 {
5774   struct fix_24k_store_info pos[3];
5775   int align, i, base_offset;
5776
5777   if (ignore >= 2)
5778     return 0;
5779
5780   /* If the previous instruction wasn't a store, there's nothing to
5781      worry about.  */
5782   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5783     return 0;
5784
5785   /* If the instructions after the previous one are unknown, we have
5786      to assume the worst.  */
5787   if (!insn)
5788     return 1;
5789
5790   /* Check whether we are dealing with three consecutive stores.  */
5791   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5792       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5793     return 0;
5794
5795   /* If we don't know the relationship between the store addresses,
5796      assume the worst.  */
5797   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5798       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5799     return 1;
5800
5801   if (!fix_24k_record_store_info (&pos[0], insn)
5802       || !fix_24k_record_store_info (&pos[1], &hist[0])
5803       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5804     return 1;
5805
5806   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5807
5808   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5809      X bytes and such that the base register + X is known to be aligned
5810      to align bytes.  */
5811
5812   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5813     align = 8;
5814   else
5815     {
5816       align = pos[0].align_to;
5817       base_offset = pos[0].off;
5818       for (i = 1; i < 3; i++)
5819         if (align < pos[i].align_to)
5820           {
5821             align = pos[i].align_to;
5822             base_offset = pos[i].off;
5823           }
5824       for (i = 0; i < 3; i++)
5825         pos[i].off -= base_offset;
5826     }
5827
5828   pos[0].off &= ~align + 1;
5829   pos[1].off &= ~align + 1;
5830   pos[2].off &= ~align + 1;
5831
5832   /* If any two stores write to the same chunk, they also write to the
5833      same doubleword.  The offsets are still sorted at this point.  */
5834   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5835     return 0;
5836
5837   /* A range of at least 9 bytes is needed for the stores to be in
5838      non-overlapping doublewords.  */
5839   if (pos[2].off - pos[0].off <= 8)
5840     return 0;
5841
5842   if (pos[2].off - pos[1].off >= 24
5843       || pos[1].off - pos[0].off >= 24
5844       || pos[2].off - pos[0].off >= 32)
5845     return 0;
5846
5847   return 1;
5848 }
5849
5850 /* Return the number of nops that would be needed if instruction INSN
5851    immediately followed the MAX_NOPS instructions given by HIST,
5852    where HIST[0] is the most recent instruction.  Ignore hazards
5853    between INSN and the first IGNORE instructions in HIST.
5854
5855    If INSN is null, return the worse-case number of nops for any
5856    instruction.  */
5857
5858 static int
5859 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5860                const struct mips_cl_insn *insn)
5861 {
5862   int i, nops, tmp_nops;
5863
5864   nops = 0;
5865   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5866     {
5867       tmp_nops = insns_between (hist + i, insn) - i;
5868       if (tmp_nops > nops)
5869         nops = tmp_nops;
5870     }
5871
5872   if (mips_fix_vr4130 && !mips_opts.micromips)
5873     {
5874       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5875       if (tmp_nops > nops)
5876         nops = tmp_nops;
5877     }
5878
5879   if (mips_fix_24k && !mips_opts.micromips)
5880     {
5881       tmp_nops = nops_for_24k (ignore, hist, insn);
5882       if (tmp_nops > nops)
5883         nops = tmp_nops;
5884     }
5885
5886   return nops;
5887 }
5888
5889 /* The variable arguments provide NUM_INSNS extra instructions that
5890    might be added to HIST.  Return the largest number of nops that
5891    would be needed after the extended sequence, ignoring hazards
5892    in the first IGNORE instructions.  */
5893
5894 static int
5895 nops_for_sequence (int num_insns, int ignore,
5896                    const struct mips_cl_insn *hist, ...)
5897 {
5898   va_list args;
5899   struct mips_cl_insn buffer[MAX_NOPS];
5900   struct mips_cl_insn *cursor;
5901   int nops;
5902
5903   va_start (args, hist);
5904   cursor = buffer + num_insns;
5905   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5906   while (cursor > buffer)
5907     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5908
5909   nops = nops_for_insn (ignore, buffer, NULL);
5910   va_end (args);
5911   return nops;
5912 }
5913
5914 /* Like nops_for_insn, but if INSN is a branch, take into account the
5915    worst-case delay for the branch target.  */
5916
5917 static int
5918 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5919                          const struct mips_cl_insn *insn)
5920 {
5921   int nops, tmp_nops;
5922
5923   nops = nops_for_insn (ignore, hist, insn);
5924   if (delayed_branch_p (insn))
5925     {
5926       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5927                                     hist, insn, get_delay_slot_nop (insn));
5928       if (tmp_nops > nops)
5929         nops = tmp_nops;
5930     }
5931   else if (compact_branch_p (insn))
5932     {
5933       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5934       if (tmp_nops > nops)
5935         nops = tmp_nops;
5936     }
5937   return nops;
5938 }
5939
5940 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5941
5942 static void
5943 fix_loongson2f_nop (struct mips_cl_insn * ip)
5944 {
5945   gas_assert (!HAVE_CODE_COMPRESSION);
5946   if (strcmp (ip->insn_mo->name, "nop") == 0)
5947     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5948 }
5949
5950 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5951                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5952
5953 static void
5954 fix_loongson2f_jump (struct mips_cl_insn * ip)
5955 {
5956   gas_assert (!HAVE_CODE_COMPRESSION);
5957   if (strcmp (ip->insn_mo->name, "j") == 0
5958       || strcmp (ip->insn_mo->name, "jr") == 0
5959       || strcmp (ip->insn_mo->name, "jalr") == 0)
5960     {
5961       int sreg;
5962       expressionS ep;
5963
5964       if (! mips_opts.at)
5965         return;
5966
5967       sreg = EXTRACT_OPERAND (0, RS, *ip);
5968       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5969         return;
5970
5971       ep.X_op = O_constant;
5972       ep.X_add_number = 0xcfff0000;
5973       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5974       ep.X_add_number = 0xffff;
5975       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5976       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5977     }
5978 }
5979
5980 static void
5981 fix_loongson2f (struct mips_cl_insn * ip)
5982 {
5983   if (mips_fix_loongson2f_nop)
5984     fix_loongson2f_nop (ip);
5985
5986   if (mips_fix_loongson2f_jump)
5987     fix_loongson2f_jump (ip);
5988 }
5989
5990 /* IP is a branch that has a delay slot, and we need to fill it
5991    automatically.   Return true if we can do that by swapping IP
5992    with the previous instruction.
5993    ADDRESS_EXPR is an operand of the instruction to be used with
5994    RELOC_TYPE.  */
5995
5996 static bfd_boolean
5997 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5998                    bfd_reloc_code_real_type *reloc_type)
5999 {
6000   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6001   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6002
6003   /* -O2 and above is required for this optimization.  */
6004   if (mips_optimize < 2)
6005     return FALSE;
6006
6007   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6008   if (mips_opts.nomove)
6009     return FALSE;
6010
6011   /* We can't swap if the previous instruction's position is fixed.  */
6012   if (history[0].fixed_p)
6013     return FALSE;
6014
6015   /* If the previous previous insn was in a .set noreorder, we can't
6016      swap.  Actually, the MIPS assembler will swap in this situation.
6017      However, gcc configured -with-gnu-as will generate code like
6018
6019         .set    noreorder
6020         lw      $4,XXX
6021         .set    reorder
6022         INSN
6023         bne     $4,$0,foo
6024
6025      in which we can not swap the bne and INSN.  If gcc is not configured
6026      -with-gnu-as, it does not output the .set pseudo-ops.  */
6027   if (history[1].noreorder_p)
6028     return FALSE;
6029
6030   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6031      This means that the previous instruction was a 4-byte one anyhow.  */
6032   if (mips_opts.mips16 && history[0].fixp[0])
6033     return FALSE;
6034
6035   /* If the branch is itself the target of a branch, we can not swap.
6036      We cheat on this; all we check for is whether there is a label on
6037      this instruction.  If there are any branches to anything other than
6038      a label, users must use .set noreorder.  */
6039   if (seg_info (now_seg)->label_list)
6040     return FALSE;
6041
6042   /* If the previous instruction is in a variant frag other than this
6043      branch's one, we cannot do the swap.  This does not apply to
6044      MIPS16 code, which uses variant frags for different purposes.  */
6045   if (!mips_opts.mips16
6046       && history[0].frag
6047       && history[0].frag->fr_type == rs_machine_dependent)
6048     return FALSE;
6049
6050   /* We do not swap with instructions that cannot architecturally
6051      be placed in a branch delay slot, such as SYNC or ERET.  We
6052      also refrain from swapping with a trap instruction, since it
6053      complicates trap handlers to have the trap instruction be in
6054      a delay slot.  */
6055   prev_pinfo = history[0].insn_mo->pinfo;
6056   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6057     return FALSE;
6058
6059   /* Check for conflicts between the branch and the instructions
6060      before the candidate delay slot.  */
6061   if (nops_for_insn (0, history + 1, ip) > 0)
6062     return FALSE;
6063
6064   /* Check for conflicts between the swapped sequence and the
6065      target of the branch.  */
6066   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6067     return FALSE;
6068
6069   /* If the branch reads a register that the previous
6070      instruction sets, we can not swap.  */
6071   gpr_read = gpr_read_mask (ip);
6072   prev_gpr_write = gpr_write_mask (&history[0]);
6073   if (gpr_read & prev_gpr_write)
6074     return FALSE;
6075
6076   /* If the branch writes a register that the previous
6077      instruction sets, we can not swap.  */
6078   gpr_write = gpr_write_mask (ip);
6079   if (gpr_write & prev_gpr_write)
6080     return FALSE;
6081
6082   /* If the branch writes a register that the previous
6083      instruction reads, we can not swap.  */
6084   prev_gpr_read = gpr_read_mask (&history[0]);
6085   if (gpr_write & prev_gpr_read)
6086     return FALSE;
6087
6088   /* If one instruction sets a condition code and the
6089      other one uses a condition code, we can not swap.  */
6090   pinfo = ip->insn_mo->pinfo;
6091   if ((pinfo & INSN_READ_COND_CODE)
6092       && (prev_pinfo & INSN_WRITE_COND_CODE))
6093     return FALSE;
6094   if ((pinfo & INSN_WRITE_COND_CODE)
6095       && (prev_pinfo & INSN_READ_COND_CODE))
6096     return FALSE;
6097
6098   /* If the previous instruction uses the PC, we can not swap.  */
6099   prev_pinfo2 = history[0].insn_mo->pinfo2;
6100   if (prev_pinfo2 & INSN2_READ_PC)
6101     return FALSE;
6102
6103   /* If the previous instruction has an incorrect size for a fixed
6104      branch delay slot in microMIPS mode, we cannot swap.  */
6105   pinfo2 = ip->insn_mo->pinfo2;
6106   if (mips_opts.micromips
6107       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6108       && insn_length (history) != 2)
6109     return FALSE;
6110   if (mips_opts.micromips
6111       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6112       && insn_length (history) != 4)
6113     return FALSE;
6114
6115   /* On R5900 short loops need to be fixed by inserting a nop in
6116      the branch delay slots.
6117      A short loop can be terminated too early.  */
6118   if (mips_opts.arch == CPU_R5900
6119       /* Check if instruction has a parameter, ignore "j $31". */
6120       && (address_expr != NULL)
6121       /* Parameter must be 16 bit. */
6122       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6123       /* Branch to same segment. */
6124       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6125       /* Branch to same code fragment. */
6126       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6127       /* Can only calculate branch offset if value is known. */
6128       && symbol_constant_p(address_expr->X_add_symbol)
6129       /* Check if branch is really conditional. */
6130       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6131         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6132         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6133     {
6134       int distance;
6135       /* Check if loop is shorter than 6 instructions including
6136          branch and delay slot.  */
6137       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6138       if (distance <= 20)
6139         {
6140           int i;
6141           int rv;
6142
6143           rv = FALSE;
6144           /* When the loop includes branches or jumps,
6145              it is not a short loop. */
6146           for (i = 0; i < (distance / 4); i++)
6147             {
6148               if ((history[i].cleared_p)
6149                   || delayed_branch_p(&history[i]))
6150                 {
6151                   rv = TRUE;
6152                   break;
6153                 }
6154             }
6155           if (rv == FALSE)
6156             {
6157               /* Insert nop after branch to fix short loop. */
6158               return FALSE;
6159             }
6160         }
6161     }
6162
6163   return TRUE;
6164 }
6165
6166 /* Decide how we should add IP to the instruction stream.
6167    ADDRESS_EXPR is an operand of the instruction to be used with
6168    RELOC_TYPE.  */
6169
6170 static enum append_method
6171 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6172                    bfd_reloc_code_real_type *reloc_type)
6173 {
6174   /* The relaxed version of a macro sequence must be inherently
6175      hazard-free.  */
6176   if (mips_relax.sequence == 2)
6177     return APPEND_ADD;
6178
6179   /* We must not dabble with instructions in a ".set norerorder" block.  */
6180   if (mips_opts.noreorder)
6181     return APPEND_ADD;
6182
6183   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6184   if (delayed_branch_p (ip))
6185     {
6186       if (!branch_likely_p (ip)
6187           && can_swap_branch_p (ip, address_expr, reloc_type))
6188         return APPEND_SWAP;
6189
6190       if (mips_opts.mips16
6191           && ISA_SUPPORTS_MIPS16E
6192           && gpr_read_mask (ip) != 0)
6193         return APPEND_ADD_COMPACT;
6194
6195       return APPEND_ADD_WITH_NOP;
6196     }
6197
6198   return APPEND_ADD;
6199 }
6200
6201 /* IP is a MIPS16 instruction whose opcode we have just changed.
6202    Point IP->insn_mo to the new opcode's definition.  */
6203
6204 static void
6205 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6206 {
6207   const struct mips_opcode *mo, *end;
6208
6209   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6210   for (mo = ip->insn_mo; mo < end; mo++)
6211     if ((ip->insn_opcode & mo->mask) == mo->match)
6212       {
6213         ip->insn_mo = mo;
6214         return;
6215       }
6216   abort ();
6217 }
6218
6219 /* For microMIPS macros, we need to generate a local number label
6220    as the target of branches.  */
6221 #define MICROMIPS_LABEL_CHAR            '\037'
6222 static unsigned long micromips_target_label;
6223 static char micromips_target_name[32];
6224
6225 static char *
6226 micromips_label_name (void)
6227 {
6228   char *p = micromips_target_name;
6229   char symbol_name_temporary[24];
6230   unsigned long l;
6231   int i;
6232
6233   if (*p)
6234     return p;
6235
6236   i = 0;
6237   l = micromips_target_label;
6238 #ifdef LOCAL_LABEL_PREFIX
6239   *p++ = LOCAL_LABEL_PREFIX;
6240 #endif
6241   *p++ = 'L';
6242   *p++ = MICROMIPS_LABEL_CHAR;
6243   do
6244     {
6245       symbol_name_temporary[i++] = l % 10 + '0';
6246       l /= 10;
6247     }
6248   while (l != 0);
6249   while (i > 0)
6250     *p++ = symbol_name_temporary[--i];
6251   *p = '\0';
6252
6253   return micromips_target_name;
6254 }
6255
6256 static void
6257 micromips_label_expr (expressionS *label_expr)
6258 {
6259   label_expr->X_op = O_symbol;
6260   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6261   label_expr->X_add_number = 0;
6262 }
6263
6264 static void
6265 micromips_label_inc (void)
6266 {
6267   micromips_target_label++;
6268   *micromips_target_name = '\0';
6269 }
6270
6271 static void
6272 micromips_add_label (void)
6273 {
6274   symbolS *s;
6275
6276   s = colon (micromips_label_name ());
6277   micromips_label_inc ();
6278   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6279 }
6280
6281 /* If assembling microMIPS code, then return the microMIPS reloc
6282    corresponding to the requested one if any.  Otherwise return
6283    the reloc unchanged.  */
6284
6285 static bfd_reloc_code_real_type
6286 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6287 {
6288   static const bfd_reloc_code_real_type relocs[][2] =
6289     {
6290       /* Keep sorted incrementally by the left-hand key.  */
6291       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6292       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6293       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6294       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6295       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6296       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6297       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6298       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6299       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6300       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6301       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6302       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6303       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6304       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6305       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6306       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6307       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6308       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6309       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6310       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6311       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6312       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6313       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6314       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6315       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6316       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6317       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6318     };
6319   bfd_reloc_code_real_type r;
6320   size_t i;
6321
6322   if (!mips_opts.micromips)
6323     return reloc;
6324   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6325     {
6326       r = relocs[i][0];
6327       if (r > reloc)
6328         return reloc;
6329       if (r == reloc)
6330         return relocs[i][1];
6331     }
6332   return reloc;
6333 }
6334
6335 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6336    Return true on success, storing the resolved value in RESULT.  */
6337
6338 static bfd_boolean
6339 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6340                  offsetT *result)
6341 {
6342   switch (reloc)
6343     {
6344     case BFD_RELOC_MIPS_HIGHEST:
6345     case BFD_RELOC_MICROMIPS_HIGHEST:
6346       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6347       return TRUE;
6348
6349     case BFD_RELOC_MIPS_HIGHER:
6350     case BFD_RELOC_MICROMIPS_HIGHER:
6351       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6352       return TRUE;
6353
6354     case BFD_RELOC_HI16_S:
6355     case BFD_RELOC_MICROMIPS_HI16_S:
6356     case BFD_RELOC_MIPS16_HI16_S:
6357       *result = ((operand + 0x8000) >> 16) & 0xffff;
6358       return TRUE;
6359
6360     case BFD_RELOC_HI16:
6361     case BFD_RELOC_MICROMIPS_HI16:
6362     case BFD_RELOC_MIPS16_HI16:
6363       *result = (operand >> 16) & 0xffff;
6364       return TRUE;
6365
6366     case BFD_RELOC_LO16:
6367     case BFD_RELOC_MICROMIPS_LO16:
6368     case BFD_RELOC_MIPS16_LO16:
6369       *result = operand & 0xffff;
6370       return TRUE;
6371
6372     case BFD_RELOC_UNUSED:
6373       *result = operand;
6374       return TRUE;
6375
6376     default:
6377       return FALSE;
6378     }
6379 }
6380
6381 /* Output an instruction.  IP is the instruction information.
6382    ADDRESS_EXPR is an operand of the instruction to be used with
6383    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6384    a macro expansion.  */
6385
6386 static void
6387 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6388              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6389 {
6390   unsigned long prev_pinfo2, pinfo;
6391   bfd_boolean relaxed_branch = FALSE;
6392   enum append_method method;
6393   bfd_boolean relax32;
6394   int branch_disp;
6395
6396   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6397     fix_loongson2f (ip);
6398
6399   file_ase_mips16 |= mips_opts.mips16;
6400   file_ase_micromips |= mips_opts.micromips;
6401
6402   prev_pinfo2 = history[0].insn_mo->pinfo2;
6403   pinfo = ip->insn_mo->pinfo;
6404
6405   if (mips_opts.micromips
6406       && !expansionp
6407       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6408            && micromips_insn_length (ip->insn_mo) != 2)
6409           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6410               && micromips_insn_length (ip->insn_mo) != 4)))
6411     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
6412              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6413
6414   if (address_expr == NULL)
6415     ip->complete_p = 1;
6416   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6417            && reloc_type[1] == BFD_RELOC_UNUSED
6418            && reloc_type[2] == BFD_RELOC_UNUSED
6419            && address_expr->X_op == O_constant)
6420     {
6421       switch (*reloc_type)
6422         {
6423         case BFD_RELOC_MIPS_JMP:
6424           {
6425             int shift;
6426
6427             shift = mips_opts.micromips ? 1 : 2;
6428             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6429               as_bad (_("jump to misaligned address (0x%lx)"),
6430                       (unsigned long) address_expr->X_add_number);
6431             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6432                                 & 0x3ffffff);
6433             ip->complete_p = 1;
6434           }
6435           break;
6436
6437         case BFD_RELOC_MIPS16_JMP:
6438           if ((address_expr->X_add_number & 3) != 0)
6439             as_bad (_("jump to misaligned address (0x%lx)"),
6440                     (unsigned long) address_expr->X_add_number);
6441           ip->insn_opcode |=
6442             (((address_expr->X_add_number & 0x7c0000) << 3)
6443                | ((address_expr->X_add_number & 0xf800000) >> 7)
6444                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6445           ip->complete_p = 1;
6446           break;
6447
6448         case BFD_RELOC_16_PCREL_S2:
6449           {
6450             int shift;
6451
6452             shift = mips_opts.micromips ? 1 : 2;
6453             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6454               as_bad (_("branch to misaligned address (0x%lx)"),
6455                       (unsigned long) address_expr->X_add_number);
6456             if (!mips_relax_branch)
6457               {
6458                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6459                     & ~((1 << (shift + 16)) - 1))
6460                   as_bad (_("branch address range overflow (0x%lx)"),
6461                           (unsigned long) address_expr->X_add_number);
6462                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6463                                     & 0xffff);
6464               }
6465           }
6466           break;
6467
6468         default:
6469           {
6470             offsetT value;
6471
6472             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6473                                  &value))
6474               {
6475                 ip->insn_opcode |= value & 0xffff;
6476                 ip->complete_p = 1;
6477               }
6478           }
6479           break;
6480         }
6481     }
6482
6483   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6484     {
6485       /* There are a lot of optimizations we could do that we don't.
6486          In particular, we do not, in general, reorder instructions.
6487          If you use gcc with optimization, it will reorder
6488          instructions and generally do much more optimization then we
6489          do here; repeating all that work in the assembler would only
6490          benefit hand written assembly code, and does not seem worth
6491          it.  */
6492       int nops = (mips_optimize == 0
6493                   ? nops_for_insn (0, history, NULL)
6494                   : nops_for_insn_or_target (0, history, ip));
6495       if (nops > 0)
6496         {
6497           fragS *old_frag;
6498           unsigned long old_frag_offset;
6499           int i;
6500
6501           old_frag = frag_now;
6502           old_frag_offset = frag_now_fix ();
6503
6504           for (i = 0; i < nops; i++)
6505             add_fixed_insn (NOP_INSN);
6506           insert_into_history (0, nops, NOP_INSN);
6507
6508           if (listing)
6509             {
6510               listing_prev_line ();
6511               /* We may be at the start of a variant frag.  In case we
6512                  are, make sure there is enough space for the frag
6513                  after the frags created by listing_prev_line.  The
6514                  argument to frag_grow here must be at least as large
6515                  as the argument to all other calls to frag_grow in
6516                  this file.  We don't have to worry about being in the
6517                  middle of a variant frag, because the variants insert
6518                  all needed nop instructions themselves.  */
6519               frag_grow (40);
6520             }
6521
6522           mips_move_text_labels ();
6523
6524 #ifndef NO_ECOFF_DEBUGGING
6525           if (ECOFF_DEBUGGING)
6526             ecoff_fix_loc (old_frag, old_frag_offset);
6527 #endif
6528         }
6529     }
6530   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6531     {
6532       int nops;
6533
6534       /* Work out how many nops in prev_nop_frag are needed by IP,
6535          ignoring hazards generated by the first prev_nop_frag_since
6536          instructions.  */
6537       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6538       gas_assert (nops <= prev_nop_frag_holds);
6539
6540       /* Enforce NOPS as a minimum.  */
6541       if (nops > prev_nop_frag_required)
6542         prev_nop_frag_required = nops;
6543
6544       if (prev_nop_frag_holds == prev_nop_frag_required)
6545         {
6546           /* Settle for the current number of nops.  Update the history
6547              accordingly (for the benefit of any future .set reorder code).  */
6548           prev_nop_frag = NULL;
6549           insert_into_history (prev_nop_frag_since,
6550                                prev_nop_frag_holds, NOP_INSN);
6551         }
6552       else
6553         {
6554           /* Allow this instruction to replace one of the nops that was
6555              tentatively added to prev_nop_frag.  */
6556           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6557           prev_nop_frag_holds--;
6558           prev_nop_frag_since++;
6559         }
6560     }
6561
6562   method = get_append_method (ip, address_expr, reloc_type);
6563   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6564
6565   dwarf2_emit_insn (0);
6566   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6567      so "move" the instruction address accordingly.
6568
6569      Also, it doesn't seem appropriate for the assembler to reorder .loc
6570      entries.  If this instruction is a branch that we are going to swap
6571      with the previous instruction, the two instructions should be
6572      treated as a unit, and the debug information for both instructions
6573      should refer to the start of the branch sequence.  Using the
6574      current position is certainly wrong when swapping a 32-bit branch
6575      and a 16-bit delay slot, since the current position would then be
6576      in the middle of a branch.  */
6577   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6578
6579   relax32 = (mips_relax_branch
6580              /* Don't try branch relaxation within .set nomacro, or within
6581                 .set noat if we use $at for PIC computations.  If it turns
6582                 out that the branch was out-of-range, we'll get an error.  */
6583              && !mips_opts.warn_about_macros
6584              && (mips_opts.at || mips_pic == NO_PIC)
6585              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6586                 as they have no complementing branches.  */
6587              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6588
6589   if (!HAVE_CODE_COMPRESSION
6590       && address_expr
6591       && relax32
6592       && *reloc_type == BFD_RELOC_16_PCREL_S2
6593       && delayed_branch_p (ip))
6594     {
6595       relaxed_branch = TRUE;
6596       add_relaxed_insn (ip, (relaxed_branch_length
6597                              (NULL, NULL,
6598                               uncond_branch_p (ip) ? -1
6599                               : branch_likely_p (ip) ? 1
6600                               : 0)), 4,
6601                         RELAX_BRANCH_ENCODE
6602                         (AT,
6603                          uncond_branch_p (ip),
6604                          branch_likely_p (ip),
6605                          pinfo & INSN_WRITE_GPR_31,
6606                          0),
6607                         address_expr->X_add_symbol,
6608                         address_expr->X_add_number);
6609       *reloc_type = BFD_RELOC_UNUSED;
6610     }
6611   else if (mips_opts.micromips
6612            && address_expr
6613            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6614                || *reloc_type > BFD_RELOC_UNUSED)
6615            && (delayed_branch_p (ip) || compact_branch_p (ip))
6616            /* Don't try branch relaxation when users specify
6617               16-bit/32-bit instructions.  */
6618            && !forced_insn_length)
6619     {
6620       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6621       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6622       int uncond = uncond_branch_p (ip) ? -1 : 0;
6623       int compact = compact_branch_p (ip);
6624       int al = pinfo & INSN_WRITE_GPR_31;
6625       int length32;
6626
6627       gas_assert (address_expr != NULL);
6628       gas_assert (!mips_relax.sequence);
6629
6630       relaxed_branch = TRUE;
6631       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6632       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6633                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6634                                                 relax32, 0, 0),
6635                         address_expr->X_add_symbol,
6636                         address_expr->X_add_number);
6637       *reloc_type = BFD_RELOC_UNUSED;
6638     }
6639   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6640     {
6641       /* We need to set up a variant frag.  */
6642       gas_assert (address_expr != NULL);
6643       add_relaxed_insn (ip, 4, 0,
6644                         RELAX_MIPS16_ENCODE
6645                         (*reloc_type - BFD_RELOC_UNUSED,
6646                          forced_insn_length == 2, forced_insn_length == 4,
6647                          delayed_branch_p (&history[0]),
6648                          history[0].mips16_absolute_jump_p),
6649                         make_expr_symbol (address_expr), 0);
6650     }
6651   else if (mips_opts.mips16 && insn_length (ip) == 2)
6652     {
6653       if (!delayed_branch_p (ip))
6654         /* Make sure there is enough room to swap this instruction with
6655            a following jump instruction.  */
6656         frag_grow (6);
6657       add_fixed_insn (ip);
6658     }
6659   else
6660     {
6661       if (mips_opts.mips16
6662           && mips_opts.noreorder
6663           && delayed_branch_p (&history[0]))
6664         as_warn (_("extended instruction in delay slot"));
6665
6666       if (mips_relax.sequence)
6667         {
6668           /* If we've reached the end of this frag, turn it into a variant
6669              frag and record the information for the instructions we've
6670              written so far.  */
6671           if (frag_room () < 4)
6672             relax_close_frag ();
6673           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6674         }
6675
6676       if (mips_relax.sequence != 2)
6677         {
6678           if (mips_macro_warning.first_insn_sizes[0] == 0)
6679             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6680           mips_macro_warning.sizes[0] += insn_length (ip);
6681           mips_macro_warning.insns[0]++;
6682         }
6683       if (mips_relax.sequence != 1)
6684         {
6685           if (mips_macro_warning.first_insn_sizes[1] == 0)
6686             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6687           mips_macro_warning.sizes[1] += insn_length (ip);
6688           mips_macro_warning.insns[1]++;
6689         }
6690
6691       if (mips_opts.mips16)
6692         {
6693           ip->fixed_p = 1;
6694           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6695         }
6696       add_fixed_insn (ip);
6697     }
6698
6699   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6700     {
6701       bfd_reloc_code_real_type final_type[3];
6702       reloc_howto_type *howto0;
6703       reloc_howto_type *howto;
6704       int i;
6705
6706       /* Perform any necessary conversion to microMIPS relocations
6707          and find out how many relocations there actually are.  */
6708       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6709         final_type[i] = micromips_map_reloc (reloc_type[i]);
6710
6711       /* In a compound relocation, it is the final (outermost)
6712          operator that determines the relocated field.  */
6713       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6714       if (!howto)
6715         abort ();
6716
6717       if (i > 1)
6718         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6719       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6720                                  bfd_get_reloc_size (howto),
6721                                  address_expr,
6722                                  howto0 && howto0->pc_relative,
6723                                  final_type[0]);
6724
6725       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6726       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6727         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6728
6729       /* These relocations can have an addend that won't fit in
6730          4 octets for 64bit assembly.  */
6731       if (HAVE_64BIT_GPRS
6732           && ! howto->partial_inplace
6733           && (reloc_type[0] == BFD_RELOC_16
6734               || reloc_type[0] == BFD_RELOC_32
6735               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6736               || reloc_type[0] == BFD_RELOC_GPREL16
6737               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6738               || reloc_type[0] == BFD_RELOC_GPREL32
6739               || reloc_type[0] == BFD_RELOC_64
6740               || reloc_type[0] == BFD_RELOC_CTOR
6741               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6742               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6743               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6744               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6745               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6746               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6747               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6748               || hi16_reloc_p (reloc_type[0])
6749               || lo16_reloc_p (reloc_type[0])))
6750         ip->fixp[0]->fx_no_overflow = 1;
6751
6752       /* These relocations can have an addend that won't fit in 2 octets.  */
6753       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6754           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6755         ip->fixp[0]->fx_no_overflow = 1;
6756
6757       if (mips_relax.sequence)
6758         {
6759           if (mips_relax.first_fixup == 0)
6760             mips_relax.first_fixup = ip->fixp[0];
6761         }
6762       else if (reloc_needs_lo_p (*reloc_type))
6763         {
6764           struct mips_hi_fixup *hi_fixup;
6765
6766           /* Reuse the last entry if it already has a matching %lo.  */
6767           hi_fixup = mips_hi_fixup_list;
6768           if (hi_fixup == 0
6769               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6770             {
6771               hi_fixup = ((struct mips_hi_fixup *)
6772                           xmalloc (sizeof (struct mips_hi_fixup)));
6773               hi_fixup->next = mips_hi_fixup_list;
6774               mips_hi_fixup_list = hi_fixup;
6775             }
6776           hi_fixup->fixp = ip->fixp[0];
6777           hi_fixup->seg = now_seg;
6778         }
6779
6780       /* Add fixups for the second and third relocations, if given.
6781          Note that the ABI allows the second relocation to be
6782          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6783          moment we only use RSS_UNDEF, but we could add support
6784          for the others if it ever becomes necessary.  */
6785       for (i = 1; i < 3; i++)
6786         if (reloc_type[i] != BFD_RELOC_UNUSED)
6787           {
6788             ip->fixp[i] = fix_new (ip->frag, ip->where,
6789                                    ip->fixp[0]->fx_size, NULL, 0,
6790                                    FALSE, final_type[i]);
6791
6792             /* Use fx_tcbit to mark compound relocs.  */
6793             ip->fixp[0]->fx_tcbit = 1;
6794             ip->fixp[i]->fx_tcbit = 1;
6795           }
6796     }
6797   install_insn (ip);
6798
6799   /* Update the register mask information.  */
6800   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6801   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6802
6803   switch (method)
6804     {
6805     case APPEND_ADD:
6806       insert_into_history (0, 1, ip);
6807       break;
6808
6809     case APPEND_ADD_WITH_NOP:
6810       {
6811         struct mips_cl_insn *nop;
6812
6813         insert_into_history (0, 1, ip);
6814         nop = get_delay_slot_nop (ip);
6815         add_fixed_insn (nop);
6816         insert_into_history (0, 1, nop);
6817         if (mips_relax.sequence)
6818           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6819       }
6820       break;
6821
6822     case APPEND_ADD_COMPACT:
6823       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6824       gas_assert (mips_opts.mips16);
6825       ip->insn_opcode |= 0x0080;
6826       find_altered_mips16_opcode (ip);
6827       install_insn (ip);
6828       insert_into_history (0, 1, ip);
6829       break;
6830
6831     case APPEND_SWAP:
6832       {
6833         struct mips_cl_insn delay = history[0];
6834         if (mips_opts.mips16)
6835           {
6836             know (delay.frag == ip->frag);
6837             move_insn (ip, delay.frag, delay.where);
6838             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6839           }
6840         else if (relaxed_branch || delay.frag != ip->frag)
6841           {
6842             /* Add the delay slot instruction to the end of the
6843                current frag and shrink the fixed part of the
6844                original frag.  If the branch occupies the tail of
6845                the latter, move it backwards to cover the gap.  */
6846             delay.frag->fr_fix -= branch_disp;
6847             if (delay.frag == ip->frag)
6848               move_insn (ip, ip->frag, ip->where - branch_disp);
6849             add_fixed_insn (&delay);
6850           }
6851         else
6852           {
6853             move_insn (&delay, ip->frag,
6854                        ip->where - branch_disp + insn_length (ip));
6855             move_insn (ip, history[0].frag, history[0].where);
6856           }
6857         history[0] = *ip;
6858         delay.fixed_p = 1;
6859         insert_into_history (0, 1, &delay);
6860       }
6861       break;
6862     }
6863
6864   /* If we have just completed an unconditional branch, clear the history.  */
6865   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6866       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6867     {
6868       unsigned int i;
6869
6870       mips_no_prev_insn ();
6871
6872       for (i = 0; i < ARRAY_SIZE (history); i++)
6873         history[i].cleared_p = 1;
6874     }
6875
6876   /* We need to emit a label at the end of branch-likely macros.  */
6877   if (emit_branch_likely_macro)
6878     {
6879       emit_branch_likely_macro = FALSE;
6880       micromips_add_label ();
6881     }
6882
6883   /* We just output an insn, so the next one doesn't have a label.  */
6884   mips_clear_insn_labels ();
6885 }
6886
6887 /* Forget that there was any previous instruction or label.
6888    When BRANCH is true, the branch history is also flushed.  */
6889
6890 static void
6891 mips_no_prev_insn (void)
6892 {
6893   prev_nop_frag = NULL;
6894   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6895   mips_clear_insn_labels ();
6896 }
6897
6898 /* This function must be called before we emit something other than
6899    instructions.  It is like mips_no_prev_insn except that it inserts
6900    any NOPS that might be needed by previous instructions.  */
6901
6902 void
6903 mips_emit_delays (void)
6904 {
6905   if (! mips_opts.noreorder)
6906     {
6907       int nops = nops_for_insn (0, history, NULL);
6908       if (nops > 0)
6909         {
6910           while (nops-- > 0)
6911             add_fixed_insn (NOP_INSN);
6912           mips_move_text_labels ();
6913         }
6914     }
6915   mips_no_prev_insn ();
6916 }
6917
6918 /* Start a (possibly nested) noreorder block.  */
6919
6920 static void
6921 start_noreorder (void)
6922 {
6923   if (mips_opts.noreorder == 0)
6924     {
6925       unsigned int i;
6926       int nops;
6927
6928       /* None of the instructions before the .set noreorder can be moved.  */
6929       for (i = 0; i < ARRAY_SIZE (history); i++)
6930         history[i].fixed_p = 1;
6931
6932       /* Insert any nops that might be needed between the .set noreorder
6933          block and the previous instructions.  We will later remove any
6934          nops that turn out not to be needed.  */
6935       nops = nops_for_insn (0, history, NULL);
6936       if (nops > 0)
6937         {
6938           if (mips_optimize != 0)
6939             {
6940               /* Record the frag which holds the nop instructions, so
6941                  that we can remove them if we don't need them.  */
6942               frag_grow (nops * NOP_INSN_SIZE);
6943               prev_nop_frag = frag_now;
6944               prev_nop_frag_holds = nops;
6945               prev_nop_frag_required = 0;
6946               prev_nop_frag_since = 0;
6947             }
6948
6949           for (; nops > 0; --nops)
6950             add_fixed_insn (NOP_INSN);
6951
6952           /* Move on to a new frag, so that it is safe to simply
6953              decrease the size of prev_nop_frag.  */
6954           frag_wane (frag_now);
6955           frag_new (0);
6956           mips_move_text_labels ();
6957         }
6958       mips_mark_labels ();
6959       mips_clear_insn_labels ();
6960     }
6961   mips_opts.noreorder++;
6962   mips_any_noreorder = 1;
6963 }
6964
6965 /* End a nested noreorder block.  */
6966
6967 static void
6968 end_noreorder (void)
6969 {
6970   mips_opts.noreorder--;
6971   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6972     {
6973       /* Commit to inserting prev_nop_frag_required nops and go back to
6974          handling nop insertion the .set reorder way.  */
6975       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6976                                 * NOP_INSN_SIZE);
6977       insert_into_history (prev_nop_frag_since,
6978                            prev_nop_frag_required, NOP_INSN);
6979       prev_nop_frag = NULL;
6980     }
6981 }
6982
6983 /* Sign-extend 32-bit mode constants that have bit 31 set and all
6984    higher bits unset.  */
6985
6986 static void
6987 normalize_constant_expr (expressionS *ex)
6988 {
6989   if (ex->X_op == O_constant
6990       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6991     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6992                         - 0x80000000);
6993 }
6994
6995 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
6996    all higher bits unset.  */
6997
6998 static void
6999 normalize_address_expr (expressionS *ex)
7000 {
7001   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7002         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7003       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7004     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7005                         - 0x80000000);
7006 }
7007
7008 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7009    Return true if the match was successful.
7010
7011    OPCODE_EXTRA is a value that should be ORed into the opcode
7012    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7013    there are more alternatives after OPCODE and SOFT_MATCH is
7014    as for mips_arg_info.  */
7015
7016 static bfd_boolean
7017 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7018             struct mips_operand_token *tokens, unsigned int opcode_extra,
7019             bfd_boolean lax_match, bfd_boolean complete_p)
7020 {
7021   const char *args;
7022   struct mips_arg_info arg;
7023   const struct mips_operand *operand;
7024   char c;
7025
7026   imm_expr.X_op = O_absent;
7027   imm2_expr.X_op = O_absent;
7028   offset_expr.X_op = O_absent;
7029   offset_reloc[0] = BFD_RELOC_UNUSED;
7030   offset_reloc[1] = BFD_RELOC_UNUSED;
7031   offset_reloc[2] = BFD_RELOC_UNUSED;
7032
7033   create_insn (insn, opcode);
7034   /* When no opcode suffix is specified, assume ".xyzw". */
7035   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7036     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7037   else
7038     insn->insn_opcode |= opcode_extra;
7039   memset (&arg, 0, sizeof (arg));
7040   arg.insn = insn;
7041   arg.token = tokens;
7042   arg.argnum = 1;
7043   arg.last_regno = ILLEGAL_REG;
7044   arg.dest_regno = ILLEGAL_REG;
7045   arg.lax_match = lax_match;
7046   for (args = opcode->args;; ++args)
7047     {
7048       if (arg.token->type == OT_END)
7049         {
7050           /* Handle unary instructions in which only one operand is given.
7051              The source is then the same as the destination.  */
7052           if (arg.opnum == 1 && *args == ',')
7053             {
7054               operand = (mips_opts.micromips
7055                          ? decode_micromips_operand (args + 1)
7056                          : decode_mips_operand (args + 1));
7057               if (operand && mips_optional_operand_p (operand))
7058                 {
7059                   arg.token = tokens;
7060                   arg.argnum = 1;
7061                   continue;
7062                 }
7063             }
7064
7065           /* Treat elided base registers as $0.  */
7066           if (strcmp (args, "(b)") == 0)
7067             args += 3;
7068
7069           if (args[0] == '+')
7070             switch (args[1])
7071               {
7072               case 'K':
7073               case 'N':
7074                 /* The register suffix is optional. */
7075                 args += 2;
7076                 break;
7077               }
7078
7079           /* Fail the match if there were too few operands.  */
7080           if (*args)
7081             return FALSE;
7082
7083           /* Successful match.  */
7084           if (!complete_p)
7085             return TRUE;
7086           clear_insn_error ();
7087           if (arg.dest_regno == arg.last_regno
7088               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7089             {
7090               if (arg.opnum == 2)
7091                 set_insn_error
7092                   (0, _("Source and destination must be different"));
7093               else if (arg.last_regno == 31)
7094                 set_insn_error
7095                   (0, _("A destination register must be supplied"));
7096             }
7097           check_completed_insn (&arg);
7098           return TRUE;
7099         }
7100
7101       /* Fail the match if the line has too many operands.   */
7102       if (*args == 0)
7103         return FALSE;
7104
7105       /* Handle characters that need to match exactly.  */
7106       if (*args == '(' || *args == ')' || *args == ',')
7107         {
7108           if (match_char (&arg, *args))
7109             continue;
7110           return FALSE;
7111         }
7112       if (*args == '#')
7113         {
7114           ++args;
7115           if (arg.token->type == OT_DOUBLE_CHAR
7116               && arg.token->u.ch == *args)
7117             {
7118               ++arg.token;
7119               continue;
7120             }
7121           return FALSE;
7122         }
7123
7124       /* Handle special macro operands.  Work out the properties of
7125          other operands.  */
7126       arg.opnum += 1;
7127       switch (*args)
7128         {
7129         case '+':
7130           switch (args[1])
7131             {
7132             case 'I':
7133               /* "+I" is like "I", except that imm2_expr is used.  */
7134               if (!match_const_int (&arg, &imm2_expr.X_add_number))
7135                 return FALSE;
7136               imm2_expr.X_op = O_constant;
7137               if (HAVE_32BIT_GPRS)
7138                 normalize_constant_expr (&imm2_expr);
7139               ++args;
7140               continue;
7141
7142             case 'i':
7143               *offset_reloc = BFD_RELOC_MIPS_JMP;
7144               break;
7145             }
7146           break;
7147
7148         case 'I':
7149           if (!match_const_int (&arg, &imm_expr.X_add_number))
7150             return FALSE;
7151           imm_expr.X_op = O_constant;
7152           if (HAVE_32BIT_GPRS)
7153             normalize_constant_expr (&imm_expr);
7154           continue;
7155
7156         case 'A':
7157           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7158             {
7159               /* Assume that the offset has been elided and that what
7160                  we saw was a base register.  The match will fail later
7161                  if that assumption turns out to be wrong.  */
7162               offset_expr.X_op = O_constant;
7163               offset_expr.X_add_number = 0;
7164             }
7165           else
7166             {
7167               if (!match_expression (&arg, &offset_expr, offset_reloc))
7168                 return FALSE;
7169               normalize_address_expr (&offset_expr);
7170             }
7171           continue;
7172
7173         case 'F':
7174           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7175                                      8, TRUE))
7176             return FALSE;
7177           continue;
7178
7179         case 'L':
7180           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7181                                      8, FALSE))
7182             return FALSE;
7183           continue;
7184
7185         case 'f':
7186           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7187                                      4, TRUE))
7188             return FALSE;
7189           continue;
7190
7191         case 'l':
7192           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7193                                      4, FALSE))
7194             return FALSE;
7195           continue;
7196
7197         case 'p':
7198           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7199           break;
7200
7201         case 'a':
7202           *offset_reloc = BFD_RELOC_MIPS_JMP;
7203           break;
7204
7205         case 'm':
7206           gas_assert (mips_opts.micromips);
7207           c = args[1];
7208           switch (c)
7209             {
7210             case 'D':
7211             case 'E':
7212               if (!forced_insn_length)
7213                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7214               else if (c == 'D')
7215                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7216               else
7217                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7218               break;
7219             }
7220           break;
7221         }
7222
7223       operand = (mips_opts.micromips
7224                  ? decode_micromips_operand (args)
7225                  : decode_mips_operand (args));
7226       if (!operand)
7227         abort ();
7228
7229       /* Skip prefixes.  */
7230       if (*args == '+' || *args == 'm')
7231         args++;
7232
7233       if (mips_optional_operand_p (operand)
7234           && args[1] == ','
7235           && (arg.token[0].type != OT_REG
7236               || arg.token[1].type == OT_END))
7237         {
7238           /* Assume that the register has been elided and is the
7239              same as the first operand.  */
7240           arg.token = tokens;
7241           arg.argnum = 1;
7242         }
7243
7244       if (!match_operand (&arg, operand))
7245         return FALSE;
7246     }
7247 }
7248
7249 /* Like match_insn, but for MIPS16.  */
7250
7251 static bfd_boolean
7252 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7253                    struct mips_operand_token *tokens)
7254 {
7255   const char *args;
7256   const struct mips_operand *operand;
7257   const struct mips_operand *ext_operand;
7258   struct mips_arg_info arg;
7259   int relax_char;
7260
7261   create_insn (insn, opcode);
7262   imm_expr.X_op = O_absent;
7263   imm2_expr.X_op = O_absent;
7264   offset_expr.X_op = O_absent;
7265   offset_reloc[0] = BFD_RELOC_UNUSED;
7266   offset_reloc[1] = BFD_RELOC_UNUSED;
7267   offset_reloc[2] = BFD_RELOC_UNUSED;
7268   relax_char = 0;
7269
7270   memset (&arg, 0, sizeof (arg));
7271   arg.insn = insn;
7272   arg.token = tokens;
7273   arg.argnum = 1;
7274   arg.last_regno = ILLEGAL_REG;
7275   arg.dest_regno = ILLEGAL_REG;
7276   relax_char = 0;
7277   for (args = opcode->args;; ++args)
7278     {
7279       int c;
7280
7281       if (arg.token->type == OT_END)
7282         {
7283           offsetT value;
7284
7285           /* Handle unary instructions in which only one operand is given.
7286              The source is then the same as the destination.  */
7287           if (arg.opnum == 1 && *args == ',')
7288             {
7289               operand = decode_mips16_operand (args[1], FALSE);
7290               if (operand && mips_optional_operand_p (operand))
7291                 {
7292                   arg.token = tokens;
7293                   arg.argnum = 1;
7294                   continue;
7295                 }
7296             }
7297
7298           /* Fail the match if there were too few operands.  */
7299           if (*args)
7300             return FALSE;
7301
7302           /* Successful match.  Stuff the immediate value in now, if
7303              we can.  */
7304           clear_insn_error ();
7305           if (opcode->pinfo == INSN_MACRO)
7306             {
7307               gas_assert (relax_char == 0 || relax_char == 'p');
7308               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7309             }
7310           else if (relax_char
7311                    && offset_expr.X_op == O_constant
7312                    && calculate_reloc (*offset_reloc,
7313                                        offset_expr.X_add_number,
7314                                        &value))
7315             {
7316               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7317                             forced_insn_length, &insn->insn_opcode);
7318               offset_expr.X_op = O_absent;
7319               *offset_reloc = BFD_RELOC_UNUSED;
7320             }
7321           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7322             {
7323               if (forced_insn_length == 2)
7324                 set_insn_error (0, _("invalid unextended operand value"));
7325               forced_insn_length = 4;
7326               insn->insn_opcode |= MIPS16_EXTEND;
7327             }
7328           else if (relax_char)
7329             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7330
7331           check_completed_insn (&arg);
7332           return TRUE;
7333         }
7334
7335       /* Fail the match if the line has too many operands.   */
7336       if (*args == 0)
7337         return FALSE;
7338
7339       /* Handle characters that need to match exactly.  */
7340       if (*args == '(' || *args == ')' || *args == ',')
7341         {
7342           if (match_char (&arg, *args))
7343             continue;
7344           return FALSE;
7345         }
7346
7347       arg.opnum += 1;
7348       c = *args;
7349       switch (c)
7350         {
7351         case 'p':
7352         case 'q':
7353         case 'A':
7354         case 'B':
7355         case 'E':
7356           relax_char = c;
7357           break;
7358
7359         case 'I':
7360           if (!match_const_int (&arg, &imm_expr.X_add_number))
7361             return FALSE;
7362           imm_expr.X_op = O_constant;
7363           if (HAVE_32BIT_GPRS)
7364             normalize_constant_expr (&imm_expr);
7365           continue;
7366
7367         case 'a':
7368         case 'i':
7369           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7370           insn->insn_opcode <<= 16;
7371           break;
7372         }
7373
7374       operand = decode_mips16_operand (c, FALSE);
7375       if (!operand)
7376         abort ();
7377
7378       /* '6' is a special case.  It is used for BREAK and SDBBP,
7379          whose operands are only meaningful to the software that decodes
7380          them.  This means that there is no architectural reason why
7381          they cannot be prefixed by EXTEND, but in practice,
7382          exception handlers will only look at the instruction
7383          itself.  We therefore allow '6' to be extended when
7384          disassembling but not when assembling.  */
7385       if (operand->type != OP_PCREL && c != '6')
7386         {
7387           ext_operand = decode_mips16_operand (c, TRUE);
7388           if (operand != ext_operand)
7389             {
7390               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7391                 {
7392                   offset_expr.X_op = O_constant;
7393                   offset_expr.X_add_number = 0;
7394                   relax_char = c;
7395                   continue;
7396                 }
7397
7398               /* We need the OT_INTEGER check because some MIPS16
7399                  immediate variants are listed before the register ones.  */
7400               if (arg.token->type != OT_INTEGER
7401                   || !match_expression (&arg, &offset_expr, offset_reloc))
7402                 return FALSE;
7403
7404               /* '8' is used for SLTI(U) and has traditionally not
7405                  been allowed to take relocation operators.  */
7406               if (offset_reloc[0] != BFD_RELOC_UNUSED
7407                   && (ext_operand->size != 16 || c == '8'))
7408                 return FALSE;
7409
7410               relax_char = c;
7411               continue;
7412             }
7413         }
7414
7415       if (mips_optional_operand_p (operand)
7416           && args[1] == ','
7417           && (arg.token[0].type != OT_REG
7418               || arg.token[1].type == OT_END))
7419         {
7420           /* Assume that the register has been elided and is the
7421              same as the first operand.  */
7422           arg.token = tokens;
7423           arg.argnum = 1;
7424         }
7425
7426       if (!match_operand (&arg, operand))
7427         return FALSE;
7428     }
7429 }
7430
7431 /* Record that the current instruction is invalid for the current ISA.  */
7432
7433 static void
7434 match_invalid_for_isa (void)
7435 {
7436   set_insn_error_ss
7437     (0, _("Opcode not supported on this processor: %s (%s)"),
7438      mips_cpu_info_from_arch (mips_opts.arch)->name,
7439      mips_cpu_info_from_isa (mips_opts.isa)->name);
7440 }
7441
7442 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7443    Return true if a definite match or failure was found, storing any match
7444    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7445    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7446    tried and failed to match under normal conditions and now want to try a
7447    more relaxed match.  */
7448
7449 static bfd_boolean
7450 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7451              const struct mips_opcode *past, struct mips_operand_token *tokens,
7452              int opcode_extra, bfd_boolean lax_match)
7453 {
7454   const struct mips_opcode *opcode;
7455   const struct mips_opcode *invalid_delay_slot;
7456   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7457
7458   /* Search for a match, ignoring alternatives that don't satisfy the
7459      current ISA or forced_length.  */
7460   invalid_delay_slot = 0;
7461   seen_valid_for_isa = FALSE;
7462   seen_valid_for_size = FALSE;
7463   opcode = first;
7464   do
7465     {
7466       gas_assert (strcmp (opcode->name, first->name) == 0);
7467       if (is_opcode_valid (opcode))
7468         {
7469           seen_valid_for_isa = TRUE;
7470           if (is_size_valid (opcode))
7471             {
7472               bfd_boolean delay_slot_ok;
7473
7474               seen_valid_for_size = TRUE;
7475               delay_slot_ok = is_delay_slot_valid (opcode);
7476               if (match_insn (insn, opcode, tokens, opcode_extra,
7477                               lax_match, delay_slot_ok))
7478                 {
7479                   if (!delay_slot_ok)
7480                     {
7481                       if (!invalid_delay_slot)
7482                         invalid_delay_slot = opcode;
7483                     }
7484                   else
7485                     return TRUE;
7486                 }
7487             }
7488         }
7489       ++opcode;
7490     }
7491   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7492
7493   /* If the only matches we found had the wrong length for the delay slot,
7494      pick the first such match.  We'll issue an appropriate warning later.  */
7495   if (invalid_delay_slot)
7496     {
7497       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7498                       lax_match, TRUE))
7499         return TRUE;
7500       abort ();
7501     }
7502
7503   /* Handle the case where we didn't try to match an instruction because
7504      all the alternatives were incompatible with the current ISA.  */
7505   if (!seen_valid_for_isa)
7506     {
7507       match_invalid_for_isa ();
7508       return TRUE;
7509     }
7510
7511   /* Handle the case where we didn't try to match an instruction because
7512      all the alternatives were of the wrong size.  */
7513   if (!seen_valid_for_size)
7514     {
7515       if (mips_opts.insn32)
7516         set_insn_error (0, _("Opcode not supported in the `insn32' mode"));
7517       else
7518         set_insn_error_i
7519           (0, _("Unrecognized %d-bit version of microMIPS opcode"),
7520            8 * forced_insn_length);
7521       return TRUE;
7522     }
7523
7524   return FALSE;
7525 }
7526
7527 /* Like match_insns, but for MIPS16.  */
7528
7529 static bfd_boolean
7530 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7531                     struct mips_operand_token *tokens)
7532 {
7533   const struct mips_opcode *opcode;
7534   bfd_boolean seen_valid_for_isa;
7535
7536   /* Search for a match, ignoring alternatives that don't satisfy the
7537      current ISA.  There are no separate entries for extended forms so
7538      we deal with forced_length later.  */
7539   seen_valid_for_isa = FALSE;
7540   opcode = first;
7541   do
7542     {
7543       gas_assert (strcmp (opcode->name, first->name) == 0);
7544       if (is_opcode_valid_16 (opcode))
7545         {
7546           seen_valid_for_isa = TRUE;
7547           if (match_mips16_insn (insn, opcode, tokens))
7548             return TRUE;
7549         }
7550       ++opcode;
7551     }
7552   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7553          && strcmp (opcode->name, first->name) == 0);
7554
7555   /* Handle the case where we didn't try to match an instruction because
7556      all the alternatives were incompatible with the current ISA.  */
7557   if (!seen_valid_for_isa)
7558     {
7559       match_invalid_for_isa ();
7560       return TRUE;
7561     }
7562
7563   return FALSE;
7564 }
7565
7566 /* Set up global variables for the start of a new macro.  */
7567
7568 static void
7569 macro_start (void)
7570 {
7571   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7572   memset (&mips_macro_warning.first_insn_sizes, 0,
7573           sizeof (mips_macro_warning.first_insn_sizes));
7574   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7575   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7576                                      && delayed_branch_p (&history[0]));
7577   switch (history[0].insn_mo->pinfo2
7578           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7579     {
7580     case INSN2_BRANCH_DELAY_32BIT:
7581       mips_macro_warning.delay_slot_length = 4;
7582       break;
7583     case INSN2_BRANCH_DELAY_16BIT:
7584       mips_macro_warning.delay_slot_length = 2;
7585       break;
7586     default:
7587       mips_macro_warning.delay_slot_length = 0;
7588       break;
7589     }
7590   mips_macro_warning.first_frag = NULL;
7591 }
7592
7593 /* Given that a macro is longer than one instruction or of the wrong size,
7594    return the appropriate warning for it.  Return null if no warning is
7595    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7596    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7597    and RELAX_NOMACRO.  */
7598
7599 static const char *
7600 macro_warning (relax_substateT subtype)
7601 {
7602   if (subtype & RELAX_DELAY_SLOT)
7603     return _("Macro instruction expanded into multiple instructions"
7604              " in a branch delay slot");
7605   else if (subtype & RELAX_NOMACRO)
7606     return _("Macro instruction expanded into multiple instructions");
7607   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7608                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7609     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7610             ? _("Macro instruction expanded into a wrong size instruction"
7611                 " in a 16-bit branch delay slot")
7612             : _("Macro instruction expanded into a wrong size instruction"
7613                 " in a 32-bit branch delay slot"));
7614   else
7615     return 0;
7616 }
7617
7618 /* Finish up a macro.  Emit warnings as appropriate.  */
7619
7620 static void
7621 macro_end (void)
7622 {
7623   /* Relaxation warning flags.  */
7624   relax_substateT subtype = 0;
7625
7626   /* Check delay slot size requirements.  */
7627   if (mips_macro_warning.delay_slot_length == 2)
7628     subtype |= RELAX_DELAY_SLOT_16BIT;
7629   if (mips_macro_warning.delay_slot_length != 0)
7630     {
7631       if (mips_macro_warning.delay_slot_length
7632           != mips_macro_warning.first_insn_sizes[0])
7633         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7634       if (mips_macro_warning.delay_slot_length
7635           != mips_macro_warning.first_insn_sizes[1])
7636         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7637     }
7638
7639   /* Check instruction count requirements.  */
7640   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7641     {
7642       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7643         subtype |= RELAX_SECOND_LONGER;
7644       if (mips_opts.warn_about_macros)
7645         subtype |= RELAX_NOMACRO;
7646       if (mips_macro_warning.delay_slot_p)
7647         subtype |= RELAX_DELAY_SLOT;
7648     }
7649
7650   /* If both alternatives fail to fill a delay slot correctly,
7651      emit the warning now.  */
7652   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7653       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7654     {
7655       relax_substateT s;
7656       const char *msg;
7657
7658       s = subtype & (RELAX_DELAY_SLOT_16BIT
7659                      | RELAX_DELAY_SLOT_SIZE_FIRST
7660                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7661       msg = macro_warning (s);
7662       if (msg != NULL)
7663         as_warn ("%s", msg);
7664       subtype &= ~s;
7665     }
7666
7667   /* If both implementations are longer than 1 instruction, then emit the
7668      warning now.  */
7669   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7670     {
7671       relax_substateT s;
7672       const char *msg;
7673
7674       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7675       msg = macro_warning (s);
7676       if (msg != NULL)
7677         as_warn ("%s", msg);
7678       subtype &= ~s;
7679     }
7680
7681   /* If any flags still set, then one implementation might need a warning
7682      and the other either will need one of a different kind or none at all.
7683      Pass any remaining flags over to relaxation.  */
7684   if (mips_macro_warning.first_frag != NULL)
7685     mips_macro_warning.first_frag->fr_subtype |= subtype;
7686 }
7687
7688 /* Instruction operand formats used in macros that vary between
7689    standard MIPS and microMIPS code.  */
7690
7691 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7692 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7693 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7694 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7695 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7696 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7697 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7698 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7699
7700 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7701 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7702 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7703 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7704 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7705 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7706 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7707 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7708
7709 /* Read a macro's relocation codes from *ARGS and store them in *R.
7710    The first argument in *ARGS will be either the code for a single
7711    relocation or -1 followed by the three codes that make up a
7712    composite relocation.  */
7713
7714 static void
7715 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7716 {
7717   int i, next;
7718
7719   next = va_arg (*args, int);
7720   if (next >= 0)
7721     r[0] = (bfd_reloc_code_real_type) next;
7722   else
7723     {
7724       for (i = 0; i < 3; i++)
7725         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7726       /* This function is only used for 16-bit relocation fields.
7727          To make the macro code simpler, treat an unrelocated value
7728          in the same way as BFD_RELOC_LO16.  */
7729       if (r[0] == BFD_RELOC_UNUSED)
7730         r[0] = BFD_RELOC_LO16;
7731     }
7732 }
7733
7734 /* Build an instruction created by a macro expansion.  This is passed
7735    a pointer to the count of instructions created so far, an
7736    expression, the name of the instruction to build, an operand format
7737    string, and corresponding arguments.  */
7738
7739 static void
7740 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7741 {
7742   const struct mips_opcode *mo = NULL;
7743   bfd_reloc_code_real_type r[3];
7744   const struct mips_opcode *amo;
7745   const struct mips_operand *operand;
7746   struct hash_control *hash;
7747   struct mips_cl_insn insn;
7748   va_list args;
7749   unsigned int uval;
7750
7751   va_start (args, fmt);
7752
7753   if (mips_opts.mips16)
7754     {
7755       mips16_macro_build (ep, name, fmt, &args);
7756       va_end (args);
7757       return;
7758     }
7759
7760   r[0] = BFD_RELOC_UNUSED;
7761   r[1] = BFD_RELOC_UNUSED;
7762   r[2] = BFD_RELOC_UNUSED;
7763   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7764   amo = (struct mips_opcode *) hash_find (hash, name);
7765   gas_assert (amo);
7766   gas_assert (strcmp (name, amo->name) == 0);
7767
7768   do
7769     {
7770       /* Search until we get a match for NAME.  It is assumed here that
7771          macros will never generate MDMX, MIPS-3D, or MT instructions.
7772          We try to match an instruction that fulfils the branch delay
7773          slot instruction length requirement (if any) of the previous
7774          instruction.  While doing this we record the first instruction
7775          seen that matches all the other conditions and use it anyway
7776          if the requirement cannot be met; we will issue an appropriate
7777          warning later on.  */
7778       if (strcmp (fmt, amo->args) == 0
7779           && amo->pinfo != INSN_MACRO
7780           && is_opcode_valid (amo)
7781           && is_size_valid (amo))
7782         {
7783           if (is_delay_slot_valid (amo))
7784             {
7785               mo = amo;
7786               break;
7787             }
7788           else if (!mo)
7789             mo = amo;
7790         }
7791
7792       ++amo;
7793       gas_assert (amo->name);
7794     }
7795   while (strcmp (name, amo->name) == 0);
7796
7797   gas_assert (mo);
7798   create_insn (&insn, mo);
7799   for (; *fmt; ++fmt)
7800     {
7801       switch (*fmt)
7802         {
7803         case ',':
7804         case '(':
7805         case ')':
7806         case 'z':
7807           break;
7808
7809         case 'i':
7810         case 'j':
7811           macro_read_relocs (&args, r);
7812           gas_assert (*r == BFD_RELOC_GPREL16
7813                       || *r == BFD_RELOC_MIPS_HIGHER
7814                       || *r == BFD_RELOC_HI16_S
7815                       || *r == BFD_RELOC_LO16
7816                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7817           break;
7818
7819         case 'o':
7820           macro_read_relocs (&args, r);
7821           break;
7822
7823         case 'u':
7824           macro_read_relocs (&args, r);
7825           gas_assert (ep != NULL
7826                       && (ep->X_op == O_constant
7827                           || (ep->X_op == O_symbol
7828                               && (*r == BFD_RELOC_MIPS_HIGHEST
7829                                   || *r == BFD_RELOC_HI16_S
7830                                   || *r == BFD_RELOC_HI16
7831                                   || *r == BFD_RELOC_GPREL16
7832                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7833                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7834           break;
7835
7836         case 'p':
7837           gas_assert (ep != NULL);
7838
7839           /*
7840            * This allows macro() to pass an immediate expression for
7841            * creating short branches without creating a symbol.
7842            *
7843            * We don't allow branch relaxation for these branches, as
7844            * they should only appear in ".set nomacro" anyway.
7845            */
7846           if (ep->X_op == O_constant)
7847             {
7848               /* For microMIPS we always use relocations for branches.
7849                  So we should not resolve immediate values.  */
7850               gas_assert (!mips_opts.micromips);
7851
7852               if ((ep->X_add_number & 3) != 0)
7853                 as_bad (_("branch to misaligned address (0x%lx)"),
7854                         (unsigned long) ep->X_add_number);
7855               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7856                 as_bad (_("branch address range overflow (0x%lx)"),
7857                         (unsigned long) ep->X_add_number);
7858               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7859               ep = NULL;
7860             }
7861           else
7862             *r = BFD_RELOC_16_PCREL_S2;
7863           break;
7864
7865         case 'a':
7866           gas_assert (ep != NULL);
7867           *r = BFD_RELOC_MIPS_JMP;
7868           break;
7869
7870         default:
7871           operand = (mips_opts.micromips
7872                      ? decode_micromips_operand (fmt)
7873                      : decode_mips_operand (fmt));
7874           if (!operand)
7875             abort ();
7876
7877           uval = va_arg (args, int);
7878           if (operand->type == OP_CLO_CLZ_DEST)
7879             uval |= (uval << 5);
7880           insn_insert_operand (&insn, operand, uval);
7881
7882           if (*fmt == '+' || *fmt == 'm')
7883             ++fmt;
7884           break;
7885         }
7886     }
7887   va_end (args);
7888   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7889
7890   append_insn (&insn, ep, r, TRUE);
7891 }
7892
7893 static void
7894 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7895                     va_list *args)
7896 {
7897   struct mips_opcode *mo;
7898   struct mips_cl_insn insn;
7899   const struct mips_operand *operand;
7900   bfd_reloc_code_real_type r[3]
7901     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7902
7903   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7904   gas_assert (mo);
7905   gas_assert (strcmp (name, mo->name) == 0);
7906
7907   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
7908     {
7909       ++mo;
7910       gas_assert (mo->name);
7911       gas_assert (strcmp (name, mo->name) == 0);
7912     }
7913
7914   create_insn (&insn, mo);
7915   for (; *fmt; ++fmt)
7916     {
7917       int c;
7918
7919       c = *fmt;
7920       switch (c)
7921         {
7922         case ',':
7923         case '(':
7924         case ')':
7925           break;
7926
7927         case '0':
7928         case 'S':
7929         case 'P':
7930         case 'R':
7931           break;
7932
7933         case '<':
7934         case '>':
7935         case '4':
7936         case '5':
7937         case 'H':
7938         case 'W':
7939         case 'D':
7940         case 'j':
7941         case '8':
7942         case 'V':
7943         case 'C':
7944         case 'U':
7945         case 'k':
7946         case 'K':
7947         case 'p':
7948         case 'q':
7949           {
7950             offsetT value;
7951
7952             gas_assert (ep != NULL);
7953
7954             if (ep->X_op != O_constant)
7955               *r = (int) BFD_RELOC_UNUSED + c;
7956             else if (calculate_reloc (*r, ep->X_add_number, &value))
7957               {
7958                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
7959                 ep = NULL;
7960                 *r = BFD_RELOC_UNUSED;
7961               }
7962           }
7963           break;
7964
7965         default:
7966           operand = decode_mips16_operand (c, FALSE);
7967           if (!operand)
7968             abort ();
7969
7970           insn_insert_operand (&insn, operand, va_arg (*args, int));
7971           break;
7972         }
7973     }
7974
7975   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7976
7977   append_insn (&insn, ep, r, TRUE);
7978 }
7979
7980 /*
7981  * Generate a "jalr" instruction with a relocation hint to the called
7982  * function.  This occurs in NewABI PIC code.
7983  */
7984 static void
7985 macro_build_jalr (expressionS *ep, int cprestore)
7986 {
7987   static const bfd_reloc_code_real_type jalr_relocs[2]
7988     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
7989   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
7990   const char *jalr;
7991   char *f = NULL;
7992
7993   if (MIPS_JALR_HINT_P (ep))
7994     {
7995       frag_grow (8);
7996       f = frag_more (0);
7997     }
7998   if (mips_opts.micromips)
7999     {
8000       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8001               ? "jalr" : "jalrs");
8002       if (MIPS_JALR_HINT_P (ep)
8003           || mips_opts.insn32
8004           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8005         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8006       else
8007         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8008     }
8009   else
8010     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8011   if (MIPS_JALR_HINT_P (ep))
8012     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8013 }
8014
8015 /*
8016  * Generate a "lui" instruction.
8017  */
8018 static void
8019 macro_build_lui (expressionS *ep, int regnum)
8020 {
8021   gas_assert (! mips_opts.mips16);
8022
8023   if (ep->X_op != O_constant)
8024     {
8025       gas_assert (ep->X_op == O_symbol);
8026       /* _gp_disp is a special case, used from s_cpload.
8027          __gnu_local_gp is used if mips_no_shared.  */
8028       gas_assert (mips_pic == NO_PIC
8029               || (! HAVE_NEWABI
8030                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8031               || (! mips_in_shared
8032                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8033                              "__gnu_local_gp") == 0));
8034     }
8035
8036   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8037 }
8038
8039 /* Generate a sequence of instructions to do a load or store from a constant
8040    offset off of a base register (breg) into/from a target register (treg),
8041    using AT if necessary.  */
8042 static void
8043 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8044                               int treg, int breg, int dbl)
8045 {
8046   gas_assert (ep->X_op == O_constant);
8047
8048   /* Sign-extending 32-bit constants makes their handling easier.  */
8049   if (!dbl)
8050     normalize_constant_expr (ep);
8051
8052   /* Right now, this routine can only handle signed 32-bit constants.  */
8053   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8054     as_warn (_("operand overflow"));
8055
8056   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8057     {
8058       /* Signed 16-bit offset will fit in the op.  Easy!  */
8059       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8060     }
8061   else
8062     {
8063       /* 32-bit offset, need multiple instructions and AT, like:
8064            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8065            addu     $tempreg,$tempreg,$breg
8066            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8067          to handle the complete offset.  */
8068       macro_build_lui (ep, AT);
8069       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8070       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8071
8072       if (!mips_opts.at)
8073         as_bad (_("Macro used $at after \".set noat\""));
8074     }
8075 }
8076
8077 /*                      set_at()
8078  * Generates code to set the $at register to true (one)
8079  * if reg is less than the immediate expression.
8080  */
8081 static void
8082 set_at (int reg, int unsignedp)
8083 {
8084   if (imm_expr.X_op == O_constant
8085       && imm_expr.X_add_number >= -0x8000
8086       && imm_expr.X_add_number < 0x8000)
8087     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8088                  AT, reg, BFD_RELOC_LO16);
8089   else
8090     {
8091       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8092       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8093     }
8094 }
8095
8096 /* Count the leading zeroes by performing a binary chop. This is a
8097    bulky bit of source, but performance is a LOT better for the
8098    majority of values than a simple loop to count the bits:
8099        for (lcnt = 0; (lcnt < 32); lcnt++)
8100          if ((v) & (1 << (31 - lcnt)))
8101            break;
8102   However it is not code size friendly, and the gain will drop a bit
8103   on certain cached systems.
8104 */
8105 #define COUNT_TOP_ZEROES(v)             \
8106   (((v) & ~0xffff) == 0                 \
8107    ? ((v) & ~0xff) == 0                 \
8108      ? ((v) & ~0xf) == 0                \
8109        ? ((v) & ~0x3) == 0              \
8110          ? ((v) & ~0x1) == 0            \
8111            ? !(v)                       \
8112              ? 32                       \
8113              : 31                       \
8114            : 30                         \
8115          : ((v) & ~0x7) == 0            \
8116            ? 29                         \
8117            : 28                         \
8118        : ((v) & ~0x3f) == 0             \
8119          ? ((v) & ~0x1f) == 0           \
8120            ? 27                         \
8121            : 26                         \
8122          : ((v) & ~0x7f) == 0           \
8123            ? 25                         \
8124            : 24                         \
8125      : ((v) & ~0xfff) == 0              \
8126        ? ((v) & ~0x3ff) == 0            \
8127          ? ((v) & ~0x1ff) == 0          \
8128            ? 23                         \
8129            : 22                         \
8130          : ((v) & ~0x7ff) == 0          \
8131            ? 21                         \
8132            : 20                         \
8133        : ((v) & ~0x3fff) == 0           \
8134          ? ((v) & ~0x1fff) == 0         \
8135            ? 19                         \
8136            : 18                         \
8137          : ((v) & ~0x7fff) == 0         \
8138            ? 17                         \
8139            : 16                         \
8140    : ((v) & ~0xffffff) == 0             \
8141      ? ((v) & ~0xfffff) == 0            \
8142        ? ((v) & ~0x3ffff) == 0          \
8143          ? ((v) & ~0x1ffff) == 0        \
8144            ? 15                         \
8145            : 14                         \
8146          : ((v) & ~0x7ffff) == 0        \
8147            ? 13                         \
8148            : 12                         \
8149        : ((v) & ~0x3fffff) == 0         \
8150          ? ((v) & ~0x1fffff) == 0       \
8151            ? 11                         \
8152            : 10                         \
8153          : ((v) & ~0x7fffff) == 0       \
8154            ? 9                          \
8155            : 8                          \
8156      : ((v) & ~0xfffffff) == 0          \
8157        ? ((v) & ~0x3ffffff) == 0        \
8158          ? ((v) & ~0x1ffffff) == 0      \
8159            ? 7                          \
8160            : 6                          \
8161          : ((v) & ~0x7ffffff) == 0      \
8162            ? 5                          \
8163            : 4                          \
8164        : ((v) & ~0x3fffffff) == 0       \
8165          ? ((v) & ~0x1fffffff) == 0     \
8166            ? 3                          \
8167            : 2                          \
8168          : ((v) & ~0x7fffffff) == 0     \
8169            ? 1                          \
8170            : 0)
8171
8172 /*                      load_register()
8173  *  This routine generates the least number of instructions necessary to load
8174  *  an absolute expression value into a register.
8175  */
8176 static void
8177 load_register (int reg, expressionS *ep, int dbl)
8178 {
8179   int freg;
8180   expressionS hi32, lo32;
8181
8182   if (ep->X_op != O_big)
8183     {
8184       gas_assert (ep->X_op == O_constant);
8185
8186       /* Sign-extending 32-bit constants makes their handling easier.  */
8187       if (!dbl)
8188         normalize_constant_expr (ep);
8189
8190       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8191         {
8192           /* We can handle 16 bit signed values with an addiu to
8193              $zero.  No need to ever use daddiu here, since $zero and
8194              the result are always correct in 32 bit mode.  */
8195           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8196           return;
8197         }
8198       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8199         {
8200           /* We can handle 16 bit unsigned values with an ori to
8201              $zero.  */
8202           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8203           return;
8204         }
8205       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8206         {
8207           /* 32 bit values require an lui.  */
8208           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8209           if ((ep->X_add_number & 0xffff) != 0)
8210             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8211           return;
8212         }
8213     }
8214
8215   /* The value is larger than 32 bits.  */
8216
8217   if (!dbl || HAVE_32BIT_GPRS)
8218     {
8219       char value[32];
8220
8221       sprintf_vma (value, ep->X_add_number);
8222       as_bad (_("Number (0x%s) larger than 32 bits"), value);
8223       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8224       return;
8225     }
8226
8227   if (ep->X_op != O_big)
8228     {
8229       hi32 = *ep;
8230       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8231       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8232       hi32.X_add_number &= 0xffffffff;
8233       lo32 = *ep;
8234       lo32.X_add_number &= 0xffffffff;
8235     }
8236   else
8237     {
8238       gas_assert (ep->X_add_number > 2);
8239       if (ep->X_add_number == 3)
8240         generic_bignum[3] = 0;
8241       else if (ep->X_add_number > 4)
8242         as_bad (_("Number larger than 64 bits"));
8243       lo32.X_op = O_constant;
8244       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8245       hi32.X_op = O_constant;
8246       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8247     }
8248
8249   if (hi32.X_add_number == 0)
8250     freg = 0;
8251   else
8252     {
8253       int shift, bit;
8254       unsigned long hi, lo;
8255
8256       if (hi32.X_add_number == (offsetT) 0xffffffff)
8257         {
8258           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8259             {
8260               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8261               return;
8262             }
8263           if (lo32.X_add_number & 0x80000000)
8264             {
8265               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8266               if (lo32.X_add_number & 0xffff)
8267                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8268               return;
8269             }
8270         }
8271
8272       /* Check for 16bit shifted constant.  We know that hi32 is
8273          non-zero, so start the mask on the first bit of the hi32
8274          value.  */
8275       shift = 17;
8276       do
8277         {
8278           unsigned long himask, lomask;
8279
8280           if (shift < 32)
8281             {
8282               himask = 0xffff >> (32 - shift);
8283               lomask = (0xffff << shift) & 0xffffffff;
8284             }
8285           else
8286             {
8287               himask = 0xffff << (shift - 32);
8288               lomask = 0;
8289             }
8290           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8291               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8292             {
8293               expressionS tmp;
8294
8295               tmp.X_op = O_constant;
8296               if (shift < 32)
8297                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8298                                     | (lo32.X_add_number >> shift));
8299               else
8300                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8301               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8302               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8303                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8304               return;
8305             }
8306           ++shift;
8307         }
8308       while (shift <= (64 - 16));
8309
8310       /* Find the bit number of the lowest one bit, and store the
8311          shifted value in hi/lo.  */
8312       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8313       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8314       if (lo != 0)
8315         {
8316           bit = 0;
8317           while ((lo & 1) == 0)
8318             {
8319               lo >>= 1;
8320               ++bit;
8321             }
8322           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8323           hi >>= bit;
8324         }
8325       else
8326         {
8327           bit = 32;
8328           while ((hi & 1) == 0)
8329             {
8330               hi >>= 1;
8331               ++bit;
8332             }
8333           lo = hi;
8334           hi = 0;
8335         }
8336
8337       /* Optimize if the shifted value is a (power of 2) - 1.  */
8338       if ((hi == 0 && ((lo + 1) & lo) == 0)
8339           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8340         {
8341           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8342           if (shift != 0)
8343             {
8344               expressionS tmp;
8345
8346               /* This instruction will set the register to be all
8347                  ones.  */
8348               tmp.X_op = O_constant;
8349               tmp.X_add_number = (offsetT) -1;
8350               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8351               if (bit != 0)
8352                 {
8353                   bit += shift;
8354                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8355                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8356                 }
8357               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8358                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8359               return;
8360             }
8361         }
8362
8363       /* Sign extend hi32 before calling load_register, because we can
8364          generally get better code when we load a sign extended value.  */
8365       if ((hi32.X_add_number & 0x80000000) != 0)
8366         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8367       load_register (reg, &hi32, 0);
8368       freg = reg;
8369     }
8370   if ((lo32.X_add_number & 0xffff0000) == 0)
8371     {
8372       if (freg != 0)
8373         {
8374           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8375           freg = reg;
8376         }
8377     }
8378   else
8379     {
8380       expressionS mid16;
8381
8382       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8383         {
8384           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8385           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8386           return;
8387         }
8388
8389       if (freg != 0)
8390         {
8391           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8392           freg = reg;
8393         }
8394       mid16 = lo32;
8395       mid16.X_add_number >>= 16;
8396       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8397       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8398       freg = reg;
8399     }
8400   if ((lo32.X_add_number & 0xffff) != 0)
8401     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8402 }
8403
8404 static inline void
8405 load_delay_nop (void)
8406 {
8407   if (!gpr_interlocks)
8408     macro_build (NULL, "nop", "");
8409 }
8410
8411 /* Load an address into a register.  */
8412
8413 static void
8414 load_address (int reg, expressionS *ep, int *used_at)
8415 {
8416   if (ep->X_op != O_constant
8417       && ep->X_op != O_symbol)
8418     {
8419       as_bad (_("expression too complex"));
8420       ep->X_op = O_constant;
8421     }
8422
8423   if (ep->X_op == O_constant)
8424     {
8425       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8426       return;
8427     }
8428
8429   if (mips_pic == NO_PIC)
8430     {
8431       /* If this is a reference to a GP relative symbol, we want
8432            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8433          Otherwise we want
8434            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8435            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8436          If we have an addend, we always use the latter form.
8437
8438          With 64bit address space and a usable $at we want
8439            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8440            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8441            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8442            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8443            dsll32       $reg,0
8444            daddu        $reg,$reg,$at
8445
8446          If $at is already in use, we use a path which is suboptimal
8447          on superscalar processors.
8448            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8449            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8450            dsll         $reg,16
8451            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8452            dsll         $reg,16
8453            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8454
8455          For GP relative symbols in 64bit address space we can use
8456          the same sequence as in 32bit address space.  */
8457       if (HAVE_64BIT_SYMBOLS)
8458         {
8459           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8460               && !nopic_need_relax (ep->X_add_symbol, 1))
8461             {
8462               relax_start (ep->X_add_symbol);
8463               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8464                            mips_gp_register, BFD_RELOC_GPREL16);
8465               relax_switch ();
8466             }
8467
8468           if (*used_at == 0 && mips_opts.at)
8469             {
8470               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8471               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8472               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8473                            BFD_RELOC_MIPS_HIGHER);
8474               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8475               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8476               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8477               *used_at = 1;
8478             }
8479           else
8480             {
8481               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8482               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8483                            BFD_RELOC_MIPS_HIGHER);
8484               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8485               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8486               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8487               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8488             }
8489
8490           if (mips_relax.sequence)
8491             relax_end ();
8492         }
8493       else
8494         {
8495           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8496               && !nopic_need_relax (ep->X_add_symbol, 1))
8497             {
8498               relax_start (ep->X_add_symbol);
8499               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8500                            mips_gp_register, BFD_RELOC_GPREL16);
8501               relax_switch ();
8502             }
8503           macro_build_lui (ep, reg);
8504           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8505                        reg, reg, BFD_RELOC_LO16);
8506           if (mips_relax.sequence)
8507             relax_end ();
8508         }
8509     }
8510   else if (!mips_big_got)
8511     {
8512       expressionS ex;
8513
8514       /* If this is a reference to an external symbol, we want
8515            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8516          Otherwise we want
8517            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8518            nop
8519            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8520          If there is a constant, it must be added in after.
8521
8522          If we have NewABI, we want
8523            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8524          unless we're referencing a global symbol with a non-zero
8525          offset, in which case cst must be added separately.  */
8526       if (HAVE_NEWABI)
8527         {
8528           if (ep->X_add_number)
8529             {
8530               ex.X_add_number = ep->X_add_number;
8531               ep->X_add_number = 0;
8532               relax_start (ep->X_add_symbol);
8533               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8534                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8535               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8536                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8537               ex.X_op = O_constant;
8538               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8539                            reg, reg, BFD_RELOC_LO16);
8540               ep->X_add_number = ex.X_add_number;
8541               relax_switch ();
8542             }
8543           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8544                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8545           if (mips_relax.sequence)
8546             relax_end ();
8547         }
8548       else
8549         {
8550           ex.X_add_number = ep->X_add_number;
8551           ep->X_add_number = 0;
8552           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8553                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8554           load_delay_nop ();
8555           relax_start (ep->X_add_symbol);
8556           relax_switch ();
8557           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8558                        BFD_RELOC_LO16);
8559           relax_end ();
8560
8561           if (ex.X_add_number != 0)
8562             {
8563               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8564                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8565               ex.X_op = O_constant;
8566               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8567                            reg, reg, BFD_RELOC_LO16);
8568             }
8569         }
8570     }
8571   else if (mips_big_got)
8572     {
8573       expressionS ex;
8574
8575       /* This is the large GOT case.  If this is a reference to an
8576          external symbol, we want
8577            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8578            addu         $reg,$reg,$gp
8579            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8580
8581          Otherwise, for a reference to a local symbol in old ABI, we want
8582            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8583            nop
8584            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8585          If there is a constant, it must be added in after.
8586
8587          In the NewABI, for local symbols, with or without offsets, we want:
8588            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8589            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8590       */
8591       if (HAVE_NEWABI)
8592         {
8593           ex.X_add_number = ep->X_add_number;
8594           ep->X_add_number = 0;
8595           relax_start (ep->X_add_symbol);
8596           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8597           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8598                        reg, reg, mips_gp_register);
8599           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8600                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8601           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8602             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8603           else if (ex.X_add_number)
8604             {
8605               ex.X_op = O_constant;
8606               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8607                            BFD_RELOC_LO16);
8608             }
8609
8610           ep->X_add_number = ex.X_add_number;
8611           relax_switch ();
8612           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8613                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8614           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8615                        BFD_RELOC_MIPS_GOT_OFST);
8616           relax_end ();
8617         }
8618       else
8619         {
8620           ex.X_add_number = ep->X_add_number;
8621           ep->X_add_number = 0;
8622           relax_start (ep->X_add_symbol);
8623           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8624           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8625                        reg, reg, mips_gp_register);
8626           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8627                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8628           relax_switch ();
8629           if (reg_needs_delay (mips_gp_register))
8630             {
8631               /* We need a nop before loading from $gp.  This special
8632                  check is required because the lui which starts the main
8633                  instruction stream does not refer to $gp, and so will not
8634                  insert the nop which may be required.  */
8635               macro_build (NULL, "nop", "");
8636             }
8637           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8638                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8639           load_delay_nop ();
8640           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8641                        BFD_RELOC_LO16);
8642           relax_end ();
8643
8644           if (ex.X_add_number != 0)
8645             {
8646               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8647                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8648               ex.X_op = O_constant;
8649               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8650                            BFD_RELOC_LO16);
8651             }
8652         }
8653     }
8654   else
8655     abort ();
8656
8657   if (!mips_opts.at && *used_at == 1)
8658     as_bad (_("Macro used $at after \".set noat\""));
8659 }
8660
8661 /* Move the contents of register SOURCE into register DEST.  */
8662
8663 static void
8664 move_register (int dest, int source)
8665 {
8666   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8667      instruction specifically requires a 32-bit one.  */
8668   if (mips_opts.micromips
8669       && !mips_opts.insn32
8670       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8671     macro_build (NULL, "move", "mp,mj", dest, source);
8672   else
8673     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8674                  dest, source, 0);
8675 }
8676
8677 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8678    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8679    The two alternatives are:
8680
8681    Global symbol                Local sybmol
8682    -------------                ------------
8683    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8684    ...                          ...
8685    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8686
8687    load_got_offset emits the first instruction and add_got_offset
8688    emits the second for a 16-bit offset or add_got_offset_hilo emits
8689    a sequence to add a 32-bit offset using a scratch register.  */
8690
8691 static void
8692 load_got_offset (int dest, expressionS *local)
8693 {
8694   expressionS global;
8695
8696   global = *local;
8697   global.X_add_number = 0;
8698
8699   relax_start (local->X_add_symbol);
8700   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8701                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8702   relax_switch ();
8703   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8704                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8705   relax_end ();
8706 }
8707
8708 static void
8709 add_got_offset (int dest, expressionS *local)
8710 {
8711   expressionS global;
8712
8713   global.X_op = O_constant;
8714   global.X_op_symbol = NULL;
8715   global.X_add_symbol = NULL;
8716   global.X_add_number = local->X_add_number;
8717
8718   relax_start (local->X_add_symbol);
8719   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8720                dest, dest, BFD_RELOC_LO16);
8721   relax_switch ();
8722   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8723   relax_end ();
8724 }
8725
8726 static void
8727 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8728 {
8729   expressionS global;
8730   int hold_mips_optimize;
8731
8732   global.X_op = O_constant;
8733   global.X_op_symbol = NULL;
8734   global.X_add_symbol = NULL;
8735   global.X_add_number = local->X_add_number;
8736
8737   relax_start (local->X_add_symbol);
8738   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8739   relax_switch ();
8740   /* Set mips_optimize around the lui instruction to avoid
8741      inserting an unnecessary nop after the lw.  */
8742   hold_mips_optimize = mips_optimize;
8743   mips_optimize = 2;
8744   macro_build_lui (&global, tmp);
8745   mips_optimize = hold_mips_optimize;
8746   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8747   relax_end ();
8748
8749   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8750 }
8751
8752 /* Emit a sequence of instructions to emulate a branch likely operation.
8753    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8754    is its complementing branch with the original condition negated.
8755    CALL is set if the original branch specified the link operation.
8756    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8757
8758    Code like this is produced in the noreorder mode:
8759
8760         BRNEG   <args>, 1f
8761          nop
8762         b       <sym>
8763          delay slot (executed only if branch taken)
8764     1:
8765
8766    or, if CALL is set:
8767
8768         BRNEG   <args>, 1f
8769          nop
8770         bal     <sym>
8771          delay slot (executed only if branch taken)
8772     1:
8773
8774    In the reorder mode the delay slot would be filled with a nop anyway,
8775    so code produced is simply:
8776
8777         BR      <args>, <sym>
8778          nop
8779
8780    This function is used when producing code for the microMIPS ASE that
8781    does not implement branch likely instructions in hardware.  */
8782
8783 static void
8784 macro_build_branch_likely (const char *br, const char *brneg,
8785                            int call, expressionS *ep, const char *fmt,
8786                            unsigned int sreg, unsigned int treg)
8787 {
8788   int noreorder = mips_opts.noreorder;
8789   expressionS expr1;
8790
8791   gas_assert (mips_opts.micromips);
8792   start_noreorder ();
8793   if (noreorder)
8794     {
8795       micromips_label_expr (&expr1);
8796       macro_build (&expr1, brneg, fmt, sreg, treg);
8797       macro_build (NULL, "nop", "");
8798       macro_build (ep, call ? "bal" : "b", "p");
8799
8800       /* Set to true so that append_insn adds a label.  */
8801       emit_branch_likely_macro = TRUE;
8802     }
8803   else
8804     {
8805       macro_build (ep, br, fmt, sreg, treg);
8806       macro_build (NULL, "nop", "");
8807     }
8808   end_noreorder ();
8809 }
8810
8811 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8812    the condition code tested.  EP specifies the branch target.  */
8813
8814 static void
8815 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8816 {
8817   const int call = 0;
8818   const char *brneg;
8819   const char *br;
8820
8821   switch (type)
8822     {
8823     case M_BC1FL:
8824       br = "bc1f";
8825       brneg = "bc1t";
8826       break;
8827     case M_BC1TL:
8828       br = "bc1t";
8829       brneg = "bc1f";
8830       break;
8831     case M_BC2FL:
8832       br = "bc2f";
8833       brneg = "bc2t";
8834       break;
8835     case M_BC2TL:
8836       br = "bc2t";
8837       brneg = "bc2f";
8838       break;
8839     default:
8840       abort ();
8841     }
8842   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8843 }
8844
8845 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8846    the register tested.  EP specifies the branch target.  */
8847
8848 static void
8849 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8850 {
8851   const char *brneg = NULL;
8852   const char *br;
8853   int call = 0;
8854
8855   switch (type)
8856     {
8857     case M_BGEZ:
8858       br = "bgez";
8859       break;
8860     case M_BGEZL:
8861       br = mips_opts.micromips ? "bgez" : "bgezl";
8862       brneg = "bltz";
8863       break;
8864     case M_BGEZALL:
8865       gas_assert (mips_opts.micromips);
8866       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8867       brneg = "bltz";
8868       call = 1;
8869       break;
8870     case M_BGTZ:
8871       br = "bgtz";
8872       break;
8873     case M_BGTZL:
8874       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8875       brneg = "blez";
8876       break;
8877     case M_BLEZ:
8878       br = "blez";
8879       break;
8880     case M_BLEZL:
8881       br = mips_opts.micromips ? "blez" : "blezl";
8882       brneg = "bgtz";
8883       break;
8884     case M_BLTZ:
8885       br = "bltz";
8886       break;
8887     case M_BLTZL:
8888       br = mips_opts.micromips ? "bltz" : "bltzl";
8889       brneg = "bgez";
8890       break;
8891     case M_BLTZALL:
8892       gas_assert (mips_opts.micromips);
8893       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8894       brneg = "bgez";
8895       call = 1;
8896       break;
8897     default:
8898       abort ();
8899     }
8900   if (mips_opts.micromips && brneg)
8901     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8902   else
8903     macro_build (ep, br, "s,p", sreg);
8904 }
8905
8906 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8907    TREG as the registers tested.  EP specifies the branch target.  */
8908
8909 static void
8910 macro_build_branch_rsrt (int type, expressionS *ep,
8911                          unsigned int sreg, unsigned int treg)
8912 {
8913   const char *brneg = NULL;
8914   const int call = 0;
8915   const char *br;
8916
8917   switch (type)
8918     {
8919     case M_BEQ:
8920     case M_BEQ_I:
8921       br = "beq";
8922       break;
8923     case M_BEQL:
8924     case M_BEQL_I:
8925       br = mips_opts.micromips ? "beq" : "beql";
8926       brneg = "bne";
8927       break;
8928     case M_BNE:
8929     case M_BNE_I:
8930       br = "bne";
8931       break;
8932     case M_BNEL:
8933     case M_BNEL_I:
8934       br = mips_opts.micromips ? "bne" : "bnel";
8935       brneg = "beq";
8936       break;
8937     default:
8938       abort ();
8939     }
8940   if (mips_opts.micromips && brneg)
8941     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
8942   else
8943     macro_build (ep, br, "s,t,p", sreg, treg);
8944 }
8945
8946 /* Return the high part that should be loaded in order to make the low
8947    part of VALUE accessible using an offset of OFFBITS bits.  */
8948
8949 static offsetT
8950 offset_high_part (offsetT value, unsigned int offbits)
8951 {
8952   offsetT bias;
8953   addressT low_mask;
8954
8955   if (offbits == 0)
8956     return value;
8957   bias = 1 << (offbits - 1);
8958   low_mask = bias * 2 - 1;
8959   return (value + bias) & ~low_mask;
8960 }
8961
8962 /* Return true if the value stored in offset_expr and offset_reloc
8963    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
8964    amount that the caller wants to add without inducing overflow
8965    and ALIGN is the known alignment of the value in bytes.  */
8966
8967 static bfd_boolean
8968 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
8969 {
8970   if (offbits == 16)
8971     {
8972       /* Accept any relocation operator if overflow isn't a concern.  */
8973       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
8974         return TRUE;
8975
8976       /* These relocations are guaranteed not to overflow in correct links.  */
8977       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
8978           || gprel16_reloc_p (*offset_reloc))
8979         return TRUE;
8980     }
8981   if (offset_expr.X_op == O_constant
8982       && offset_high_part (offset_expr.X_add_number, offbits) == 0
8983       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
8984     return TRUE;
8985   return FALSE;
8986 }
8987
8988 /*
8989  *                      Build macros
8990  *   This routine implements the seemingly endless macro or synthesized
8991  * instructions and addressing modes in the mips assembly language. Many
8992  * of these macros are simple and are similar to each other. These could
8993  * probably be handled by some kind of table or grammar approach instead of
8994  * this verbose method. Others are not simple macros but are more like
8995  * optimizing code generation.
8996  *   One interesting optimization is when several store macros appear
8997  * consecutively that would load AT with the upper half of the same address.
8998  * The ensuing load upper instructions are ommited. This implies some kind
8999  * of global optimization. We currently only optimize within a single macro.
9000  *   For many of the load and store macros if the address is specified as a
9001  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9002  * first load register 'at' with zero and use it as the base register. The
9003  * mips assembler simply uses register $zero. Just one tiny optimization
9004  * we're missing.
9005  */
9006 static void
9007 macro (struct mips_cl_insn *ip, char *str)
9008 {
9009   const struct mips_operand_array *operands;
9010   unsigned int breg, i;
9011   unsigned int tempreg;
9012   int mask;
9013   int used_at = 0;
9014   expressionS label_expr;
9015   expressionS expr1;
9016   expressionS *ep;
9017   const char *s;
9018   const char *s2;
9019   const char *fmt;
9020   int likely = 0;
9021   int coproc = 0;
9022   int offbits = 16;
9023   int call = 0;
9024   int jals = 0;
9025   int dbl = 0;
9026   int imm = 0;
9027   int ust = 0;
9028   int lp = 0;
9029   bfd_boolean large_offset;
9030   int off;
9031   int hold_mips_optimize;
9032   unsigned int align;
9033   unsigned int op[MAX_OPERANDS];
9034
9035   gas_assert (! mips_opts.mips16);
9036
9037   operands = insn_operands (ip);
9038   for (i = 0; i < MAX_OPERANDS; i++)
9039     if (operands->operand[i])
9040       op[i] = insn_extract_operand (ip, operands->operand[i]);
9041     else
9042       op[i] = -1;
9043
9044   mask = ip->insn_mo->mask;
9045
9046   label_expr.X_op = O_constant;
9047   label_expr.X_op_symbol = NULL;
9048   label_expr.X_add_symbol = NULL;
9049   label_expr.X_add_number = 0;
9050
9051   expr1.X_op = O_constant;
9052   expr1.X_op_symbol = NULL;
9053   expr1.X_add_symbol = NULL;
9054   expr1.X_add_number = 1;
9055   align = 1;
9056
9057   switch (mask)
9058     {
9059     case M_DABS:
9060       dbl = 1;
9061     case M_ABS:
9062       /*    bgez    $a0,1f
9063             move    v0,$a0
9064             sub     v0,$zero,$a0
9065          1:
9066        */
9067
9068       start_noreorder ();
9069
9070       if (mips_opts.micromips)
9071         micromips_label_expr (&label_expr);
9072       else
9073         label_expr.X_add_number = 8;
9074       macro_build (&label_expr, "bgez", "s,p", op[1]);
9075       if (op[0] == op[1])
9076         macro_build (NULL, "nop", "");
9077       else
9078         move_register (op[0], op[1]);
9079       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9080       if (mips_opts.micromips)
9081         micromips_add_label ();
9082
9083       end_noreorder ();
9084       break;
9085
9086     case M_ADD_I:
9087       s = "addi";
9088       s2 = "add";
9089       goto do_addi;
9090     case M_ADDU_I:
9091       s = "addiu";
9092       s2 = "addu";
9093       goto do_addi;
9094     case M_DADD_I:
9095       dbl = 1;
9096       s = "daddi";
9097       s2 = "dadd";
9098       if (!mips_opts.micromips)
9099         goto do_addi;
9100       if (imm_expr.X_op == O_constant
9101           && imm_expr.X_add_number >= -0x200
9102           && imm_expr.X_add_number < 0x200)
9103         {
9104           macro_build (NULL, s, "t,r,.", op[0], op[1], imm_expr.X_add_number);
9105           break;
9106         }
9107       goto do_addi_i;
9108     case M_DADDU_I:
9109       dbl = 1;
9110       s = "daddiu";
9111       s2 = "daddu";
9112     do_addi:
9113       if (imm_expr.X_op == O_constant
9114           && imm_expr.X_add_number >= -0x8000
9115           && imm_expr.X_add_number < 0x8000)
9116         {
9117           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9118           break;
9119         }
9120     do_addi_i:
9121       used_at = 1;
9122       load_register (AT, &imm_expr, dbl);
9123       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9124       break;
9125
9126     case M_AND_I:
9127       s = "andi";
9128       s2 = "and";
9129       goto do_bit;
9130     case M_OR_I:
9131       s = "ori";
9132       s2 = "or";
9133       goto do_bit;
9134     case M_NOR_I:
9135       s = "";
9136       s2 = "nor";
9137       goto do_bit;
9138     case M_XOR_I:
9139       s = "xori";
9140       s2 = "xor";
9141     do_bit:
9142       if (imm_expr.X_op == O_constant
9143           && imm_expr.X_add_number >= 0
9144           && imm_expr.X_add_number < 0x10000)
9145         {
9146           if (mask != M_NOR_I)
9147             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9148           else
9149             {
9150               macro_build (&imm_expr, "ori", "t,r,i",
9151                            op[0], op[1], BFD_RELOC_LO16);
9152               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9153             }
9154           break;
9155         }
9156
9157       used_at = 1;
9158       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9159       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9160       break;
9161
9162     case M_BALIGN:
9163       switch (imm_expr.X_add_number)
9164         {
9165         case 0:
9166           macro_build (NULL, "nop", "");
9167           break;
9168         case 2:
9169           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9170           break;
9171         case 1:
9172         case 3:
9173           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9174                        (int) imm_expr.X_add_number);
9175           break;
9176         default:
9177           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9178                   (unsigned long) imm_expr.X_add_number);
9179           break;
9180         }
9181       break;
9182
9183     case M_BC1FL:
9184     case M_BC1TL:
9185     case M_BC2FL:
9186     case M_BC2TL:
9187       gas_assert (mips_opts.micromips);
9188       macro_build_branch_ccl (mask, &offset_expr,
9189                               EXTRACT_OPERAND (1, BCC, *ip));
9190       break;
9191
9192     case M_BEQ_I:
9193     case M_BEQL_I:
9194     case M_BNE_I:
9195     case M_BNEL_I:
9196       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9197         op[1] = 0;
9198       else
9199         {
9200           op[1] = AT;
9201           used_at = 1;
9202           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9203         }
9204       /* Fall through.  */
9205     case M_BEQL:
9206     case M_BNEL:
9207       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9208       break;
9209
9210     case M_BGEL:
9211       likely = 1;
9212     case M_BGE:
9213       if (op[1] == 0)
9214         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9215       else if (op[0] == 0)
9216         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9217       else
9218         {
9219           used_at = 1;
9220           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9221           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9222                                    &offset_expr, AT, ZERO);
9223         }
9224       break;
9225
9226     case M_BGEZL:
9227     case M_BGEZALL:
9228     case M_BGTZL:
9229     case M_BLEZL:
9230     case M_BLTZL:
9231     case M_BLTZALL:
9232       macro_build_branch_rs (mask, &offset_expr, op[0]);
9233       break;
9234
9235     case M_BGTL_I:
9236       likely = 1;
9237     case M_BGT_I:
9238       /* Check for > max integer.  */
9239       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
9240         {
9241         do_false:
9242           /* Result is always false.  */
9243           if (! likely)
9244             macro_build (NULL, "nop", "");
9245           else
9246             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9247           break;
9248         }
9249       if (imm_expr.X_op != O_constant)
9250         as_bad (_("Unsupported large constant"));
9251       ++imm_expr.X_add_number;
9252       /* FALLTHROUGH */
9253     case M_BGE_I:
9254     case M_BGEL_I:
9255       if (mask == M_BGEL_I)
9256         likely = 1;
9257       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9258         {
9259           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9260                                  &offset_expr, op[0]);
9261           break;
9262         }
9263       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9264         {
9265           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9266                                  &offset_expr, op[0]);
9267           break;
9268         }
9269       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
9270         {
9271         do_true:
9272           /* result is always true */
9273           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
9274           macro_build (&offset_expr, "b", "p");
9275           break;
9276         }
9277       used_at = 1;
9278       set_at (op[0], 0);
9279       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9280                                &offset_expr, AT, ZERO);
9281       break;
9282
9283     case M_BGEUL:
9284       likely = 1;
9285     case M_BGEU:
9286       if (op[1] == 0)
9287         goto do_true;
9288       else if (op[0] == 0)
9289         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9290                                  &offset_expr, ZERO, op[1]);
9291       else
9292         {
9293           used_at = 1;
9294           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9295           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9296                                    &offset_expr, AT, ZERO);
9297         }
9298       break;
9299
9300     case M_BGTUL_I:
9301       likely = 1;
9302     case M_BGTU_I:
9303       if (op[0] == 0
9304           || (HAVE_32BIT_GPRS
9305               && imm_expr.X_op == O_constant
9306               && imm_expr.X_add_number == -1))
9307         goto do_false;
9308       if (imm_expr.X_op != O_constant)
9309         as_bad (_("Unsupported large constant"));
9310       ++imm_expr.X_add_number;
9311       /* FALLTHROUGH */
9312     case M_BGEU_I:
9313     case M_BGEUL_I:
9314       if (mask == M_BGEUL_I)
9315         likely = 1;
9316       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9317         goto do_true;
9318       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9319         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9320                                  &offset_expr, op[0], ZERO);
9321       else
9322         {
9323           used_at = 1;
9324           set_at (op[0], 1);
9325           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9326                                    &offset_expr, AT, ZERO);
9327         }
9328       break;
9329
9330     case M_BGTL:
9331       likely = 1;
9332     case M_BGT:
9333       if (op[1] == 0)
9334         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9335       else if (op[0] == 0)
9336         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9337       else
9338         {
9339           used_at = 1;
9340           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9341           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9342                                    &offset_expr, AT, ZERO);
9343         }
9344       break;
9345
9346     case M_BGTUL:
9347       likely = 1;
9348     case M_BGTU:
9349       if (op[1] == 0)
9350         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9351                                  &offset_expr, op[0], ZERO);
9352       else if (op[0] == 0)
9353         goto do_false;
9354       else
9355         {
9356           used_at = 1;
9357           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9358           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9359                                    &offset_expr, AT, ZERO);
9360         }
9361       break;
9362
9363     case M_BLEL:
9364       likely = 1;
9365     case M_BLE:
9366       if (op[1] == 0)
9367         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9368       else if (op[0] == 0)
9369         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9370       else
9371         {
9372           used_at = 1;
9373           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9374           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9375                                    &offset_expr, AT, ZERO);
9376         }
9377       break;
9378
9379     case M_BLEL_I:
9380       likely = 1;
9381     case M_BLE_I:
9382       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
9383         goto do_true;
9384       if (imm_expr.X_op != O_constant)
9385         as_bad (_("Unsupported large constant"));
9386       ++imm_expr.X_add_number;
9387       /* FALLTHROUGH */
9388     case M_BLT_I:
9389     case M_BLTL_I:
9390       if (mask == M_BLTL_I)
9391         likely = 1;
9392       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9393         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9394       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9395         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9396       else
9397         {
9398           used_at = 1;
9399           set_at (op[0], 0);
9400           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9401                                    &offset_expr, AT, ZERO);
9402         }
9403       break;
9404
9405     case M_BLEUL:
9406       likely = 1;
9407     case M_BLEU:
9408       if (op[1] == 0)
9409         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9410                                  &offset_expr, op[0], ZERO);
9411       else if (op[0] == 0)
9412         goto do_true;
9413       else
9414         {
9415           used_at = 1;
9416           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9417           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9418                                    &offset_expr, AT, ZERO);
9419         }
9420       break;
9421
9422     case M_BLEUL_I:
9423       likely = 1;
9424     case M_BLEU_I:
9425       if (op[0] == 0
9426           || (HAVE_32BIT_GPRS
9427               && imm_expr.X_op == O_constant
9428               && imm_expr.X_add_number == -1))
9429         goto do_true;
9430       if (imm_expr.X_op != O_constant)
9431         as_bad (_("Unsupported large constant"));
9432       ++imm_expr.X_add_number;
9433       /* FALLTHROUGH */
9434     case M_BLTU_I:
9435     case M_BLTUL_I:
9436       if (mask == M_BLTUL_I)
9437         likely = 1;
9438       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9439         goto do_false;
9440       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9441         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9442                                  &offset_expr, op[0], ZERO);
9443       else
9444         {
9445           used_at = 1;
9446           set_at (op[0], 1);
9447           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9448                                    &offset_expr, AT, ZERO);
9449         }
9450       break;
9451
9452     case M_BLTL:
9453       likely = 1;
9454     case M_BLT:
9455       if (op[1] == 0)
9456         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9457       else if (op[0] == 0)
9458         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9459       else
9460         {
9461           used_at = 1;
9462           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9463           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9464                                    &offset_expr, AT, ZERO);
9465         }
9466       break;
9467
9468     case M_BLTUL:
9469       likely = 1;
9470     case M_BLTU:
9471       if (op[1] == 0)
9472         goto do_false;
9473       else if (op[0] == 0)
9474         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9475                                  &offset_expr, ZERO, op[1]);
9476       else
9477         {
9478           used_at = 1;
9479           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9480           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9481                                    &offset_expr, AT, ZERO);
9482         }
9483       break;
9484
9485     case M_DDIV_3:
9486       dbl = 1;
9487     case M_DIV_3:
9488       s = "mflo";
9489       goto do_div3;
9490     case M_DREM_3:
9491       dbl = 1;
9492     case M_REM_3:
9493       s = "mfhi";
9494     do_div3:
9495       if (op[2] == 0)
9496         {
9497           as_warn (_("Divide by zero."));
9498           if (mips_trap)
9499             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9500           else
9501             macro_build (NULL, "break", BRK_FMT, 7);
9502           break;
9503         }
9504
9505       start_noreorder ();
9506       if (mips_trap)
9507         {
9508           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9509           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9510         }
9511       else
9512         {
9513           if (mips_opts.micromips)
9514             micromips_label_expr (&label_expr);
9515           else
9516             label_expr.X_add_number = 8;
9517           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9518           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9519           macro_build (NULL, "break", BRK_FMT, 7);
9520           if (mips_opts.micromips)
9521             micromips_add_label ();
9522         }
9523       expr1.X_add_number = -1;
9524       used_at = 1;
9525       load_register (AT, &expr1, dbl);
9526       if (mips_opts.micromips)
9527         micromips_label_expr (&label_expr);
9528       else
9529         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9530       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9531       if (dbl)
9532         {
9533           expr1.X_add_number = 1;
9534           load_register (AT, &expr1, dbl);
9535           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9536         }
9537       else
9538         {
9539           expr1.X_add_number = 0x80000000;
9540           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9541         }
9542       if (mips_trap)
9543         {
9544           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9545           /* We want to close the noreorder block as soon as possible, so
9546              that later insns are available for delay slot filling.  */
9547           end_noreorder ();
9548         }
9549       else
9550         {
9551           if (mips_opts.micromips)
9552             micromips_label_expr (&label_expr);
9553           else
9554             label_expr.X_add_number = 8;
9555           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9556           macro_build (NULL, "nop", "");
9557
9558           /* We want to close the noreorder block as soon as possible, so
9559              that later insns are available for delay slot filling.  */
9560           end_noreorder ();
9561
9562           macro_build (NULL, "break", BRK_FMT, 6);
9563         }
9564       if (mips_opts.micromips)
9565         micromips_add_label ();
9566       macro_build (NULL, s, MFHL_FMT, op[0]);
9567       break;
9568
9569     case M_DIV_3I:
9570       s = "div";
9571       s2 = "mflo";
9572       goto do_divi;
9573     case M_DIVU_3I:
9574       s = "divu";
9575       s2 = "mflo";
9576       goto do_divi;
9577     case M_REM_3I:
9578       s = "div";
9579       s2 = "mfhi";
9580       goto do_divi;
9581     case M_REMU_3I:
9582       s = "divu";
9583       s2 = "mfhi";
9584       goto do_divi;
9585     case M_DDIV_3I:
9586       dbl = 1;
9587       s = "ddiv";
9588       s2 = "mflo";
9589       goto do_divi;
9590     case M_DDIVU_3I:
9591       dbl = 1;
9592       s = "ddivu";
9593       s2 = "mflo";
9594       goto do_divi;
9595     case M_DREM_3I:
9596       dbl = 1;
9597       s = "ddiv";
9598       s2 = "mfhi";
9599       goto do_divi;
9600     case M_DREMU_3I:
9601       dbl = 1;
9602       s = "ddivu";
9603       s2 = "mfhi";
9604     do_divi:
9605       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9606         {
9607           as_warn (_("Divide by zero."));
9608           if (mips_trap)
9609             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9610           else
9611             macro_build (NULL, "break", BRK_FMT, 7);
9612           break;
9613         }
9614       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9615         {
9616           if (strcmp (s2, "mflo") == 0)
9617             move_register (op[0], op[1]);
9618           else
9619             move_register (op[0], ZERO);
9620           break;
9621         }
9622       if (imm_expr.X_op == O_constant
9623           && imm_expr.X_add_number == -1
9624           && s[strlen (s) - 1] != 'u')
9625         {
9626           if (strcmp (s2, "mflo") == 0)
9627             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9628           else
9629             move_register (op[0], ZERO);
9630           break;
9631         }
9632
9633       used_at = 1;
9634       load_register (AT, &imm_expr, dbl);
9635       macro_build (NULL, s, "z,s,t", op[1], AT);
9636       macro_build (NULL, s2, MFHL_FMT, op[0]);
9637       break;
9638
9639     case M_DIVU_3:
9640       s = "divu";
9641       s2 = "mflo";
9642       goto do_divu3;
9643     case M_REMU_3:
9644       s = "divu";
9645       s2 = "mfhi";
9646       goto do_divu3;
9647     case M_DDIVU_3:
9648       s = "ddivu";
9649       s2 = "mflo";
9650       goto do_divu3;
9651     case M_DREMU_3:
9652       s = "ddivu";
9653       s2 = "mfhi";
9654     do_divu3:
9655       start_noreorder ();
9656       if (mips_trap)
9657         {
9658           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9659           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9660           /* We want to close the noreorder block as soon as possible, so
9661              that later insns are available for delay slot filling.  */
9662           end_noreorder ();
9663         }
9664       else
9665         {
9666           if (mips_opts.micromips)
9667             micromips_label_expr (&label_expr);
9668           else
9669             label_expr.X_add_number = 8;
9670           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9671           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9672
9673           /* We want to close the noreorder block as soon as possible, so
9674              that later insns are available for delay slot filling.  */
9675           end_noreorder ();
9676           macro_build (NULL, "break", BRK_FMT, 7);
9677           if (mips_opts.micromips)
9678             micromips_add_label ();
9679         }
9680       macro_build (NULL, s2, MFHL_FMT, op[0]);
9681       break;
9682
9683     case M_DLCA_AB:
9684       dbl = 1;
9685     case M_LCA_AB:
9686       call = 1;
9687       goto do_la;
9688     case M_DLA_AB:
9689       dbl = 1;
9690     case M_LA_AB:
9691     do_la:
9692       /* Load the address of a symbol into a register.  If breg is not
9693          zero, we then add a base register to it.  */
9694
9695       breg = op[2];
9696       if (dbl && HAVE_32BIT_GPRS)
9697         as_warn (_("dla used to load 32-bit register"));
9698
9699       if (!dbl && HAVE_64BIT_OBJECTS)
9700         as_warn (_("la used to load 64-bit address"));
9701
9702       if (small_offset_p (0, align, 16))
9703         {
9704           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9705                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9706           break;
9707         }
9708
9709       if (mips_opts.at && (op[0] == breg))
9710         {
9711           tempreg = AT;
9712           used_at = 1;
9713         }
9714       else
9715         tempreg = op[0];
9716
9717       if (offset_expr.X_op != O_symbol
9718           && offset_expr.X_op != O_constant)
9719         {
9720           as_bad (_("Expression too complex"));
9721           offset_expr.X_op = O_constant;
9722         }
9723
9724       if (offset_expr.X_op == O_constant)
9725         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9726       else if (mips_pic == NO_PIC)
9727         {
9728           /* If this is a reference to a GP relative symbol, we want
9729                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9730              Otherwise we want
9731                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9732                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9733              If we have a constant, we need two instructions anyhow,
9734              so we may as well always use the latter form.
9735
9736              With 64bit address space and a usable $at we want
9737                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9738                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9739                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9740                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9741                dsll32   $tempreg,0
9742                daddu    $tempreg,$tempreg,$at
9743
9744              If $at is already in use, we use a path which is suboptimal
9745              on superscalar processors.
9746                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9747                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9748                dsll     $tempreg,16
9749                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9750                dsll     $tempreg,16
9751                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9752
9753              For GP relative symbols in 64bit address space we can use
9754              the same sequence as in 32bit address space.  */
9755           if (HAVE_64BIT_SYMBOLS)
9756             {
9757               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9758                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9759                 {
9760                   relax_start (offset_expr.X_add_symbol);
9761                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9762                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9763                   relax_switch ();
9764                 }
9765
9766               if (used_at == 0 && mips_opts.at)
9767                 {
9768                   macro_build (&offset_expr, "lui", LUI_FMT,
9769                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9770                   macro_build (&offset_expr, "lui", LUI_FMT,
9771                                AT, BFD_RELOC_HI16_S);
9772                   macro_build (&offset_expr, "daddiu", "t,r,j",
9773                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9774                   macro_build (&offset_expr, "daddiu", "t,r,j",
9775                                AT, AT, BFD_RELOC_LO16);
9776                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9777                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9778                   used_at = 1;
9779                 }
9780               else
9781                 {
9782                   macro_build (&offset_expr, "lui", LUI_FMT,
9783                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9784                   macro_build (&offset_expr, "daddiu", "t,r,j",
9785                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9786                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9787                   macro_build (&offset_expr, "daddiu", "t,r,j",
9788                                tempreg, tempreg, BFD_RELOC_HI16_S);
9789                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9790                   macro_build (&offset_expr, "daddiu", "t,r,j",
9791                                tempreg, tempreg, BFD_RELOC_LO16);
9792                 }
9793
9794               if (mips_relax.sequence)
9795                 relax_end ();
9796             }
9797           else
9798             {
9799               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9800                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9801                 {
9802                   relax_start (offset_expr.X_add_symbol);
9803                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9804                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9805                   relax_switch ();
9806                 }
9807               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9808                 as_bad (_("Offset too large"));
9809               macro_build_lui (&offset_expr, tempreg);
9810               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9811                            tempreg, tempreg, BFD_RELOC_LO16);
9812               if (mips_relax.sequence)
9813                 relax_end ();
9814             }
9815         }
9816       else if (!mips_big_got && !HAVE_NEWABI)
9817         {
9818           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9819
9820           /* If this is a reference to an external symbol, and there
9821              is no constant, we want
9822                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9823              or for lca or if tempreg is PIC_CALL_REG
9824                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9825              For a local symbol, we want
9826                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9827                nop
9828                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9829
9830              If we have a small constant, and this is a reference to
9831              an external symbol, we want
9832                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9833                nop
9834                addiu    $tempreg,$tempreg,<constant>
9835              For a local symbol, we want the same instruction
9836              sequence, but we output a BFD_RELOC_LO16 reloc on the
9837              addiu instruction.
9838
9839              If we have a large constant, and this is a reference to
9840              an external symbol, we want
9841                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9842                lui      $at,<hiconstant>
9843                addiu    $at,$at,<loconstant>
9844                addu     $tempreg,$tempreg,$at
9845              For a local symbol, we want the same instruction
9846              sequence, but we output a BFD_RELOC_LO16 reloc on the
9847              addiu instruction.
9848            */
9849
9850           if (offset_expr.X_add_number == 0)
9851             {
9852               if (mips_pic == SVR4_PIC
9853                   && breg == 0
9854                   && (call || tempreg == PIC_CALL_REG))
9855                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9856
9857               relax_start (offset_expr.X_add_symbol);
9858               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9859                            lw_reloc_type, mips_gp_register);
9860               if (breg != 0)
9861                 {
9862                   /* We're going to put in an addu instruction using
9863                      tempreg, so we may as well insert the nop right
9864                      now.  */
9865                   load_delay_nop ();
9866                 }
9867               relax_switch ();
9868               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9869                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9870               load_delay_nop ();
9871               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9872                            tempreg, tempreg, BFD_RELOC_LO16);
9873               relax_end ();
9874               /* FIXME: If breg == 0, and the next instruction uses
9875                  $tempreg, then if this variant case is used an extra
9876                  nop will be generated.  */
9877             }
9878           else if (offset_expr.X_add_number >= -0x8000
9879                    && offset_expr.X_add_number < 0x8000)
9880             {
9881               load_got_offset (tempreg, &offset_expr);
9882               load_delay_nop ();
9883               add_got_offset (tempreg, &offset_expr);
9884             }
9885           else
9886             {
9887               expr1.X_add_number = offset_expr.X_add_number;
9888               offset_expr.X_add_number =
9889                 SEXT_16BIT (offset_expr.X_add_number);
9890               load_got_offset (tempreg, &offset_expr);
9891               offset_expr.X_add_number = expr1.X_add_number;
9892               /* If we are going to add in a base register, and the
9893                  target register and the base register are the same,
9894                  then we are using AT as a temporary register.  Since
9895                  we want to load the constant into AT, we add our
9896                  current AT (from the global offset table) and the
9897                  register into the register now, and pretend we were
9898                  not using a base register.  */
9899               if (breg == op[0])
9900                 {
9901                   load_delay_nop ();
9902                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9903                                op[0], AT, breg);
9904                   breg = 0;
9905                   tempreg = op[0];
9906                 }
9907               add_got_offset_hilo (tempreg, &offset_expr, AT);
9908               used_at = 1;
9909             }
9910         }
9911       else if (!mips_big_got && HAVE_NEWABI)
9912         {
9913           int add_breg_early = 0;
9914
9915           /* If this is a reference to an external, and there is no
9916              constant, or local symbol (*), with or without a
9917              constant, we want
9918                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9919              or for lca or if tempreg is PIC_CALL_REG
9920                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9921
9922              If we have a small constant, and this is a reference to
9923              an external symbol, we want
9924                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9925                addiu    $tempreg,$tempreg,<constant>
9926
9927              If we have a large constant, and this is a reference to
9928              an external symbol, we want
9929                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9930                lui      $at,<hiconstant>
9931                addiu    $at,$at,<loconstant>
9932                addu     $tempreg,$tempreg,$at
9933
9934              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
9935              local symbols, even though it introduces an additional
9936              instruction.  */
9937
9938           if (offset_expr.X_add_number)
9939             {
9940               expr1.X_add_number = offset_expr.X_add_number;
9941               offset_expr.X_add_number = 0;
9942
9943               relax_start (offset_expr.X_add_symbol);
9944               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9945                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9946
9947               if (expr1.X_add_number >= -0x8000
9948                   && expr1.X_add_number < 0x8000)
9949                 {
9950                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9951                                tempreg, tempreg, BFD_RELOC_LO16);
9952                 }
9953               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9954                 {
9955                   unsigned int dreg;
9956
9957                   /* If we are going to add in a base register, and the
9958                      target register and the base register are the same,
9959                      then we are using AT as a temporary register.  Since
9960                      we want to load the constant into AT, we add our
9961                      current AT (from the global offset table) and the
9962                      register into the register now, and pretend we were
9963                      not using a base register.  */
9964                   if (breg != op[0])
9965                     dreg = tempreg;
9966                   else
9967                     {
9968                       gas_assert (tempreg == AT);
9969                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9970                                    op[0], AT, breg);
9971                       dreg = op[0];
9972                       add_breg_early = 1;
9973                     }
9974
9975                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9976                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9977                                dreg, dreg, AT);
9978
9979                   used_at = 1;
9980                 }
9981               else
9982                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9983
9984               relax_switch ();
9985               offset_expr.X_add_number = expr1.X_add_number;
9986
9987               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9988                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9989               if (add_breg_early)
9990                 {
9991                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9992                                op[0], tempreg, breg);
9993                   breg = 0;
9994                   tempreg = op[0];
9995                 }
9996               relax_end ();
9997             }
9998           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
9999             {
10000               relax_start (offset_expr.X_add_symbol);
10001               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10002                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10003               relax_switch ();
10004               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10005                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10006               relax_end ();
10007             }
10008           else
10009             {
10010               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10011                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10012             }
10013         }
10014       else if (mips_big_got && !HAVE_NEWABI)
10015         {
10016           int gpdelay;
10017           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10018           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10019           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10020
10021           /* This is the large GOT case.  If this is a reference to an
10022              external symbol, and there is no constant, we want
10023                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10024                addu     $tempreg,$tempreg,$gp
10025                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10026              or for lca or if tempreg is PIC_CALL_REG
10027                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10028                addu     $tempreg,$tempreg,$gp
10029                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10030              For a local symbol, we want
10031                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10032                nop
10033                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10034
10035              If we have a small constant, and this is a reference to
10036              an external symbol, we want
10037                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10038                addu     $tempreg,$tempreg,$gp
10039                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10040                nop
10041                addiu    $tempreg,$tempreg,<constant>
10042              For a local symbol, we want
10043                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10044                nop
10045                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10046
10047              If we have a large constant, and this is a reference to
10048              an external symbol, we want
10049                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10050                addu     $tempreg,$tempreg,$gp
10051                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10052                lui      $at,<hiconstant>
10053                addiu    $at,$at,<loconstant>
10054                addu     $tempreg,$tempreg,$at
10055              For a local symbol, we want
10056                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10057                lui      $at,<hiconstant>
10058                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10059                addu     $tempreg,$tempreg,$at
10060           */
10061
10062           expr1.X_add_number = offset_expr.X_add_number;
10063           offset_expr.X_add_number = 0;
10064           relax_start (offset_expr.X_add_symbol);
10065           gpdelay = reg_needs_delay (mips_gp_register);
10066           if (expr1.X_add_number == 0 && breg == 0
10067               && (call || tempreg == PIC_CALL_REG))
10068             {
10069               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10070               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10071             }
10072           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10073           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10074                        tempreg, tempreg, mips_gp_register);
10075           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10076                        tempreg, lw_reloc_type, tempreg);
10077           if (expr1.X_add_number == 0)
10078             {
10079               if (breg != 0)
10080                 {
10081                   /* We're going to put in an addu instruction using
10082                      tempreg, so we may as well insert the nop right
10083                      now.  */
10084                   load_delay_nop ();
10085                 }
10086             }
10087           else if (expr1.X_add_number >= -0x8000
10088                    && expr1.X_add_number < 0x8000)
10089             {
10090               load_delay_nop ();
10091               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10092                            tempreg, tempreg, BFD_RELOC_LO16);
10093             }
10094           else
10095             {
10096               unsigned int dreg;
10097
10098               /* If we are going to add in a base register, and the
10099                  target register and the base register are the same,
10100                  then we are using AT as a temporary register.  Since
10101                  we want to load the constant into AT, we add our
10102                  current AT (from the global offset table) and the
10103                  register into the register now, and pretend we were
10104                  not using a base register.  */
10105               if (breg != op[0])
10106                 dreg = tempreg;
10107               else
10108                 {
10109                   gas_assert (tempreg == AT);
10110                   load_delay_nop ();
10111                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10112                                op[0], AT, breg);
10113                   dreg = op[0];
10114                 }
10115
10116               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10117               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10118
10119               used_at = 1;
10120             }
10121           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10122           relax_switch ();
10123
10124           if (gpdelay)
10125             {
10126               /* This is needed because this instruction uses $gp, but
10127                  the first instruction on the main stream does not.  */
10128               macro_build (NULL, "nop", "");
10129             }
10130
10131           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10132                        local_reloc_type, mips_gp_register);
10133           if (expr1.X_add_number >= -0x8000
10134               && expr1.X_add_number < 0x8000)
10135             {
10136               load_delay_nop ();
10137               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10138                            tempreg, tempreg, BFD_RELOC_LO16);
10139               /* FIXME: If add_number is 0, and there was no base
10140                  register, the external symbol case ended with a load,
10141                  so if the symbol turns out to not be external, and
10142                  the next instruction uses tempreg, an unnecessary nop
10143                  will be inserted.  */
10144             }
10145           else
10146             {
10147               if (breg == op[0])
10148                 {
10149                   /* We must add in the base register now, as in the
10150                      external symbol case.  */
10151                   gas_assert (tempreg == AT);
10152                   load_delay_nop ();
10153                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10154                                op[0], AT, breg);
10155                   tempreg = op[0];
10156                   /* We set breg to 0 because we have arranged to add
10157                      it in in both cases.  */
10158                   breg = 0;
10159                 }
10160
10161               macro_build_lui (&expr1, AT);
10162               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10163                            AT, AT, BFD_RELOC_LO16);
10164               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10165                            tempreg, tempreg, AT);
10166               used_at = 1;
10167             }
10168           relax_end ();
10169         }
10170       else if (mips_big_got && HAVE_NEWABI)
10171         {
10172           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10173           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10174           int add_breg_early = 0;
10175
10176           /* This is the large GOT case.  If this is a reference to an
10177              external symbol, and there is no constant, we want
10178                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10179                add      $tempreg,$tempreg,$gp
10180                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10181              or for lca or if tempreg is PIC_CALL_REG
10182                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10183                add      $tempreg,$tempreg,$gp
10184                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10185
10186              If we have a small constant, and this is a reference to
10187              an external symbol, we want
10188                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10189                add      $tempreg,$tempreg,$gp
10190                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10191                addi     $tempreg,$tempreg,<constant>
10192
10193              If we have a large constant, and this is a reference to
10194              an external symbol, we want
10195                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10196                addu     $tempreg,$tempreg,$gp
10197                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10198                lui      $at,<hiconstant>
10199                addi     $at,$at,<loconstant>
10200                add      $tempreg,$tempreg,$at
10201
10202              If we have NewABI, and we know it's a local symbol, we want
10203                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10204                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10205              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10206
10207           relax_start (offset_expr.X_add_symbol);
10208
10209           expr1.X_add_number = offset_expr.X_add_number;
10210           offset_expr.X_add_number = 0;
10211
10212           if (expr1.X_add_number == 0 && breg == 0
10213               && (call || tempreg == PIC_CALL_REG))
10214             {
10215               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10216               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10217             }
10218           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10219           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10220                        tempreg, tempreg, mips_gp_register);
10221           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10222                        tempreg, lw_reloc_type, tempreg);
10223
10224           if (expr1.X_add_number == 0)
10225             ;
10226           else if (expr1.X_add_number >= -0x8000
10227                    && expr1.X_add_number < 0x8000)
10228             {
10229               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10230                            tempreg, tempreg, BFD_RELOC_LO16);
10231             }
10232           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10233             {
10234               unsigned int dreg;
10235
10236               /* If we are going to add in a base register, and the
10237                  target register and the base register are the same,
10238                  then we are using AT as a temporary register.  Since
10239                  we want to load the constant into AT, we add our
10240                  current AT (from the global offset table) and the
10241                  register into the register now, and pretend we were
10242                  not using a base register.  */
10243               if (breg != op[0])
10244                 dreg = tempreg;
10245               else
10246                 {
10247                   gas_assert (tempreg == AT);
10248                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10249                                op[0], AT, breg);
10250                   dreg = op[0];
10251                   add_breg_early = 1;
10252                 }
10253
10254               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10255               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10256
10257               used_at = 1;
10258             }
10259           else
10260             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10261
10262           relax_switch ();
10263           offset_expr.X_add_number = expr1.X_add_number;
10264           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10265                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10266           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10267                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10268           if (add_breg_early)
10269             {
10270               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10271                            op[0], tempreg, breg);
10272               breg = 0;
10273               tempreg = op[0];
10274             }
10275           relax_end ();
10276         }
10277       else
10278         abort ();
10279
10280       if (breg != 0)
10281         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10282       break;
10283
10284     case M_MSGSND:
10285       gas_assert (!mips_opts.micromips);
10286       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10287       break;
10288
10289     case M_MSGLD:
10290       gas_assert (!mips_opts.micromips);
10291       macro_build (NULL, "c2", "C", 0x02);
10292       break;
10293
10294     case M_MSGLD_T:
10295       gas_assert (!mips_opts.micromips);
10296       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10297       break;
10298
10299     case M_MSGWAIT:
10300       gas_assert (!mips_opts.micromips);
10301       macro_build (NULL, "c2", "C", 3);
10302       break;
10303
10304     case M_MSGWAIT_T:
10305       gas_assert (!mips_opts.micromips);
10306       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10307       break;
10308
10309     case M_J_A:
10310       /* The j instruction may not be used in PIC code, since it
10311          requires an absolute address.  We convert it to a b
10312          instruction.  */
10313       if (mips_pic == NO_PIC)
10314         macro_build (&offset_expr, "j", "a");
10315       else
10316         macro_build (&offset_expr, "b", "p");
10317       break;
10318
10319       /* The jal instructions must be handled as macros because when
10320          generating PIC code they expand to multi-instruction
10321          sequences.  Normally they are simple instructions.  */
10322     case M_JALS_1:
10323       op[1] = op[0];
10324       op[0] = RA;
10325       /* Fall through.  */
10326     case M_JALS_2:
10327       gas_assert (mips_opts.micromips);
10328       if (mips_opts.insn32)
10329         {
10330           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
10331           break;
10332         }
10333       jals = 1;
10334       goto jal;
10335     case M_JAL_1:
10336       op[1] = op[0];
10337       op[0] = RA;
10338       /* Fall through.  */
10339     case M_JAL_2:
10340     jal:
10341       if (mips_pic == NO_PIC)
10342         {
10343           s = jals ? "jalrs" : "jalr";
10344           if (mips_opts.micromips
10345               && !mips_opts.insn32
10346               && op[0] == RA
10347               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10348             macro_build (NULL, s, "mj", op[1]);
10349           else
10350             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10351         }
10352       else
10353         {
10354           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10355                            && mips_cprestore_offset >= 0);
10356
10357           if (op[1] != PIC_CALL_REG)
10358             as_warn (_("MIPS PIC call to register other than $25"));
10359
10360           s = ((mips_opts.micromips
10361                 && !mips_opts.insn32
10362                 && (!mips_opts.noreorder || cprestore))
10363                ? "jalrs" : "jalr");
10364           if (mips_opts.micromips
10365               && !mips_opts.insn32
10366               && op[0] == RA
10367               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10368             macro_build (NULL, s, "mj", op[1]);
10369           else
10370             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10371           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10372             {
10373               if (mips_cprestore_offset < 0)
10374                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
10375               else
10376                 {
10377                   if (!mips_frame_reg_valid)
10378                     {
10379                       as_warn (_("No .frame pseudo-op used in PIC code"));
10380                       /* Quiet this warning.  */
10381                       mips_frame_reg_valid = 1;
10382                     }
10383                   if (!mips_cprestore_valid)
10384                     {
10385                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
10386                       /* Quiet this warning.  */
10387                       mips_cprestore_valid = 1;
10388                     }
10389                   if (mips_opts.noreorder)
10390                     macro_build (NULL, "nop", "");
10391                   expr1.X_add_number = mips_cprestore_offset;
10392                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10393                                                 mips_gp_register,
10394                                                 mips_frame_reg,
10395                                                 HAVE_64BIT_ADDRESSES);
10396                 }
10397             }
10398         }
10399
10400       break;
10401
10402     case M_JALS_A:
10403       gas_assert (mips_opts.micromips);
10404       if (mips_opts.insn32)
10405         {
10406           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
10407           break;
10408         }
10409       jals = 1;
10410       /* Fall through.  */
10411     case M_JAL_A:
10412       if (mips_pic == NO_PIC)
10413         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10414       else if (mips_pic == SVR4_PIC)
10415         {
10416           /* If this is a reference to an external symbol, and we are
10417              using a small GOT, we want
10418                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10419                nop
10420                jalr     $ra,$25
10421                nop
10422                lw       $gp,cprestore($sp)
10423              The cprestore value is set using the .cprestore
10424              pseudo-op.  If we are using a big GOT, we want
10425                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10426                addu     $25,$25,$gp
10427                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10428                nop
10429                jalr     $ra,$25
10430                nop
10431                lw       $gp,cprestore($sp)
10432              If the symbol is not external, we want
10433                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10434                nop
10435                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10436                jalr     $ra,$25
10437                nop
10438                lw $gp,cprestore($sp)
10439
10440              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10441              sequences above, minus nops, unless the symbol is local,
10442              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10443              GOT_DISP.  */
10444           if (HAVE_NEWABI)
10445             {
10446               if (!mips_big_got)
10447                 {
10448                   relax_start (offset_expr.X_add_symbol);
10449                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10450                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10451                                mips_gp_register);
10452                   relax_switch ();
10453                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10454                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10455                                mips_gp_register);
10456                   relax_end ();
10457                 }
10458               else
10459                 {
10460                   relax_start (offset_expr.X_add_symbol);
10461                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10462                                BFD_RELOC_MIPS_CALL_HI16);
10463                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10464                                PIC_CALL_REG, mips_gp_register);
10465                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10466                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10467                                PIC_CALL_REG);
10468                   relax_switch ();
10469                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10470                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10471                                mips_gp_register);
10472                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10473                                PIC_CALL_REG, PIC_CALL_REG,
10474                                BFD_RELOC_MIPS_GOT_OFST);
10475                   relax_end ();
10476                 }
10477
10478               macro_build_jalr (&offset_expr, 0);
10479             }
10480           else
10481             {
10482               relax_start (offset_expr.X_add_symbol);
10483               if (!mips_big_got)
10484                 {
10485                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10486                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10487                                mips_gp_register);
10488                   load_delay_nop ();
10489                   relax_switch ();
10490                 }
10491               else
10492                 {
10493                   int gpdelay;
10494
10495                   gpdelay = reg_needs_delay (mips_gp_register);
10496                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10497                                BFD_RELOC_MIPS_CALL_HI16);
10498                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10499                                PIC_CALL_REG, mips_gp_register);
10500                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10501                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10502                                PIC_CALL_REG);
10503                   load_delay_nop ();
10504                   relax_switch ();
10505                   if (gpdelay)
10506                     macro_build (NULL, "nop", "");
10507                 }
10508               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10509                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10510                            mips_gp_register);
10511               load_delay_nop ();
10512               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10513                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10514               relax_end ();
10515               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10516
10517               if (mips_cprestore_offset < 0)
10518                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
10519               else
10520                 {
10521                   if (!mips_frame_reg_valid)
10522                     {
10523                       as_warn (_("No .frame pseudo-op used in PIC code"));
10524                       /* Quiet this warning.  */
10525                       mips_frame_reg_valid = 1;
10526                     }
10527                   if (!mips_cprestore_valid)
10528                     {
10529                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
10530                       /* Quiet this warning.  */
10531                       mips_cprestore_valid = 1;
10532                     }
10533                   if (mips_opts.noreorder)
10534                     macro_build (NULL, "nop", "");
10535                   expr1.X_add_number = mips_cprestore_offset;
10536                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10537                                                 mips_gp_register,
10538                                                 mips_frame_reg,
10539                                                 HAVE_64BIT_ADDRESSES);
10540                 }
10541             }
10542         }
10543       else if (mips_pic == VXWORKS_PIC)
10544         as_bad (_("Non-PIC jump used in PIC library"));
10545       else
10546         abort ();
10547
10548       break;
10549
10550     case M_LBUE_AB:
10551       s = "lbue";
10552       fmt = "t,+j(b)";
10553       offbits = 9;
10554       goto ld_st;
10555     case M_LHUE_AB:
10556       s = "lhue";
10557       fmt = "t,+j(b)";
10558       offbits = 9;
10559       goto ld_st;
10560     case M_LBE_AB:
10561       s = "lbe";
10562       fmt = "t,+j(b)";
10563       offbits = 9;
10564       goto ld_st;
10565     case M_LHE_AB:
10566       s = "lhe";
10567       fmt = "t,+j(b)";
10568       offbits = 9;
10569       goto ld_st;
10570     case M_LLE_AB:
10571       s = "lle";
10572       fmt = "t,+j(b)";
10573       offbits = 9;
10574       goto ld_st;
10575     case M_LWE_AB:
10576       s = "lwe";
10577       fmt = "t,+j(b)";
10578       offbits = 9;
10579       goto ld_st;
10580     case M_LWLE_AB:
10581       s = "lwle";
10582       fmt = "t,+j(b)";
10583       offbits = 9;
10584       goto ld_st;
10585     case M_LWRE_AB:
10586       s = "lwre";
10587       fmt = "t,+j(b)";
10588       offbits = 9;
10589       goto ld_st;
10590     case M_SBE_AB:
10591       s = "sbe";
10592       fmt = "t,+j(b)";
10593       offbits = 9;
10594       goto ld_st;
10595     case M_SCE_AB:
10596       s = "sce";
10597       fmt = "t,+j(b)";
10598       offbits = 9;
10599       goto ld_st;
10600     case M_SHE_AB:
10601       s = "she";
10602       fmt = "t,+j(b)";
10603       offbits = 9;
10604       goto ld_st;
10605     case M_SWE_AB:
10606       s = "swe";
10607       fmt = "t,+j(b)";
10608       offbits = 9;
10609       goto ld_st;
10610     case M_SWLE_AB:
10611       s = "swle";
10612       fmt = "t,+j(b)";
10613       offbits = 9;
10614       goto ld_st;
10615     case M_SWRE_AB:
10616       s = "swre";
10617       fmt = "t,+j(b)";
10618       offbits = 9;
10619       goto ld_st;
10620     case M_ACLR_AB:
10621       s = "aclr";
10622       fmt = "\\,~(b)";
10623       offbits = 12;
10624       goto ld_st;
10625     case M_ASET_AB:
10626       s = "aset";
10627       fmt = "\\,~(b)";
10628       offbits = 12;
10629       goto ld_st;
10630     case M_LB_AB:
10631       s = "lb";
10632       fmt = "t,o(b)";
10633       goto ld;
10634     case M_LBU_AB:
10635       s = "lbu";
10636       fmt = "t,o(b)";
10637       goto ld;
10638     case M_LH_AB:
10639       s = "lh";
10640       fmt = "t,o(b)";
10641       goto ld;
10642     case M_LHU_AB:
10643       s = "lhu";
10644       fmt = "t,o(b)";
10645       goto ld;
10646     case M_LW_AB:
10647       s = "lw";
10648       fmt = "t,o(b)";
10649       goto ld;
10650     case M_LWC0_AB:
10651       gas_assert (!mips_opts.micromips);
10652       s = "lwc0";
10653       fmt = "E,o(b)";
10654       /* Itbl support may require additional care here.  */
10655       coproc = 1;
10656       goto ld_st;
10657     case M_LWC1_AB:
10658       s = "lwc1";
10659       fmt = "T,o(b)";
10660       /* Itbl support may require additional care here.  */
10661       coproc = 1;
10662       goto ld_st;
10663     case M_LWC2_AB:
10664       s = "lwc2";
10665       fmt = COP12_FMT;
10666       offbits = (mips_opts.micromips ? 12 : 16);
10667       /* Itbl support may require additional care here.  */
10668       coproc = 1;
10669       goto ld_st;
10670     case M_LWC3_AB:
10671       gas_assert (!mips_opts.micromips);
10672       s = "lwc3";
10673       fmt = "E,o(b)";
10674       /* Itbl support may require additional care here.  */
10675       coproc = 1;
10676       goto ld_st;
10677     case M_LWL_AB:
10678       s = "lwl";
10679       fmt = MEM12_FMT;
10680       offbits = (mips_opts.micromips ? 12 : 16);
10681       goto ld_st;
10682     case M_LWR_AB:
10683       s = "lwr";
10684       fmt = MEM12_FMT;
10685       offbits = (mips_opts.micromips ? 12 : 16);
10686       goto ld_st;
10687     case M_LDC1_AB:
10688       s = "ldc1";
10689       fmt = "T,o(b)";
10690       /* Itbl support may require additional care here.  */
10691       coproc = 1;
10692       goto ld_st;
10693     case M_LDC2_AB:
10694       s = "ldc2";
10695       fmt = COP12_FMT;
10696       offbits = (mips_opts.micromips ? 12 : 16);
10697       /* Itbl support may require additional care here.  */
10698       coproc = 1;
10699       goto ld_st;
10700     case M_LQC2_AB:
10701       s = "lqc2";
10702       fmt = "+7,o(b)";
10703       /* Itbl support may require additional care here.  */
10704       coproc = 1;
10705       goto ld_st;
10706     case M_LDC3_AB:
10707       s = "ldc3";
10708       fmt = "E,o(b)";
10709       /* Itbl support may require additional care here.  */
10710       coproc = 1;
10711       goto ld_st;
10712     case M_LDL_AB:
10713       s = "ldl";
10714       fmt = MEM12_FMT;
10715       offbits = (mips_opts.micromips ? 12 : 16);
10716       goto ld_st;
10717     case M_LDR_AB:
10718       s = "ldr";
10719       fmt = MEM12_FMT;
10720       offbits = (mips_opts.micromips ? 12 : 16);
10721       goto ld_st;
10722     case M_LL_AB:
10723       s = "ll";
10724       fmt = MEM12_FMT;
10725       offbits = (mips_opts.micromips ? 12 : 16);
10726       goto ld;
10727     case M_LLD_AB:
10728       s = "lld";
10729       fmt = MEM12_FMT;
10730       offbits = (mips_opts.micromips ? 12 : 16);
10731       goto ld;
10732     case M_LWU_AB:
10733       s = "lwu";
10734       fmt = MEM12_FMT;
10735       offbits = (mips_opts.micromips ? 12 : 16);
10736       goto ld;
10737     case M_LWP_AB:
10738       gas_assert (mips_opts.micromips);
10739       s = "lwp";
10740       fmt = "t,~(b)";
10741       offbits = 12;
10742       lp = 1;
10743       goto ld;
10744     case M_LDP_AB:
10745       gas_assert (mips_opts.micromips);
10746       s = "ldp";
10747       fmt = "t,~(b)";
10748       offbits = 12;
10749       lp = 1;
10750       goto ld;
10751     case M_LWM_AB:
10752       gas_assert (mips_opts.micromips);
10753       s = "lwm";
10754       fmt = "n,~(b)";
10755       offbits = 12;
10756       goto ld_st;
10757     case M_LDM_AB:
10758       gas_assert (mips_opts.micromips);
10759       s = "ldm";
10760       fmt = "n,~(b)";
10761       offbits = 12;
10762       goto ld_st;
10763
10764     ld:
10765       /* We don't want to use $0 as tempreg.  */
10766       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10767         goto ld_st;
10768       else
10769         tempreg = op[0] + lp;
10770       goto ld_noat;
10771
10772     case M_SB_AB:
10773       s = "sb";
10774       fmt = "t,o(b)";
10775       goto ld_st;
10776     case M_SH_AB:
10777       s = "sh";
10778       fmt = "t,o(b)";
10779       goto ld_st;
10780     case M_SW_AB:
10781       s = "sw";
10782       fmt = "t,o(b)";
10783       goto ld_st;
10784     case M_SWC0_AB:
10785       gas_assert (!mips_opts.micromips);
10786       s = "swc0";
10787       fmt = "E,o(b)";
10788       /* Itbl support may require additional care here.  */
10789       coproc = 1;
10790       goto ld_st;
10791     case M_SWC1_AB:
10792       s = "swc1";
10793       fmt = "T,o(b)";
10794       /* Itbl support may require additional care here.  */
10795       coproc = 1;
10796       goto ld_st;
10797     case M_SWC2_AB:
10798       s = "swc2";
10799       fmt = COP12_FMT;
10800       offbits = (mips_opts.micromips ? 12 : 16);
10801       /* Itbl support may require additional care here.  */
10802       coproc = 1;
10803       goto ld_st;
10804     case M_SWC3_AB:
10805       gas_assert (!mips_opts.micromips);
10806       s = "swc3";
10807       fmt = "E,o(b)";
10808       /* Itbl support may require additional care here.  */
10809       coproc = 1;
10810       goto ld_st;
10811     case M_SWL_AB:
10812       s = "swl";
10813       fmt = MEM12_FMT;
10814       offbits = (mips_opts.micromips ? 12 : 16);
10815       goto ld_st;
10816     case M_SWR_AB:
10817       s = "swr";
10818       fmt = MEM12_FMT;
10819       offbits = (mips_opts.micromips ? 12 : 16);
10820       goto ld_st;
10821     case M_SC_AB:
10822       s = "sc";
10823       fmt = MEM12_FMT;
10824       offbits = (mips_opts.micromips ? 12 : 16);
10825       goto ld_st;
10826     case M_SCD_AB:
10827       s = "scd";
10828       fmt = MEM12_FMT;
10829       offbits = (mips_opts.micromips ? 12 : 16);
10830       goto ld_st;
10831     case M_CACHE_AB:
10832       s = "cache";
10833       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10834       offbits = (mips_opts.micromips ? 12 : 16);
10835       goto ld_st;
10836     case M_CACHEE_AB:
10837       s = "cachee";
10838       fmt = "k,+j(b)";
10839       offbits = 9;
10840       goto ld_st;
10841     case M_PREF_AB:
10842       s = "pref";
10843       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10844       offbits = (mips_opts.micromips ? 12 : 16);
10845       goto ld_st;
10846     case M_PREFE_AB:
10847       s = "prefe";
10848       fmt = "k,+j(b)";
10849       offbits = 9;
10850       goto ld_st;
10851     case M_SDC1_AB:
10852       s = "sdc1";
10853       fmt = "T,o(b)";
10854       coproc = 1;
10855       /* Itbl support may require additional care here.  */
10856       goto ld_st;
10857     case M_SDC2_AB:
10858       s = "sdc2";
10859       fmt = COP12_FMT;
10860       offbits = (mips_opts.micromips ? 12 : 16);
10861       /* Itbl support may require additional care here.  */
10862       coproc = 1;
10863       goto ld_st;
10864     case M_SQC2_AB:
10865       s = "sqc2";
10866       fmt = "+7,o(b)";
10867       /* Itbl support may require additional care here.  */
10868       coproc = 1;
10869       goto ld_st;
10870     case M_SDC3_AB:
10871       gas_assert (!mips_opts.micromips);
10872       s = "sdc3";
10873       fmt = "E,o(b)";
10874       /* Itbl support may require additional care here.  */
10875       coproc = 1;
10876       goto ld_st;
10877     case M_SDL_AB:
10878       s = "sdl";
10879       fmt = MEM12_FMT;
10880       offbits = (mips_opts.micromips ? 12 : 16);
10881       goto ld_st;
10882     case M_SDR_AB:
10883       s = "sdr";
10884       fmt = MEM12_FMT;
10885       offbits = (mips_opts.micromips ? 12 : 16);
10886       goto ld_st;
10887     case M_SWP_AB:
10888       gas_assert (mips_opts.micromips);
10889       s = "swp";
10890       fmt = "t,~(b)";
10891       offbits = 12;
10892       goto ld_st;
10893     case M_SDP_AB:
10894       gas_assert (mips_opts.micromips);
10895       s = "sdp";
10896       fmt = "t,~(b)";
10897       offbits = 12;
10898       goto ld_st;
10899     case M_SWM_AB:
10900       gas_assert (mips_opts.micromips);
10901       s = "swm";
10902       fmt = "n,~(b)";
10903       offbits = 12;
10904       goto ld_st;
10905     case M_SDM_AB:
10906       gas_assert (mips_opts.micromips);
10907       s = "sdm";
10908       fmt = "n,~(b)";
10909       offbits = 12;
10910
10911     ld_st:
10912       tempreg = AT;
10913     ld_noat:
10914       breg = op[2];
10915       if (small_offset_p (0, align, 16))
10916         {
10917           /* The first case exists for M_LD_AB and M_SD_AB, which are
10918              macros for o32 but which should act like normal instructions
10919              otherwise.  */
10920           if (offbits == 16)
10921             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10922                          offset_reloc[1], offset_reloc[2], breg);
10923           else if (small_offset_p (0, align, offbits))
10924             {
10925               if (offbits == 0)
10926                 macro_build (NULL, s, fmt, op[0], breg);
10927               else
10928                 macro_build (NULL, s, fmt, op[0],
10929                              (int) offset_expr.X_add_number, breg);
10930             }
10931           else
10932             {
10933               if (tempreg == AT)
10934                 used_at = 1;
10935               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10936                            tempreg, breg, -1, offset_reloc[0],
10937                            offset_reloc[1], offset_reloc[2]);
10938               if (offbits == 0)
10939                 macro_build (NULL, s, fmt, op[0], tempreg);
10940               else
10941                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
10942             }
10943           break;
10944         }
10945
10946       if (tempreg == AT)
10947         used_at = 1;
10948
10949       if (offset_expr.X_op != O_constant
10950           && offset_expr.X_op != O_symbol)
10951         {
10952           as_bad (_("Expression too complex"));
10953           offset_expr.X_op = O_constant;
10954         }
10955
10956       if (HAVE_32BIT_ADDRESSES
10957           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10958         {
10959           char value [32];
10960
10961           sprintf_vma (value, offset_expr.X_add_number);
10962           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10963         }
10964
10965       /* A constant expression in PIC code can be handled just as it
10966          is in non PIC code.  */
10967       if (offset_expr.X_op == O_constant)
10968         {
10969           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
10970                                                  offbits == 0 ? 16 : offbits);
10971           offset_expr.X_add_number -= expr1.X_add_number;
10972
10973           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
10974           if (breg != 0)
10975             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10976                          tempreg, tempreg, breg);
10977           if (offbits == 0)
10978             {
10979               if (offset_expr.X_add_number != 0)
10980                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
10981                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
10982               macro_build (NULL, s, fmt, op[0], tempreg);
10983             }
10984           else if (offbits == 16)
10985             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10986           else
10987             macro_build (NULL, s, fmt, op[0],
10988                          (int) offset_expr.X_add_number, tempreg);
10989         }
10990       else if (offbits != 16)
10991         {
10992           /* The offset field is too narrow to be used for a low-part
10993              relocation, so load the whole address into the auxillary
10994              register.  */
10995           load_address (tempreg, &offset_expr, &used_at);
10996           if (breg != 0)
10997             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10998                          tempreg, tempreg, breg);
10999           if (offbits == 0)
11000             macro_build (NULL, s, fmt, op[0], tempreg);
11001           else
11002             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11003         }
11004       else if (mips_pic == NO_PIC)
11005         {
11006           /* If this is a reference to a GP relative symbol, and there
11007              is no base register, we want
11008                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11009              Otherwise, if there is no base register, we want
11010                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11011                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11012              If we have a constant, we need two instructions anyhow,
11013              so we always use the latter form.
11014
11015              If we have a base register, and this is a reference to a
11016              GP relative symbol, we want
11017                addu     $tempreg,$breg,$gp
11018                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11019              Otherwise we want
11020                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11021                addu     $tempreg,$tempreg,$breg
11022                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11023              With a constant we always use the latter case.
11024
11025              With 64bit address space and no base register and $at usable,
11026              we want
11027                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11028                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11029                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11030                dsll32   $tempreg,0
11031                daddu    $tempreg,$at
11032                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11033              If we have a base register, we want
11034                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11035                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11036                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11037                daddu    $at,$breg
11038                dsll32   $tempreg,0
11039                daddu    $tempreg,$at
11040                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11041
11042              Without $at we can't generate the optimal path for superscalar
11043              processors here since this would require two temporary registers.
11044                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11045                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11046                dsll     $tempreg,16
11047                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11048                dsll     $tempreg,16
11049                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11050              If we have a base register, we want
11051                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11052                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11053                dsll     $tempreg,16
11054                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11055                dsll     $tempreg,16
11056                daddu    $tempreg,$tempreg,$breg
11057                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11058
11059              For GP relative symbols in 64bit address space we can use
11060              the same sequence as in 32bit address space.  */
11061           if (HAVE_64BIT_SYMBOLS)
11062             {
11063               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11064                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11065                 {
11066                   relax_start (offset_expr.X_add_symbol);
11067                   if (breg == 0)
11068                     {
11069                       macro_build (&offset_expr, s, fmt, op[0],
11070                                    BFD_RELOC_GPREL16, mips_gp_register);
11071                     }
11072                   else
11073                     {
11074                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11075                                    tempreg, breg, mips_gp_register);
11076                       macro_build (&offset_expr, s, fmt, op[0],
11077                                    BFD_RELOC_GPREL16, tempreg);
11078                     }
11079                   relax_switch ();
11080                 }
11081
11082               if (used_at == 0 && mips_opts.at)
11083                 {
11084                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11085                                BFD_RELOC_MIPS_HIGHEST);
11086                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11087                                BFD_RELOC_HI16_S);
11088                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11089                                tempreg, BFD_RELOC_MIPS_HIGHER);
11090                   if (breg != 0)
11091                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11092                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11093                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11094                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11095                                tempreg);
11096                   used_at = 1;
11097                 }
11098               else
11099                 {
11100                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11101                                BFD_RELOC_MIPS_HIGHEST);
11102                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11103                                tempreg, BFD_RELOC_MIPS_HIGHER);
11104                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11105                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11106                                tempreg, BFD_RELOC_HI16_S);
11107                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11108                   if (breg != 0)
11109                     macro_build (NULL, "daddu", "d,v,t",
11110                                  tempreg, tempreg, breg);
11111                   macro_build (&offset_expr, s, fmt, op[0],
11112                                BFD_RELOC_LO16, tempreg);
11113                 }
11114
11115               if (mips_relax.sequence)
11116                 relax_end ();
11117               break;
11118             }
11119
11120           if (breg == 0)
11121             {
11122               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11123                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11124                 {
11125                   relax_start (offset_expr.X_add_symbol);
11126                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11127                                mips_gp_register);
11128                   relax_switch ();
11129                 }
11130               macro_build_lui (&offset_expr, tempreg);
11131               macro_build (&offset_expr, s, fmt, op[0],
11132                            BFD_RELOC_LO16, tempreg);
11133               if (mips_relax.sequence)
11134                 relax_end ();
11135             }
11136           else
11137             {
11138               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11139                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11140                 {
11141                   relax_start (offset_expr.X_add_symbol);
11142                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11143                                tempreg, breg, mips_gp_register);
11144                   macro_build (&offset_expr, s, fmt, op[0],
11145                                BFD_RELOC_GPREL16, tempreg);
11146                   relax_switch ();
11147                 }
11148               macro_build_lui (&offset_expr, tempreg);
11149               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11150                            tempreg, tempreg, breg);
11151               macro_build (&offset_expr, s, fmt, op[0],
11152                            BFD_RELOC_LO16, tempreg);
11153               if (mips_relax.sequence)
11154                 relax_end ();
11155             }
11156         }
11157       else if (!mips_big_got)
11158         {
11159           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11160
11161           /* If this is a reference to an external symbol, we want
11162                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11163                nop
11164                <op>     op[0],0($tempreg)
11165              Otherwise we want
11166                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11167                nop
11168                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11169                <op>     op[0],0($tempreg)
11170
11171              For NewABI, we want
11172                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11173                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11174
11175              If there is a base register, we add it to $tempreg before
11176              the <op>.  If there is a constant, we stick it in the
11177              <op> instruction.  We don't handle constants larger than
11178              16 bits, because we have no way to load the upper 16 bits
11179              (actually, we could handle them for the subset of cases
11180              in which we are not using $at).  */
11181           gas_assert (offset_expr.X_op == O_symbol);
11182           if (HAVE_NEWABI)
11183             {
11184               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11185                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11186               if (breg != 0)
11187                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11188                              tempreg, tempreg, breg);
11189               macro_build (&offset_expr, s, fmt, op[0],
11190                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11191               break;
11192             }
11193           expr1.X_add_number = offset_expr.X_add_number;
11194           offset_expr.X_add_number = 0;
11195           if (expr1.X_add_number < -0x8000
11196               || expr1.X_add_number >= 0x8000)
11197             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11198           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11199                        lw_reloc_type, mips_gp_register);
11200           load_delay_nop ();
11201           relax_start (offset_expr.X_add_symbol);
11202           relax_switch ();
11203           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11204                        tempreg, BFD_RELOC_LO16);
11205           relax_end ();
11206           if (breg != 0)
11207             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11208                          tempreg, tempreg, breg);
11209           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11210         }
11211       else if (mips_big_got && !HAVE_NEWABI)
11212         {
11213           int gpdelay;
11214
11215           /* If this is a reference to an external symbol, we want
11216                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11217                addu     $tempreg,$tempreg,$gp
11218                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11219                <op>     op[0],0($tempreg)
11220              Otherwise we want
11221                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11222                nop
11223                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11224                <op>     op[0],0($tempreg)
11225              If there is a base register, we add it to $tempreg before
11226              the <op>.  If there is a constant, we stick it in the
11227              <op> instruction.  We don't handle constants larger than
11228              16 bits, because we have no way to load the upper 16 bits
11229              (actually, we could handle them for the subset of cases
11230              in which we are not using $at).  */
11231           gas_assert (offset_expr.X_op == O_symbol);
11232           expr1.X_add_number = offset_expr.X_add_number;
11233           offset_expr.X_add_number = 0;
11234           if (expr1.X_add_number < -0x8000
11235               || expr1.X_add_number >= 0x8000)
11236             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11237           gpdelay = reg_needs_delay (mips_gp_register);
11238           relax_start (offset_expr.X_add_symbol);
11239           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11240                        BFD_RELOC_MIPS_GOT_HI16);
11241           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11242                        mips_gp_register);
11243           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11244                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11245           relax_switch ();
11246           if (gpdelay)
11247             macro_build (NULL, "nop", "");
11248           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11249                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11250           load_delay_nop ();
11251           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11252                        tempreg, BFD_RELOC_LO16);
11253           relax_end ();
11254
11255           if (breg != 0)
11256             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11257                          tempreg, tempreg, breg);
11258           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11259         }
11260       else if (mips_big_got && HAVE_NEWABI)
11261         {
11262           /* If this is a reference to an external symbol, we want
11263                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11264                add      $tempreg,$tempreg,$gp
11265                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11266                <op>     op[0],<ofst>($tempreg)
11267              Otherwise, for local symbols, we want:
11268                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11269                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11270           gas_assert (offset_expr.X_op == O_symbol);
11271           expr1.X_add_number = offset_expr.X_add_number;
11272           offset_expr.X_add_number = 0;
11273           if (expr1.X_add_number < -0x8000
11274               || expr1.X_add_number >= 0x8000)
11275             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11276           relax_start (offset_expr.X_add_symbol);
11277           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11278                        BFD_RELOC_MIPS_GOT_HI16);
11279           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11280                        mips_gp_register);
11281           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11282                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11283           if (breg != 0)
11284             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11285                          tempreg, tempreg, breg);
11286           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11287
11288           relax_switch ();
11289           offset_expr.X_add_number = expr1.X_add_number;
11290           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11291                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11292           if (breg != 0)
11293             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11294                          tempreg, tempreg, breg);
11295           macro_build (&offset_expr, s, fmt, op[0],
11296                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11297           relax_end ();
11298         }
11299       else
11300         abort ();
11301
11302       break;
11303
11304     case M_JRADDIUSP:
11305       gas_assert (mips_opts.micromips);
11306       gas_assert (mips_opts.insn32);
11307       start_noreorder ();
11308       macro_build (NULL, "jr", "s", RA);
11309       expr1.X_add_number = op[0] << 2;
11310       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11311       end_noreorder ();
11312       break;
11313
11314     case M_JRC:
11315       gas_assert (mips_opts.micromips);
11316       gas_assert (mips_opts.insn32);
11317       macro_build (NULL, "jr", "s", op[0]);
11318       if (mips_opts.noreorder)
11319         macro_build (NULL, "nop", "");
11320       break;
11321
11322     case M_LI:
11323     case M_LI_S:
11324       load_register (op[0], &imm_expr, 0);
11325       break;
11326
11327     case M_DLI:
11328       load_register (op[0], &imm_expr, 1);
11329       break;
11330
11331     case M_LI_SS:
11332       if (imm_expr.X_op == O_constant)
11333         {
11334           used_at = 1;
11335           load_register (AT, &imm_expr, 0);
11336           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11337           break;
11338         }
11339       else
11340         {
11341           gas_assert (offset_expr.X_op == O_symbol
11342                       && strcmp (segment_name (S_GET_SEGMENT
11343                                                (offset_expr.X_add_symbol)),
11344                                  ".lit4") == 0
11345                       && offset_expr.X_add_number == 0);
11346           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11347                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11348           break;
11349         }
11350
11351     case M_LI_D:
11352       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11353          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11354          order 32 bits of the value and the low order 32 bits are either
11355          zero or in OFFSET_EXPR.  */
11356       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
11357         {
11358           if (HAVE_64BIT_GPRS)
11359             load_register (op[0], &imm_expr, 1);
11360           else
11361             {
11362               int hreg, lreg;
11363
11364               if (target_big_endian)
11365                 {
11366                   hreg = op[0];
11367                   lreg = op[0] + 1;
11368                 }
11369               else
11370                 {
11371                   hreg = op[0] + 1;
11372                   lreg = op[0];
11373                 }
11374
11375               if (hreg <= 31)
11376                 load_register (hreg, &imm_expr, 0);
11377               if (lreg <= 31)
11378                 {
11379                   if (offset_expr.X_op == O_absent)
11380                     move_register (lreg, 0);
11381                   else
11382                     {
11383                       gas_assert (offset_expr.X_op == O_constant);
11384                       load_register (lreg, &offset_expr, 0);
11385                     }
11386                 }
11387             }
11388           break;
11389         }
11390
11391       /* We know that sym is in the .rdata section.  First we get the
11392          upper 16 bits of the address.  */
11393       if (mips_pic == NO_PIC)
11394         {
11395           macro_build_lui (&offset_expr, AT);
11396           used_at = 1;
11397         }
11398       else
11399         {
11400           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11401                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11402           used_at = 1;
11403         }
11404
11405       /* Now we load the register(s).  */
11406       if (HAVE_64BIT_GPRS)
11407         {
11408           used_at = 1;
11409           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11410                        BFD_RELOC_LO16, AT);
11411         }
11412       else
11413         {
11414           used_at = 1;
11415           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11416                        BFD_RELOC_LO16, AT);
11417           if (op[0] != RA)
11418             {
11419               /* FIXME: How in the world do we deal with the possible
11420                  overflow here?  */
11421               offset_expr.X_add_number += 4;
11422               macro_build (&offset_expr, "lw", "t,o(b)",
11423                            op[0] + 1, BFD_RELOC_LO16, AT);
11424             }
11425         }
11426       break;
11427
11428     case M_LI_DD:
11429       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11430          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11431          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11432          the value and the low order 32 bits are either zero or in
11433          OFFSET_EXPR.  */
11434       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
11435         {
11436           used_at = 1;
11437           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11438           if (HAVE_64BIT_FPRS)
11439             {
11440               gas_assert (HAVE_64BIT_GPRS);
11441               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11442             }
11443           else
11444             {
11445               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11446               if (offset_expr.X_op == O_absent)
11447                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11448               else
11449                 {
11450                   gas_assert (offset_expr.X_op == O_constant);
11451                   load_register (AT, &offset_expr, 0);
11452                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11453                 }
11454             }
11455           break;
11456         }
11457
11458       gas_assert (offset_expr.X_op == O_symbol
11459                   && offset_expr.X_add_number == 0);
11460       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11461       if (strcmp (s, ".lit8") == 0)
11462         {
11463           op[2] = mips_gp_register;
11464           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11465           offset_reloc[1] = BFD_RELOC_UNUSED;
11466           offset_reloc[2] = BFD_RELOC_UNUSED;
11467         }
11468       else
11469         {
11470           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11471           used_at = 1;
11472           if (mips_pic != NO_PIC)
11473             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11474                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11475           else
11476             {
11477               /* FIXME: This won't work for a 64 bit address.  */
11478               macro_build_lui (&offset_expr, AT);
11479             }
11480
11481           op[2] = AT;
11482           offset_reloc[0] = BFD_RELOC_LO16;
11483           offset_reloc[1] = BFD_RELOC_UNUSED;
11484           offset_reloc[2] = BFD_RELOC_UNUSED;
11485         }
11486       align = 8;
11487       /* Fall through */
11488
11489     case M_L_DAB:
11490       /*
11491        * The MIPS assembler seems to check for X_add_number not
11492        * being double aligned and generating:
11493        *        lui     at,%hi(foo+1)
11494        *        addu    at,at,v1
11495        *        addiu   at,at,%lo(foo+1)
11496        *        lwc1    f2,0(at)
11497        *        lwc1    f3,4(at)
11498        * But, the resulting address is the same after relocation so why
11499        * generate the extra instruction?
11500        */
11501       /* Itbl support may require additional care here.  */
11502       coproc = 1;
11503       fmt = "T,o(b)";
11504       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11505         {
11506           s = "ldc1";
11507           goto ld_st;
11508         }
11509       s = "lwc1";
11510       goto ldd_std;
11511
11512     case M_S_DAB:
11513       gas_assert (!mips_opts.micromips);
11514       /* Itbl support may require additional care here.  */
11515       coproc = 1;
11516       fmt = "T,o(b)";
11517       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11518         {
11519           s = "sdc1";
11520           goto ld_st;
11521         }
11522       s = "swc1";
11523       goto ldd_std;
11524
11525     case M_LQ_AB:
11526       fmt = "t,o(b)";
11527       s = "lq";
11528       goto ld;
11529
11530     case M_SQ_AB:
11531       fmt = "t,o(b)";
11532       s = "sq";
11533       goto ld_st;
11534
11535     case M_LD_AB:
11536       fmt = "t,o(b)";
11537       if (HAVE_64BIT_GPRS)
11538         {
11539           s = "ld";
11540           goto ld;
11541         }
11542       s = "lw";
11543       goto ldd_std;
11544
11545     case M_SD_AB:
11546       fmt = "t,o(b)";
11547       if (HAVE_64BIT_GPRS)
11548         {
11549           s = "sd";
11550           goto ld_st;
11551         }
11552       s = "sw";
11553
11554     ldd_std:
11555       /* Even on a big endian machine $fn comes before $fn+1.  We have
11556          to adjust when loading from memory.  We set coproc if we must
11557          load $fn+1 first.  */
11558       /* Itbl support may require additional care here.  */
11559       if (!target_big_endian)
11560         coproc = 0;
11561
11562       breg = op[2];
11563       if (small_offset_p (0, align, 16))
11564         {
11565           ep = &offset_expr;
11566           if (!small_offset_p (4, align, 16))
11567             {
11568               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11569                            -1, offset_reloc[0], offset_reloc[1],
11570                            offset_reloc[2]);
11571               expr1.X_add_number = 0;
11572               ep = &expr1;
11573               breg = AT;
11574               used_at = 1;
11575               offset_reloc[0] = BFD_RELOC_LO16;
11576               offset_reloc[1] = BFD_RELOC_UNUSED;
11577               offset_reloc[2] = BFD_RELOC_UNUSED;
11578             }
11579           if (strcmp (s, "lw") == 0 && op[0] == breg)
11580             {
11581               ep->X_add_number += 4;
11582               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11583                            offset_reloc[1], offset_reloc[2], breg);
11584               ep->X_add_number -= 4;
11585               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11586                            offset_reloc[1], offset_reloc[2], breg);
11587             }
11588           else
11589             {
11590               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11591                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11592                            breg);
11593               ep->X_add_number += 4;
11594               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11595                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11596                            breg);
11597             }
11598           break;
11599         }
11600
11601       if (offset_expr.X_op != O_symbol
11602           && offset_expr.X_op != O_constant)
11603         {
11604           as_bad (_("Expression too complex"));
11605           offset_expr.X_op = O_constant;
11606         }
11607
11608       if (HAVE_32BIT_ADDRESSES
11609           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11610         {
11611           char value [32];
11612
11613           sprintf_vma (value, offset_expr.X_add_number);
11614           as_bad (_("Number (0x%s) larger than 32 bits"), value);
11615         }
11616
11617       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11618         {
11619           /* If this is a reference to a GP relative symbol, we want
11620                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11621                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11622              If we have a base register, we use this
11623                addu     $at,$breg,$gp
11624                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11625                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11626              If this is not a GP relative symbol, we want
11627                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11628                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11629                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11630              If there is a base register, we add it to $at after the
11631              lui instruction.  If there is a constant, we always use
11632              the last case.  */
11633           if (offset_expr.X_op == O_symbol
11634               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11635               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11636             {
11637               relax_start (offset_expr.X_add_symbol);
11638               if (breg == 0)
11639                 {
11640                   tempreg = mips_gp_register;
11641                 }
11642               else
11643                 {
11644                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11645                                AT, breg, mips_gp_register);
11646                   tempreg = AT;
11647                   used_at = 1;
11648                 }
11649
11650               /* Itbl support may require additional care here.  */
11651               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11652                            BFD_RELOC_GPREL16, tempreg);
11653               offset_expr.X_add_number += 4;
11654
11655               /* Set mips_optimize to 2 to avoid inserting an
11656                  undesired nop.  */
11657               hold_mips_optimize = mips_optimize;
11658               mips_optimize = 2;
11659               /* Itbl support may require additional care here.  */
11660               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11661                            BFD_RELOC_GPREL16, tempreg);
11662               mips_optimize = hold_mips_optimize;
11663
11664               relax_switch ();
11665
11666               offset_expr.X_add_number -= 4;
11667             }
11668           used_at = 1;
11669           if (offset_high_part (offset_expr.X_add_number, 16)
11670               != offset_high_part (offset_expr.X_add_number + 4, 16))
11671             {
11672               load_address (AT, &offset_expr, &used_at);
11673               offset_expr.X_op = O_constant;
11674               offset_expr.X_add_number = 0;
11675             }
11676           else
11677             macro_build_lui (&offset_expr, AT);
11678           if (breg != 0)
11679             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11680           /* Itbl support may require additional care here.  */
11681           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11682                        BFD_RELOC_LO16, AT);
11683           /* FIXME: How do we handle overflow here?  */
11684           offset_expr.X_add_number += 4;
11685           /* Itbl support may require additional care here.  */
11686           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11687                        BFD_RELOC_LO16, AT);
11688           if (mips_relax.sequence)
11689             relax_end ();
11690         }
11691       else if (!mips_big_got)
11692         {
11693           /* If this is a reference to an external symbol, we want
11694                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11695                nop
11696                <op>     op[0],0($at)
11697                <op>     op[0]+1,4($at)
11698              Otherwise we want
11699                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11700                nop
11701                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11702                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11703              If there is a base register we add it to $at before the
11704              lwc1 instructions.  If there is a constant we include it
11705              in the lwc1 instructions.  */
11706           used_at = 1;
11707           expr1.X_add_number = offset_expr.X_add_number;
11708           if (expr1.X_add_number < -0x8000
11709               || expr1.X_add_number >= 0x8000 - 4)
11710             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11711           load_got_offset (AT, &offset_expr);
11712           load_delay_nop ();
11713           if (breg != 0)
11714             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11715
11716           /* Set mips_optimize to 2 to avoid inserting an undesired
11717              nop.  */
11718           hold_mips_optimize = mips_optimize;
11719           mips_optimize = 2;
11720
11721           /* Itbl support may require additional care here.  */
11722           relax_start (offset_expr.X_add_symbol);
11723           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11724                        BFD_RELOC_LO16, AT);
11725           expr1.X_add_number += 4;
11726           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11727                        BFD_RELOC_LO16, AT);
11728           relax_switch ();
11729           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11730                        BFD_RELOC_LO16, AT);
11731           offset_expr.X_add_number += 4;
11732           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11733                        BFD_RELOC_LO16, AT);
11734           relax_end ();
11735
11736           mips_optimize = hold_mips_optimize;
11737         }
11738       else if (mips_big_got)
11739         {
11740           int gpdelay;
11741
11742           /* If this is a reference to an external symbol, we want
11743                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11744                addu     $at,$at,$gp
11745                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11746                nop
11747                <op>     op[0],0($at)
11748                <op>     op[0]+1,4($at)
11749              Otherwise we want
11750                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11751                nop
11752                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11753                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11754              If there is a base register we add it to $at before the
11755              lwc1 instructions.  If there is a constant we include it
11756              in the lwc1 instructions.  */
11757           used_at = 1;
11758           expr1.X_add_number = offset_expr.X_add_number;
11759           offset_expr.X_add_number = 0;
11760           if (expr1.X_add_number < -0x8000
11761               || expr1.X_add_number >= 0x8000 - 4)
11762             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11763           gpdelay = reg_needs_delay (mips_gp_register);
11764           relax_start (offset_expr.X_add_symbol);
11765           macro_build (&offset_expr, "lui", LUI_FMT,
11766                        AT, BFD_RELOC_MIPS_GOT_HI16);
11767           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11768                        AT, AT, mips_gp_register);
11769           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11770                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11771           load_delay_nop ();
11772           if (breg != 0)
11773             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11774           /* Itbl support may require additional care here.  */
11775           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11776                        BFD_RELOC_LO16, AT);
11777           expr1.X_add_number += 4;
11778
11779           /* Set mips_optimize to 2 to avoid inserting an undesired
11780              nop.  */
11781           hold_mips_optimize = mips_optimize;
11782           mips_optimize = 2;
11783           /* Itbl support may require additional care here.  */
11784           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11785                        BFD_RELOC_LO16, AT);
11786           mips_optimize = hold_mips_optimize;
11787           expr1.X_add_number -= 4;
11788
11789           relax_switch ();
11790           offset_expr.X_add_number = expr1.X_add_number;
11791           if (gpdelay)
11792             macro_build (NULL, "nop", "");
11793           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11794                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11795           load_delay_nop ();
11796           if (breg != 0)
11797             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11798           /* Itbl support may require additional care here.  */
11799           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11800                        BFD_RELOC_LO16, AT);
11801           offset_expr.X_add_number += 4;
11802
11803           /* Set mips_optimize to 2 to avoid inserting an undesired
11804              nop.  */
11805           hold_mips_optimize = mips_optimize;
11806           mips_optimize = 2;
11807           /* Itbl support may require additional care here.  */
11808           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11809                        BFD_RELOC_LO16, AT);
11810           mips_optimize = hold_mips_optimize;
11811           relax_end ();
11812         }
11813       else
11814         abort ();
11815
11816       break;
11817         
11818     case M_SAA_AB:
11819       s = "saa";
11820       offbits = 0;
11821       fmt = "t,(b)";
11822       goto ld_st;
11823     case M_SAAD_AB:
11824       s = "saad";
11825       offbits = 0;
11826       fmt = "t,(b)";
11827       goto ld_st;
11828
11829    /* New code added to support COPZ instructions.
11830       This code builds table entries out of the macros in mip_opcodes.
11831       R4000 uses interlocks to handle coproc delays.
11832       Other chips (like the R3000) require nops to be inserted for delays.
11833
11834       FIXME: Currently, we require that the user handle delays.
11835       In order to fill delay slots for non-interlocked chips,
11836       we must have a way to specify delays based on the coprocessor.
11837       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11838       What are the side-effects of the cop instruction?
11839       What cache support might we have and what are its effects?
11840       Both coprocessor & memory require delays. how long???
11841       What registers are read/set/modified?
11842
11843       If an itbl is provided to interpret cop instructions,
11844       this knowledge can be encoded in the itbl spec.  */
11845
11846     case M_COP0:
11847       s = "c0";
11848       goto copz;
11849     case M_COP1:
11850       s = "c1";
11851       goto copz;
11852     case M_COP2:
11853       s = "c2";
11854       goto copz;
11855     case M_COP3:
11856       s = "c3";
11857     copz:
11858       gas_assert (!mips_opts.micromips);
11859       /* For now we just do C (same as Cz).  The parameter will be
11860          stored in insn_opcode by mips_ip.  */
11861       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11862       break;
11863
11864     case M_MOVE:
11865       move_register (op[0], op[1]);
11866       break;
11867
11868     case M_MOVEP:
11869       gas_assert (mips_opts.micromips);
11870       gas_assert (mips_opts.insn32);
11871       move_register (micromips_to_32_reg_h_map1[op[0]],
11872                      micromips_to_32_reg_m_map[op[1]]);
11873       move_register (micromips_to_32_reg_h_map2[op[0]],
11874                      micromips_to_32_reg_n_map[op[2]]);
11875       break;
11876
11877     case M_DMUL:
11878       dbl = 1;
11879     case M_MUL:
11880       if (mips_opts.arch == CPU_R5900)
11881         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11882                      op[2]);
11883       else
11884         {
11885           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11886           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11887         }
11888       break;
11889
11890     case M_DMUL_I:
11891       dbl = 1;
11892     case M_MUL_I:
11893       /* The MIPS assembler some times generates shifts and adds.  I'm
11894          not trying to be that fancy. GCC should do this for us
11895          anyway.  */
11896       used_at = 1;
11897       load_register (AT, &imm_expr, dbl);
11898       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11899       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11900       break;
11901
11902     case M_DMULO_I:
11903       dbl = 1;
11904     case M_MULO_I:
11905       imm = 1;
11906       goto do_mulo;
11907
11908     case M_DMULO:
11909       dbl = 1;
11910     case M_MULO:
11911     do_mulo:
11912       start_noreorder ();
11913       used_at = 1;
11914       if (imm)
11915         load_register (AT, &imm_expr, dbl);
11916       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11917                    op[1], imm ? AT : op[2]);
11918       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11919       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
11920       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11921       if (mips_trap)
11922         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
11923       else
11924         {
11925           if (mips_opts.micromips)
11926             micromips_label_expr (&label_expr);
11927           else
11928             label_expr.X_add_number = 8;
11929           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
11930           macro_build (NULL, "nop", "");
11931           macro_build (NULL, "break", BRK_FMT, 6);
11932           if (mips_opts.micromips)
11933             micromips_add_label ();
11934         }
11935       end_noreorder ();
11936       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11937       break;
11938
11939     case M_DMULOU_I:
11940       dbl = 1;
11941     case M_MULOU_I:
11942       imm = 1;
11943       goto do_mulou;
11944
11945     case M_DMULOU:
11946       dbl = 1;
11947     case M_MULOU:
11948     do_mulou:
11949       start_noreorder ();
11950       used_at = 1;
11951       if (imm)
11952         load_register (AT, &imm_expr, dbl);
11953       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
11954                    op[1], imm ? AT : op[2]);
11955       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11956       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11957       if (mips_trap)
11958         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
11959       else
11960         {
11961           if (mips_opts.micromips)
11962             micromips_label_expr (&label_expr);
11963           else
11964             label_expr.X_add_number = 8;
11965           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
11966           macro_build (NULL, "nop", "");
11967           macro_build (NULL, "break", BRK_FMT, 6);
11968           if (mips_opts.micromips)
11969             micromips_add_label ();
11970         }
11971       end_noreorder ();
11972       break;
11973
11974     case M_DROL:
11975       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11976         {
11977           if (op[0] == op[1])
11978             {
11979               tempreg = AT;
11980               used_at = 1;
11981             }
11982           else
11983             tempreg = op[0];
11984           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
11985           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
11986           break;
11987         }
11988       used_at = 1;
11989       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
11990       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
11991       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
11992       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11993       break;
11994
11995     case M_ROL:
11996       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11997         {
11998           if (op[0] == op[1])
11999             {
12000               tempreg = AT;
12001               used_at = 1;
12002             }
12003           else
12004             tempreg = op[0];
12005           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12006           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12007           break;
12008         }
12009       used_at = 1;
12010       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12011       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12012       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12013       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12014       break;
12015
12016     case M_DROL_I:
12017       {
12018         unsigned int rot;
12019         char *l;
12020         char *rr;
12021
12022         if (imm_expr.X_op != O_constant)
12023           as_bad (_("Improper rotate count"));
12024         rot = imm_expr.X_add_number & 0x3f;
12025         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12026           {
12027             rot = (64 - rot) & 0x3f;
12028             if (rot >= 32)
12029               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12030             else
12031               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12032             break;
12033           }
12034         if (rot == 0)
12035           {
12036             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12037             break;
12038           }
12039         l = (rot < 0x20) ? "dsll" : "dsll32";
12040         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12041         rot &= 0x1f;
12042         used_at = 1;
12043         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12044         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12045         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12046       }
12047       break;
12048
12049     case M_ROL_I:
12050       {
12051         unsigned int rot;
12052
12053         if (imm_expr.X_op != O_constant)
12054           as_bad (_("Improper rotate count"));
12055         rot = imm_expr.X_add_number & 0x1f;
12056         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12057           {
12058             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12059                          (32 - rot) & 0x1f);
12060             break;
12061           }
12062         if (rot == 0)
12063           {
12064             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12065             break;
12066           }
12067         used_at = 1;
12068         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12069         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12070         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12071       }
12072       break;
12073
12074     case M_DROR:
12075       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12076         {
12077           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12078           break;
12079         }
12080       used_at = 1;
12081       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12082       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12083       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12084       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12085       break;
12086
12087     case M_ROR:
12088       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12089         {
12090           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12091           break;
12092         }
12093       used_at = 1;
12094       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12095       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12096       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12097       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12098       break;
12099
12100     case M_DROR_I:
12101       {
12102         unsigned int rot;
12103         char *l;
12104         char *rr;
12105
12106         if (imm_expr.X_op != O_constant)
12107           as_bad (_("Improper rotate count"));
12108         rot = imm_expr.X_add_number & 0x3f;
12109         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12110           {
12111             if (rot >= 32)
12112               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12113             else
12114               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12115             break;
12116           }
12117         if (rot == 0)
12118           {
12119             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12120             break;
12121           }
12122         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12123         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12124         rot &= 0x1f;
12125         used_at = 1;
12126         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12127         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12128         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12129       }
12130       break;
12131
12132     case M_ROR_I:
12133       {
12134         unsigned int rot;
12135
12136         if (imm_expr.X_op != O_constant)
12137           as_bad (_("Improper rotate count"));
12138         rot = imm_expr.X_add_number & 0x1f;
12139         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12140           {
12141             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12142             break;
12143           }
12144         if (rot == 0)
12145           {
12146             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12147             break;
12148           }
12149         used_at = 1;
12150         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12151         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12152         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12153       }
12154       break;
12155
12156     case M_SEQ:
12157       if (op[1] == 0)
12158         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12159       else if (op[2] == 0)
12160         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12161       else
12162         {
12163           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12164           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12165         }
12166       break;
12167
12168     case M_SEQ_I:
12169       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
12170         {
12171           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12172           break;
12173         }
12174       if (op[1] == 0)
12175         {
12176           as_warn (_("Instruction %s: result is always false"),
12177                    ip->insn_mo->name);
12178           move_register (op[0], 0);
12179           break;
12180         }
12181       if (CPU_HAS_SEQ (mips_opts.arch)
12182           && -512 <= imm_expr.X_add_number
12183           && imm_expr.X_add_number < 512)
12184         {
12185           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12186                        (int) imm_expr.X_add_number);
12187           break;
12188         }
12189       if (imm_expr.X_op == O_constant
12190           && imm_expr.X_add_number >= 0
12191           && imm_expr.X_add_number < 0x10000)
12192         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12193       else if (imm_expr.X_op == O_constant
12194                && imm_expr.X_add_number > -0x8000
12195                && imm_expr.X_add_number < 0)
12196         {
12197           imm_expr.X_add_number = -imm_expr.X_add_number;
12198           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12199                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12200         }
12201       else if (CPU_HAS_SEQ (mips_opts.arch))
12202         {
12203           used_at = 1;
12204           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12205           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12206           break;
12207         }
12208       else
12209         {
12210           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12211           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12212           used_at = 1;
12213         }
12214       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12215       break;
12216
12217     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12218       s = "slt";
12219       goto sge;
12220     case M_SGEU:
12221       s = "sltu";
12222     sge:
12223       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12224       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12225       break;
12226
12227     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12228     case M_SGEU_I:
12229       if (imm_expr.X_op == O_constant
12230           && imm_expr.X_add_number >= -0x8000
12231           && imm_expr.X_add_number < 0x8000)
12232         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12233                      op[0], op[1], BFD_RELOC_LO16);
12234       else
12235         {
12236           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12237           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12238                        op[0], op[1], AT);
12239           used_at = 1;
12240         }
12241       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12242       break;
12243
12244     case M_SGT:         /* X > Y  <==>  Y < X */
12245       s = "slt";
12246       goto sgt;
12247     case M_SGTU:
12248       s = "sltu";
12249     sgt:
12250       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12251       break;
12252
12253     case M_SGT_I:       /* X > I  <==>  I < X */
12254       s = "slt";
12255       goto sgti;
12256     case M_SGTU_I:
12257       s = "sltu";
12258     sgti:
12259       used_at = 1;
12260       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12261       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12262       break;
12263
12264     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12265       s = "slt";
12266       goto sle;
12267     case M_SLEU:
12268       s = "sltu";
12269     sle:
12270       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12271       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12272       break;
12273
12274     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12275       s = "slt";
12276       goto slei;
12277     case M_SLEU_I:
12278       s = "sltu";
12279     slei:
12280       used_at = 1;
12281       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12282       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12283       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12284       break;
12285
12286     case M_SLT_I:
12287       if (imm_expr.X_op == O_constant
12288           && imm_expr.X_add_number >= -0x8000
12289           && imm_expr.X_add_number < 0x8000)
12290         {
12291           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12292                        BFD_RELOC_LO16);
12293           break;
12294         }
12295       used_at = 1;
12296       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12297       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12298       break;
12299
12300     case M_SLTU_I:
12301       if (imm_expr.X_op == O_constant
12302           && imm_expr.X_add_number >= -0x8000
12303           && imm_expr.X_add_number < 0x8000)
12304         {
12305           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12306                        BFD_RELOC_LO16);
12307           break;
12308         }
12309       used_at = 1;
12310       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12311       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12312       break;
12313
12314     case M_SNE:
12315       if (op[1] == 0)
12316         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12317       else if (op[2] == 0)
12318         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12319       else
12320         {
12321           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12322           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12323         }
12324       break;
12325
12326     case M_SNE_I:
12327       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
12328         {
12329           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12330           break;
12331         }
12332       if (op[1] == 0)
12333         {
12334           as_warn (_("Instruction %s: result is always true"),
12335                    ip->insn_mo->name);
12336           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12337                        op[0], 0, BFD_RELOC_LO16);
12338           break;
12339         }
12340       if (CPU_HAS_SEQ (mips_opts.arch)
12341           && -512 <= imm_expr.X_add_number
12342           && imm_expr.X_add_number < 512)
12343         {
12344           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12345                        (int) imm_expr.X_add_number);
12346           break;
12347         }
12348       if (imm_expr.X_op == O_constant
12349           && imm_expr.X_add_number >= 0
12350           && imm_expr.X_add_number < 0x10000)
12351         {
12352           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12353                        BFD_RELOC_LO16);
12354         }
12355       else if (imm_expr.X_op == O_constant
12356                && imm_expr.X_add_number > -0x8000
12357                && imm_expr.X_add_number < 0)
12358         {
12359           imm_expr.X_add_number = -imm_expr.X_add_number;
12360           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12361                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12362         }
12363       else if (CPU_HAS_SEQ (mips_opts.arch))
12364         {
12365           used_at = 1;
12366           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12367           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12368           break;
12369         }
12370       else
12371         {
12372           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12373           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12374           used_at = 1;
12375         }
12376       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12377       break;
12378
12379     case M_SUB_I:
12380       s = "addi";
12381       s2 = "sub";
12382       goto do_subi;
12383     case M_SUBU_I:
12384       s = "addiu";
12385       s2 = "subu";
12386       goto do_subi;
12387     case M_DSUB_I:
12388       dbl = 1;
12389       s = "daddi";
12390       s2 = "dsub";
12391       if (!mips_opts.micromips)
12392         goto do_subi;
12393       if (imm_expr.X_op == O_constant
12394           && imm_expr.X_add_number > -0x200
12395           && imm_expr.X_add_number <= 0x200)
12396         {
12397           macro_build (NULL, s, "t,r,.", op[0], op[1], -imm_expr.X_add_number);
12398           break;
12399         }
12400       goto do_subi_i;
12401     case M_DSUBU_I:
12402       dbl = 1;
12403       s = "daddiu";
12404       s2 = "dsubu";
12405     do_subi:
12406       if (imm_expr.X_op == O_constant
12407           && imm_expr.X_add_number > -0x8000
12408           && imm_expr.X_add_number <= 0x8000)
12409         {
12410           imm_expr.X_add_number = -imm_expr.X_add_number;
12411           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12412           break;
12413         }
12414     do_subi_i:
12415       used_at = 1;
12416       load_register (AT, &imm_expr, dbl);
12417       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12418       break;
12419
12420     case M_TEQ_I:
12421       s = "teq";
12422       goto trap;
12423     case M_TGE_I:
12424       s = "tge";
12425       goto trap;
12426     case M_TGEU_I:
12427       s = "tgeu";
12428       goto trap;
12429     case M_TLT_I:
12430       s = "tlt";
12431       goto trap;
12432     case M_TLTU_I:
12433       s = "tltu";
12434       goto trap;
12435     case M_TNE_I:
12436       s = "tne";
12437     trap:
12438       used_at = 1;
12439       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12440       macro_build (NULL, s, "s,t", op[0], AT);
12441       break;
12442
12443     case M_TRUNCWS:
12444     case M_TRUNCWD:
12445       gas_assert (!mips_opts.micromips);
12446       gas_assert (mips_opts.isa == ISA_MIPS1);
12447       used_at = 1;
12448
12449       /*
12450        * Is the double cfc1 instruction a bug in the mips assembler;
12451        * or is there a reason for it?
12452        */
12453       start_noreorder ();
12454       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12455       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12456       macro_build (NULL, "nop", "");
12457       expr1.X_add_number = 3;
12458       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12459       expr1.X_add_number = 2;
12460       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12461       macro_build (NULL, "ctc1", "t,G", AT, RA);
12462       macro_build (NULL, "nop", "");
12463       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12464                    op[0], op[1]);
12465       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12466       macro_build (NULL, "nop", "");
12467       end_noreorder ();
12468       break;
12469
12470     case M_ULH_AB:
12471       s = "lb";
12472       s2 = "lbu";
12473       off = 1;
12474       goto uld_st;
12475     case M_ULHU_AB:
12476       s = "lbu";
12477       s2 = "lbu";
12478       off = 1;
12479       goto uld_st;
12480     case M_ULW_AB:
12481       s = "lwl";
12482       s2 = "lwr";
12483       offbits = (mips_opts.micromips ? 12 : 16);
12484       off = 3;
12485       goto uld_st;
12486     case M_ULD_AB:
12487       s = "ldl";
12488       s2 = "ldr";
12489       offbits = (mips_opts.micromips ? 12 : 16);
12490       off = 7;
12491       goto uld_st;
12492     case M_USH_AB:
12493       s = "sb";
12494       s2 = "sb";
12495       off = 1;
12496       ust = 1;
12497       goto uld_st;
12498     case M_USW_AB:
12499       s = "swl";
12500       s2 = "swr";
12501       offbits = (mips_opts.micromips ? 12 : 16);
12502       off = 3;
12503       ust = 1;
12504       goto uld_st;
12505     case M_USD_AB:
12506       s = "sdl";
12507       s2 = "sdr";
12508       offbits = (mips_opts.micromips ? 12 : 16);
12509       off = 7;
12510       ust = 1;
12511
12512     uld_st:
12513       breg = op[2];
12514       large_offset = !small_offset_p (off, align, offbits);
12515       ep = &offset_expr;
12516       expr1.X_add_number = 0;
12517       if (large_offset)
12518         {
12519           used_at = 1;
12520           tempreg = AT;
12521           if (small_offset_p (0, align, 16))
12522             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12523                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12524           else
12525             {
12526               load_address (tempreg, ep, &used_at);
12527               if (breg != 0)
12528                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12529                              tempreg, tempreg, breg);
12530             }
12531           offset_reloc[0] = BFD_RELOC_LO16;
12532           offset_reloc[1] = BFD_RELOC_UNUSED;
12533           offset_reloc[2] = BFD_RELOC_UNUSED;
12534           breg = tempreg;
12535           tempreg = op[0];
12536           ep = &expr1;
12537         }
12538       else if (!ust && op[0] == breg)
12539         {
12540           used_at = 1;
12541           tempreg = AT;
12542         }
12543       else
12544         tempreg = op[0];
12545
12546       if (off == 1)
12547         goto ulh_sh;
12548
12549       if (!target_big_endian)
12550         ep->X_add_number += off;
12551       if (offbits == 12)
12552         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12553       else
12554         macro_build (ep, s, "t,o(b)", tempreg, -1,
12555                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12556
12557       if (!target_big_endian)
12558         ep->X_add_number -= off;
12559       else
12560         ep->X_add_number += off;
12561       if (offbits == 12)
12562         macro_build (NULL, s2, "t,~(b)",
12563                      tempreg, (int) ep->X_add_number, breg);
12564       else
12565         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12566                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12567
12568       /* If necessary, move the result in tempreg to the final destination.  */
12569       if (!ust && op[0] != tempreg)
12570         {
12571           /* Protect second load's delay slot.  */
12572           load_delay_nop ();
12573           move_register (op[0], tempreg);
12574         }
12575       break;
12576
12577     ulh_sh:
12578       used_at = 1;
12579       if (target_big_endian == ust)
12580         ep->X_add_number += off;
12581       tempreg = ust || large_offset ? op[0] : AT;
12582       macro_build (ep, s, "t,o(b)", tempreg, -1,
12583                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12584
12585       /* For halfword transfers we need a temporary register to shuffle
12586          bytes.  Unfortunately for M_USH_A we have none available before
12587          the next store as AT holds the base address.  We deal with this
12588          case by clobbering TREG and then restoring it as with ULH.  */
12589       tempreg = ust == large_offset ? op[0] : AT;
12590       if (ust)
12591         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12592
12593       if (target_big_endian == ust)
12594         ep->X_add_number -= off;
12595       else
12596         ep->X_add_number += off;
12597       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12598                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12599
12600       /* For M_USH_A re-retrieve the LSB.  */
12601       if (ust && large_offset)
12602         {
12603           if (target_big_endian)
12604             ep->X_add_number += off;
12605           else
12606             ep->X_add_number -= off;
12607           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12608                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12609         }
12610       /* For ULH and M_USH_A OR the LSB in.  */
12611       if (!ust || large_offset)
12612         {
12613           tempreg = !large_offset ? AT : op[0];
12614           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12615           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12616         }
12617       break;
12618
12619     default:
12620       /* FIXME: Check if this is one of the itbl macros, since they
12621          are added dynamically.  */
12622       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
12623       break;
12624     }
12625   if (!mips_opts.at && used_at)
12626     as_bad (_("Macro used $at after \".set noat\""));
12627 }
12628
12629 /* Implement macros in mips16 mode.  */
12630
12631 static void
12632 mips16_macro (struct mips_cl_insn *ip)
12633 {
12634   const struct mips_operand_array *operands;
12635   int mask;
12636   int tmp;
12637   expressionS expr1;
12638   int dbl;
12639   const char *s, *s2, *s3;
12640   unsigned int op[MAX_OPERANDS];
12641   unsigned int i;
12642
12643   mask = ip->insn_mo->mask;
12644
12645   operands = insn_operands (ip);
12646   for (i = 0; i < MAX_OPERANDS; i++)
12647     if (operands->operand[i])
12648       op[i] = insn_extract_operand (ip, operands->operand[i]);
12649     else
12650       op[i] = -1;
12651
12652   expr1.X_op = O_constant;
12653   expr1.X_op_symbol = NULL;
12654   expr1.X_add_symbol = NULL;
12655   expr1.X_add_number = 1;
12656
12657   dbl = 0;
12658
12659   switch (mask)
12660     {
12661     default:
12662       abort ();
12663
12664     case M_DDIV_3:
12665       dbl = 1;
12666     case M_DIV_3:
12667       s = "mflo";
12668       goto do_div3;
12669     case M_DREM_3:
12670       dbl = 1;
12671     case M_REM_3:
12672       s = "mfhi";
12673     do_div3:
12674       start_noreorder ();
12675       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12676       expr1.X_add_number = 2;
12677       macro_build (&expr1, "bnez", "x,p", op[2]);
12678       macro_build (NULL, "break", "6", 7);
12679
12680       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12681          since that causes an overflow.  We should do that as well,
12682          but I don't see how to do the comparisons without a temporary
12683          register.  */
12684       end_noreorder ();
12685       macro_build (NULL, s, "x", op[0]);
12686       break;
12687
12688     case M_DIVU_3:
12689       s = "divu";
12690       s2 = "mflo";
12691       goto do_divu3;
12692     case M_REMU_3:
12693       s = "divu";
12694       s2 = "mfhi";
12695       goto do_divu3;
12696     case M_DDIVU_3:
12697       s = "ddivu";
12698       s2 = "mflo";
12699       goto do_divu3;
12700     case M_DREMU_3:
12701       s = "ddivu";
12702       s2 = "mfhi";
12703     do_divu3:
12704       start_noreorder ();
12705       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12706       expr1.X_add_number = 2;
12707       macro_build (&expr1, "bnez", "x,p", op[2]);
12708       macro_build (NULL, "break", "6", 7);
12709       end_noreorder ();
12710       macro_build (NULL, s2, "x", op[0]);
12711       break;
12712
12713     case M_DMUL:
12714       dbl = 1;
12715     case M_MUL:
12716       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12717       macro_build (NULL, "mflo", "x", op[0]);
12718       break;
12719
12720     case M_DSUBU_I:
12721       dbl = 1;
12722       goto do_subu;
12723     case M_SUBU_I:
12724     do_subu:
12725       if (imm_expr.X_op != O_constant)
12726         as_bad (_("Unsupported large constant"));
12727       imm_expr.X_add_number = -imm_expr.X_add_number;
12728       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12729       break;
12730
12731     case M_SUBU_I_2:
12732       if (imm_expr.X_op != O_constant)
12733         as_bad (_("Unsupported large constant"));
12734       imm_expr.X_add_number = -imm_expr.X_add_number;
12735       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12736       break;
12737
12738     case M_DSUBU_I_2:
12739       if (imm_expr.X_op != O_constant)
12740         as_bad (_("Unsupported large constant"));
12741       imm_expr.X_add_number = -imm_expr.X_add_number;
12742       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12743       break;
12744
12745     case M_BEQ:
12746       s = "cmp";
12747       s2 = "bteqz";
12748       goto do_branch;
12749     case M_BNE:
12750       s = "cmp";
12751       s2 = "btnez";
12752       goto do_branch;
12753     case M_BLT:
12754       s = "slt";
12755       s2 = "btnez";
12756       goto do_branch;
12757     case M_BLTU:
12758       s = "sltu";
12759       s2 = "btnez";
12760       goto do_branch;
12761     case M_BLE:
12762       s = "slt";
12763       s2 = "bteqz";
12764       goto do_reverse_branch;
12765     case M_BLEU:
12766       s = "sltu";
12767       s2 = "bteqz";
12768       goto do_reverse_branch;
12769     case M_BGE:
12770       s = "slt";
12771       s2 = "bteqz";
12772       goto do_branch;
12773     case M_BGEU:
12774       s = "sltu";
12775       s2 = "bteqz";
12776       goto do_branch;
12777     case M_BGT:
12778       s = "slt";
12779       s2 = "btnez";
12780       goto do_reverse_branch;
12781     case M_BGTU:
12782       s = "sltu";
12783       s2 = "btnez";
12784
12785     do_reverse_branch:
12786       tmp = op[1];
12787       op[1] = op[0];
12788       op[0] = tmp;
12789
12790     do_branch:
12791       macro_build (NULL, s, "x,y", op[0], op[1]);
12792       macro_build (&offset_expr, s2, "p");
12793       break;
12794
12795     case M_BEQ_I:
12796       s = "cmpi";
12797       s2 = "bteqz";
12798       s3 = "x,U";
12799       goto do_branch_i;
12800     case M_BNE_I:
12801       s = "cmpi";
12802       s2 = "btnez";
12803       s3 = "x,U";
12804       goto do_branch_i;
12805     case M_BLT_I:
12806       s = "slti";
12807       s2 = "btnez";
12808       s3 = "x,8";
12809       goto do_branch_i;
12810     case M_BLTU_I:
12811       s = "sltiu";
12812       s2 = "btnez";
12813       s3 = "x,8";
12814       goto do_branch_i;
12815     case M_BLE_I:
12816       s = "slti";
12817       s2 = "btnez";
12818       s3 = "x,8";
12819       goto do_addone_branch_i;
12820     case M_BLEU_I:
12821       s = "sltiu";
12822       s2 = "btnez";
12823       s3 = "x,8";
12824       goto do_addone_branch_i;
12825     case M_BGE_I:
12826       s = "slti";
12827       s2 = "bteqz";
12828       s3 = "x,8";
12829       goto do_branch_i;
12830     case M_BGEU_I:
12831       s = "sltiu";
12832       s2 = "bteqz";
12833       s3 = "x,8";
12834       goto do_branch_i;
12835     case M_BGT_I:
12836       s = "slti";
12837       s2 = "bteqz";
12838       s3 = "x,8";
12839       goto do_addone_branch_i;
12840     case M_BGTU_I:
12841       s = "sltiu";
12842       s2 = "bteqz";
12843       s3 = "x,8";
12844
12845     do_addone_branch_i:
12846       if (imm_expr.X_op != O_constant)
12847         as_bad (_("Unsupported large constant"));
12848       ++imm_expr.X_add_number;
12849
12850     do_branch_i:
12851       macro_build (&imm_expr, s, s3, op[0]);
12852       macro_build (&offset_expr, s2, "p");
12853       break;
12854
12855     case M_ABS:
12856       expr1.X_add_number = 0;
12857       macro_build (&expr1, "slti", "x,8", op[1]);
12858       if (op[0] != op[1])
12859         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12860       expr1.X_add_number = 2;
12861       macro_build (&expr1, "bteqz", "p");
12862       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12863       break;
12864     }
12865 }
12866
12867 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12868    opcode bits in *OPCODE_EXTRA.  */
12869
12870 static struct mips_opcode *
12871 mips_lookup_insn (struct hash_control *hash, const char *start,
12872                   ssize_t length, unsigned int *opcode_extra)
12873 {
12874   char *name, *dot, *p;
12875   unsigned int mask, suffix;
12876   ssize_t opend;
12877   struct mips_opcode *insn;
12878
12879   /* Make a copy of the instruction so that we can fiddle with it.  */
12880   name = alloca (length + 1);
12881   memcpy (name, start, length);
12882   name[length] = '\0';
12883
12884   /* Look up the instruction as-is.  */
12885   insn = (struct mips_opcode *) hash_find (hash, name);
12886   if (insn)
12887     return insn;
12888
12889   dot = strchr (name, '.');
12890   if (dot && dot[1])
12891     {
12892       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12893       p = mips_parse_vu0_channels (dot + 1, &mask);
12894       if (*p == 0 && mask != 0)
12895         {
12896           *dot = 0;
12897           insn = (struct mips_opcode *) hash_find (hash, name);
12898           *dot = '.';
12899           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12900             {
12901               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12902               return insn;
12903             }
12904         }
12905     }
12906
12907   if (mips_opts.micromips)
12908     {
12909       /* See if there's an instruction size override suffix,
12910          either `16' or `32', at the end of the mnemonic proper,
12911          that defines the operation, i.e. before the first `.'
12912          character if any.  Strip it and retry.  */
12913       opend = dot != NULL ? dot - name : length;
12914       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12915         suffix = 2;
12916       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12917         suffix = 4;
12918       else
12919         suffix = 0;
12920       if (suffix)
12921         {
12922           memcpy (name + opend - 2, name + opend, length - opend + 1);
12923           insn = (struct mips_opcode *) hash_find (hash, name);
12924           if (insn)
12925             {
12926               forced_insn_length = suffix;
12927               return insn;
12928             }
12929         }
12930     }
12931
12932   return NULL;
12933 }
12934
12935 /* Assemble an instruction into its binary format.  If the instruction
12936    is a macro, set imm_expr, imm2_expr and offset_expr to the values
12937    associated with "I", "+I" and "A" operands respectively.  Otherwise
12938    store the value of the relocatable field (if any) in offset_expr.
12939    In both cases set offset_reloc to the relocation operators applied
12940    to offset_expr.  */
12941
12942 static void
12943 mips_ip (char *str, struct mips_cl_insn *insn)
12944 {
12945   const struct mips_opcode *first, *past;
12946   struct hash_control *hash;
12947   char format;
12948   size_t end;
12949   struct mips_operand_token *tokens;
12950   unsigned int opcode_extra;
12951
12952   if (mips_opts.micromips)
12953     {
12954       hash = micromips_op_hash;
12955       past = &micromips_opcodes[bfd_micromips_num_opcodes];
12956     }
12957   else
12958     {
12959       hash = op_hash;
12960       past = &mips_opcodes[NUMOPCODES];
12961     }
12962   forced_insn_length = 0;
12963   opcode_extra = 0;
12964
12965   /* We first try to match an instruction up to a space or to the end.  */
12966   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
12967     continue;
12968
12969   first = mips_lookup_insn (hash, str, end, &opcode_extra);
12970   if (first == NULL)
12971     {
12972       set_insn_error (0, _("Unrecognized opcode"));
12973       return;
12974     }
12975
12976   if (strcmp (first->name, "li.s") == 0)
12977     format = 'f';
12978   else if (strcmp (first->name, "li.d") == 0)
12979     format = 'd';
12980   else
12981     format = 0;
12982   tokens = mips_parse_arguments (str + end, format);
12983   if (!tokens)
12984     return;
12985
12986   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
12987       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
12988     set_insn_error (0, _("Illegal operands"));
12989
12990   obstack_free (&mips_operand_tokens, tokens);
12991 }
12992
12993 /* As for mips_ip, but used when assembling MIPS16 code.
12994    Also set forced_insn_length to the resulting instruction size in
12995    bytes if the user explicitly requested a small or extended instruction.  */
12996
12997 static void
12998 mips16_ip (char *str, struct mips_cl_insn *insn)
12999 {
13000   char *end, *s, c;
13001   struct mips_opcode *first;
13002   struct mips_operand_token *tokens;
13003
13004   forced_insn_length = 0;
13005
13006   for (s = str; ISLOWER (*s); ++s)
13007     ;
13008   end = s;
13009   c = *end;
13010   switch (c)
13011     {
13012     case '\0':
13013       break;
13014
13015     case ' ':
13016       s++;
13017       break;
13018
13019     case '.':
13020       if (s[1] == 't' && s[2] == ' ')
13021         {
13022           forced_insn_length = 2;
13023           s += 3;
13024           break;
13025         }
13026       else if (s[1] == 'e' && s[2] == ' ')
13027         {
13028           forced_insn_length = 4;
13029           s += 3;
13030           break;
13031         }
13032       /* Fall through.  */
13033     default:
13034       set_insn_error (0, _("Unrecognized opcode"));
13035       return;
13036     }
13037
13038   if (mips_opts.noautoextend && !forced_insn_length)
13039     forced_insn_length = 2;
13040
13041   *end = 0;
13042   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13043   *end = c;
13044
13045   if (!first)
13046     {
13047       set_insn_error (0, _("Unrecognized opcode"));
13048       return;
13049     }
13050
13051   tokens = mips_parse_arguments (s, 0);
13052   if (!tokens)
13053     return;
13054
13055   if (!match_mips16_insns (insn, first, tokens))
13056     set_insn_error (0, _("Illegal operands"));
13057
13058   obstack_free (&mips_operand_tokens, tokens);
13059 }
13060
13061 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13062    NBITS is the number of significant bits in VAL.  */
13063
13064 static unsigned long
13065 mips16_immed_extend (offsetT val, unsigned int nbits)
13066 {
13067   int extval;
13068   if (nbits == 16)
13069     {
13070       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13071       val &= 0x1f;
13072     }
13073   else if (nbits == 15)
13074     {
13075       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13076       val &= 0xf;
13077     }
13078   else
13079     {
13080       extval = ((val & 0x1f) << 6) | (val & 0x20);
13081       val = 0;
13082     }
13083   return (extval << 16) | val;
13084 }
13085
13086 /* Like decode_mips16_operand, but require the operand to be defined and
13087    require it to be an integer.  */
13088
13089 static const struct mips_int_operand *
13090 mips16_immed_operand (int type, bfd_boolean extended_p)
13091 {
13092   const struct mips_operand *operand;
13093
13094   operand = decode_mips16_operand (type, extended_p);
13095   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13096     abort ();
13097   return (const struct mips_int_operand *) operand;
13098 }
13099
13100 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13101
13102 static bfd_boolean
13103 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13104                          bfd_reloc_code_real_type reloc, offsetT sval)
13105 {
13106   int min_val, max_val;
13107
13108   min_val = mips_int_operand_min (operand);
13109   max_val = mips_int_operand_max (operand);
13110   if (reloc != BFD_RELOC_UNUSED)
13111     {
13112       if (min_val < 0)
13113         sval = SEXT_16BIT (sval);
13114       else
13115         sval &= 0xffff;
13116     }
13117
13118   return (sval >= min_val
13119           && sval <= max_val
13120           && (sval & ((1 << operand->shift) - 1)) == 0);
13121 }
13122
13123 /* Install immediate value VAL into MIPS16 instruction *INSN,
13124    extending it if necessary.  The instruction in *INSN may
13125    already be extended.
13126
13127    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13128    if none.  In the former case, VAL is a 16-bit number with no
13129    defined signedness.
13130
13131    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13132    is the length that the user requested, or 0 if none.  */
13133
13134 static void
13135 mips16_immed (char *file, unsigned int line, int type,
13136               bfd_reloc_code_real_type reloc, offsetT val,
13137               unsigned int user_insn_length, unsigned long *insn)
13138 {
13139   const struct mips_int_operand *operand;
13140   unsigned int uval, length;
13141
13142   operand = mips16_immed_operand (type, FALSE);
13143   if (!mips16_immed_in_range_p (operand, reloc, val))
13144     {
13145       /* We need an extended instruction.  */
13146       if (user_insn_length == 2)
13147         as_bad_where (file, line, _("invalid unextended operand value"));
13148       else
13149         *insn |= MIPS16_EXTEND;
13150     }
13151   else if (user_insn_length == 4)
13152     {
13153       /* The operand doesn't force an unextended instruction to be extended.
13154          Warn if the user wanted an extended instruction anyway.  */
13155       *insn |= MIPS16_EXTEND;
13156       as_warn_where (file, line,
13157                      _("extended operand requested but not required"));
13158     }
13159
13160   length = mips16_opcode_length (*insn);
13161   if (length == 4)
13162     {
13163       operand = mips16_immed_operand (type, TRUE);
13164       if (!mips16_immed_in_range_p (operand, reloc, val))
13165         as_bad_where (file, line,
13166                       _("operand value out of range for instruction"));
13167     }
13168   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13169   if (length == 2)
13170     *insn = mips_insert_operand (&operand->root, *insn, uval);
13171   else
13172     *insn |= mips16_immed_extend (uval, operand->root.size);
13173 }
13174 \f
13175 struct percent_op_match
13176 {
13177   const char *str;
13178   bfd_reloc_code_real_type reloc;
13179 };
13180
13181 static const struct percent_op_match mips_percent_op[] =
13182 {
13183   {"%lo", BFD_RELOC_LO16},
13184   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13185   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13186   {"%call16", BFD_RELOC_MIPS_CALL16},
13187   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13188   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13189   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13190   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13191   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13192   {"%got", BFD_RELOC_MIPS_GOT16},
13193   {"%gp_rel", BFD_RELOC_GPREL16},
13194   {"%half", BFD_RELOC_16},
13195   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13196   {"%higher", BFD_RELOC_MIPS_HIGHER},
13197   {"%neg", BFD_RELOC_MIPS_SUB},
13198   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13199   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13200   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13201   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13202   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13203   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13204   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13205   {"%hi", BFD_RELOC_HI16_S}
13206 };
13207
13208 static const struct percent_op_match mips16_percent_op[] =
13209 {
13210   {"%lo", BFD_RELOC_MIPS16_LO16},
13211   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13212   {"%got", BFD_RELOC_MIPS16_GOT16},
13213   {"%call16", BFD_RELOC_MIPS16_CALL16},
13214   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13215   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13216   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13217   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13218   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13219   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13220   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13221   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13222 };
13223
13224
13225 /* Return true if *STR points to a relocation operator.  When returning true,
13226    move *STR over the operator and store its relocation code in *RELOC.
13227    Leave both *STR and *RELOC alone when returning false.  */
13228
13229 static bfd_boolean
13230 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13231 {
13232   const struct percent_op_match *percent_op;
13233   size_t limit, i;
13234
13235   if (mips_opts.mips16)
13236     {
13237       percent_op = mips16_percent_op;
13238       limit = ARRAY_SIZE (mips16_percent_op);
13239     }
13240   else
13241     {
13242       percent_op = mips_percent_op;
13243       limit = ARRAY_SIZE (mips_percent_op);
13244     }
13245
13246   for (i = 0; i < limit; i++)
13247     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13248       {
13249         int len = strlen (percent_op[i].str);
13250
13251         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13252           continue;
13253
13254         *str += strlen (percent_op[i].str);
13255         *reloc = percent_op[i].reloc;
13256
13257         /* Check whether the output BFD supports this relocation.
13258            If not, issue an error and fall back on something safe.  */
13259         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13260           {
13261             as_bad (_("relocation %s isn't supported by the current ABI"),
13262                     percent_op[i].str);
13263             *reloc = BFD_RELOC_UNUSED;
13264           }
13265         return TRUE;
13266       }
13267   return FALSE;
13268 }
13269
13270
13271 /* Parse string STR as a 16-bit relocatable operand.  Store the
13272    expression in *EP and the relocations in the array starting
13273    at RELOC.  Return the number of relocation operators used.
13274
13275    On exit, EXPR_END points to the first character after the expression.  */
13276
13277 static size_t
13278 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13279                        char *str)
13280 {
13281   bfd_reloc_code_real_type reversed_reloc[3];
13282   size_t reloc_index, i;
13283   int crux_depth, str_depth;
13284   char *crux;
13285
13286   /* Search for the start of the main expression, recoding relocations
13287      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13288      of the main expression and with CRUX_DEPTH containing the number
13289      of open brackets at that point.  */
13290   reloc_index = -1;
13291   str_depth = 0;
13292   do
13293     {
13294       reloc_index++;
13295       crux = str;
13296       crux_depth = str_depth;
13297
13298       /* Skip over whitespace and brackets, keeping count of the number
13299          of brackets.  */
13300       while (*str == ' ' || *str == '\t' || *str == '(')
13301         if (*str++ == '(')
13302           str_depth++;
13303     }
13304   while (*str == '%'
13305          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13306          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13307
13308   my_getExpression (ep, crux);
13309   str = expr_end;
13310
13311   /* Match every open bracket.  */
13312   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13313     if (*str++ == ')')
13314       crux_depth--;
13315
13316   if (crux_depth > 0)
13317     as_bad (_("unclosed '('"));
13318
13319   expr_end = str;
13320
13321   if (reloc_index != 0)
13322     {
13323       prev_reloc_op_frag = frag_now;
13324       for (i = 0; i < reloc_index; i++)
13325         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13326     }
13327
13328   return reloc_index;
13329 }
13330
13331 static void
13332 my_getExpression (expressionS *ep, char *str)
13333 {
13334   char *save_in;
13335
13336   save_in = input_line_pointer;
13337   input_line_pointer = str;
13338   expression (ep);
13339   expr_end = input_line_pointer;
13340   input_line_pointer = save_in;
13341 }
13342
13343 char *
13344 md_atof (int type, char *litP, int *sizeP)
13345 {
13346   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13347 }
13348
13349 void
13350 md_number_to_chars (char *buf, valueT val, int n)
13351 {
13352   if (target_big_endian)
13353     number_to_chars_bigendian (buf, val, n);
13354   else
13355     number_to_chars_littleendian (buf, val, n);
13356 }
13357 \f
13358 static int support_64bit_objects(void)
13359 {
13360   const char **list, **l;
13361   int yes;
13362
13363   list = bfd_target_list ();
13364   for (l = list; *l != NULL; l++)
13365     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13366         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13367       break;
13368   yes = (*l != NULL);
13369   free (list);
13370   return yes;
13371 }
13372
13373 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13374    NEW_VALUE.  Warn if another value was already specified.  Note:
13375    we have to defer parsing the -march and -mtune arguments in order
13376    to handle 'from-abi' correctly, since the ABI might be specified
13377    in a later argument.  */
13378
13379 static void
13380 mips_set_option_string (const char **string_ptr, const char *new_value)
13381 {
13382   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13383     as_warn (_("A different %s was already specified, is now %s"),
13384              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13385              new_value);
13386
13387   *string_ptr = new_value;
13388 }
13389
13390 int
13391 md_parse_option (int c, char *arg)
13392 {
13393   unsigned int i;
13394
13395   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13396     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13397       {
13398         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13399                                            c == mips_ases[i].option_on);
13400         return 1;
13401       }
13402
13403   switch (c)
13404     {
13405     case OPTION_CONSTRUCT_FLOATS:
13406       mips_disable_float_construction = 0;
13407       break;
13408
13409     case OPTION_NO_CONSTRUCT_FLOATS:
13410       mips_disable_float_construction = 1;
13411       break;
13412
13413     case OPTION_TRAP:
13414       mips_trap = 1;
13415       break;
13416
13417     case OPTION_BREAK:
13418       mips_trap = 0;
13419       break;
13420
13421     case OPTION_EB:
13422       target_big_endian = 1;
13423       break;
13424
13425     case OPTION_EL:
13426       target_big_endian = 0;
13427       break;
13428
13429     case 'O':
13430       if (arg == NULL)
13431         mips_optimize = 1;
13432       else if (arg[0] == '0')
13433         mips_optimize = 0;
13434       else if (arg[0] == '1')
13435         mips_optimize = 1;
13436       else
13437         mips_optimize = 2;
13438       break;
13439
13440     case 'g':
13441       if (arg == NULL)
13442         mips_debug = 2;
13443       else
13444         mips_debug = atoi (arg);
13445       break;
13446
13447     case OPTION_MIPS1:
13448       file_mips_isa = ISA_MIPS1;
13449       break;
13450
13451     case OPTION_MIPS2:
13452       file_mips_isa = ISA_MIPS2;
13453       break;
13454
13455     case OPTION_MIPS3:
13456       file_mips_isa = ISA_MIPS3;
13457       break;
13458
13459     case OPTION_MIPS4:
13460       file_mips_isa = ISA_MIPS4;
13461       break;
13462
13463     case OPTION_MIPS5:
13464       file_mips_isa = ISA_MIPS5;
13465       break;
13466
13467     case OPTION_MIPS32:
13468       file_mips_isa = ISA_MIPS32;
13469       break;
13470
13471     case OPTION_MIPS32R2:
13472       file_mips_isa = ISA_MIPS32R2;
13473       break;
13474
13475     case OPTION_MIPS64R2:
13476       file_mips_isa = ISA_MIPS64R2;
13477       break;
13478
13479     case OPTION_MIPS64:
13480       file_mips_isa = ISA_MIPS64;
13481       break;
13482
13483     case OPTION_MTUNE:
13484       mips_set_option_string (&mips_tune_string, arg);
13485       break;
13486
13487     case OPTION_MARCH:
13488       mips_set_option_string (&mips_arch_string, arg);
13489       break;
13490
13491     case OPTION_M4650:
13492       mips_set_option_string (&mips_arch_string, "4650");
13493       mips_set_option_string (&mips_tune_string, "4650");
13494       break;
13495
13496     case OPTION_NO_M4650:
13497       break;
13498
13499     case OPTION_M4010:
13500       mips_set_option_string (&mips_arch_string, "4010");
13501       mips_set_option_string (&mips_tune_string, "4010");
13502       break;
13503
13504     case OPTION_NO_M4010:
13505       break;
13506
13507     case OPTION_M4100:
13508       mips_set_option_string (&mips_arch_string, "4100");
13509       mips_set_option_string (&mips_tune_string, "4100");
13510       break;
13511
13512     case OPTION_NO_M4100:
13513       break;
13514
13515     case OPTION_M3900:
13516       mips_set_option_string (&mips_arch_string, "3900");
13517       mips_set_option_string (&mips_tune_string, "3900");
13518       break;
13519
13520     case OPTION_NO_M3900:
13521       break;
13522
13523     case OPTION_MICROMIPS:
13524       if (mips_opts.mips16 == 1)
13525         {
13526           as_bad (_("-mmicromips cannot be used with -mips16"));
13527           return 0;
13528         }
13529       mips_opts.micromips = 1;
13530       mips_no_prev_insn ();
13531       break;
13532
13533     case OPTION_NO_MICROMIPS:
13534       mips_opts.micromips = 0;
13535       mips_no_prev_insn ();
13536       break;
13537
13538     case OPTION_MIPS16:
13539       if (mips_opts.micromips == 1)
13540         {
13541           as_bad (_("-mips16 cannot be used with -micromips"));
13542           return 0;
13543         }
13544       mips_opts.mips16 = 1;
13545       mips_no_prev_insn ();
13546       break;
13547
13548     case OPTION_NO_MIPS16:
13549       mips_opts.mips16 = 0;
13550       mips_no_prev_insn ();
13551       break;
13552
13553     case OPTION_FIX_24K:
13554       mips_fix_24k = 1;
13555       break;
13556
13557     case OPTION_NO_FIX_24K:
13558       mips_fix_24k = 0;
13559       break;
13560
13561     case OPTION_FIX_LOONGSON2F_JUMP:
13562       mips_fix_loongson2f_jump = TRUE;
13563       break;
13564
13565     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13566       mips_fix_loongson2f_jump = FALSE;
13567       break;
13568
13569     case OPTION_FIX_LOONGSON2F_NOP:
13570       mips_fix_loongson2f_nop = TRUE;
13571       break;
13572
13573     case OPTION_NO_FIX_LOONGSON2F_NOP:
13574       mips_fix_loongson2f_nop = FALSE;
13575       break;
13576
13577     case OPTION_FIX_VR4120:
13578       mips_fix_vr4120 = 1;
13579       break;
13580
13581     case OPTION_NO_FIX_VR4120:
13582       mips_fix_vr4120 = 0;
13583       break;
13584
13585     case OPTION_FIX_VR4130:
13586       mips_fix_vr4130 = 1;
13587       break;
13588
13589     case OPTION_NO_FIX_VR4130:
13590       mips_fix_vr4130 = 0;
13591       break;
13592
13593     case OPTION_FIX_CN63XXP1:
13594       mips_fix_cn63xxp1 = TRUE;
13595       break;
13596
13597     case OPTION_NO_FIX_CN63XXP1:
13598       mips_fix_cn63xxp1 = FALSE;
13599       break;
13600
13601     case OPTION_RELAX_BRANCH:
13602       mips_relax_branch = 1;
13603       break;
13604
13605     case OPTION_NO_RELAX_BRANCH:
13606       mips_relax_branch = 0;
13607       break;
13608
13609     case OPTION_INSN32:
13610       mips_opts.insn32 = TRUE;
13611       break;
13612
13613     case OPTION_NO_INSN32:
13614       mips_opts.insn32 = FALSE;
13615       break;
13616
13617     case OPTION_MSHARED:
13618       mips_in_shared = TRUE;
13619       break;
13620
13621     case OPTION_MNO_SHARED:
13622       mips_in_shared = FALSE;
13623       break;
13624
13625     case OPTION_MSYM32:
13626       mips_opts.sym32 = TRUE;
13627       break;
13628
13629     case OPTION_MNO_SYM32:
13630       mips_opts.sym32 = FALSE;
13631       break;
13632
13633       /* When generating ELF code, we permit -KPIC and -call_shared to
13634          select SVR4_PIC, and -non_shared to select no PIC.  This is
13635          intended to be compatible with Irix 5.  */
13636     case OPTION_CALL_SHARED:
13637       mips_pic = SVR4_PIC;
13638       mips_abicalls = TRUE;
13639       break;
13640
13641     case OPTION_CALL_NONPIC:
13642       mips_pic = NO_PIC;
13643       mips_abicalls = TRUE;
13644       break;
13645
13646     case OPTION_NON_SHARED:
13647       mips_pic = NO_PIC;
13648       mips_abicalls = FALSE;
13649       break;
13650
13651       /* The -xgot option tells the assembler to use 32 bit offsets
13652          when accessing the got in SVR4_PIC mode.  It is for Irix
13653          compatibility.  */
13654     case OPTION_XGOT:
13655       mips_big_got = 1;
13656       break;
13657
13658     case 'G':
13659       g_switch_value = atoi (arg);
13660       g_switch_seen = 1;
13661       break;
13662
13663       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13664          and -mabi=64.  */
13665     case OPTION_32:
13666       mips_abi = O32_ABI;
13667       break;
13668
13669     case OPTION_N32:
13670       mips_abi = N32_ABI;
13671       break;
13672
13673     case OPTION_64:
13674       mips_abi = N64_ABI;
13675       if (!support_64bit_objects())
13676         as_fatal (_("No compiled in support for 64 bit object file format"));
13677       break;
13678
13679     case OPTION_GP32:
13680       file_mips_gp32 = 1;
13681       break;
13682
13683     case OPTION_GP64:
13684       file_mips_gp32 = 0;
13685       break;
13686
13687     case OPTION_FP32:
13688       file_mips_fp32 = 1;
13689       break;
13690
13691     case OPTION_FP64:
13692       file_mips_fp32 = 0;
13693       break;
13694
13695     case OPTION_SINGLE_FLOAT:
13696       file_mips_single_float = 1;
13697       break;
13698
13699     case OPTION_DOUBLE_FLOAT:
13700       file_mips_single_float = 0;
13701       break;
13702
13703     case OPTION_SOFT_FLOAT:
13704       file_mips_soft_float = 1;
13705       break;
13706
13707     case OPTION_HARD_FLOAT:
13708       file_mips_soft_float = 0;
13709       break;
13710
13711     case OPTION_MABI:
13712       if (strcmp (arg, "32") == 0)
13713         mips_abi = O32_ABI;
13714       else if (strcmp (arg, "o64") == 0)
13715         mips_abi = O64_ABI;
13716       else if (strcmp (arg, "n32") == 0)
13717         mips_abi = N32_ABI;
13718       else if (strcmp (arg, "64") == 0)
13719         {
13720           mips_abi = N64_ABI;
13721           if (! support_64bit_objects())
13722             as_fatal (_("No compiled in support for 64 bit object file "
13723                         "format"));
13724         }
13725       else if (strcmp (arg, "eabi") == 0)
13726         mips_abi = EABI_ABI;
13727       else
13728         {
13729           as_fatal (_("invalid abi -mabi=%s"), arg);
13730           return 0;
13731         }
13732       break;
13733
13734     case OPTION_M7000_HILO_FIX:
13735       mips_7000_hilo_fix = TRUE;
13736       break;
13737
13738     case OPTION_MNO_7000_HILO_FIX:
13739       mips_7000_hilo_fix = FALSE;
13740       break;
13741
13742     case OPTION_MDEBUG:
13743       mips_flag_mdebug = TRUE;
13744       break;
13745
13746     case OPTION_NO_MDEBUG:
13747       mips_flag_mdebug = FALSE;
13748       break;
13749
13750     case OPTION_PDR:
13751       mips_flag_pdr = TRUE;
13752       break;
13753
13754     case OPTION_NO_PDR:
13755       mips_flag_pdr = FALSE;
13756       break;
13757
13758     case OPTION_MVXWORKS_PIC:
13759       mips_pic = VXWORKS_PIC;
13760       break;
13761
13762     case OPTION_NAN:
13763       if (strcmp (arg, "2008") == 0)
13764         mips_flag_nan2008 = TRUE;
13765       else if (strcmp (arg, "legacy") == 0)
13766         mips_flag_nan2008 = FALSE;
13767       else
13768         {
13769           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13770           return 0;
13771         }
13772       break;
13773
13774     default:
13775       return 0;
13776     }
13777
13778     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13779
13780   return 1;
13781 }
13782 \f
13783 /* Set up globals to generate code for the ISA or processor
13784    described by INFO.  */
13785
13786 static void
13787 mips_set_architecture (const struct mips_cpu_info *info)
13788 {
13789   if (info != 0)
13790     {
13791       file_mips_arch = info->cpu;
13792       mips_opts.arch = info->cpu;
13793       mips_opts.isa = info->isa;
13794     }
13795 }
13796
13797
13798 /* Likewise for tuning.  */
13799
13800 static void
13801 mips_set_tune (const struct mips_cpu_info *info)
13802 {
13803   if (info != 0)
13804     mips_tune = info->cpu;
13805 }
13806
13807
13808 void
13809 mips_after_parse_args (void)
13810 {
13811   const struct mips_cpu_info *arch_info = 0;
13812   const struct mips_cpu_info *tune_info = 0;
13813
13814   /* GP relative stuff not working for PE */
13815   if (strncmp (TARGET_OS, "pe", 2) == 0)
13816     {
13817       if (g_switch_seen && g_switch_value != 0)
13818         as_bad (_("-G not supported in this configuration."));
13819       g_switch_value = 0;
13820     }
13821
13822   if (mips_abi == NO_ABI)
13823     mips_abi = MIPS_DEFAULT_ABI;
13824
13825   /* The following code determines the architecture and register size.
13826      Similar code was added to GCC 3.3 (see override_options() in
13827      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13828      as much as possible.  */
13829
13830   if (mips_arch_string != 0)
13831     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13832
13833   if (file_mips_isa != ISA_UNKNOWN)
13834     {
13835       /* Handle -mipsN.  At this point, file_mips_isa contains the
13836          ISA level specified by -mipsN, while arch_info->isa contains
13837          the -march selection (if any).  */
13838       if (arch_info != 0)
13839         {
13840           /* -march takes precedence over -mipsN, since it is more descriptive.
13841              There's no harm in specifying both as long as the ISA levels
13842              are the same.  */
13843           if (file_mips_isa != arch_info->isa)
13844             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13845                     mips_cpu_info_from_isa (file_mips_isa)->name,
13846                     mips_cpu_info_from_isa (arch_info->isa)->name);
13847         }
13848       else
13849         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13850     }
13851
13852   if (arch_info == 0)
13853     {
13854       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13855       gas_assert (arch_info);
13856     }
13857
13858   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13859     as_bad (_("-march=%s is not compatible with the selected ABI"),
13860             arch_info->name);
13861
13862   mips_set_architecture (arch_info);
13863
13864   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13865   if (mips_tune_string != 0)
13866     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13867
13868   if (tune_info == 0)
13869     mips_set_tune (arch_info);
13870   else
13871     mips_set_tune (tune_info);
13872
13873   if (file_mips_gp32 >= 0)
13874     {
13875       /* The user specified the size of the integer registers.  Make sure
13876          it agrees with the ABI and ISA.  */
13877       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13878         as_bad (_("-mgp64 used with a 32-bit processor"));
13879       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13880         as_bad (_("-mgp32 used with a 64-bit ABI"));
13881       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13882         as_bad (_("-mgp64 used with a 32-bit ABI"));
13883     }
13884   else
13885     {
13886       /* Infer the integer register size from the ABI and processor.
13887          Restrict ourselves to 32-bit registers if that's all the
13888          processor has, or if the ABI cannot handle 64-bit registers.  */
13889       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13890                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13891     }
13892
13893   switch (file_mips_fp32)
13894     {
13895     default:
13896     case -1:
13897       /* No user specified float register size.
13898          ??? GAS treats single-float processors as though they had 64-bit
13899          float registers (although it complains when double-precision
13900          instructions are used).  As things stand, saying they have 32-bit
13901          registers would lead to spurious "register must be even" messages.
13902          So here we assume float registers are never smaller than the
13903          integer ones.  */
13904       if (file_mips_gp32 == 0)
13905         /* 64-bit integer registers implies 64-bit float registers.  */
13906         file_mips_fp32 = 0;
13907       else if ((mips_opts.ase & FP64_ASES)
13908                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13909         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13910         file_mips_fp32 = 0;
13911       else
13912         /* 32-bit float registers.  */
13913         file_mips_fp32 = 1;
13914       break;
13915
13916     /* The user specified the size of the float registers.  Check if it
13917        agrees with the ABI and ISA.  */
13918     case 0:
13919       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13920         as_bad (_("-mfp64 used with a 32-bit fpu"));
13921       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13922                && !ISA_HAS_MXHC1 (mips_opts.isa))
13923         as_warn (_("-mfp64 used with a 32-bit ABI"));
13924       break;
13925     case 1:
13926       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13927         as_warn (_("-mfp32 used with a 64-bit ABI"));
13928       break;
13929     }
13930
13931   /* End of GCC-shared inference code.  */
13932
13933   /* This flag is set when we have a 64-bit capable CPU but use only
13934      32-bit wide registers.  Note that EABI does not use it.  */
13935   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13936       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13937           || mips_abi == O32_ABI))
13938     mips_32bitmode = 1;
13939
13940   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13941     as_bad (_("trap exception not supported at ISA 1"));
13942
13943   /* If the selected architecture includes support for ASEs, enable
13944      generation of code for them.  */
13945   if (mips_opts.mips16 == -1)
13946     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13947   if (mips_opts.micromips == -1)
13948     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13949
13950   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13951      ASEs from being selected implicitly.  */
13952   if (file_mips_fp32 == 1)
13953     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13954
13955   /* If the user didn't explicitly select or deselect a particular ASE,
13956      use the default setting for the CPU.  */
13957   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13958
13959   file_mips_isa = mips_opts.isa;
13960   file_ase = mips_opts.ase;
13961   mips_opts.gp32 = file_mips_gp32;
13962   mips_opts.fp32 = file_mips_fp32;
13963   mips_opts.soft_float = file_mips_soft_float;
13964   mips_opts.single_float = file_mips_single_float;
13965
13966   mips_check_isa_supports_ases ();
13967
13968   if (mips_flag_mdebug < 0)
13969     mips_flag_mdebug = 0;
13970 }
13971 \f
13972 void
13973 mips_init_after_args (void)
13974 {
13975   /* initialize opcodes */
13976   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
13977   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
13978 }
13979
13980 long
13981 md_pcrel_from (fixS *fixP)
13982 {
13983   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
13984   switch (fixP->fx_r_type)
13985     {
13986     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13987     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13988       /* Return the address of the delay slot.  */
13989       return addr + 2;
13990
13991     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13992     case BFD_RELOC_MICROMIPS_JMP:
13993     case BFD_RELOC_16_PCREL_S2:
13994     case BFD_RELOC_MIPS_JMP:
13995       /* Return the address of the delay slot.  */
13996       return addr + 4;
13997
13998     case BFD_RELOC_32_PCREL:
13999       return addr;
14000
14001     default:
14002       /* We have no relocation type for PC relative MIPS16 instructions.  */
14003       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
14004         as_bad_where (fixP->fx_file, fixP->fx_line,
14005                       _("PC relative MIPS16 instruction references a different section"));
14006       return addr;
14007     }
14008 }
14009
14010 /* This is called before the symbol table is processed.  In order to
14011    work with gcc when using mips-tfile, we must keep all local labels.
14012    However, in other cases, we want to discard them.  If we were
14013    called with -g, but we didn't see any debugging information, it may
14014    mean that gcc is smuggling debugging information through to
14015    mips-tfile, in which case we must generate all local labels.  */
14016
14017 void
14018 mips_frob_file_before_adjust (void)
14019 {
14020 #ifndef NO_ECOFF_DEBUGGING
14021   if (ECOFF_DEBUGGING
14022       && mips_debug != 0
14023       && ! ecoff_debugging_seen)
14024     flag_keep_locals = 1;
14025 #endif
14026 }
14027
14028 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14029    the corresponding LO16 reloc.  This is called before md_apply_fix and
14030    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14031    relocation operators.
14032
14033    For our purposes, a %lo() expression matches a %got() or %hi()
14034    expression if:
14035
14036       (a) it refers to the same symbol; and
14037       (b) the offset applied in the %lo() expression is no lower than
14038           the offset applied in the %got() or %hi().
14039
14040    (b) allows us to cope with code like:
14041
14042         lui     $4,%hi(foo)
14043         lh      $4,%lo(foo+2)($4)
14044
14045    ...which is legal on RELA targets, and has a well-defined behaviour
14046    if the user knows that adding 2 to "foo" will not induce a carry to
14047    the high 16 bits.
14048
14049    When several %lo()s match a particular %got() or %hi(), we use the
14050    following rules to distinguish them:
14051
14052      (1) %lo()s with smaller offsets are a better match than %lo()s with
14053          higher offsets.
14054
14055      (2) %lo()s with no matching %got() or %hi() are better than those
14056          that already have a matching %got() or %hi().
14057
14058      (3) later %lo()s are better than earlier %lo()s.
14059
14060    These rules are applied in order.
14061
14062    (1) means, among other things, that %lo()s with identical offsets are
14063    chosen if they exist.
14064
14065    (2) means that we won't associate several high-part relocations with
14066    the same low-part relocation unless there's no alternative.  Having
14067    several high parts for the same low part is a GNU extension; this rule
14068    allows careful users to avoid it.
14069
14070    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14071    with the last high-part relocation being at the front of the list.
14072    It therefore makes sense to choose the last matching low-part
14073    relocation, all other things being equal.  It's also easier
14074    to code that way.  */
14075
14076 void
14077 mips_frob_file (void)
14078 {
14079   struct mips_hi_fixup *l;
14080   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14081
14082   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14083     {
14084       segment_info_type *seginfo;
14085       bfd_boolean matched_lo_p;
14086       fixS **hi_pos, **lo_pos, **pos;
14087
14088       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14089
14090       /* If a GOT16 relocation turns out to be against a global symbol,
14091          there isn't supposed to be a matching LO.  Ignore %gots against
14092          constants; we'll report an error for those later.  */
14093       if (got16_reloc_p (l->fixp->fx_r_type)
14094           && !(l->fixp->fx_addsy
14095                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14096         continue;
14097
14098       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14099       if (fixup_has_matching_lo_p (l->fixp))
14100         continue;
14101
14102       seginfo = seg_info (l->seg);
14103
14104       /* Set HI_POS to the position of this relocation in the chain.
14105          Set LO_POS to the position of the chosen low-part relocation.
14106          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14107          relocation that matches an immediately-preceding high-part
14108          relocation.  */
14109       hi_pos = NULL;
14110       lo_pos = NULL;
14111       matched_lo_p = FALSE;
14112       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14113
14114       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14115         {
14116           if (*pos == l->fixp)
14117             hi_pos = pos;
14118
14119           if ((*pos)->fx_r_type == looking_for_rtype
14120               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14121               && (*pos)->fx_offset >= l->fixp->fx_offset
14122               && (lo_pos == NULL
14123                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14124                   || (!matched_lo_p
14125                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14126             lo_pos = pos;
14127
14128           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14129                           && fixup_has_matching_lo_p (*pos));
14130         }
14131
14132       /* If we found a match, remove the high-part relocation from its
14133          current position and insert it before the low-part relocation.
14134          Make the offsets match so that fixup_has_matching_lo_p()
14135          will return true.
14136
14137          We don't warn about unmatched high-part relocations since some
14138          versions of gcc have been known to emit dead "lui ...%hi(...)"
14139          instructions.  */
14140       if (lo_pos != NULL)
14141         {
14142           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14143           if (l->fixp->fx_next != *lo_pos)
14144             {
14145               *hi_pos = l->fixp->fx_next;
14146               l->fixp->fx_next = *lo_pos;
14147               *lo_pos = l->fixp;
14148             }
14149         }
14150     }
14151 }
14152
14153 int
14154 mips_force_relocation (fixS *fixp)
14155 {
14156   if (generic_force_reloc (fixp))
14157     return 1;
14158
14159   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14160      so that the linker relaxation can update targets.  */
14161   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14162       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14163       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14164     return 1;
14165
14166   return 0;
14167 }
14168
14169 /* Read the instruction associated with RELOC from BUF.  */
14170
14171 static unsigned int
14172 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14173 {
14174   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14175     return read_compressed_insn (buf, 4);
14176   else
14177     return read_insn (buf);
14178 }
14179
14180 /* Write instruction INSN to BUF, given that it has been relocated
14181    by RELOC.  */
14182
14183 static void
14184 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14185                   unsigned long insn)
14186 {
14187   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14188     write_compressed_insn (buf, insn, 4);
14189   else
14190     write_insn (buf, insn);
14191 }
14192
14193 /* Apply a fixup to the object file.  */
14194
14195 void
14196 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14197 {
14198   char *buf;
14199   unsigned long insn;
14200   reloc_howto_type *howto;
14201
14202   /* We ignore generic BFD relocations we don't know about.  */
14203   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14204   if (! howto)
14205     return;
14206
14207   gas_assert (fixP->fx_size == 2
14208               || fixP->fx_size == 4
14209               || fixP->fx_r_type == BFD_RELOC_16
14210               || fixP->fx_r_type == BFD_RELOC_64
14211               || fixP->fx_r_type == BFD_RELOC_CTOR
14212               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14213               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14214               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14215               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14216               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14217
14218   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14219
14220   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
14221               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14222               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14223               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
14224               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
14225
14226   /* Don't treat parts of a composite relocation as done.  There are two
14227      reasons for this:
14228
14229      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14230          should nevertheless be emitted if the first part is.
14231
14232      (2) In normal usage, composite relocations are never assembly-time
14233          constants.  The easiest way of dealing with the pathological
14234          exceptions is to generate a relocation against STN_UNDEF and
14235          leave everything up to the linker.  */
14236   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14237     fixP->fx_done = 1;
14238
14239   switch (fixP->fx_r_type)
14240     {
14241     case BFD_RELOC_MIPS_TLS_GD:
14242     case BFD_RELOC_MIPS_TLS_LDM:
14243     case BFD_RELOC_MIPS_TLS_DTPREL32:
14244     case BFD_RELOC_MIPS_TLS_DTPREL64:
14245     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14246     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14247     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14248     case BFD_RELOC_MIPS_TLS_TPREL32:
14249     case BFD_RELOC_MIPS_TLS_TPREL64:
14250     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14251     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14252     case BFD_RELOC_MICROMIPS_TLS_GD:
14253     case BFD_RELOC_MICROMIPS_TLS_LDM:
14254     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14255     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14256     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14257     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14258     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14259     case BFD_RELOC_MIPS16_TLS_GD:
14260     case BFD_RELOC_MIPS16_TLS_LDM:
14261     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14262     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14263     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14264     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14265     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14266       if (!fixP->fx_addsy)
14267         {
14268           as_bad_where (fixP->fx_file, fixP->fx_line,
14269                         _("TLS relocation against a constant"));
14270           break;
14271         }
14272       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14273       /* fall through */
14274
14275     case BFD_RELOC_MIPS_JMP:
14276     case BFD_RELOC_MIPS_SHIFT5:
14277     case BFD_RELOC_MIPS_SHIFT6:
14278     case BFD_RELOC_MIPS_GOT_DISP:
14279     case BFD_RELOC_MIPS_GOT_PAGE:
14280     case BFD_RELOC_MIPS_GOT_OFST:
14281     case BFD_RELOC_MIPS_SUB:
14282     case BFD_RELOC_MIPS_INSERT_A:
14283     case BFD_RELOC_MIPS_INSERT_B:
14284     case BFD_RELOC_MIPS_DELETE:
14285     case BFD_RELOC_MIPS_HIGHEST:
14286     case BFD_RELOC_MIPS_HIGHER:
14287     case BFD_RELOC_MIPS_SCN_DISP:
14288     case BFD_RELOC_MIPS_REL16:
14289     case BFD_RELOC_MIPS_RELGOT:
14290     case BFD_RELOC_MIPS_JALR:
14291     case BFD_RELOC_HI16:
14292     case BFD_RELOC_HI16_S:
14293     case BFD_RELOC_LO16:
14294     case BFD_RELOC_GPREL16:
14295     case BFD_RELOC_MIPS_LITERAL:
14296     case BFD_RELOC_MIPS_CALL16:
14297     case BFD_RELOC_MIPS_GOT16:
14298     case BFD_RELOC_GPREL32:
14299     case BFD_RELOC_MIPS_GOT_HI16:
14300     case BFD_RELOC_MIPS_GOT_LO16:
14301     case BFD_RELOC_MIPS_CALL_HI16:
14302     case BFD_RELOC_MIPS_CALL_LO16:
14303     case BFD_RELOC_MIPS16_GPREL:
14304     case BFD_RELOC_MIPS16_GOT16:
14305     case BFD_RELOC_MIPS16_CALL16:
14306     case BFD_RELOC_MIPS16_HI16:
14307     case BFD_RELOC_MIPS16_HI16_S:
14308     case BFD_RELOC_MIPS16_LO16:
14309     case BFD_RELOC_MIPS16_JMP:
14310     case BFD_RELOC_MICROMIPS_JMP:
14311     case BFD_RELOC_MICROMIPS_GOT_DISP:
14312     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14313     case BFD_RELOC_MICROMIPS_GOT_OFST:
14314     case BFD_RELOC_MICROMIPS_SUB:
14315     case BFD_RELOC_MICROMIPS_HIGHEST:
14316     case BFD_RELOC_MICROMIPS_HIGHER:
14317     case BFD_RELOC_MICROMIPS_SCN_DISP:
14318     case BFD_RELOC_MICROMIPS_JALR:
14319     case BFD_RELOC_MICROMIPS_HI16:
14320     case BFD_RELOC_MICROMIPS_HI16_S:
14321     case BFD_RELOC_MICROMIPS_LO16:
14322     case BFD_RELOC_MICROMIPS_GPREL16:
14323     case BFD_RELOC_MICROMIPS_LITERAL:
14324     case BFD_RELOC_MICROMIPS_CALL16:
14325     case BFD_RELOC_MICROMIPS_GOT16:
14326     case BFD_RELOC_MICROMIPS_GOT_HI16:
14327     case BFD_RELOC_MICROMIPS_GOT_LO16:
14328     case BFD_RELOC_MICROMIPS_CALL_HI16:
14329     case BFD_RELOC_MICROMIPS_CALL_LO16:
14330     case BFD_RELOC_MIPS_EH:
14331       if (fixP->fx_done)
14332         {
14333           offsetT value;
14334
14335           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14336             {
14337               insn = read_reloc_insn (buf, fixP->fx_r_type);
14338               if (mips16_reloc_p (fixP->fx_r_type))
14339                 insn |= mips16_immed_extend (value, 16);
14340               else
14341                 insn |= (value & 0xffff);
14342               write_reloc_insn (buf, fixP->fx_r_type, insn);
14343             }
14344           else
14345             as_bad_where (fixP->fx_file, fixP->fx_line,
14346                           _("Unsupported constant in relocation"));
14347         }
14348       break;
14349
14350     case BFD_RELOC_64:
14351       /* This is handled like BFD_RELOC_32, but we output a sign
14352          extended value if we are only 32 bits.  */
14353       if (fixP->fx_done)
14354         {
14355           if (8 <= sizeof (valueT))
14356             md_number_to_chars (buf, *valP, 8);
14357           else
14358             {
14359               valueT hiv;
14360
14361               if ((*valP & 0x80000000) != 0)
14362                 hiv = 0xffffffff;
14363               else
14364                 hiv = 0;
14365               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14366               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14367             }
14368         }
14369       break;
14370
14371     case BFD_RELOC_RVA:
14372     case BFD_RELOC_32:
14373     case BFD_RELOC_32_PCREL:
14374     case BFD_RELOC_16:
14375       /* If we are deleting this reloc entry, we must fill in the
14376          value now.  This can happen if we have a .word which is not
14377          resolved when it appears but is later defined.  */
14378       if (fixP->fx_done)
14379         md_number_to_chars (buf, *valP, fixP->fx_size);
14380       break;
14381
14382     case BFD_RELOC_16_PCREL_S2:
14383       if ((*valP & 0x3) != 0)
14384         as_bad_where (fixP->fx_file, fixP->fx_line,
14385                       _("Branch to misaligned address (%lx)"), (long) *valP);
14386
14387       /* We need to save the bits in the instruction since fixup_segment()
14388          might be deleting the relocation entry (i.e., a branch within
14389          the current segment).  */
14390       if (! fixP->fx_done)
14391         break;
14392
14393       /* Update old instruction data.  */
14394       insn = read_insn (buf);
14395
14396       if (*valP + 0x20000 <= 0x3ffff)
14397         {
14398           insn |= (*valP >> 2) & 0xffff;
14399           write_insn (buf, insn);
14400         }
14401       else if (mips_pic == NO_PIC
14402                && fixP->fx_done
14403                && fixP->fx_frag->fr_address >= text_section->vma
14404                && (fixP->fx_frag->fr_address
14405                    < text_section->vma + bfd_get_section_size (text_section))
14406                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14407                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14408                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14409         {
14410           /* The branch offset is too large.  If this is an
14411              unconditional branch, and we are not generating PIC code,
14412              we can convert it to an absolute jump instruction.  */
14413           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14414             insn = 0x0c000000;  /* jal */
14415           else
14416             insn = 0x08000000;  /* j */
14417           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14418           fixP->fx_done = 0;
14419           fixP->fx_addsy = section_symbol (text_section);
14420           *valP += md_pcrel_from (fixP);
14421           write_insn (buf, insn);
14422         }
14423       else
14424         {
14425           /* If we got here, we have branch-relaxation disabled,
14426              and there's nothing we can do to fix this instruction
14427              without turning it into a longer sequence.  */
14428           as_bad_where (fixP->fx_file, fixP->fx_line,
14429                         _("Branch out of range"));
14430         }
14431       break;
14432
14433     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14434     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14435     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14436       /* We adjust the offset back to even.  */
14437       if ((*valP & 0x1) != 0)
14438         --(*valP);
14439
14440       if (! fixP->fx_done)
14441         break;
14442
14443       /* Should never visit here, because we keep the relocation.  */
14444       abort ();
14445       break;
14446
14447     case BFD_RELOC_VTABLE_INHERIT:
14448       fixP->fx_done = 0;
14449       if (fixP->fx_addsy
14450           && !S_IS_DEFINED (fixP->fx_addsy)
14451           && !S_IS_WEAK (fixP->fx_addsy))
14452         S_SET_WEAK (fixP->fx_addsy);
14453       break;
14454
14455     case BFD_RELOC_VTABLE_ENTRY:
14456       fixP->fx_done = 0;
14457       break;
14458
14459     default:
14460       abort ();
14461     }
14462
14463   /* Remember value for tc_gen_reloc.  */
14464   fixP->fx_addnumber = *valP;
14465 }
14466
14467 static symbolS *
14468 get_symbol (void)
14469 {
14470   int c;
14471   char *name;
14472   symbolS *p;
14473
14474   name = input_line_pointer;
14475   c = get_symbol_end ();
14476   p = (symbolS *) symbol_find_or_make (name);
14477   *input_line_pointer = c;
14478   return p;
14479 }
14480
14481 /* Align the current frag to a given power of two.  If a particular
14482    fill byte should be used, FILL points to an integer that contains
14483    that byte, otherwise FILL is null.
14484
14485    This function used to have the comment:
14486
14487       The MIPS assembler also automatically adjusts any preceding label.
14488
14489    The implementation therefore applied the adjustment to a maximum of
14490    one label.  However, other label adjustments are applied to batches
14491    of labels, and adjusting just one caused problems when new labels
14492    were added for the sake of debugging or unwind information.
14493    We therefore adjust all preceding labels (given as LABELS) instead.  */
14494
14495 static void
14496 mips_align (int to, int *fill, struct insn_label_list *labels)
14497 {
14498   mips_emit_delays ();
14499   mips_record_compressed_mode ();
14500   if (fill == NULL && subseg_text_p (now_seg))
14501     frag_align_code (to, 0);
14502   else
14503     frag_align (to, fill ? *fill : 0, 0);
14504   record_alignment (now_seg, to);
14505   mips_move_labels (labels, FALSE);
14506 }
14507
14508 /* Align to a given power of two.  .align 0 turns off the automatic
14509    alignment used by the data creating pseudo-ops.  */
14510
14511 static void
14512 s_align (int x ATTRIBUTE_UNUSED)
14513 {
14514   int temp, fill_value, *fill_ptr;
14515   long max_alignment = 28;
14516
14517   /* o Note that the assembler pulls down any immediately preceding label
14518        to the aligned address.
14519      o It's not documented but auto alignment is reinstated by
14520        a .align pseudo instruction.
14521      o Note also that after auto alignment is turned off the mips assembler
14522        issues an error on attempt to assemble an improperly aligned data item.
14523        We don't.  */
14524
14525   temp = get_absolute_expression ();
14526   if (temp > max_alignment)
14527     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14528   else if (temp < 0)
14529     {
14530       as_warn (_("Alignment negative: 0 assumed."));
14531       temp = 0;
14532     }
14533   if (*input_line_pointer == ',')
14534     {
14535       ++input_line_pointer;
14536       fill_value = get_absolute_expression ();
14537       fill_ptr = &fill_value;
14538     }
14539   else
14540     fill_ptr = 0;
14541   if (temp)
14542     {
14543       segment_info_type *si = seg_info (now_seg);
14544       struct insn_label_list *l = si->label_list;
14545       /* Auto alignment should be switched on by next section change.  */
14546       auto_align = 1;
14547       mips_align (temp, fill_ptr, l);
14548     }
14549   else
14550     {
14551       auto_align = 0;
14552     }
14553
14554   demand_empty_rest_of_line ();
14555 }
14556
14557 static void
14558 s_change_sec (int sec)
14559 {
14560   segT seg;
14561
14562   /* The ELF backend needs to know that we are changing sections, so
14563      that .previous works correctly.  We could do something like check
14564      for an obj_section_change_hook macro, but that might be confusing
14565      as it would not be appropriate to use it in the section changing
14566      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14567      This should be cleaner, somehow.  */
14568   obj_elf_section_change_hook ();
14569
14570   mips_emit_delays ();
14571
14572   switch (sec)
14573     {
14574     case 't':
14575       s_text (0);
14576       break;
14577     case 'd':
14578       s_data (0);
14579       break;
14580     case 'b':
14581       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14582       demand_empty_rest_of_line ();
14583       break;
14584
14585     case 'r':
14586       seg = subseg_new (RDATA_SECTION_NAME,
14587                         (subsegT) get_absolute_expression ());
14588       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14589                                               | SEC_READONLY | SEC_RELOC
14590                                               | SEC_DATA));
14591       if (strncmp (TARGET_OS, "elf", 3) != 0)
14592         record_alignment (seg, 4);
14593       demand_empty_rest_of_line ();
14594       break;
14595
14596     case 's':
14597       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14598       bfd_set_section_flags (stdoutput, seg,
14599                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14600       if (strncmp (TARGET_OS, "elf", 3) != 0)
14601         record_alignment (seg, 4);
14602       demand_empty_rest_of_line ();
14603       break;
14604
14605     case 'B':
14606       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14607       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14608       if (strncmp (TARGET_OS, "elf", 3) != 0)
14609         record_alignment (seg, 4);
14610       demand_empty_rest_of_line ();
14611       break;
14612     }
14613
14614   auto_align = 1;
14615 }
14616
14617 void
14618 s_change_section (int ignore ATTRIBUTE_UNUSED)
14619 {
14620   char *section_name;
14621   char c;
14622   char next_c = 0;
14623   int section_type;
14624   int section_flag;
14625   int section_entry_size;
14626   int section_alignment;
14627
14628   section_name = input_line_pointer;
14629   c = get_symbol_end ();
14630   if (c)
14631     next_c = *(input_line_pointer + 1);
14632
14633   /* Do we have .section Name<,"flags">?  */
14634   if (c != ',' || (c == ',' && next_c == '"'))
14635     {
14636       /* just after name is now '\0'.  */
14637       *input_line_pointer = c;
14638       input_line_pointer = section_name;
14639       obj_elf_section (ignore);
14640       return;
14641     }
14642   input_line_pointer++;
14643
14644   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14645   if (c == ',')
14646     section_type = get_absolute_expression ();
14647   else
14648     section_type = 0;
14649   if (*input_line_pointer++ == ',')
14650     section_flag = get_absolute_expression ();
14651   else
14652     section_flag = 0;
14653   if (*input_line_pointer++ == ',')
14654     section_entry_size = get_absolute_expression ();
14655   else
14656     section_entry_size = 0;
14657   if (*input_line_pointer++ == ',')
14658     section_alignment = get_absolute_expression ();
14659   else
14660     section_alignment = 0;
14661   /* FIXME: really ignore?  */
14662   (void) section_alignment;
14663
14664   section_name = xstrdup (section_name);
14665
14666   /* When using the generic form of .section (as implemented by obj-elf.c),
14667      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14668      traditionally had to fall back on the more common @progbits instead.
14669
14670      There's nothing really harmful in this, since bfd will correct
14671      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14672      means that, for backwards compatibility, the special_section entries
14673      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14674
14675      Even so, we shouldn't force users of the MIPS .section syntax to
14676      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14677      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14678      generic type-checking code.  */
14679   if (section_type == SHT_MIPS_DWARF)
14680     section_type = SHT_PROGBITS;
14681
14682   obj_elf_change_section (section_name, section_type, section_flag,
14683                           section_entry_size, 0, 0, 0);
14684
14685   if (now_seg->name != section_name)
14686     free (section_name);
14687 }
14688
14689 void
14690 mips_enable_auto_align (void)
14691 {
14692   auto_align = 1;
14693 }
14694
14695 static void
14696 s_cons (int log_size)
14697 {
14698   segment_info_type *si = seg_info (now_seg);
14699   struct insn_label_list *l = si->label_list;
14700
14701   mips_emit_delays ();
14702   if (log_size > 0 && auto_align)
14703     mips_align (log_size, 0, l);
14704   cons (1 << log_size);
14705   mips_clear_insn_labels ();
14706 }
14707
14708 static void
14709 s_float_cons (int type)
14710 {
14711   segment_info_type *si = seg_info (now_seg);
14712   struct insn_label_list *l = si->label_list;
14713
14714   mips_emit_delays ();
14715
14716   if (auto_align)
14717     {
14718       if (type == 'd')
14719         mips_align (3, 0, l);
14720       else
14721         mips_align (2, 0, l);
14722     }
14723
14724   float_cons (type);
14725   mips_clear_insn_labels ();
14726 }
14727
14728 /* Handle .globl.  We need to override it because on Irix 5 you are
14729    permitted to say
14730        .globl foo .text
14731    where foo is an undefined symbol, to mean that foo should be
14732    considered to be the address of a function.  */
14733
14734 static void
14735 s_mips_globl (int x ATTRIBUTE_UNUSED)
14736 {
14737   char *name;
14738   int c;
14739   symbolS *symbolP;
14740   flagword flag;
14741
14742   do
14743     {
14744       name = input_line_pointer;
14745       c = get_symbol_end ();
14746       symbolP = symbol_find_or_make (name);
14747       S_SET_EXTERNAL (symbolP);
14748
14749       *input_line_pointer = c;
14750       SKIP_WHITESPACE ();
14751
14752       /* On Irix 5, every global symbol that is not explicitly labelled as
14753          being a function is apparently labelled as being an object.  */
14754       flag = BSF_OBJECT;
14755
14756       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14757           && (*input_line_pointer != ','))
14758         {
14759           char *secname;
14760           asection *sec;
14761
14762           secname = input_line_pointer;
14763           c = get_symbol_end ();
14764           sec = bfd_get_section_by_name (stdoutput, secname);
14765           if (sec == NULL)
14766             as_bad (_("%s: no such section"), secname);
14767           *input_line_pointer = c;
14768
14769           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14770             flag = BSF_FUNCTION;
14771         }
14772
14773       symbol_get_bfdsym (symbolP)->flags |= flag;
14774
14775       c = *input_line_pointer;
14776       if (c == ',')
14777         {
14778           input_line_pointer++;
14779           SKIP_WHITESPACE ();
14780           if (is_end_of_line[(unsigned char) *input_line_pointer])
14781             c = '\n';
14782         }
14783     }
14784   while (c == ',');
14785
14786   demand_empty_rest_of_line ();
14787 }
14788
14789 static void
14790 s_option (int x ATTRIBUTE_UNUSED)
14791 {
14792   char *opt;
14793   char c;
14794
14795   opt = input_line_pointer;
14796   c = get_symbol_end ();
14797
14798   if (*opt == 'O')
14799     {
14800       /* FIXME: What does this mean?  */
14801     }
14802   else if (strncmp (opt, "pic", 3) == 0)
14803     {
14804       int i;
14805
14806       i = atoi (opt + 3);
14807       if (i == 0)
14808         mips_pic = NO_PIC;
14809       else if (i == 2)
14810         {
14811           mips_pic = SVR4_PIC;
14812           mips_abicalls = TRUE;
14813         }
14814       else
14815         as_bad (_(".option pic%d not supported"), i);
14816
14817       if (mips_pic == SVR4_PIC)
14818         {
14819           if (g_switch_seen && g_switch_value != 0)
14820             as_warn (_("-G may not be used with SVR4 PIC code"));
14821           g_switch_value = 0;
14822           bfd_set_gp_size (stdoutput, 0);
14823         }
14824     }
14825   else
14826     as_warn (_("Unrecognized option \"%s\""), opt);
14827
14828   *input_line_pointer = c;
14829   demand_empty_rest_of_line ();
14830 }
14831
14832 /* This structure is used to hold a stack of .set values.  */
14833
14834 struct mips_option_stack
14835 {
14836   struct mips_option_stack *next;
14837   struct mips_set_options options;
14838 };
14839
14840 static struct mips_option_stack *mips_opts_stack;
14841
14842 /* Handle the .set pseudo-op.  */
14843
14844 static void
14845 s_mipsset (int x ATTRIBUTE_UNUSED)
14846 {
14847   char *name = input_line_pointer, ch;
14848   const struct mips_ase *ase;
14849
14850   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14851     ++input_line_pointer;
14852   ch = *input_line_pointer;
14853   *input_line_pointer = '\0';
14854
14855   if (strcmp (name, "reorder") == 0)
14856     {
14857       if (mips_opts.noreorder)
14858         end_noreorder ();
14859     }
14860   else if (strcmp (name, "noreorder") == 0)
14861     {
14862       if (!mips_opts.noreorder)
14863         start_noreorder ();
14864     }
14865   else if (strncmp (name, "at=", 3) == 0)
14866     {
14867       char *s = name + 3;
14868
14869       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14870         as_bad (_("Unrecognized register name `%s'"), s);
14871     }
14872   else if (strcmp (name, "at") == 0)
14873     {
14874       mips_opts.at = ATREG;
14875     }
14876   else if (strcmp (name, "noat") == 0)
14877     {
14878       mips_opts.at = ZERO;
14879     }
14880   else if (strcmp (name, "macro") == 0)
14881     {
14882       mips_opts.warn_about_macros = 0;
14883     }
14884   else if (strcmp (name, "nomacro") == 0)
14885     {
14886       if (mips_opts.noreorder == 0)
14887         as_bad (_("`noreorder' must be set before `nomacro'"));
14888       mips_opts.warn_about_macros = 1;
14889     }
14890   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14891     {
14892       mips_opts.nomove = 0;
14893     }
14894   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14895     {
14896       mips_opts.nomove = 1;
14897     }
14898   else if (strcmp (name, "bopt") == 0)
14899     {
14900       mips_opts.nobopt = 0;
14901     }
14902   else if (strcmp (name, "nobopt") == 0)
14903     {
14904       mips_opts.nobopt = 1;
14905     }
14906   else if (strcmp (name, "gp=default") == 0)
14907     mips_opts.gp32 = file_mips_gp32;
14908   else if (strcmp (name, "gp=32") == 0)
14909     mips_opts.gp32 = 1;
14910   else if (strcmp (name, "gp=64") == 0)
14911     {
14912       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14913         as_warn (_("%s isa does not support 64-bit registers"),
14914                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14915       mips_opts.gp32 = 0;
14916     }
14917   else if (strcmp (name, "fp=default") == 0)
14918     mips_opts.fp32 = file_mips_fp32;
14919   else if (strcmp (name, "fp=32") == 0)
14920     mips_opts.fp32 = 1;
14921   else if (strcmp (name, "fp=64") == 0)
14922     {
14923       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14924         as_warn (_("%s isa does not support 64-bit floating point registers"),
14925                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14926       mips_opts.fp32 = 0;
14927     }
14928   else if (strcmp (name, "softfloat") == 0)
14929     mips_opts.soft_float = 1;
14930   else if (strcmp (name, "hardfloat") == 0)
14931     mips_opts.soft_float = 0;
14932   else if (strcmp (name, "singlefloat") == 0)
14933     mips_opts.single_float = 1;
14934   else if (strcmp (name, "doublefloat") == 0)
14935     mips_opts.single_float = 0;
14936   else if (strcmp (name, "mips16") == 0
14937            || strcmp (name, "MIPS-16") == 0)
14938     {
14939       if (mips_opts.micromips == 1)
14940         as_fatal (_("`mips16' cannot be used with `micromips'"));
14941       mips_opts.mips16 = 1;
14942     }
14943   else if (strcmp (name, "nomips16") == 0
14944            || strcmp (name, "noMIPS-16") == 0)
14945     mips_opts.mips16 = 0;
14946   else if (strcmp (name, "micromips") == 0)
14947     {
14948       if (mips_opts.mips16 == 1)
14949         as_fatal (_("`micromips' cannot be used with `mips16'"));
14950       mips_opts.micromips = 1;
14951     }
14952   else if (strcmp (name, "nomicromips") == 0)
14953     mips_opts.micromips = 0;
14954   else if (name[0] == 'n'
14955            && name[1] == 'o'
14956            && (ase = mips_lookup_ase (name + 2)))
14957     mips_set_ase (ase, FALSE);
14958   else if ((ase = mips_lookup_ase (name)))
14959     mips_set_ase (ase, TRUE);
14960   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
14961     {
14962       int reset = 0;
14963
14964       /* Permit the user to change the ISA and architecture on the fly.
14965          Needless to say, misuse can cause serious problems.  */
14966       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
14967         {
14968           reset = 1;
14969           mips_opts.isa = file_mips_isa;
14970           mips_opts.arch = file_mips_arch;
14971         }
14972       else if (strncmp (name, "arch=", 5) == 0)
14973         {
14974           const struct mips_cpu_info *p;
14975
14976           p = mips_parse_cpu("internal use", name + 5);
14977           if (!p)
14978             as_bad (_("unknown architecture %s"), name + 5);
14979           else
14980             {
14981               mips_opts.arch = p->cpu;
14982               mips_opts.isa = p->isa;
14983             }
14984         }
14985       else if (strncmp (name, "mips", 4) == 0)
14986         {
14987           const struct mips_cpu_info *p;
14988
14989           p = mips_parse_cpu("internal use", name);
14990           if (!p)
14991             as_bad (_("unknown ISA level %s"), name + 4);
14992           else
14993             {
14994               mips_opts.arch = p->cpu;
14995               mips_opts.isa = p->isa;
14996             }
14997         }
14998       else
14999         as_bad (_("unknown ISA or architecture %s"), name);
15000
15001       switch (mips_opts.isa)
15002         {
15003         case  0:
15004           break;
15005         case ISA_MIPS1:
15006         case ISA_MIPS2:
15007         case ISA_MIPS32:
15008         case ISA_MIPS32R2:
15009           mips_opts.gp32 = 1;
15010           mips_opts.fp32 = 1;
15011           break;
15012         case ISA_MIPS3:
15013         case ISA_MIPS4:
15014         case ISA_MIPS5:
15015         case ISA_MIPS64:
15016         case ISA_MIPS64R2:
15017           mips_opts.gp32 = 0;
15018           if (mips_opts.arch == CPU_R5900)
15019             {
15020                 mips_opts.fp32 = 1;
15021             }
15022           else
15023             {
15024           mips_opts.fp32 = 0;
15025             }
15026           break;
15027         default:
15028           as_bad (_("unknown ISA level %s"), name + 4);
15029           break;
15030         }
15031       if (reset)
15032         {
15033           mips_opts.gp32 = file_mips_gp32;
15034           mips_opts.fp32 = file_mips_fp32;
15035         }
15036     }
15037   else if (strcmp (name, "autoextend") == 0)
15038     mips_opts.noautoextend = 0;
15039   else if (strcmp (name, "noautoextend") == 0)
15040     mips_opts.noautoextend = 1;
15041   else if (strcmp (name, "insn32") == 0)
15042     mips_opts.insn32 = TRUE;
15043   else if (strcmp (name, "noinsn32") == 0)
15044     mips_opts.insn32 = FALSE;
15045   else if (strcmp (name, "push") == 0)
15046     {
15047       struct mips_option_stack *s;
15048
15049       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15050       s->next = mips_opts_stack;
15051       s->options = mips_opts;
15052       mips_opts_stack = s;
15053     }
15054   else if (strcmp (name, "pop") == 0)
15055     {
15056       struct mips_option_stack *s;
15057
15058       s = mips_opts_stack;
15059       if (s == NULL)
15060         as_bad (_(".set pop with no .set push"));
15061       else
15062         {
15063           /* If we're changing the reorder mode we need to handle
15064              delay slots correctly.  */
15065           if (s->options.noreorder && ! mips_opts.noreorder)
15066             start_noreorder ();
15067           else if (! s->options.noreorder && mips_opts.noreorder)
15068             end_noreorder ();
15069
15070           mips_opts = s->options;
15071           mips_opts_stack = s->next;
15072           free (s);
15073         }
15074     }
15075   else if (strcmp (name, "sym32") == 0)
15076     mips_opts.sym32 = TRUE;
15077   else if (strcmp (name, "nosym32") == 0)
15078     mips_opts.sym32 = FALSE;
15079   else if (strchr (name, ','))
15080     {
15081       /* Generic ".set" directive; use the generic handler.  */
15082       *input_line_pointer = ch;
15083       input_line_pointer = name;
15084       s_set (0);
15085       return;
15086     }
15087   else
15088     {
15089       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
15090     }
15091   mips_check_isa_supports_ases ();
15092   *input_line_pointer = ch;
15093   demand_empty_rest_of_line ();
15094 }
15095
15096 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15097    .option pic2.  It means to generate SVR4 PIC calls.  */
15098
15099 static void
15100 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15101 {
15102   mips_pic = SVR4_PIC;
15103   mips_abicalls = TRUE;
15104
15105   if (g_switch_seen && g_switch_value != 0)
15106     as_warn (_("-G may not be used with SVR4 PIC code"));
15107   g_switch_value = 0;
15108
15109   bfd_set_gp_size (stdoutput, 0);
15110   demand_empty_rest_of_line ();
15111 }
15112
15113 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15114    PIC code.  It sets the $gp register for the function based on the
15115    function address, which is in the register named in the argument.
15116    This uses a relocation against _gp_disp, which is handled specially
15117    by the linker.  The result is:
15118         lui     $gp,%hi(_gp_disp)
15119         addiu   $gp,$gp,%lo(_gp_disp)
15120         addu    $gp,$gp,.cpload argument
15121    The .cpload argument is normally $25 == $t9.
15122
15123    The -mno-shared option changes this to:
15124         lui     $gp,%hi(__gnu_local_gp)
15125         addiu   $gp,$gp,%lo(__gnu_local_gp)
15126    and the argument is ignored.  This saves an instruction, but the
15127    resulting code is not position independent; it uses an absolute
15128    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15129    can go into an ordinary executable, but not into a shared library.  */
15130
15131 static void
15132 s_cpload (int ignore ATTRIBUTE_UNUSED)
15133 {
15134   expressionS ex;
15135   int reg;
15136   int in_shared;
15137
15138   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15139      .cpload is ignored.  */
15140   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15141     {
15142       s_ignore (0);
15143       return;
15144     }
15145
15146   if (mips_opts.mips16)
15147     {
15148       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15149       ignore_rest_of_line ();
15150       return;
15151     }
15152
15153   /* .cpload should be in a .set noreorder section.  */
15154   if (mips_opts.noreorder == 0)
15155     as_warn (_(".cpload not in noreorder section"));
15156
15157   reg = tc_get_register (0);
15158
15159   /* If we need to produce a 64-bit address, we are better off using
15160      the default instruction sequence.  */
15161   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15162
15163   ex.X_op = O_symbol;
15164   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15165                                          "__gnu_local_gp");
15166   ex.X_op_symbol = NULL;
15167   ex.X_add_number = 0;
15168
15169   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15170   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15171
15172   mips_mark_labels ();
15173   mips_assembling_insn = TRUE;
15174
15175   macro_start ();
15176   macro_build_lui (&ex, mips_gp_register);
15177   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15178                mips_gp_register, BFD_RELOC_LO16);
15179   if (in_shared)
15180     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15181                  mips_gp_register, reg);
15182   macro_end ();
15183
15184   mips_assembling_insn = FALSE;
15185   demand_empty_rest_of_line ();
15186 }
15187
15188 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15189      .cpsetup $reg1, offset|$reg2, label
15190
15191    If offset is given, this results in:
15192      sd         $gp, offset($sp)
15193      lui        $gp, %hi(%neg(%gp_rel(label)))
15194      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15195      daddu      $gp, $gp, $reg1
15196
15197    If $reg2 is given, this results in:
15198      daddu      $reg2, $gp, $0
15199      lui        $gp, %hi(%neg(%gp_rel(label)))
15200      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15201      daddu      $gp, $gp, $reg1
15202    $reg1 is normally $25 == $t9.
15203
15204    The -mno-shared option replaces the last three instructions with
15205         lui     $gp,%hi(_gp)
15206         addiu   $gp,$gp,%lo(_gp)  */
15207
15208 static void
15209 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15210 {
15211   expressionS ex_off;
15212   expressionS ex_sym;
15213   int reg1;
15214
15215   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15216      We also need NewABI support.  */
15217   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15218     {
15219       s_ignore (0);
15220       return;
15221     }
15222
15223   if (mips_opts.mips16)
15224     {
15225       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15226       ignore_rest_of_line ();
15227       return;
15228     }
15229
15230   reg1 = tc_get_register (0);
15231   SKIP_WHITESPACE ();
15232   if (*input_line_pointer != ',')
15233     {
15234       as_bad (_("missing argument separator ',' for .cpsetup"));
15235       return;
15236     }
15237   else
15238     ++input_line_pointer;
15239   SKIP_WHITESPACE ();
15240   if (*input_line_pointer == '$')
15241     {
15242       mips_cpreturn_register = tc_get_register (0);
15243       mips_cpreturn_offset = -1;
15244     }
15245   else
15246     {
15247       mips_cpreturn_offset = get_absolute_expression ();
15248       mips_cpreturn_register = -1;
15249     }
15250   SKIP_WHITESPACE ();
15251   if (*input_line_pointer != ',')
15252     {
15253       as_bad (_("missing argument separator ',' for .cpsetup"));
15254       return;
15255     }
15256   else
15257     ++input_line_pointer;
15258   SKIP_WHITESPACE ();
15259   expression (&ex_sym);
15260
15261   mips_mark_labels ();
15262   mips_assembling_insn = TRUE;
15263
15264   macro_start ();
15265   if (mips_cpreturn_register == -1)
15266     {
15267       ex_off.X_op = O_constant;
15268       ex_off.X_add_symbol = NULL;
15269       ex_off.X_op_symbol = NULL;
15270       ex_off.X_add_number = mips_cpreturn_offset;
15271
15272       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15273                    BFD_RELOC_LO16, SP);
15274     }
15275   else
15276     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15277                  mips_gp_register, 0);
15278
15279   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15280     {
15281       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15282                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15283                    BFD_RELOC_HI16_S);
15284
15285       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15286                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15287                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15288
15289       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15290                    mips_gp_register, reg1);
15291     }
15292   else
15293     {
15294       expressionS ex;
15295
15296       ex.X_op = O_symbol;
15297       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15298       ex.X_op_symbol = NULL;
15299       ex.X_add_number = 0;
15300
15301       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15302       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15303
15304       macro_build_lui (&ex, mips_gp_register);
15305       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15306                    mips_gp_register, BFD_RELOC_LO16);
15307     }
15308
15309   macro_end ();
15310
15311   mips_assembling_insn = FALSE;
15312   demand_empty_rest_of_line ();
15313 }
15314
15315 static void
15316 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15317 {
15318   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15319      .cplocal is ignored.  */
15320   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15321     {
15322       s_ignore (0);
15323       return;
15324     }
15325
15326   if (mips_opts.mips16)
15327     {
15328       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15329       ignore_rest_of_line ();
15330       return;
15331     }
15332
15333   mips_gp_register = tc_get_register (0);
15334   demand_empty_rest_of_line ();
15335 }
15336
15337 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15338    offset from $sp.  The offset is remembered, and after making a PIC
15339    call $gp is restored from that location.  */
15340
15341 static void
15342 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15343 {
15344   expressionS ex;
15345
15346   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15347      .cprestore is ignored.  */
15348   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15349     {
15350       s_ignore (0);
15351       return;
15352     }
15353
15354   if (mips_opts.mips16)
15355     {
15356       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15357       ignore_rest_of_line ();
15358       return;
15359     }
15360
15361   mips_cprestore_offset = get_absolute_expression ();
15362   mips_cprestore_valid = 1;
15363
15364   ex.X_op = O_constant;
15365   ex.X_add_symbol = NULL;
15366   ex.X_op_symbol = NULL;
15367   ex.X_add_number = mips_cprestore_offset;
15368
15369   mips_mark_labels ();
15370   mips_assembling_insn = TRUE;
15371
15372   macro_start ();
15373   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15374                                 SP, HAVE_64BIT_ADDRESSES);
15375   macro_end ();
15376
15377   mips_assembling_insn = FALSE;
15378   demand_empty_rest_of_line ();
15379 }
15380
15381 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15382    was given in the preceding .cpsetup, it results in:
15383      ld         $gp, offset($sp)
15384
15385    If a register $reg2 was given there, it results in:
15386      daddu      $gp, $reg2, $0  */
15387
15388 static void
15389 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15390 {
15391   expressionS ex;
15392
15393   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15394      We also need NewABI support.  */
15395   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15396     {
15397       s_ignore (0);
15398       return;
15399     }
15400
15401   if (mips_opts.mips16)
15402     {
15403       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15404       ignore_rest_of_line ();
15405       return;
15406     }
15407
15408   mips_mark_labels ();
15409   mips_assembling_insn = TRUE;
15410
15411   macro_start ();
15412   if (mips_cpreturn_register == -1)
15413     {
15414       ex.X_op = O_constant;
15415       ex.X_add_symbol = NULL;
15416       ex.X_op_symbol = NULL;
15417       ex.X_add_number = mips_cpreturn_offset;
15418
15419       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15420     }
15421   else
15422     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15423                  mips_cpreturn_register, 0);
15424   macro_end ();
15425
15426   mips_assembling_insn = FALSE;
15427   demand_empty_rest_of_line ();
15428 }
15429
15430 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15431    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15432    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15433    debug information or MIPS16 TLS.  */
15434
15435 static void
15436 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15437                      bfd_reloc_code_real_type rtype)
15438 {
15439   expressionS ex;
15440   char *p;
15441
15442   expression (&ex);
15443
15444   if (ex.X_op != O_symbol)
15445     {
15446       as_bad (_("Unsupported use of %s"), dirstr);
15447       ignore_rest_of_line ();
15448     }
15449
15450   p = frag_more (bytes);
15451   md_number_to_chars (p, 0, bytes);
15452   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15453   demand_empty_rest_of_line ();
15454   mips_clear_insn_labels ();
15455 }
15456
15457 /* Handle .dtprelword.  */
15458
15459 static void
15460 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15461 {
15462   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15463 }
15464
15465 /* Handle .dtpreldword.  */
15466
15467 static void
15468 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15469 {
15470   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15471 }
15472
15473 /* Handle .tprelword.  */
15474
15475 static void
15476 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15477 {
15478   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15479 }
15480
15481 /* Handle .tpreldword.  */
15482
15483 static void
15484 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15485 {
15486   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15487 }
15488
15489 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15490    code.  It sets the offset to use in gp_rel relocations.  */
15491
15492 static void
15493 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15494 {
15495   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15496      We also need NewABI support.  */
15497   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15498     {
15499       s_ignore (0);
15500       return;
15501     }
15502
15503   mips_gprel_offset = get_absolute_expression ();
15504
15505   demand_empty_rest_of_line ();
15506 }
15507
15508 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15509    code.  It generates a 32 bit GP relative reloc.  */
15510
15511 static void
15512 s_gpword (int ignore ATTRIBUTE_UNUSED)
15513 {
15514   segment_info_type *si;
15515   struct insn_label_list *l;
15516   expressionS ex;
15517   char *p;
15518
15519   /* When not generating PIC code, this is treated as .word.  */
15520   if (mips_pic != SVR4_PIC)
15521     {
15522       s_cons (2);
15523       return;
15524     }
15525
15526   si = seg_info (now_seg);
15527   l = si->label_list;
15528   mips_emit_delays ();
15529   if (auto_align)
15530     mips_align (2, 0, l);
15531
15532   expression (&ex);
15533   mips_clear_insn_labels ();
15534
15535   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15536     {
15537       as_bad (_("Unsupported use of .gpword"));
15538       ignore_rest_of_line ();
15539     }
15540
15541   p = frag_more (4);
15542   md_number_to_chars (p, 0, 4);
15543   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15544                BFD_RELOC_GPREL32);
15545
15546   demand_empty_rest_of_line ();
15547 }
15548
15549 static void
15550 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15551 {
15552   segment_info_type *si;
15553   struct insn_label_list *l;
15554   expressionS ex;
15555   char *p;
15556
15557   /* When not generating PIC code, this is treated as .dword.  */
15558   if (mips_pic != SVR4_PIC)
15559     {
15560       s_cons (3);
15561       return;
15562     }
15563
15564   si = seg_info (now_seg);
15565   l = si->label_list;
15566   mips_emit_delays ();
15567   if (auto_align)
15568     mips_align (3, 0, l);
15569
15570   expression (&ex);
15571   mips_clear_insn_labels ();
15572
15573   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15574     {
15575       as_bad (_("Unsupported use of .gpdword"));
15576       ignore_rest_of_line ();
15577     }
15578
15579   p = frag_more (8);
15580   md_number_to_chars (p, 0, 8);
15581   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15582                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15583
15584   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15585   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15586            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15587
15588   demand_empty_rest_of_line ();
15589 }
15590
15591 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15592    tables.  It generates a R_MIPS_EH reloc.  */
15593
15594 static void
15595 s_ehword (int ignore ATTRIBUTE_UNUSED)
15596 {
15597   expressionS ex;
15598   char *p;
15599
15600   mips_emit_delays ();
15601
15602   expression (&ex);
15603   mips_clear_insn_labels ();
15604
15605   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15606     {
15607       as_bad (_("Unsupported use of .ehword"));
15608       ignore_rest_of_line ();
15609     }
15610
15611   p = frag_more (4);
15612   md_number_to_chars (p, 0, 4);
15613   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15614                BFD_RELOC_MIPS_EH);
15615
15616   demand_empty_rest_of_line ();
15617 }
15618
15619 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15620    tables in SVR4 PIC code.  */
15621
15622 static void
15623 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15624 {
15625   int reg;
15626
15627   /* This is ignored when not generating SVR4 PIC code.  */
15628   if (mips_pic != SVR4_PIC)
15629     {
15630       s_ignore (0);
15631       return;
15632     }
15633
15634   mips_mark_labels ();
15635   mips_assembling_insn = TRUE;
15636
15637   /* Add $gp to the register named as an argument.  */
15638   macro_start ();
15639   reg = tc_get_register (0);
15640   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15641   macro_end ();
15642
15643   mips_assembling_insn = FALSE;
15644   demand_empty_rest_of_line ();
15645 }
15646
15647 /* Handle the .insn pseudo-op.  This marks instruction labels in
15648    mips16/micromips mode.  This permits the linker to handle them specially,
15649    such as generating jalx instructions when needed.  We also make
15650    them odd for the duration of the assembly, in order to generate the
15651    right sort of code.  We will make them even in the adjust_symtab
15652    routine, while leaving them marked.  This is convenient for the
15653    debugger and the disassembler.  The linker knows to make them odd
15654    again.  */
15655
15656 static void
15657 s_insn (int ignore ATTRIBUTE_UNUSED)
15658 {
15659   mips_mark_labels ();
15660
15661   demand_empty_rest_of_line ();
15662 }
15663
15664 /* Handle the .nan pseudo-op.  */
15665
15666 static void
15667 s_nan (int ignore ATTRIBUTE_UNUSED)
15668 {
15669   static const char str_legacy[] = "legacy";
15670   static const char str_2008[] = "2008";
15671   size_t i;
15672
15673   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15674
15675   if (i == sizeof (str_2008) - 1
15676       && memcmp (input_line_pointer, str_2008, i) == 0)
15677     mips_flag_nan2008 = TRUE;
15678   else if (i == sizeof (str_legacy) - 1
15679            && memcmp (input_line_pointer, str_legacy, i) == 0)
15680     mips_flag_nan2008 = FALSE;
15681   else
15682     as_bad (_("Bad .nan directive"));
15683
15684   input_line_pointer += i;
15685   demand_empty_rest_of_line ();
15686 }
15687
15688 /* Handle a .stab[snd] directive.  Ideally these directives would be
15689    implemented in a transparent way, so that removing them would not
15690    have any effect on the generated instructions.  However, s_stab
15691    internally changes the section, so in practice we need to decide
15692    now whether the preceding label marks compressed code.  We do not
15693    support changing the compression mode of a label after a .stab*
15694    directive, such as in:
15695
15696    foo:
15697         .stabs ...
15698         .set mips16
15699
15700    so the current mode wins.  */
15701
15702 static void
15703 s_mips_stab (int type)
15704 {
15705   mips_mark_labels ();
15706   s_stab (type);
15707 }
15708
15709 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15710
15711 static void
15712 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15713 {
15714   char *name;
15715   int c;
15716   symbolS *symbolP;
15717   expressionS exp;
15718
15719   name = input_line_pointer;
15720   c = get_symbol_end ();
15721   symbolP = symbol_find_or_make (name);
15722   S_SET_WEAK (symbolP);
15723   *input_line_pointer = c;
15724
15725   SKIP_WHITESPACE ();
15726
15727   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15728     {
15729       if (S_IS_DEFINED (symbolP))
15730         {
15731           as_bad (_("ignoring attempt to redefine symbol %s"),
15732                   S_GET_NAME (symbolP));
15733           ignore_rest_of_line ();
15734           return;
15735         }
15736
15737       if (*input_line_pointer == ',')
15738         {
15739           ++input_line_pointer;
15740           SKIP_WHITESPACE ();
15741         }
15742
15743       expression (&exp);
15744       if (exp.X_op != O_symbol)
15745         {
15746           as_bad (_("bad .weakext directive"));
15747           ignore_rest_of_line ();
15748           return;
15749         }
15750       symbol_set_value_expression (symbolP, &exp);
15751     }
15752
15753   demand_empty_rest_of_line ();
15754 }
15755
15756 /* Parse a register string into a number.  Called from the ECOFF code
15757    to parse .frame.  The argument is non-zero if this is the frame
15758    register, so that we can record it in mips_frame_reg.  */
15759
15760 int
15761 tc_get_register (int frame)
15762 {
15763   unsigned int reg;
15764
15765   SKIP_WHITESPACE ();
15766   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15767     reg = 0;
15768   if (frame)
15769     {
15770       mips_frame_reg = reg != 0 ? reg : SP;
15771       mips_frame_reg_valid = 1;
15772       mips_cprestore_valid = 0;
15773     }
15774   return reg;
15775 }
15776
15777 valueT
15778 md_section_align (asection *seg, valueT addr)
15779 {
15780   int align = bfd_get_section_alignment (stdoutput, seg);
15781
15782   /* We don't need to align ELF sections to the full alignment.
15783      However, Irix 5 may prefer that we align them at least to a 16
15784      byte boundary.  We don't bother to align the sections if we
15785      are targeted for an embedded system.  */
15786   if (strncmp (TARGET_OS, "elf", 3) == 0)
15787     return addr;
15788   if (align > 4)
15789     align = 4;
15790
15791   return ((addr + (1 << align) - 1) & (-1 << align));
15792 }
15793
15794 /* Utility routine, called from above as well.  If called while the
15795    input file is still being read, it's only an approximation.  (For
15796    example, a symbol may later become defined which appeared to be
15797    undefined earlier.)  */
15798
15799 static int
15800 nopic_need_relax (symbolS *sym, int before_relaxing)
15801 {
15802   if (sym == 0)
15803     return 0;
15804
15805   if (g_switch_value > 0)
15806     {
15807       const char *symname;
15808       int change;
15809
15810       /* Find out whether this symbol can be referenced off the $gp
15811          register.  It can be if it is smaller than the -G size or if
15812          it is in the .sdata or .sbss section.  Certain symbols can
15813          not be referenced off the $gp, although it appears as though
15814          they can.  */
15815       symname = S_GET_NAME (sym);
15816       if (symname != (const char *) NULL
15817           && (strcmp (symname, "eprol") == 0
15818               || strcmp (symname, "etext") == 0
15819               || strcmp (symname, "_gp") == 0
15820               || strcmp (symname, "edata") == 0
15821               || strcmp (symname, "_fbss") == 0
15822               || strcmp (symname, "_fdata") == 0
15823               || strcmp (symname, "_ftext") == 0
15824               || strcmp (symname, "end") == 0
15825               || strcmp (symname, "_gp_disp") == 0))
15826         change = 1;
15827       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15828                && (0
15829 #ifndef NO_ECOFF_DEBUGGING
15830                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15831                        && (symbol_get_obj (sym)->ecoff_extern_size
15832                            <= g_switch_value))
15833 #endif
15834                    /* We must defer this decision until after the whole
15835                       file has been read, since there might be a .extern
15836                       after the first use of this symbol.  */
15837                    || (before_relaxing
15838 #ifndef NO_ECOFF_DEBUGGING
15839                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15840 #endif
15841                        && S_GET_VALUE (sym) == 0)
15842                    || (S_GET_VALUE (sym) != 0
15843                        && S_GET_VALUE (sym) <= g_switch_value)))
15844         change = 0;
15845       else
15846         {
15847           const char *segname;
15848
15849           segname = segment_name (S_GET_SEGMENT (sym));
15850           gas_assert (strcmp (segname, ".lit8") != 0
15851                   && strcmp (segname, ".lit4") != 0);
15852           change = (strcmp (segname, ".sdata") != 0
15853                     && strcmp (segname, ".sbss") != 0
15854                     && strncmp (segname, ".sdata.", 7) != 0
15855                     && strncmp (segname, ".sbss.", 6) != 0
15856                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15857                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15858         }
15859       return change;
15860     }
15861   else
15862     /* We are not optimizing for the $gp register.  */
15863     return 1;
15864 }
15865
15866
15867 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15868
15869 static bfd_boolean
15870 pic_need_relax (symbolS *sym, asection *segtype)
15871 {
15872   asection *symsec;
15873
15874   /* Handle the case of a symbol equated to another symbol.  */
15875   while (symbol_equated_reloc_p (sym))
15876     {
15877       symbolS *n;
15878
15879       /* It's possible to get a loop here in a badly written program.  */
15880       n = symbol_get_value_expression (sym)->X_add_symbol;
15881       if (n == sym)
15882         break;
15883       sym = n;
15884     }
15885
15886   if (symbol_section_p (sym))
15887     return TRUE;
15888
15889   symsec = S_GET_SEGMENT (sym);
15890
15891   /* This must duplicate the test in adjust_reloc_syms.  */
15892   return (!bfd_is_und_section (symsec)
15893           && !bfd_is_abs_section (symsec)
15894           && !bfd_is_com_section (symsec)
15895           && !s_is_linkonce (sym, segtype)
15896           /* A global or weak symbol is treated as external.  */
15897           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15898 }
15899
15900
15901 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15902    extended opcode.  SEC is the section the frag is in.  */
15903
15904 static int
15905 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15906 {
15907   int type;
15908   const struct mips_int_operand *operand;
15909   offsetT val;
15910   segT symsec;
15911   fragS *sym_frag;
15912
15913   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15914     return 0;
15915   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15916     return 1;
15917
15918   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15919   operand = mips16_immed_operand (type, FALSE);
15920
15921   sym_frag = symbol_get_frag (fragp->fr_symbol);
15922   val = S_GET_VALUE (fragp->fr_symbol);
15923   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15924
15925   if (operand->root.type == OP_PCREL)
15926     {
15927       const struct mips_pcrel_operand *pcrel_op;
15928       addressT addr;
15929       offsetT maxtiny;
15930
15931       /* We won't have the section when we are called from
15932          mips_relax_frag.  However, we will always have been called
15933          from md_estimate_size_before_relax first.  If this is a
15934          branch to a different section, we mark it as such.  If SEC is
15935          NULL, and the frag is not marked, then it must be a branch to
15936          the same section.  */
15937       pcrel_op = (const struct mips_pcrel_operand *) operand;
15938       if (sec == NULL)
15939         {
15940           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15941             return 1;
15942         }
15943       else
15944         {
15945           /* Must have been called from md_estimate_size_before_relax.  */
15946           if (symsec != sec)
15947             {
15948               fragp->fr_subtype =
15949                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15950
15951               /* FIXME: We should support this, and let the linker
15952                  catch branches and loads that are out of range.  */
15953               as_bad_where (fragp->fr_file, fragp->fr_line,
15954                             _("unsupported PC relative reference to different section"));
15955
15956               return 1;
15957             }
15958           if (fragp != sym_frag && sym_frag->fr_address == 0)
15959             /* Assume non-extended on the first relaxation pass.
15960                The address we have calculated will be bogus if this is
15961                a forward branch to another frag, as the forward frag
15962                will have fr_address == 0.  */
15963             return 0;
15964         }
15965
15966       /* In this case, we know for sure that the symbol fragment is in
15967          the same section.  If the relax_marker of the symbol fragment
15968          differs from the relax_marker of this fragment, we have not
15969          yet adjusted the symbol fragment fr_address.  We want to add
15970          in STRETCH in order to get a better estimate of the address.
15971          This particularly matters because of the shift bits.  */
15972       if (stretch != 0
15973           && sym_frag->relax_marker != fragp->relax_marker)
15974         {
15975           fragS *f;
15976
15977           /* Adjust stretch for any alignment frag.  Note that if have
15978              been expanding the earlier code, the symbol may be
15979              defined in what appears to be an earlier frag.  FIXME:
15980              This doesn't handle the fr_subtype field, which specifies
15981              a maximum number of bytes to skip when doing an
15982              alignment.  */
15983           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
15984             {
15985               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
15986                 {
15987                   if (stretch < 0)
15988                     stretch = - ((- stretch)
15989                                  & ~ ((1 << (int) f->fr_offset) - 1));
15990                   else
15991                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
15992                   if (stretch == 0)
15993                     break;
15994                 }
15995             }
15996           if (f != NULL)
15997             val += stretch;
15998         }
15999
16000       addr = fragp->fr_address + fragp->fr_fix;
16001
16002       /* The base address rules are complicated.  The base address of
16003          a branch is the following instruction.  The base address of a
16004          PC relative load or add is the instruction itself, but if it
16005          is in a delay slot (in which case it can not be extended) use
16006          the address of the instruction whose delay slot it is in.  */
16007       if (pcrel_op->include_isa_bit)
16008         {
16009           addr += 2;
16010
16011           /* If we are currently assuming that this frag should be
16012              extended, then, the current address is two bytes
16013              higher.  */
16014           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16015             addr += 2;
16016
16017           /* Ignore the low bit in the target, since it will be set
16018              for a text label.  */
16019           val &= -2;
16020         }
16021       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16022         addr -= 4;
16023       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16024         addr -= 2;
16025
16026       val -= addr & -(1 << pcrel_op->align_log2);
16027
16028       /* If any of the shifted bits are set, we must use an extended
16029          opcode.  If the address depends on the size of this
16030          instruction, this can lead to a loop, so we arrange to always
16031          use an extended opcode.  We only check this when we are in
16032          the main relaxation loop, when SEC is NULL.  */
16033       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16034         {
16035           fragp->fr_subtype =
16036             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16037           return 1;
16038         }
16039
16040       /* If we are about to mark a frag as extended because the value
16041          is precisely the next value above maxtiny, then there is a
16042          chance of an infinite loop as in the following code:
16043              la $4,foo
16044              .skip      1020
16045              .align     2
16046            foo:
16047          In this case when the la is extended, foo is 0x3fc bytes
16048          away, so the la can be shrunk, but then foo is 0x400 away, so
16049          the la must be extended.  To avoid this loop, we mark the
16050          frag as extended if it was small, and is about to become
16051          extended with the next value above maxtiny.  */
16052       maxtiny = mips_int_operand_max (operand);
16053       if (val == maxtiny + (1 << operand->shift)
16054           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16055           && sec == NULL)
16056         {
16057           fragp->fr_subtype =
16058             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16059           return 1;
16060         }
16061     }
16062   else if (symsec != absolute_section && sec != NULL)
16063     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16064
16065   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16066 }
16067
16068 /* Compute the length of a branch sequence, and adjust the
16069    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16070    worst-case length is computed, with UPDATE being used to indicate
16071    whether an unconditional (-1), branch-likely (+1) or regular (0)
16072    branch is to be computed.  */
16073 static int
16074 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16075 {
16076   bfd_boolean toofar;
16077   int length;
16078
16079   if (fragp
16080       && S_IS_DEFINED (fragp->fr_symbol)
16081       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16082     {
16083       addressT addr;
16084       offsetT val;
16085
16086       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16087
16088       addr = fragp->fr_address + fragp->fr_fix + 4;
16089
16090       val -= addr;
16091
16092       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16093     }
16094   else if (fragp)
16095     /* If the symbol is not defined or it's in a different segment,
16096        assume the user knows what's going on and emit a short
16097        branch.  */
16098     toofar = FALSE;
16099   else
16100     toofar = TRUE;
16101
16102   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16103     fragp->fr_subtype
16104       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16105                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16106                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16107                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16108                              toofar);
16109
16110   length = 4;
16111   if (toofar)
16112     {
16113       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16114         length += 8;
16115
16116       if (mips_pic != NO_PIC)
16117         {
16118           /* Additional space for PIC loading of target address.  */
16119           length += 8;
16120           if (mips_opts.isa == ISA_MIPS1)
16121             /* Additional space for $at-stabilizing nop.  */
16122             length += 4;
16123         }
16124
16125       /* If branch is conditional.  */
16126       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16127         length += 8;
16128     }
16129
16130   return length;
16131 }
16132
16133 /* Compute the length of a branch sequence, and adjust the
16134    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16135    worst-case length is computed, with UPDATE being used to indicate
16136    whether an unconditional (-1), or regular (0) branch is to be
16137    computed.  */
16138
16139 static int
16140 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16141 {
16142   bfd_boolean toofar;
16143   int length;
16144
16145   if (fragp
16146       && S_IS_DEFINED (fragp->fr_symbol)
16147       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16148     {
16149       addressT addr;
16150       offsetT val;
16151
16152       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16153       /* Ignore the low bit in the target, since it will be set
16154          for a text label.  */
16155       if ((val & 1) != 0)
16156         --val;
16157
16158       addr = fragp->fr_address + fragp->fr_fix + 4;
16159
16160       val -= addr;
16161
16162       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16163     }
16164   else if (fragp)
16165     /* If the symbol is not defined or it's in a different segment,
16166        assume the user knows what's going on and emit a short
16167        branch.  */
16168     toofar = FALSE;
16169   else
16170     toofar = TRUE;
16171
16172   if (fragp && update
16173       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16174     fragp->fr_subtype = (toofar
16175                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16176                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16177
16178   length = 4;
16179   if (toofar)
16180     {
16181       bfd_boolean compact_known = fragp != NULL;
16182       bfd_boolean compact = FALSE;
16183       bfd_boolean uncond;
16184
16185       if (compact_known)
16186         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16187       if (fragp)
16188         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16189       else
16190         uncond = update < 0;
16191
16192       /* If label is out of range, we turn branch <br>:
16193
16194                 <br>    label                   # 4 bytes
16195             0:
16196
16197          into:
16198
16199                 j       label                   # 4 bytes
16200                 nop                             # 2 bytes if compact && !PIC
16201             0:
16202        */
16203       if (mips_pic == NO_PIC && (!compact_known || compact))
16204         length += 2;
16205
16206       /* If assembling PIC code, we further turn:
16207
16208                         j       label                   # 4 bytes
16209
16210          into:
16211
16212                         lw/ld   at, %got(label)(gp)     # 4 bytes
16213                         d/addiu at, %lo(label)          # 4 bytes
16214                         jr/c    at                      # 2 bytes
16215        */
16216       if (mips_pic != NO_PIC)
16217         length += 6;
16218
16219       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16220
16221                         <brneg> 0f                      # 4 bytes
16222                         nop                             # 2 bytes if !compact
16223        */
16224       if (!uncond)
16225         length += (compact_known && compact) ? 4 : 6;
16226     }
16227
16228   return length;
16229 }
16230
16231 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16232    bit accordingly.  */
16233
16234 static int
16235 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16236 {
16237   bfd_boolean toofar;
16238
16239   if (fragp
16240       && S_IS_DEFINED (fragp->fr_symbol)
16241       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16242     {
16243       addressT addr;
16244       offsetT val;
16245       int type;
16246
16247       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16248       /* Ignore the low bit in the target, since it will be set
16249          for a text label.  */
16250       if ((val & 1) != 0)
16251         --val;
16252
16253       /* Assume this is a 2-byte branch.  */
16254       addr = fragp->fr_address + fragp->fr_fix + 2;
16255
16256       /* We try to avoid the infinite loop by not adding 2 more bytes for
16257          long branches.  */
16258
16259       val -= addr;
16260
16261       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16262       if (type == 'D')
16263         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16264       else if (type == 'E')
16265         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16266       else
16267         abort ();
16268     }
16269   else
16270     /* If the symbol is not defined or it's in a different segment,
16271        we emit a normal 32-bit branch.  */
16272     toofar = TRUE;
16273
16274   if (fragp && update
16275       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16276     fragp->fr_subtype
16277       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16278                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16279
16280   if (toofar)
16281     return 4;
16282
16283   return 2;
16284 }
16285
16286 /* Estimate the size of a frag before relaxing.  Unless this is the
16287    mips16, we are not really relaxing here, and the final size is
16288    encoded in the subtype information.  For the mips16, we have to
16289    decide whether we are using an extended opcode or not.  */
16290
16291 int
16292 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16293 {
16294   int change;
16295
16296   if (RELAX_BRANCH_P (fragp->fr_subtype))
16297     {
16298
16299       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16300
16301       return fragp->fr_var;
16302     }
16303
16304   if (RELAX_MIPS16_P (fragp->fr_subtype))
16305     /* We don't want to modify the EXTENDED bit here; it might get us
16306        into infinite loops.  We change it only in mips_relax_frag().  */
16307     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16308
16309   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16310     {
16311       int length = 4;
16312
16313       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16314         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16315       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16316         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16317       fragp->fr_var = length;
16318
16319       return length;
16320     }
16321
16322   if (mips_pic == NO_PIC)
16323     change = nopic_need_relax (fragp->fr_symbol, 0);
16324   else if (mips_pic == SVR4_PIC)
16325     change = pic_need_relax (fragp->fr_symbol, segtype);
16326   else if (mips_pic == VXWORKS_PIC)
16327     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16328     change = 0;
16329   else
16330     abort ();
16331
16332   if (change)
16333     {
16334       fragp->fr_subtype |= RELAX_USE_SECOND;
16335       return -RELAX_FIRST (fragp->fr_subtype);
16336     }
16337   else
16338     return -RELAX_SECOND (fragp->fr_subtype);
16339 }
16340
16341 /* This is called to see whether a reloc against a defined symbol
16342    should be converted into a reloc against a section.  */
16343
16344 int
16345 mips_fix_adjustable (fixS *fixp)
16346 {
16347   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16348       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16349     return 0;
16350
16351   if (fixp->fx_addsy == NULL)
16352     return 1;
16353
16354   /* If symbol SYM is in a mergeable section, relocations of the form
16355      SYM + 0 can usually be made section-relative.  The mergeable data
16356      is then identified by the section offset rather than by the symbol.
16357
16358      However, if we're generating REL LO16 relocations, the offset is split
16359      between the LO16 and parterning high part relocation.  The linker will
16360      need to recalculate the complete offset in order to correctly identify
16361      the merge data.
16362
16363      The linker has traditionally not looked for the parterning high part
16364      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16365      placed anywhere.  Rather than break backwards compatibility by changing
16366      this, it seems better not to force the issue, and instead keep the
16367      original symbol.  This will work with either linker behavior.  */
16368   if ((lo16_reloc_p (fixp->fx_r_type)
16369        || reloc_needs_lo_p (fixp->fx_r_type))
16370       && HAVE_IN_PLACE_ADDENDS
16371       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16372     return 0;
16373
16374   /* There is no place to store an in-place offset for JALR relocations.
16375      Likewise an in-range offset of limited PC-relative relocations may
16376      overflow the in-place relocatable field if recalculated against the
16377      start address of the symbol's containing section.  */
16378   if (HAVE_IN_PLACE_ADDENDS
16379       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16380           || jalr_reloc_p (fixp->fx_r_type)))
16381     return 0;
16382
16383   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16384      to a floating-point stub.  The same is true for non-R_MIPS16_26
16385      relocations against MIPS16 functions; in this case, the stub becomes
16386      the function's canonical address.
16387
16388      Floating-point stubs are stored in unique .mips16.call.* or
16389      .mips16.fn.* sections.  If a stub T for function F is in section S,
16390      the first relocation in section S must be against F; this is how the
16391      linker determines the target function.  All relocations that might
16392      resolve to T must also be against F.  We therefore have the following
16393      restrictions, which are given in an intentionally-redundant way:
16394
16395        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16396           symbols.
16397
16398        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16399           if that stub might be used.
16400
16401        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16402           symbols.
16403
16404        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16405           that stub might be used.
16406
16407      There is a further restriction:
16408
16409        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16410           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16411           targets with in-place addends; the relocation field cannot
16412           encode the low bit.
16413
16414      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16415      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16416      such relocations on REL targets.
16417
16418      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16419      relocation against some symbol R, no relocation against R may be
16420      reduced.  (Note that this deals with (2) as well as (1) because
16421      relocations against global symbols will never be reduced on ELF
16422      targets.)  This approach is a little simpler than trying to detect
16423      stub sections, and gives the "all or nothing" per-symbol consistency
16424      that we have for MIPS16 symbols.  */
16425   if (fixp->fx_subsy == NULL
16426       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16427           || *symbol_get_tc (fixp->fx_addsy)
16428           || (HAVE_IN_PLACE_ADDENDS
16429               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16430               && jmp_reloc_p (fixp->fx_r_type))))
16431     return 0;
16432
16433   return 1;
16434 }
16435
16436 /* Translate internal representation of relocation info to BFD target
16437    format.  */
16438
16439 arelent **
16440 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16441 {
16442   static arelent *retval[4];
16443   arelent *reloc;
16444   bfd_reloc_code_real_type code;
16445
16446   memset (retval, 0, sizeof(retval));
16447   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16448   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16449   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16450   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16451
16452   if (fixp->fx_pcrel)
16453     {
16454       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16455                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16456                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16457                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16458                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16459
16460       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16461          Relocations want only the symbol offset.  */
16462       reloc->addend = fixp->fx_addnumber + reloc->address;
16463     }
16464   else
16465     reloc->addend = fixp->fx_addnumber;
16466
16467   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16468      entry to be used in the relocation's section offset.  */
16469   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16470     {
16471       reloc->address = reloc->addend;
16472       reloc->addend = 0;
16473     }
16474
16475   code = fixp->fx_r_type;
16476
16477   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16478   if (reloc->howto == NULL)
16479     {
16480       as_bad_where (fixp->fx_file, fixp->fx_line,
16481                     _("Can not represent %s relocation in this object file format"),
16482                     bfd_get_reloc_code_name (code));
16483       retval[0] = NULL;
16484     }
16485
16486   return retval;
16487 }
16488
16489 /* Relax a machine dependent frag.  This returns the amount by which
16490    the current size of the frag should change.  */
16491
16492 int
16493 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16494 {
16495   if (RELAX_BRANCH_P (fragp->fr_subtype))
16496     {
16497       offsetT old_var = fragp->fr_var;
16498
16499       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16500
16501       return fragp->fr_var - old_var;
16502     }
16503
16504   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16505     {
16506       offsetT old_var = fragp->fr_var;
16507       offsetT new_var = 4;
16508
16509       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16510         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16511       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16512         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16513       fragp->fr_var = new_var;
16514
16515       return new_var - old_var;
16516     }
16517
16518   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16519     return 0;
16520
16521   if (mips16_extended_frag (fragp, NULL, stretch))
16522     {
16523       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16524         return 0;
16525       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16526       return 2;
16527     }
16528   else
16529     {
16530       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16531         return 0;
16532       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16533       return -2;
16534     }
16535
16536   return 0;
16537 }
16538
16539 /* Convert a machine dependent frag.  */
16540
16541 void
16542 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16543 {
16544   if (RELAX_BRANCH_P (fragp->fr_subtype))
16545     {
16546       char *buf;
16547       unsigned long insn;
16548       expressionS exp;
16549       fixS *fixp;
16550
16551       buf = fragp->fr_literal + fragp->fr_fix;
16552       insn = read_insn (buf);
16553
16554       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16555         {
16556           /* We generate a fixup instead of applying it right now
16557              because, if there are linker relaxations, we're going to
16558              need the relocations.  */
16559           exp.X_op = O_symbol;
16560           exp.X_add_symbol = fragp->fr_symbol;
16561           exp.X_add_number = fragp->fr_offset;
16562
16563           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16564                               BFD_RELOC_16_PCREL_S2);
16565           fixp->fx_file = fragp->fr_file;
16566           fixp->fx_line = fragp->fr_line;
16567
16568           buf = write_insn (buf, insn);
16569         }
16570       else
16571         {
16572           int i;
16573
16574           as_warn_where (fragp->fr_file, fragp->fr_line,
16575                          _("Relaxed out-of-range branch into a jump"));
16576
16577           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16578             goto uncond;
16579
16580           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16581             {
16582               /* Reverse the branch.  */
16583               switch ((insn >> 28) & 0xf)
16584                 {
16585                 case 4:
16586                   /* bc[0-3][tf]l? instructions can have the condition
16587                      reversed by tweaking a single TF bit, and their
16588                      opcodes all have 0x4???????.  */
16589                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16590                   insn ^= 0x00010000;
16591                   break;
16592
16593                 case 0:
16594                   /* bltz       0x04000000      bgez    0x04010000
16595                      bltzal     0x04100000      bgezal  0x04110000  */
16596                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16597                   insn ^= 0x00010000;
16598                   break;
16599
16600                 case 1:
16601                   /* beq        0x10000000      bne     0x14000000
16602                      blez       0x18000000      bgtz    0x1c000000  */
16603                   insn ^= 0x04000000;
16604                   break;
16605
16606                 default:
16607                   abort ();
16608                 }
16609             }
16610
16611           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16612             {
16613               /* Clear the and-link bit.  */
16614               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16615
16616               /* bltzal         0x04100000      bgezal  0x04110000
16617                  bltzall        0x04120000      bgezall 0x04130000  */
16618               insn &= ~0x00100000;
16619             }
16620
16621           /* Branch over the branch (if the branch was likely) or the
16622              full jump (not likely case).  Compute the offset from the
16623              current instruction to branch to.  */
16624           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16625             i = 16;
16626           else
16627             {
16628               /* How many bytes in instructions we've already emitted?  */
16629               i = buf - fragp->fr_literal - fragp->fr_fix;
16630               /* How many bytes in instructions from here to the end?  */
16631               i = fragp->fr_var - i;
16632             }
16633           /* Convert to instruction count.  */
16634           i >>= 2;
16635           /* Branch counts from the next instruction.  */
16636           i--;
16637           insn |= i;
16638           /* Branch over the jump.  */
16639           buf = write_insn (buf, insn);
16640
16641           /* nop */
16642           buf = write_insn (buf, 0);
16643
16644           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16645             {
16646               /* beql $0, $0, 2f */
16647               insn = 0x50000000;
16648               /* Compute the PC offset from the current instruction to
16649                  the end of the variable frag.  */
16650               /* How many bytes in instructions we've already emitted?  */
16651               i = buf - fragp->fr_literal - fragp->fr_fix;
16652               /* How many bytes in instructions from here to the end?  */
16653               i = fragp->fr_var - i;
16654               /* Convert to instruction count.  */
16655               i >>= 2;
16656               /* Don't decrement i, because we want to branch over the
16657                  delay slot.  */
16658               insn |= i;
16659
16660               buf = write_insn (buf, insn);
16661               buf = write_insn (buf, 0);
16662             }
16663
16664         uncond:
16665           if (mips_pic == NO_PIC)
16666             {
16667               /* j or jal.  */
16668               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16669                       ? 0x0c000000 : 0x08000000);
16670               exp.X_op = O_symbol;
16671               exp.X_add_symbol = fragp->fr_symbol;
16672               exp.X_add_number = fragp->fr_offset;
16673
16674               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16675                                   FALSE, BFD_RELOC_MIPS_JMP);
16676               fixp->fx_file = fragp->fr_file;
16677               fixp->fx_line = fragp->fr_line;
16678
16679               buf = write_insn (buf, insn);
16680             }
16681           else
16682             {
16683               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16684
16685               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16686               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16687               insn |= at << OP_SH_RT;
16688               exp.X_op = O_symbol;
16689               exp.X_add_symbol = fragp->fr_symbol;
16690               exp.X_add_number = fragp->fr_offset;
16691
16692               if (fragp->fr_offset)
16693                 {
16694                   exp.X_add_symbol = make_expr_symbol (&exp);
16695                   exp.X_add_number = 0;
16696                 }
16697
16698               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16699                                   FALSE, BFD_RELOC_MIPS_GOT16);
16700               fixp->fx_file = fragp->fr_file;
16701               fixp->fx_line = fragp->fr_line;
16702
16703               buf = write_insn (buf, insn);
16704
16705               if (mips_opts.isa == ISA_MIPS1)
16706                 /* nop */
16707                 buf = write_insn (buf, 0);
16708
16709               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16710               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16711               insn |= at << OP_SH_RS | at << OP_SH_RT;
16712
16713               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16714                                   FALSE, BFD_RELOC_LO16);
16715               fixp->fx_file = fragp->fr_file;
16716               fixp->fx_line = fragp->fr_line;
16717
16718               buf = write_insn (buf, insn);
16719
16720               /* j(al)r $at.  */
16721               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16722                 insn = 0x0000f809;
16723               else
16724                 insn = 0x00000008;
16725               insn |= at << OP_SH_RS;
16726
16727               buf = write_insn (buf, insn);
16728             }
16729         }
16730
16731       fragp->fr_fix += fragp->fr_var;
16732       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16733       return;
16734     }
16735
16736   /* Relax microMIPS branches.  */
16737   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16738     {
16739       char *buf = fragp->fr_literal + fragp->fr_fix;
16740       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16741       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16742       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16743       bfd_boolean short_ds;
16744       unsigned long insn;
16745       expressionS exp;
16746       fixS *fixp;
16747
16748       exp.X_op = O_symbol;
16749       exp.X_add_symbol = fragp->fr_symbol;
16750       exp.X_add_number = fragp->fr_offset;
16751
16752       fragp->fr_fix += fragp->fr_var;
16753
16754       /* Handle 16-bit branches that fit or are forced to fit.  */
16755       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16756         {
16757           /* We generate a fixup instead of applying it right now,
16758              because if there is linker relaxation, we're going to
16759              need the relocations.  */
16760           if (type == 'D')
16761             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16762                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16763           else if (type == 'E')
16764             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16765                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16766           else
16767             abort ();
16768
16769           fixp->fx_file = fragp->fr_file;
16770           fixp->fx_line = fragp->fr_line;
16771
16772           /* These relocations can have an addend that won't fit in
16773              2 octets.  */
16774           fixp->fx_no_overflow = 1;
16775
16776           return;
16777         }
16778
16779       /* Handle 32-bit branches that fit or are forced to fit.  */
16780       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16781           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16782         {
16783           /* We generate a fixup instead of applying it right now,
16784              because if there is linker relaxation, we're going to
16785              need the relocations.  */
16786           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16787                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16788           fixp->fx_file = fragp->fr_file;
16789           fixp->fx_line = fragp->fr_line;
16790
16791           if (type == 0)
16792             return;
16793         }
16794
16795       /* Relax 16-bit branches to 32-bit branches.  */
16796       if (type != 0)
16797         {
16798           insn = read_compressed_insn (buf, 2);
16799
16800           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16801             insn = 0x94000000;                          /* beq  */
16802           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16803             {
16804               unsigned long regno;
16805
16806               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16807               regno = micromips_to_32_reg_d_map [regno];
16808               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16809               insn |= regno << MICROMIPSOP_SH_RS;
16810             }
16811           else
16812             abort ();
16813
16814           /* Nothing else to do, just write it out.  */
16815           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16816               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16817             {
16818               buf = write_compressed_insn (buf, insn, 4);
16819               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16820               return;
16821             }
16822         }
16823       else
16824         insn = read_compressed_insn (buf, 4);
16825
16826       /* Relax 32-bit branches to a sequence of instructions.  */
16827       as_warn_where (fragp->fr_file, fragp->fr_line,
16828                      _("Relaxed out-of-range branch into a jump"));
16829
16830       /* Set the short-delay-slot bit.  */
16831       short_ds = al && (insn & 0x02000000) != 0;
16832
16833       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16834         {
16835           symbolS *l;
16836
16837           /* Reverse the branch.  */
16838           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16839               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16840             insn ^= 0x20000000;
16841           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16842                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16843                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16844                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16845                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16846                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16847                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16848                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16849                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16850                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16851             insn ^= 0x00400000;
16852           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16853                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16854                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16855                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16856             insn ^= 0x00200000;
16857           else
16858             abort ();
16859
16860           if (al)
16861             {
16862               /* Clear the and-link and short-delay-slot bits.  */
16863               gas_assert ((insn & 0xfda00000) == 0x40200000);
16864
16865               /* bltzal  0x40200000     bgezal  0x40600000  */
16866               /* bltzals 0x42200000     bgezals 0x42600000  */
16867               insn &= ~0x02200000;
16868             }
16869
16870           /* Make a label at the end for use with the branch.  */
16871           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16872           micromips_label_inc ();
16873           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16874
16875           /* Refer to it.  */
16876           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16877                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16878           fixp->fx_file = fragp->fr_file;
16879           fixp->fx_line = fragp->fr_line;
16880
16881           /* Branch over the jump.  */
16882           buf = write_compressed_insn (buf, insn, 4);
16883           if (!compact)
16884             /* nop */
16885             buf = write_compressed_insn (buf, 0x0c00, 2);
16886         }
16887
16888       if (mips_pic == NO_PIC)
16889         {
16890           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16891
16892           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16893           insn = al ? jal : 0xd4000000;
16894
16895           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16896                               BFD_RELOC_MICROMIPS_JMP);
16897           fixp->fx_file = fragp->fr_file;
16898           fixp->fx_line = fragp->fr_line;
16899
16900           buf = write_compressed_insn (buf, insn, 4);
16901           if (compact)
16902             /* nop */
16903             buf = write_compressed_insn (buf, 0x0c00, 2);
16904         }
16905       else
16906         {
16907           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16908           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16909           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16910
16911           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16912           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16913           insn |= at << MICROMIPSOP_SH_RT;
16914
16915           if (exp.X_add_number)
16916             {
16917               exp.X_add_symbol = make_expr_symbol (&exp);
16918               exp.X_add_number = 0;
16919             }
16920
16921           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16922                               BFD_RELOC_MICROMIPS_GOT16);
16923           fixp->fx_file = fragp->fr_file;
16924           fixp->fx_line = fragp->fr_line;
16925
16926           buf = write_compressed_insn (buf, insn, 4);
16927
16928           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16929           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16930           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16931
16932           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16933                               BFD_RELOC_MICROMIPS_LO16);
16934           fixp->fx_file = fragp->fr_file;
16935           fixp->fx_line = fragp->fr_line;
16936
16937           buf = write_compressed_insn (buf, insn, 4);
16938
16939           /* jr/jrc/jalr/jalrs $at  */
16940           insn = al ? jalr : jr;
16941           insn |= at << MICROMIPSOP_SH_MJ;
16942
16943           buf = write_compressed_insn (buf, insn, 2);
16944         }
16945
16946       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16947       return;
16948     }
16949
16950   if (RELAX_MIPS16_P (fragp->fr_subtype))
16951     {
16952       int type;
16953       const struct mips_int_operand *operand;
16954       offsetT val;
16955       char *buf;
16956       unsigned int user_length, length;
16957       unsigned long insn;
16958       bfd_boolean ext;
16959
16960       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16961       operand = mips16_immed_operand (type, FALSE);
16962
16963       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
16964       val = resolve_symbol_value (fragp->fr_symbol);
16965       if (operand->root.type == OP_PCREL)
16966         {
16967           const struct mips_pcrel_operand *pcrel_op;
16968           addressT addr;
16969
16970           pcrel_op = (const struct mips_pcrel_operand *) operand;
16971           addr = fragp->fr_address + fragp->fr_fix;
16972
16973           /* The rules for the base address of a PC relative reloc are
16974              complicated; see mips16_extended_frag.  */
16975           if (pcrel_op->include_isa_bit)
16976             {
16977               addr += 2;
16978               if (ext)
16979                 addr += 2;
16980               /* Ignore the low bit in the target, since it will be
16981                  set for a text label.  */
16982               val &= -2;
16983             }
16984           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16985             addr -= 4;
16986           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16987             addr -= 2;
16988
16989           addr &= -(1 << pcrel_op->align_log2);
16990           val -= addr;
16991
16992           /* Make sure the section winds up with the alignment we have
16993              assumed.  */
16994           if (operand->shift > 0)
16995             record_alignment (asec, operand->shift);
16996         }
16997
16998       if (ext
16999           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17000               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17001         as_warn_where (fragp->fr_file, fragp->fr_line,
17002                        _("extended instruction in delay slot"));
17003
17004       buf = fragp->fr_literal + fragp->fr_fix;
17005
17006       insn = read_compressed_insn (buf, 2);
17007       if (ext)
17008         insn |= MIPS16_EXTEND;
17009
17010       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17011         user_length = 4;
17012       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17013         user_length = 2;
17014       else
17015         user_length = 0;
17016
17017       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17018                     BFD_RELOC_UNUSED, val, user_length, &insn);
17019
17020       length = (ext ? 4 : 2);
17021       gas_assert (mips16_opcode_length (insn) == length);
17022       write_compressed_insn (buf, insn, length);
17023       fragp->fr_fix += length;
17024     }
17025   else
17026     {
17027       relax_substateT subtype = fragp->fr_subtype;
17028       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17029       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17030       int first, second;
17031       fixS *fixp;
17032
17033       first = RELAX_FIRST (subtype);
17034       second = RELAX_SECOND (subtype);
17035       fixp = (fixS *) fragp->fr_opcode;
17036
17037       /* If the delay slot chosen does not match the size of the instruction,
17038          then emit a warning.  */
17039       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17040            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17041         {
17042           relax_substateT s;
17043           const char *msg;
17044
17045           s = subtype & (RELAX_DELAY_SLOT_16BIT
17046                          | RELAX_DELAY_SLOT_SIZE_FIRST
17047                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17048           msg = macro_warning (s);
17049           if (msg != NULL)
17050             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17051           subtype &= ~s;
17052         }
17053
17054       /* Possibly emit a warning if we've chosen the longer option.  */
17055       if (use_second == second_longer)
17056         {
17057           relax_substateT s;
17058           const char *msg;
17059
17060           s = (subtype
17061                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17062           msg = macro_warning (s);
17063           if (msg != NULL)
17064             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17065           subtype &= ~s;
17066         }
17067
17068       /* Go through all the fixups for the first sequence.  Disable them
17069          (by marking them as done) if we're going to use the second
17070          sequence instead.  */
17071       while (fixp
17072              && fixp->fx_frag == fragp
17073              && fixp->fx_where < fragp->fr_fix - second)
17074         {
17075           if (subtype & RELAX_USE_SECOND)
17076             fixp->fx_done = 1;
17077           fixp = fixp->fx_next;
17078         }
17079
17080       /* Go through the fixups for the second sequence.  Disable them if
17081          we're going to use the first sequence, otherwise adjust their
17082          addresses to account for the relaxation.  */
17083       while (fixp && fixp->fx_frag == fragp)
17084         {
17085           if (subtype & RELAX_USE_SECOND)
17086             fixp->fx_where -= first;
17087           else
17088             fixp->fx_done = 1;
17089           fixp = fixp->fx_next;
17090         }
17091
17092       /* Now modify the frag contents.  */
17093       if (subtype & RELAX_USE_SECOND)
17094         {
17095           char *start;
17096
17097           start = fragp->fr_literal + fragp->fr_fix - first - second;
17098           memmove (start, start + first, second);
17099           fragp->fr_fix -= first;
17100         }
17101       else
17102         fragp->fr_fix -= second;
17103     }
17104 }
17105
17106 /* This function is called after the relocs have been generated.
17107    We've been storing mips16 text labels as odd.  Here we convert them
17108    back to even for the convenience of the debugger.  */
17109
17110 void
17111 mips_frob_file_after_relocs (void)
17112 {
17113   asymbol **syms;
17114   unsigned int count, i;
17115
17116   syms = bfd_get_outsymbols (stdoutput);
17117   count = bfd_get_symcount (stdoutput);
17118   for (i = 0; i < count; i++, syms++)
17119     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17120         && ((*syms)->value & 1) != 0)
17121       {
17122         (*syms)->value &= ~1;
17123         /* If the symbol has an odd size, it was probably computed
17124            incorrectly, so adjust that as well.  */
17125         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17126           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17127       }
17128 }
17129
17130 /* This function is called whenever a label is defined, including fake
17131    labels instantiated off the dot special symbol.  It is used when
17132    handling branch delays; if a branch has a label, we assume we cannot
17133    move it.  This also bumps the value of the symbol by 1 in compressed
17134    code.  */
17135
17136 static void
17137 mips_record_label (symbolS *sym)
17138 {
17139   segment_info_type *si = seg_info (now_seg);
17140   struct insn_label_list *l;
17141
17142   if (free_insn_labels == NULL)
17143     l = (struct insn_label_list *) xmalloc (sizeof *l);
17144   else
17145     {
17146       l = free_insn_labels;
17147       free_insn_labels = l->next;
17148     }
17149
17150   l->label = sym;
17151   l->next = si->label_list;
17152   si->label_list = l;
17153 }
17154
17155 /* This function is called as tc_frob_label() whenever a label is defined
17156    and adds a DWARF-2 record we only want for true labels.  */
17157
17158 void
17159 mips_define_label (symbolS *sym)
17160 {
17161   mips_record_label (sym);
17162   dwarf2_emit_label (sym);
17163 }
17164
17165 /* This function is called by tc_new_dot_label whenever a new dot symbol
17166    is defined.  */
17167
17168 void
17169 mips_add_dot_label (symbolS *sym)
17170 {
17171   mips_record_label (sym);
17172   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17173     mips_compressed_mark_label (sym);
17174 }
17175 \f
17176 /* Some special processing for a MIPS ELF file.  */
17177
17178 void
17179 mips_elf_final_processing (void)
17180 {
17181   /* Write out the register information.  */
17182   if (mips_abi != N64_ABI)
17183     {
17184       Elf32_RegInfo s;
17185
17186       s.ri_gprmask = mips_gprmask;
17187       s.ri_cprmask[0] = mips_cprmask[0];
17188       s.ri_cprmask[1] = mips_cprmask[1];
17189       s.ri_cprmask[2] = mips_cprmask[2];
17190       s.ri_cprmask[3] = mips_cprmask[3];
17191       /* The gp_value field is set by the MIPS ELF backend.  */
17192
17193       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17194                                        ((Elf32_External_RegInfo *)
17195                                         mips_regmask_frag));
17196     }
17197   else
17198     {
17199       Elf64_Internal_RegInfo s;
17200
17201       s.ri_gprmask = mips_gprmask;
17202       s.ri_pad = 0;
17203       s.ri_cprmask[0] = mips_cprmask[0];
17204       s.ri_cprmask[1] = mips_cprmask[1];
17205       s.ri_cprmask[2] = mips_cprmask[2];
17206       s.ri_cprmask[3] = mips_cprmask[3];
17207       /* The gp_value field is set by the MIPS ELF backend.  */
17208
17209       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17210                                        ((Elf64_External_RegInfo *)
17211                                         mips_regmask_frag));
17212     }
17213
17214   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17215      sort of BFD interface for this.  */
17216   if (mips_any_noreorder)
17217     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17218   if (mips_pic != NO_PIC)
17219     {
17220       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17221       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17222     }
17223   if (mips_abicalls)
17224     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17225
17226   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17227      defined at present; this might need to change in future.  */
17228   if (file_ase_mips16)
17229     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17230   if (file_ase_micromips)
17231     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17232   if (file_ase & ASE_MDMX)
17233     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17234
17235   /* Set the MIPS ELF ABI flags.  */
17236   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17237     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17238   else if (mips_abi == O64_ABI)
17239     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17240   else if (mips_abi == EABI_ABI)
17241     {
17242       if (!file_mips_gp32)
17243         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17244       else
17245         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17246     }
17247   else if (mips_abi == N32_ABI)
17248     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17249
17250   /* Nothing to do for N64_ABI.  */
17251
17252   if (mips_32bitmode)
17253     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17254
17255   if (mips_flag_nan2008)
17256     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17257
17258 #if 0 /* XXX FIXME */
17259   /* 32 bit code with 64 bit FP registers.  */
17260   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17261     elf_elfheader (stdoutput)->e_flags |= ???;
17262 #endif
17263 }
17264 \f
17265 typedef struct proc {
17266   symbolS *func_sym;
17267   symbolS *func_end_sym;
17268   unsigned long reg_mask;
17269   unsigned long reg_offset;
17270   unsigned long fpreg_mask;
17271   unsigned long fpreg_offset;
17272   unsigned long frame_offset;
17273   unsigned long frame_reg;
17274   unsigned long pc_reg;
17275 } procS;
17276
17277 static procS cur_proc;
17278 static procS *cur_proc_ptr;
17279 static int numprocs;
17280
17281 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17282    as "2", and a normal nop as "0".  */
17283
17284 #define NOP_OPCODE_MIPS         0
17285 #define NOP_OPCODE_MIPS16       1
17286 #define NOP_OPCODE_MICROMIPS    2
17287
17288 char
17289 mips_nop_opcode (void)
17290 {
17291   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17292     return NOP_OPCODE_MICROMIPS;
17293   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17294     return NOP_OPCODE_MIPS16;
17295   else
17296     return NOP_OPCODE_MIPS;
17297 }
17298
17299 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17300    32-bit microMIPS NOPs here (if applicable).  */
17301
17302 void
17303 mips_handle_align (fragS *fragp)
17304 {
17305   char nop_opcode;
17306   char *p;
17307   int bytes, size, excess;
17308   valueT opcode;
17309
17310   if (fragp->fr_type != rs_align_code)
17311     return;
17312
17313   p = fragp->fr_literal + fragp->fr_fix;
17314   nop_opcode = *p;
17315   switch (nop_opcode)
17316     {
17317     case NOP_OPCODE_MICROMIPS:
17318       opcode = micromips_nop32_insn.insn_opcode;
17319       size = 4;
17320       break;
17321     case NOP_OPCODE_MIPS16:
17322       opcode = mips16_nop_insn.insn_opcode;
17323       size = 2;
17324       break;
17325     case NOP_OPCODE_MIPS:
17326     default:
17327       opcode = nop_insn.insn_opcode;
17328       size = 4;
17329       break;
17330     }
17331
17332   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17333   excess = bytes % size;
17334
17335   /* Handle the leading part if we're not inserting a whole number of
17336      instructions, and make it the end of the fixed part of the frag.
17337      Try to fit in a short microMIPS NOP if applicable and possible,
17338      and use zeroes otherwise.  */
17339   gas_assert (excess < 4);
17340   fragp->fr_fix += excess;
17341   switch (excess)
17342     {
17343     case 3:
17344       *p++ = '\0';
17345       /* Fall through.  */
17346     case 2:
17347       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17348         {
17349           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17350           break;
17351         }
17352       *p++ = '\0';
17353       /* Fall through.  */
17354     case 1:
17355       *p++ = '\0';
17356       /* Fall through.  */
17357     case 0:
17358       break;
17359     }
17360
17361   md_number_to_chars (p, opcode, size);
17362   fragp->fr_var = size;
17363 }
17364
17365 static void
17366 md_obj_begin (void)
17367 {
17368 }
17369
17370 static void
17371 md_obj_end (void)
17372 {
17373   /* Check for premature end, nesting errors, etc.  */
17374   if (cur_proc_ptr)
17375     as_warn (_("missing .end at end of assembly"));
17376 }
17377
17378 static long
17379 get_number (void)
17380 {
17381   int negative = 0;
17382   long val = 0;
17383
17384   if (*input_line_pointer == '-')
17385     {
17386       ++input_line_pointer;
17387       negative = 1;
17388     }
17389   if (!ISDIGIT (*input_line_pointer))
17390     as_bad (_("expected simple number"));
17391   if (input_line_pointer[0] == '0')
17392     {
17393       if (input_line_pointer[1] == 'x')
17394         {
17395           input_line_pointer += 2;
17396           while (ISXDIGIT (*input_line_pointer))
17397             {
17398               val <<= 4;
17399               val |= hex_value (*input_line_pointer++);
17400             }
17401           return negative ? -val : val;
17402         }
17403       else
17404         {
17405           ++input_line_pointer;
17406           while (ISDIGIT (*input_line_pointer))
17407             {
17408               val <<= 3;
17409               val |= *input_line_pointer++ - '0';
17410             }
17411           return negative ? -val : val;
17412         }
17413     }
17414   if (!ISDIGIT (*input_line_pointer))
17415     {
17416       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17417               *input_line_pointer, *input_line_pointer);
17418       as_warn (_("invalid number"));
17419       return -1;
17420     }
17421   while (ISDIGIT (*input_line_pointer))
17422     {
17423       val *= 10;
17424       val += *input_line_pointer++ - '0';
17425     }
17426   return negative ? -val : val;
17427 }
17428
17429 /* The .file directive; just like the usual .file directive, but there
17430    is an initial number which is the ECOFF file index.  In the non-ECOFF
17431    case .file implies DWARF-2.  */
17432
17433 static void
17434 s_mips_file (int x ATTRIBUTE_UNUSED)
17435 {
17436   static int first_file_directive = 0;
17437
17438   if (ECOFF_DEBUGGING)
17439     {
17440       get_number ();
17441       s_app_file (0);
17442     }
17443   else
17444     {
17445       char *filename;
17446
17447       filename = dwarf2_directive_file (0);
17448
17449       /* Versions of GCC up to 3.1 start files with a ".file"
17450          directive even for stabs output.  Make sure that this
17451          ".file" is handled.  Note that you need a version of GCC
17452          after 3.1 in order to support DWARF-2 on MIPS.  */
17453       if (filename != NULL && ! first_file_directive)
17454         {
17455           (void) new_logical_line (filename, -1);
17456           s_app_file_string (filename, 0);
17457         }
17458       first_file_directive = 1;
17459     }
17460 }
17461
17462 /* The .loc directive, implying DWARF-2.  */
17463
17464 static void
17465 s_mips_loc (int x ATTRIBUTE_UNUSED)
17466 {
17467   if (!ECOFF_DEBUGGING)
17468     dwarf2_directive_loc (0);
17469 }
17470
17471 /* The .end directive.  */
17472
17473 static void
17474 s_mips_end (int x ATTRIBUTE_UNUSED)
17475 {
17476   symbolS *p;
17477
17478   /* Following functions need their own .frame and .cprestore directives.  */
17479   mips_frame_reg_valid = 0;
17480   mips_cprestore_valid = 0;
17481
17482   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17483     {
17484       p = get_symbol ();
17485       demand_empty_rest_of_line ();
17486     }
17487   else
17488     p = NULL;
17489
17490   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17491     as_warn (_(".end not in text section"));
17492
17493   if (!cur_proc_ptr)
17494     {
17495       as_warn (_(".end directive without a preceding .ent directive."));
17496       demand_empty_rest_of_line ();
17497       return;
17498     }
17499
17500   if (p != NULL)
17501     {
17502       gas_assert (S_GET_NAME (p));
17503       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17504         as_warn (_(".end symbol does not match .ent symbol."));
17505
17506       if (debug_type == DEBUG_STABS)
17507         stabs_generate_asm_endfunc (S_GET_NAME (p),
17508                                     S_GET_NAME (p));
17509     }
17510   else
17511     as_warn (_(".end directive missing or unknown symbol"));
17512
17513   /* Create an expression to calculate the size of the function.  */
17514   if (p && cur_proc_ptr)
17515     {
17516       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17517       expressionS *exp = xmalloc (sizeof (expressionS));
17518
17519       obj->size = exp;
17520       exp->X_op = O_subtract;
17521       exp->X_add_symbol = symbol_temp_new_now ();
17522       exp->X_op_symbol = p;
17523       exp->X_add_number = 0;
17524
17525       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17526     }
17527
17528   /* Generate a .pdr section.  */
17529   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17530     {
17531       segT saved_seg = now_seg;
17532       subsegT saved_subseg = now_subseg;
17533       expressionS exp;
17534       char *fragp;
17535
17536 #ifdef md_flush_pending_output
17537       md_flush_pending_output ();
17538 #endif
17539
17540       gas_assert (pdr_seg);
17541       subseg_set (pdr_seg, 0);
17542
17543       /* Write the symbol.  */
17544       exp.X_op = O_symbol;
17545       exp.X_add_symbol = p;
17546       exp.X_add_number = 0;
17547       emit_expr (&exp, 4);
17548
17549       fragp = frag_more (7 * 4);
17550
17551       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17552       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17553       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17554       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17555       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17556       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17557       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17558
17559       subseg_set (saved_seg, saved_subseg);
17560     }
17561
17562   cur_proc_ptr = NULL;
17563 }
17564
17565 /* The .aent and .ent directives.  */
17566
17567 static void
17568 s_mips_ent (int aent)
17569 {
17570   symbolS *symbolP;
17571
17572   symbolP = get_symbol ();
17573   if (*input_line_pointer == ',')
17574     ++input_line_pointer;
17575   SKIP_WHITESPACE ();
17576   if (ISDIGIT (*input_line_pointer)
17577       || *input_line_pointer == '-')
17578     get_number ();
17579
17580   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17581     as_warn (_(".ent or .aent not in text section."));
17582
17583   if (!aent && cur_proc_ptr)
17584     as_warn (_("missing .end"));
17585
17586   if (!aent)
17587     {
17588       /* This function needs its own .frame and .cprestore directives.  */
17589       mips_frame_reg_valid = 0;
17590       mips_cprestore_valid = 0;
17591
17592       cur_proc_ptr = &cur_proc;
17593       memset (cur_proc_ptr, '\0', sizeof (procS));
17594
17595       cur_proc_ptr->func_sym = symbolP;
17596
17597       ++numprocs;
17598
17599       if (debug_type == DEBUG_STABS)
17600         stabs_generate_asm_func (S_GET_NAME (symbolP),
17601                                  S_GET_NAME (symbolP));
17602     }
17603
17604   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17605
17606   demand_empty_rest_of_line ();
17607 }
17608
17609 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17610    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17611    s_mips_frame is used so that we can set the PDR information correctly.
17612    We can't use the ecoff routines because they make reference to the ecoff
17613    symbol table (in the mdebug section).  */
17614
17615 static void
17616 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17617 {
17618   if (ECOFF_DEBUGGING)
17619     s_ignore (ignore);
17620   else
17621     {
17622       long val;
17623
17624       if (cur_proc_ptr == (procS *) NULL)
17625         {
17626           as_warn (_(".frame outside of .ent"));
17627           demand_empty_rest_of_line ();
17628           return;
17629         }
17630
17631       cur_proc_ptr->frame_reg = tc_get_register (1);
17632
17633       SKIP_WHITESPACE ();
17634       if (*input_line_pointer++ != ','
17635           || get_absolute_expression_and_terminator (&val) != ',')
17636         {
17637           as_warn (_("Bad .frame directive"));
17638           --input_line_pointer;
17639           demand_empty_rest_of_line ();
17640           return;
17641         }
17642
17643       cur_proc_ptr->frame_offset = val;
17644       cur_proc_ptr->pc_reg = tc_get_register (0);
17645
17646       demand_empty_rest_of_line ();
17647     }
17648 }
17649
17650 /* The .fmask and .mask directives. If the mdebug section is present
17651    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17652    embedded targets, s_mips_mask is used so that we can set the PDR
17653    information correctly. We can't use the ecoff routines because they
17654    make reference to the ecoff symbol table (in the mdebug section).  */
17655
17656 static void
17657 s_mips_mask (int reg_type)
17658 {
17659   if (ECOFF_DEBUGGING)
17660     s_ignore (reg_type);
17661   else
17662     {
17663       long mask, off;
17664
17665       if (cur_proc_ptr == (procS *) NULL)
17666         {
17667           as_warn (_(".mask/.fmask outside of .ent"));
17668           demand_empty_rest_of_line ();
17669           return;
17670         }
17671
17672       if (get_absolute_expression_and_terminator (&mask) != ',')
17673         {
17674           as_warn (_("Bad .mask/.fmask directive"));
17675           --input_line_pointer;
17676           demand_empty_rest_of_line ();
17677           return;
17678         }
17679
17680       off = get_absolute_expression ();
17681
17682       if (reg_type == 'F')
17683         {
17684           cur_proc_ptr->fpreg_mask = mask;
17685           cur_proc_ptr->fpreg_offset = off;
17686         }
17687       else
17688         {
17689           cur_proc_ptr->reg_mask = mask;
17690           cur_proc_ptr->reg_offset = off;
17691         }
17692
17693       demand_empty_rest_of_line ();
17694     }
17695 }
17696
17697 /* A table describing all the processors gas knows about.  Names are
17698    matched in the order listed.
17699
17700    To ease comparison, please keep this table in the same order as
17701    gcc's mips_cpu_info_table[].  */
17702 static const struct mips_cpu_info mips_cpu_info_table[] =
17703 {
17704   /* Entries for generic ISAs */
17705   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17706   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17707   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17708   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17709   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17710   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17711   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17712   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17713   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17714
17715   /* MIPS I */
17716   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17717   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17718   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17719
17720   /* MIPS II */
17721   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17722
17723   /* MIPS III */
17724   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17725   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17726   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17727   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17728   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17729   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17730   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17731   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17732   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17733   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17734   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17735   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17736   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17737   /* ST Microelectronics Loongson 2E and 2F cores */
17738   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17739   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17740
17741   /* MIPS IV */
17742   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17743   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17744   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17745   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17746   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17747   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17748   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17749   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17750   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17751   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17752   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17753   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17754   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17755   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17756   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17757
17758   /* MIPS 32 */
17759   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17760   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17761   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17762   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17763
17764   /* MIPS 32 Release 2 */
17765   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17766   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17767   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17768   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17769   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17770   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17771   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17772   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17773   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17774                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17775   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17776                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17777   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17778   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17779   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17780   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17781   /* Deprecated forms of the above.  */
17782   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17783   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17784   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17785   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17786   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17787   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17788   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17789   /* Deprecated forms of the above.  */
17790   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17791   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17792   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17793   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17794   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17795   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17796   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17797   /* Deprecated forms of the above.  */
17798   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17799   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17800   /* 34Kn is a 34kc without DSP.  */
17801   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17802   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17803   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17804   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17805   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17806   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17807   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17808   /* Deprecated forms of the above.  */
17809   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17810   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17811   /* 1004K cores are multiprocessor versions of the 34K.  */
17812   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17813   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17814   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17815   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17816
17817   /* MIPS 64 */
17818   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17819   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17820   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17821   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17822
17823   /* Broadcom SB-1 CPU core */
17824   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17825   /* Broadcom SB-1A CPU core */
17826   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17827   
17828   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17829
17830   /* MIPS 64 Release 2 */
17831
17832   /* Cavium Networks Octeon CPU core */
17833   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17834   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17835   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17836
17837   /* RMI Xlr */
17838   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17839
17840   /* Broadcom XLP.
17841      XLP is mostly like XLR, with the prominent exception that it is
17842      MIPS64R2 rather than MIPS64.  */
17843   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17844
17845   /* End marker */
17846   { NULL, 0, 0, 0, 0 }
17847 };
17848
17849
17850 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17851    with a final "000" replaced by "k".  Ignore case.
17852
17853    Note: this function is shared between GCC and GAS.  */
17854
17855 static bfd_boolean
17856 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17857 {
17858   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17859     given++, canonical++;
17860
17861   return ((*given == 0 && *canonical == 0)
17862           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17863 }
17864
17865
17866 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17867    CPU name.  We've traditionally allowed a lot of variation here.
17868
17869    Note: this function is shared between GCC and GAS.  */
17870
17871 static bfd_boolean
17872 mips_matching_cpu_name_p (const char *canonical, const char *given)
17873 {
17874   /* First see if the name matches exactly, or with a final "000"
17875      turned into "k".  */
17876   if (mips_strict_matching_cpu_name_p (canonical, given))
17877     return TRUE;
17878
17879   /* If not, try comparing based on numerical designation alone.
17880      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17881   if (TOLOWER (*given) == 'r')
17882     given++;
17883   if (!ISDIGIT (*given))
17884     return FALSE;
17885
17886   /* Skip over some well-known prefixes in the canonical name,
17887      hoping to find a number there too.  */
17888   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17889     canonical += 2;
17890   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17891     canonical += 2;
17892   else if (TOLOWER (canonical[0]) == 'r')
17893     canonical += 1;
17894
17895   return mips_strict_matching_cpu_name_p (canonical, given);
17896 }
17897
17898
17899 /* Parse an option that takes the name of a processor as its argument.
17900    OPTION is the name of the option and CPU_STRING is the argument.
17901    Return the corresponding processor enumeration if the CPU_STRING is
17902    recognized, otherwise report an error and return null.
17903
17904    A similar function exists in GCC.  */
17905
17906 static const struct mips_cpu_info *
17907 mips_parse_cpu (const char *option, const char *cpu_string)
17908 {
17909   const struct mips_cpu_info *p;
17910
17911   /* 'from-abi' selects the most compatible architecture for the given
17912      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17913      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17914      version.  Look first at the -mgp options, if given, otherwise base
17915      the choice on MIPS_DEFAULT_64BIT.
17916
17917      Treat NO_ABI like the EABIs.  One reason to do this is that the
17918      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17919      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17920      'mips64', just as we did in the days before 'from-abi'.  */
17921   if (strcasecmp (cpu_string, "from-abi") == 0)
17922     {
17923       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17924         return mips_cpu_info_from_isa (ISA_MIPS1);
17925
17926       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17927         return mips_cpu_info_from_isa (ISA_MIPS3);
17928
17929       if (file_mips_gp32 >= 0)
17930         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17931
17932       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17933                                      ? ISA_MIPS3
17934                                      : ISA_MIPS1);
17935     }
17936
17937   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17938   if (strcasecmp (cpu_string, "default") == 0)
17939     return 0;
17940
17941   for (p = mips_cpu_info_table; p->name != 0; p++)
17942     if (mips_matching_cpu_name_p (p->name, cpu_string))
17943       return p;
17944
17945   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
17946   return 0;
17947 }
17948
17949 /* Return the canonical processor information for ISA (a member of the
17950    ISA_MIPS* enumeration).  */
17951
17952 static const struct mips_cpu_info *
17953 mips_cpu_info_from_isa (int isa)
17954 {
17955   int i;
17956
17957   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17958     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17959         && isa == mips_cpu_info_table[i].isa)
17960       return (&mips_cpu_info_table[i]);
17961
17962   return NULL;
17963 }
17964
17965 static const struct mips_cpu_info *
17966 mips_cpu_info_from_arch (int arch)
17967 {
17968   int i;
17969
17970   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17971     if (arch == mips_cpu_info_table[i].cpu)
17972       return (&mips_cpu_info_table[i]);
17973
17974   return NULL;
17975 }
17976 \f
17977 static void
17978 show (FILE *stream, const char *string, int *col_p, int *first_p)
17979 {
17980   if (*first_p)
17981     {
17982       fprintf (stream, "%24s", "");
17983       *col_p = 24;
17984     }
17985   else
17986     {
17987       fprintf (stream, ", ");
17988       *col_p += 2;
17989     }
17990
17991   if (*col_p + strlen (string) > 72)
17992     {
17993       fprintf (stream, "\n%24s", "");
17994       *col_p = 24;
17995     }
17996
17997   fprintf (stream, "%s", string);
17998   *col_p += strlen (string);
17999
18000   *first_p = 0;
18001 }
18002
18003 void
18004 md_show_usage (FILE *stream)
18005 {
18006   int column, first;
18007   size_t i;
18008
18009   fprintf (stream, _("\
18010 MIPS options:\n\
18011 -EB                     generate big endian output\n\
18012 -EL                     generate little endian output\n\
18013 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18014 -G NUM                  allow referencing objects up to NUM bytes\n\
18015                         implicitly with the gp register [default 8]\n"));
18016   fprintf (stream, _("\
18017 -mips1                  generate MIPS ISA I instructions\n\
18018 -mips2                  generate MIPS ISA II instructions\n\
18019 -mips3                  generate MIPS ISA III instructions\n\
18020 -mips4                  generate MIPS ISA IV instructions\n\
18021 -mips5                  generate MIPS ISA V instructions\n\
18022 -mips32                 generate MIPS32 ISA instructions\n\
18023 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18024 -mips64                 generate MIPS64 ISA instructions\n\
18025 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18026 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18027
18028   first = 1;
18029
18030   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18031     show (stream, mips_cpu_info_table[i].name, &column, &first);
18032   show (stream, "from-abi", &column, &first);
18033   fputc ('\n', stream);
18034
18035   fprintf (stream, _("\
18036 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18037 -no-mCPU                don't generate code specific to CPU.\n\
18038                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18039
18040   first = 1;
18041
18042   show (stream, "3900", &column, &first);
18043   show (stream, "4010", &column, &first);
18044   show (stream, "4100", &column, &first);
18045   show (stream, "4650", &column, &first);
18046   fputc ('\n', stream);
18047
18048   fprintf (stream, _("\
18049 -mips16                 generate mips16 instructions\n\
18050 -no-mips16              do not generate mips16 instructions\n"));
18051   fprintf (stream, _("\
18052 -mmicromips             generate microMIPS instructions\n\
18053 -mno-micromips          do not generate microMIPS instructions\n"));
18054   fprintf (stream, _("\
18055 -msmartmips             generate smartmips instructions\n\
18056 -mno-smartmips          do not generate smartmips instructions\n"));  
18057   fprintf (stream, _("\
18058 -mdsp                   generate DSP instructions\n\
18059 -mno-dsp                do not generate DSP instructions\n"));
18060   fprintf (stream, _("\
18061 -mdspr2                 generate DSP R2 instructions\n\
18062 -mno-dspr2              do not generate DSP R2 instructions\n"));
18063   fprintf (stream, _("\
18064 -mmt                    generate MT instructions\n\
18065 -mno-mt                 do not generate MT instructions\n"));
18066   fprintf (stream, _("\
18067 -mmcu                   generate MCU instructions\n\
18068 -mno-mcu                do not generate MCU instructions\n"));
18069   fprintf (stream, _("\
18070 -mvirt                  generate Virtualization instructions\n\
18071 -mno-virt               do not generate Virtualization instructions\n"));
18072   fprintf (stream, _("\
18073 -minsn32                only generate 32-bit microMIPS instructions\n\
18074 -mno-insn32             generate all microMIPS instructions\n"));
18075   fprintf (stream, _("\
18076 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18077 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18078 -mfix-vr4120            work around certain VR4120 errata\n\
18079 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18080 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18081 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18082 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18083 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18084 -msym32                 assume all symbols have 32-bit values\n\
18085 -O0                     remove unneeded NOPs, do not swap branches\n\
18086 -O                      remove unneeded NOPs and swap branches\n\
18087 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18088 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18089   fprintf (stream, _("\
18090 -mhard-float            allow floating-point instructions\n\
18091 -msoft-float            do not allow floating-point instructions\n\
18092 -msingle-float          only allow 32-bit floating-point operations\n\
18093 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18094 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18095 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18096 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18097
18098   first = 1;
18099
18100   show (stream, "legacy", &column, &first);
18101   show (stream, "2008", &column, &first);
18102
18103   fputc ('\n', stream);
18104
18105   fprintf (stream, _("\
18106 -KPIC, -call_shared     generate SVR4 position independent code\n\
18107 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18108 -mvxworks-pic           generate VxWorks position independent code\n\
18109 -non_shared             do not generate code that can operate with DSOs\n\
18110 -xgot                   assume a 32 bit GOT\n\
18111 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18112 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18113                         position dependent (non shared) code\n\
18114 -mabi=ABI               create ABI conformant object file for:\n"));
18115
18116   first = 1;
18117
18118   show (stream, "32", &column, &first);
18119   show (stream, "o64", &column, &first);
18120   show (stream, "n32", &column, &first);
18121   show (stream, "64", &column, &first);
18122   show (stream, "eabi", &column, &first);
18123
18124   fputc ('\n', stream);
18125
18126   fprintf (stream, _("\
18127 -32                     create o32 ABI object file (default)\n\
18128 -n32                    create n32 ABI object file\n\
18129 -64                     create 64 ABI object file\n"));
18130 }
18131
18132 #ifdef TE_IRIX
18133 enum dwarf2_format
18134 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18135 {
18136   if (HAVE_64BIT_SYMBOLS)
18137     return dwarf2_format_64bit_irix;
18138   else
18139     return dwarf2_format_32bit;
18140 }
18141 #endif
18142
18143 int
18144 mips_dwarf2_addr_size (void)
18145 {
18146   if (HAVE_64BIT_OBJECTS)
18147     return 8;
18148   else
18149     return 4;
18150 }
18151
18152 /* Standard calling conventions leave the CFA at SP on entry.  */
18153 void
18154 mips_cfi_frame_initial_instructions (void)
18155 {
18156   cfi_add_CFA_def_cfa_register (SP);
18157 }
18158
18159 int
18160 tc_mips_regname_to_dw2regnum (char *regname)
18161 {
18162   unsigned int regnum = -1;
18163   unsigned int reg;
18164
18165   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18166     regnum = reg;
18167
18168   return regnum;
18169 }