gas/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5    Contributed by the OSF and Ralph Campbell.
6    Written by Keith Knowles and Ralph Campbell, working independently.
7    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
8    Support.
9
10    This file is part of GAS.
11
12    GAS is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GAS is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with GAS; see the file COPYING.  If not, write to the Free
24    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
25    02110-1301, USA.  */
26
27 #include "as.h"
28 #include "config.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31
32 #include "opcode/mips.h"
33 #include "itbl-ops.h"
34 #include "dwarf2dbg.h"
35 #include "dw2gencfi.h"
36
37 /* Check assumptions made in this file.  */
38 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
39 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
40
41 #ifdef DEBUG
42 #define DBG(x) printf x
43 #else
44 #define DBG(x)
45 #endif
46
47 #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 static char *insn_error;
634
635 static int auto_align = 1;
636
637 /* When outputting SVR4 PIC code, the assembler needs to know the
638    offset in the stack frame from which to restore the $gp register.
639    This is set by the .cprestore pseudo-op, and saved in this
640    variable.  */
641 static offsetT mips_cprestore_offset = -1;
642
643 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
644    more optimizations, it can use a register value instead of a memory-saved
645    offset and even an other register than $gp as global pointer.  */
646 static offsetT mips_cpreturn_offset = -1;
647 static int mips_cpreturn_register = -1;
648 static int mips_gp_register = GP;
649 static int mips_gprel_offset = 0;
650
651 /* Whether mips_cprestore_offset has been set in the current function
652    (or whether it has already been warned about, if not).  */
653 static int mips_cprestore_valid = 0;
654
655 /* This is the register which holds the stack frame, as set by the
656    .frame pseudo-op.  This is needed to implement .cprestore.  */
657 static int mips_frame_reg = SP;
658
659 /* Whether mips_frame_reg has been set in the current function
660    (or whether it has already been warned about, if not).  */
661 static int mips_frame_reg_valid = 0;
662
663 /* To output NOP instructions correctly, we need to keep information
664    about the previous two instructions.  */
665
666 /* Whether we are optimizing.  The default value of 2 means to remove
667    unneeded NOPs and swap branch instructions when possible.  A value
668    of 1 means to not swap branches.  A value of 0 means to always
669    insert NOPs.  */
670 static int mips_optimize = 2;
671
672 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
673    equivalent to seeing no -g option at all.  */
674 static int mips_debug = 0;
675
676 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
677 #define MAX_VR4130_NOPS 4
678
679 /* The maximum number of NOPs needed to fill delay slots.  */
680 #define MAX_DELAY_NOPS 2
681
682 /* The maximum number of NOPs needed for any purpose.  */
683 #define MAX_NOPS 4
684
685 /* A list of previous instructions, with index 0 being the most recent.
686    We need to look back MAX_NOPS instructions when filling delay slots
687    or working around processor errata.  We need to look back one
688    instruction further if we're thinking about using history[0] to
689    fill a branch delay slot.  */
690 static struct mips_cl_insn history[1 + MAX_NOPS];
691
692 /* Nop instructions used by emit_nop.  */
693 static struct mips_cl_insn nop_insn;
694 static struct mips_cl_insn mips16_nop_insn;
695 static struct mips_cl_insn micromips_nop16_insn;
696 static struct mips_cl_insn micromips_nop32_insn;
697
698 /* The appropriate nop for the current mode.  */
699 #define NOP_INSN (mips_opts.mips16                                      \
700                   ? &mips16_nop_insn                                    \
701                   : (mips_opts.micromips                                \
702                      ? (mips_opts.insn32                                \
703                         ? &micromips_nop32_insn                         \
704                         : &micromips_nop16_insn)                        \
705                      : &nop_insn))
706
707 /* The size of NOP_INSN in bytes.  */
708 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
709                         || (mips_opts.micromips && !mips_opts.insn32))  \
710                        ? 2 : 4)
711
712 /* If this is set, it points to a frag holding nop instructions which
713    were inserted before the start of a noreorder section.  If those
714    nops turn out to be unnecessary, the size of the frag can be
715    decreased.  */
716 static fragS *prev_nop_frag;
717
718 /* The number of nop instructions we created in prev_nop_frag.  */
719 static int prev_nop_frag_holds;
720
721 /* The number of nop instructions that we know we need in
722    prev_nop_frag.  */
723 static int prev_nop_frag_required;
724
725 /* The number of instructions we've seen since prev_nop_frag.  */
726 static int prev_nop_frag_since;
727
728 /* Relocations against symbols are sometimes done in two parts, with a HI
729    relocation and a LO relocation.  Each relocation has only 16 bits of
730    space to store an addend.  This means that in order for the linker to
731    handle carries correctly, it must be able to locate both the HI and
732    the LO relocation.  This means that the relocations must appear in
733    order in the relocation table.
734
735    In order to implement this, we keep track of each unmatched HI
736    relocation.  We then sort them so that they immediately precede the
737    corresponding LO relocation.  */
738
739 struct mips_hi_fixup
740 {
741   /* Next HI fixup.  */
742   struct mips_hi_fixup *next;
743   /* This fixup.  */
744   fixS *fixp;
745   /* The section this fixup is in.  */
746   segT seg;
747 };
748
749 /* The list of unmatched HI relocs.  */
750
751 static struct mips_hi_fixup *mips_hi_fixup_list;
752
753 /* The frag containing the last explicit relocation operator.
754    Null if explicit relocations have not been used.  */
755
756 static fragS *prev_reloc_op_frag;
757
758 /* Map mips16 register numbers to normal MIPS register numbers.  */
759
760 static const unsigned int mips16_to_32_reg_map[] =
761 {
762   16, 17, 2, 3, 4, 5, 6, 7
763 };
764
765 /* Map microMIPS register numbers to normal MIPS register numbers.  */
766
767 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
768 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
769 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
770 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
771 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
772 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
773
774 /* The microMIPS registers with type h.  */
775 static const unsigned int micromips_to_32_reg_h_map1[] =
776 {
777   5, 5, 6, 4, 4, 4, 4, 4
778 };
779 static const unsigned int micromips_to_32_reg_h_map2[] =
780 {
781   6, 7, 7, 21, 22, 5, 6, 7
782 };
783
784 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
785
786 /* The microMIPS registers with type m.  */
787 static const unsigned int micromips_to_32_reg_m_map[] =
788 {
789   0, 17, 2, 3, 16, 18, 19, 20
790 };
791
792 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
793
794 /* The microMIPS registers with type q.  */
795 static const unsigned int micromips_to_32_reg_q_map[] =
796 {
797   0, 17, 2, 3, 4, 5, 6, 7
798 };
799
800 /* Classifies the kind of instructions we're interested in when
801    implementing -mfix-vr4120.  */
802 enum fix_vr4120_class
803 {
804   FIX_VR4120_MACC,
805   FIX_VR4120_DMACC,
806   FIX_VR4120_MULT,
807   FIX_VR4120_DMULT,
808   FIX_VR4120_DIV,
809   FIX_VR4120_MTHILO,
810   NUM_FIX_VR4120_CLASSES
811 };
812
813 /* ...likewise -mfix-loongson2f-jump.  */
814 static bfd_boolean mips_fix_loongson2f_jump;
815
816 /* ...likewise -mfix-loongson2f-nop.  */
817 static bfd_boolean mips_fix_loongson2f_nop;
818
819 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
820 static bfd_boolean mips_fix_loongson2f;
821
822 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
823    there must be at least one other instruction between an instruction
824    of type X and an instruction of type Y.  */
825 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
826
827 /* True if -mfix-vr4120 is in force.  */
828 static int mips_fix_vr4120;
829
830 /* ...likewise -mfix-vr4130.  */
831 static int mips_fix_vr4130;
832
833 /* ...likewise -mfix-24k.  */
834 static int mips_fix_24k;
835
836 /* ...likewise -mfix-cn63xxp1 */
837 static bfd_boolean mips_fix_cn63xxp1;
838
839 /* We don't relax branches by default, since this causes us to expand
840    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
841    fail to compute the offset before expanding the macro to the most
842    efficient expansion.  */
843
844 static int mips_relax_branch;
845 \f
846 /* The expansion of many macros depends on the type of symbol that
847    they refer to.  For example, when generating position-dependent code,
848    a macro that refers to a symbol may have two different expansions,
849    one which uses GP-relative addresses and one which uses absolute
850    addresses.  When generating SVR4-style PIC, a macro may have
851    different expansions for local and global symbols.
852
853    We handle these situations by generating both sequences and putting
854    them in variant frags.  In position-dependent code, the first sequence
855    will be the GP-relative one and the second sequence will be the
856    absolute one.  In SVR4 PIC, the first sequence will be for global
857    symbols and the second will be for local symbols.
858
859    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
860    SECOND are the lengths of the two sequences in bytes.  These fields
861    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
862    the subtype has the following flags:
863
864    RELAX_USE_SECOND
865         Set if it has been decided that we should use the second
866         sequence instead of the first.
867
868    RELAX_SECOND_LONGER
869         Set in the first variant frag if the macro's second implementation
870         is longer than its first.  This refers to the macro as a whole,
871         not an individual relaxation.
872
873    RELAX_NOMACRO
874         Set in the first variant frag if the macro appeared in a .set nomacro
875         block and if one alternative requires a warning but the other does not.
876
877    RELAX_DELAY_SLOT
878         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
879         delay slot.
880
881    RELAX_DELAY_SLOT_16BIT
882         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
883         16-bit instruction.
884
885    RELAX_DELAY_SLOT_SIZE_FIRST
886         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
887         the macro is of the wrong size for the branch delay slot.
888
889    RELAX_DELAY_SLOT_SIZE_SECOND
890         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
891         the macro is of the wrong size for the branch delay slot.
892
893    The frag's "opcode" points to the first fixup for relaxable code.
894
895    Relaxable macros are generated using a sequence such as:
896
897       relax_start (SYMBOL);
898       ... generate first expansion ...
899       relax_switch ();
900       ... generate second expansion ...
901       relax_end ();
902
903    The code and fixups for the unwanted alternative are discarded
904    by md_convert_frag.  */
905 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
906
907 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
908 #define RELAX_SECOND(X) ((X) & 0xff)
909 #define RELAX_USE_SECOND 0x10000
910 #define RELAX_SECOND_LONGER 0x20000
911 #define RELAX_NOMACRO 0x40000
912 #define RELAX_DELAY_SLOT 0x80000
913 #define RELAX_DELAY_SLOT_16BIT 0x100000
914 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
915 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
916
917 /* Branch without likely bit.  If label is out of range, we turn:
918
919         beq reg1, reg2, label
920         delay slot
921
922    into
923
924         bne reg1, reg2, 0f
925         nop
926         j label
927      0: delay slot
928
929    with the following opcode replacements:
930
931         beq <-> bne
932         blez <-> bgtz
933         bltz <-> bgez
934         bc1f <-> bc1t
935
936         bltzal <-> bgezal  (with jal label instead of j label)
937
938    Even though keeping the delay slot instruction in the delay slot of
939    the branch would be more efficient, it would be very tricky to do
940    correctly, because we'd have to introduce a variable frag *after*
941    the delay slot instruction, and expand that instead.  Let's do it
942    the easy way for now, even if the branch-not-taken case now costs
943    one additional instruction.  Out-of-range branches are not supposed
944    to be common, anyway.
945
946    Branch likely.  If label is out of range, we turn:
947
948         beql reg1, reg2, label
949         delay slot (annulled if branch not taken)
950
951    into
952
953         beql reg1, reg2, 1f
954         nop
955         beql $0, $0, 2f
956         nop
957      1: j[al] label
958         delay slot (executed only if branch taken)
959      2:
960
961    It would be possible to generate a shorter sequence by losing the
962    likely bit, generating something like:
963
964         bne reg1, reg2, 0f
965         nop
966         j[al] label
967         delay slot (executed only if branch taken)
968      0:
969
970         beql -> bne
971         bnel -> beq
972         blezl -> bgtz
973         bgtzl -> blez
974         bltzl -> bgez
975         bgezl -> bltz
976         bc1fl -> bc1t
977         bc1tl -> bc1f
978
979         bltzall -> bgezal  (with jal label instead of j label)
980         bgezall -> bltzal  (ditto)
981
982
983    but it's not clear that it would actually improve performance.  */
984 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
985   ((relax_substateT)                                            \
986    (0xc0000000                                                  \
987     | ((at) & 0x1f)                                             \
988     | ((toofar) ? 0x20 : 0)                                     \
989     | ((link) ? 0x40 : 0)                                       \
990     | ((likely) ? 0x80 : 0)                                     \
991     | ((uncond) ? 0x100 : 0)))
992 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
993 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
994 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
995 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
996 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
997 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
998
999 /* For mips16 code, we use an entirely different form of relaxation.
1000    mips16 supports two versions of most instructions which take
1001    immediate values: a small one which takes some small value, and a
1002    larger one which takes a 16 bit value.  Since branches also follow
1003    this pattern, relaxing these values is required.
1004
1005    We can assemble both mips16 and normal MIPS code in a single
1006    object.  Therefore, we need to support this type of relaxation at
1007    the same time that we support the relaxation described above.  We
1008    use the high bit of the subtype field to distinguish these cases.
1009
1010    The information we store for this type of relaxation is the
1011    argument code found in the opcode file for this relocation, whether
1012    the user explicitly requested a small or extended form, and whether
1013    the relocation is in a jump or jal delay slot.  That tells us the
1014    size of the value, and how it should be stored.  We also store
1015    whether the fragment is considered to be extended or not.  We also
1016    store whether this is known to be a branch to a different section,
1017    whether we have tried to relax this frag yet, and whether we have
1018    ever extended a PC relative fragment because of a shift count.  */
1019 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1020   (0x80000000                                                   \
1021    | ((type) & 0xff)                                            \
1022    | ((small) ? 0x100 : 0)                                      \
1023    | ((ext) ? 0x200 : 0)                                        \
1024    | ((dslot) ? 0x400 : 0)                                      \
1025    | ((jal_dslot) ? 0x800 : 0))
1026 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1027 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1028 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1029 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1030 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1031 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1032 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1033 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1034 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1035 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1036 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1037 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1038
1039 /* For microMIPS code, we use relaxation similar to one we use for
1040    MIPS16 code.  Some instructions that take immediate values support
1041    two encodings: a small one which takes some small value, and a
1042    larger one which takes a 16 bit value.  As some branches also follow
1043    this pattern, relaxing these values is required.
1044
1045    We can assemble both microMIPS and normal MIPS code in a single
1046    object.  Therefore, we need to support this type of relaxation at
1047    the same time that we support the relaxation described above.  We
1048    use one of the high bits of the subtype field to distinguish these
1049    cases.
1050
1051    The information we store for this type of relaxation is the argument
1052    code found in the opcode file for this relocation, the register
1053    selected as the assembler temporary, whether the branch is
1054    unconditional, whether it is compact, whether it stores the link
1055    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1056    branches to a sequence of instructions is enabled, and whether the
1057    displacement of a branch is too large to fit as an immediate argument
1058    of a 16-bit and a 32-bit branch, respectively.  */
1059 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1060                                relax32, toofar16, toofar32)     \
1061   (0x40000000                                                   \
1062    | ((type) & 0xff)                                            \
1063    | (((at) & 0x1f) << 8)                                       \
1064    | ((uncond) ? 0x2000 : 0)                                    \
1065    | ((compact) ? 0x4000 : 0)                                   \
1066    | ((link) ? 0x8000 : 0)                                      \
1067    | ((relax32) ? 0x10000 : 0)                                  \
1068    | ((toofar16) ? 0x20000 : 0)                                 \
1069    | ((toofar32) ? 0x40000 : 0))
1070 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1071 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1072 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1073 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1074 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1075 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1076 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1077
1078 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1079 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1080 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1081 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1082 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1083 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1084
1085 /* Sign-extend 16-bit value X.  */
1086 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1087
1088 /* Is the given value a sign-extended 32-bit value?  */
1089 #define IS_SEXT_32BIT_NUM(x)                                            \
1090   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1091    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1092
1093 /* Is the given value a sign-extended 16-bit value?  */
1094 #define IS_SEXT_16BIT_NUM(x)                                            \
1095   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1096    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1097
1098 /* Is the given value a sign-extended 12-bit value?  */
1099 #define IS_SEXT_12BIT_NUM(x)                                            \
1100   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1101
1102 /* Is the given value a sign-extended 9-bit value?  */
1103 #define IS_SEXT_9BIT_NUM(x)                                             \
1104   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1105
1106 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1107 #define IS_ZEXT_32BIT_NUM(x)                                            \
1108   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1109    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1110
1111 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1112    SHIFT places.  */
1113 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1114   (((STRUCT) >> (SHIFT)) & (MASK))
1115
1116 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1117 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1118   (!(MICROMIPS) \
1119    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1120    : EXTRACT_BITS ((INSN).insn_opcode, \
1121                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1122 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1123   EXTRACT_BITS ((INSN).insn_opcode, \
1124                 MIPS16OP_MASK_##FIELD, \
1125                 MIPS16OP_SH_##FIELD)
1126
1127 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1128 #define MIPS16_EXTEND (0xf000U << 16)
1129 \f
1130 /* Whether or not we are emitting a branch-likely macro.  */
1131 static bfd_boolean emit_branch_likely_macro = FALSE;
1132
1133 /* Global variables used when generating relaxable macros.  See the
1134    comment above RELAX_ENCODE for more details about how relaxation
1135    is used.  */
1136 static struct {
1137   /* 0 if we're not emitting a relaxable macro.
1138      1 if we're emitting the first of the two relaxation alternatives.
1139      2 if we're emitting the second alternative.  */
1140   int sequence;
1141
1142   /* The first relaxable fixup in the current frag.  (In other words,
1143      the first fixup that refers to relaxable code.)  */
1144   fixS *first_fixup;
1145
1146   /* sizes[0] says how many bytes of the first alternative are stored in
1147      the current frag.  Likewise sizes[1] for the second alternative.  */
1148   unsigned int sizes[2];
1149
1150   /* The symbol on which the choice of sequence depends.  */
1151   symbolS *symbol;
1152 } mips_relax;
1153 \f
1154 /* Global variables used to decide whether a macro needs a warning.  */
1155 static struct {
1156   /* True if the macro is in a branch delay slot.  */
1157   bfd_boolean delay_slot_p;
1158
1159   /* Set to the length in bytes required if the macro is in a delay slot
1160      that requires a specific length of instruction, otherwise zero.  */
1161   unsigned int delay_slot_length;
1162
1163   /* For relaxable macros, sizes[0] is the length of the first alternative
1164      in bytes and sizes[1] is the length of the second alternative.
1165      For non-relaxable macros, both elements give the length of the
1166      macro in bytes.  */
1167   unsigned int sizes[2];
1168
1169   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1170      instruction of the first alternative in bytes and first_insn_sizes[1]
1171      is the length of the first instruction of the second alternative.
1172      For non-relaxable macros, both elements give the length of the first
1173      instruction in bytes.
1174
1175      Set to zero if we haven't yet seen the first instruction.  */
1176   unsigned int first_insn_sizes[2];
1177
1178   /* For relaxable macros, insns[0] is the number of instructions for the
1179      first alternative and insns[1] is the number of instructions for the
1180      second alternative.
1181
1182      For non-relaxable macros, both elements give the number of
1183      instructions for the macro.  */
1184   unsigned int insns[2];
1185
1186   /* The first variant frag for this macro.  */
1187   fragS *first_frag;
1188 } mips_macro_warning;
1189 \f
1190 /* Prototypes for static functions.  */
1191
1192 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1193
1194 static void append_insn
1195   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1196    bfd_boolean expansionp);
1197 static void mips_no_prev_insn (void);
1198 static void macro_build (expressionS *, const char *, const char *, ...);
1199 static void mips16_macro_build
1200   (expressionS *, const char *, const char *, va_list *);
1201 static void load_register (int, expressionS *, int);
1202 static void macro_start (void);
1203 static void macro_end (void);
1204 static void macro (struct mips_cl_insn *ip, char *str);
1205 static void mips16_macro (struct mips_cl_insn * ip);
1206 static void mips_ip (char *str, struct mips_cl_insn * ip);
1207 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1208 static void mips16_immed
1209   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1210    unsigned int, unsigned long *);
1211 static size_t my_getSmallExpression
1212   (expressionS *, bfd_reloc_code_real_type *, char *);
1213 static void my_getExpression (expressionS *, char *);
1214 static void s_align (int);
1215 static void s_change_sec (int);
1216 static void s_change_section (int);
1217 static void s_cons (int);
1218 static void s_float_cons (int);
1219 static void s_mips_globl (int);
1220 static void s_option (int);
1221 static void s_mipsset (int);
1222 static void s_abicalls (int);
1223 static void s_cpload (int);
1224 static void s_cpsetup (int);
1225 static void s_cplocal (int);
1226 static void s_cprestore (int);
1227 static void s_cpreturn (int);
1228 static void s_dtprelword (int);
1229 static void s_dtpreldword (int);
1230 static void s_tprelword (int);
1231 static void s_tpreldword (int);
1232 static void s_gpvalue (int);
1233 static void s_gpword (int);
1234 static void s_gpdword (int);
1235 static void s_ehword (int);
1236 static void s_cpadd (int);
1237 static void s_insn (int);
1238 static void s_nan (int);
1239 static void md_obj_begin (void);
1240 static void md_obj_end (void);
1241 static void s_mips_ent (int);
1242 static void s_mips_end (int);
1243 static void s_mips_frame (int);
1244 static void s_mips_mask (int reg_type);
1245 static void s_mips_stab (int);
1246 static void s_mips_weakext (int);
1247 static void s_mips_file (int);
1248 static void s_mips_loc (int);
1249 static bfd_boolean pic_need_relax (symbolS *, asection *);
1250 static int relaxed_branch_length (fragS *, asection *, int);
1251 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1252 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1253
1254 /* Table and functions used to map between CPU/ISA names, and
1255    ISA levels, and CPU numbers.  */
1256
1257 struct mips_cpu_info
1258 {
1259   const char *name;           /* CPU or ISA name.  */
1260   int flags;                  /* MIPS_CPU_* flags.  */
1261   int ase;                    /* Set of ASEs implemented by the CPU.  */
1262   int isa;                    /* ISA level.  */
1263   int cpu;                    /* CPU number (default CPU if ISA).  */
1264 };
1265
1266 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1267
1268 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1269 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1270 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1271 \f
1272 /* Command-line options.  */
1273 const char *md_shortopts = "O::g::G:";
1274
1275 enum options
1276   {
1277     OPTION_MARCH = OPTION_MD_BASE,
1278     OPTION_MTUNE,
1279     OPTION_MIPS1,
1280     OPTION_MIPS2,
1281     OPTION_MIPS3,
1282     OPTION_MIPS4,
1283     OPTION_MIPS5,
1284     OPTION_MIPS32,
1285     OPTION_MIPS64,
1286     OPTION_MIPS32R2,
1287     OPTION_MIPS64R2,
1288     OPTION_MIPS16,
1289     OPTION_NO_MIPS16,
1290     OPTION_MIPS3D,
1291     OPTION_NO_MIPS3D,
1292     OPTION_MDMX,
1293     OPTION_NO_MDMX,
1294     OPTION_DSP,
1295     OPTION_NO_DSP,
1296     OPTION_MT,
1297     OPTION_NO_MT,
1298     OPTION_VIRT,
1299     OPTION_NO_VIRT,
1300     OPTION_SMARTMIPS,
1301     OPTION_NO_SMARTMIPS,
1302     OPTION_DSPR2,
1303     OPTION_NO_DSPR2,
1304     OPTION_EVA,
1305     OPTION_NO_EVA,
1306     OPTION_MICROMIPS,
1307     OPTION_NO_MICROMIPS,
1308     OPTION_MCU,
1309     OPTION_NO_MCU,
1310     OPTION_COMPAT_ARCH_BASE,
1311     OPTION_M4650,
1312     OPTION_NO_M4650,
1313     OPTION_M4010,
1314     OPTION_NO_M4010,
1315     OPTION_M4100,
1316     OPTION_NO_M4100,
1317     OPTION_M3900,
1318     OPTION_NO_M3900,
1319     OPTION_M7000_HILO_FIX,
1320     OPTION_MNO_7000_HILO_FIX,
1321     OPTION_FIX_24K,
1322     OPTION_NO_FIX_24K,
1323     OPTION_FIX_LOONGSON2F_JUMP,
1324     OPTION_NO_FIX_LOONGSON2F_JUMP,
1325     OPTION_FIX_LOONGSON2F_NOP,
1326     OPTION_NO_FIX_LOONGSON2F_NOP,
1327     OPTION_FIX_VR4120,
1328     OPTION_NO_FIX_VR4120,
1329     OPTION_FIX_VR4130,
1330     OPTION_NO_FIX_VR4130,
1331     OPTION_FIX_CN63XXP1,
1332     OPTION_NO_FIX_CN63XXP1,
1333     OPTION_TRAP,
1334     OPTION_BREAK,
1335     OPTION_EB,
1336     OPTION_EL,
1337     OPTION_FP32,
1338     OPTION_GP32,
1339     OPTION_CONSTRUCT_FLOATS,
1340     OPTION_NO_CONSTRUCT_FLOATS,
1341     OPTION_FP64,
1342     OPTION_GP64,
1343     OPTION_RELAX_BRANCH,
1344     OPTION_NO_RELAX_BRANCH,
1345     OPTION_INSN32,
1346     OPTION_NO_INSN32,
1347     OPTION_MSHARED,
1348     OPTION_MNO_SHARED,
1349     OPTION_MSYM32,
1350     OPTION_MNO_SYM32,
1351     OPTION_SOFT_FLOAT,
1352     OPTION_HARD_FLOAT,
1353     OPTION_SINGLE_FLOAT,
1354     OPTION_DOUBLE_FLOAT,
1355     OPTION_32,
1356     OPTION_CALL_SHARED,
1357     OPTION_CALL_NONPIC,
1358     OPTION_NON_SHARED,
1359     OPTION_XGOT,
1360     OPTION_MABI,
1361     OPTION_N32,
1362     OPTION_64,
1363     OPTION_MDEBUG,
1364     OPTION_NO_MDEBUG,
1365     OPTION_PDR,
1366     OPTION_NO_PDR,
1367     OPTION_MVXWORKS_PIC,
1368     OPTION_NAN,
1369     OPTION_END_OF_ENUM
1370   };
1371
1372 struct option md_longopts[] =
1373 {
1374   /* Options which specify architecture.  */
1375   {"march", required_argument, NULL, OPTION_MARCH},
1376   {"mtune", required_argument, NULL, OPTION_MTUNE},
1377   {"mips0", no_argument, NULL, OPTION_MIPS1},
1378   {"mips1", no_argument, NULL, OPTION_MIPS1},
1379   {"mips2", no_argument, NULL, OPTION_MIPS2},
1380   {"mips3", no_argument, NULL, OPTION_MIPS3},
1381   {"mips4", no_argument, NULL, OPTION_MIPS4},
1382   {"mips5", no_argument, NULL, OPTION_MIPS5},
1383   {"mips32", no_argument, NULL, OPTION_MIPS32},
1384   {"mips64", no_argument, NULL, OPTION_MIPS64},
1385   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1386   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1387
1388   /* Options which specify Application Specific Extensions (ASEs).  */
1389   {"mips16", no_argument, NULL, OPTION_MIPS16},
1390   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1391   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1392   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1393   {"mdmx", no_argument, NULL, OPTION_MDMX},
1394   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1395   {"mdsp", no_argument, NULL, OPTION_DSP},
1396   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1397   {"mmt", no_argument, NULL, OPTION_MT},
1398   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1399   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1400   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1401   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1402   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1403   {"meva", no_argument, NULL, OPTION_EVA},
1404   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1405   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1406   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1407   {"mmcu", no_argument, NULL, OPTION_MCU},
1408   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1409   {"mvirt", no_argument, NULL, OPTION_VIRT},
1410   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1411
1412   /* Old-style architecture options.  Don't add more of these.  */
1413   {"m4650", no_argument, NULL, OPTION_M4650},
1414   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1415   {"m4010", no_argument, NULL, OPTION_M4010},
1416   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1417   {"m4100", no_argument, NULL, OPTION_M4100},
1418   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1419   {"m3900", no_argument, NULL, OPTION_M3900},
1420   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1421
1422   /* Options which enable bug fixes.  */
1423   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1424   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1425   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1426   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1427   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1428   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1429   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1430   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1431   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1432   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1433   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1434   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1435   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1436   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1437   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1438
1439   /* Miscellaneous options.  */
1440   {"trap", no_argument, NULL, OPTION_TRAP},
1441   {"no-break", no_argument, NULL, OPTION_TRAP},
1442   {"break", no_argument, NULL, OPTION_BREAK},
1443   {"no-trap", no_argument, NULL, OPTION_BREAK},
1444   {"EB", no_argument, NULL, OPTION_EB},
1445   {"EL", no_argument, NULL, OPTION_EL},
1446   {"mfp32", no_argument, NULL, OPTION_FP32},
1447   {"mgp32", no_argument, NULL, OPTION_GP32},
1448   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1449   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1450   {"mfp64", no_argument, NULL, OPTION_FP64},
1451   {"mgp64", no_argument, NULL, OPTION_GP64},
1452   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1453   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1454   {"minsn32", no_argument, NULL, OPTION_INSN32},
1455   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1456   {"mshared", no_argument, NULL, OPTION_MSHARED},
1457   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1458   {"msym32", no_argument, NULL, OPTION_MSYM32},
1459   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1460   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1461   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1462   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1463   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1464
1465   /* Strictly speaking this next option is ELF specific,
1466      but we allow it for other ports as well in order to
1467      make testing easier.  */
1468   {"32", no_argument, NULL, OPTION_32},
1469
1470   /* ELF-specific options.  */
1471   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1472   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1473   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1474   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1475   {"xgot", no_argument, NULL, OPTION_XGOT},
1476   {"mabi", required_argument, NULL, OPTION_MABI},
1477   {"n32", no_argument, NULL, OPTION_N32},
1478   {"64", no_argument, NULL, OPTION_64},
1479   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1480   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1481   {"mpdr", no_argument, NULL, OPTION_PDR},
1482   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1483   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1484   {"mnan", required_argument, NULL, OPTION_NAN},
1485
1486   {NULL, no_argument, NULL, 0}
1487 };
1488 size_t md_longopts_size = sizeof (md_longopts);
1489 \f
1490 /* Information about either an Application Specific Extension or an
1491    optional architecture feature that, for simplicity, we treat in the
1492    same way as an ASE.  */
1493 struct mips_ase
1494 {
1495   /* The name of the ASE, used in both the command-line and .set options.  */
1496   const char *name;
1497
1498   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1499      and 64-bit architectures, the flags here refer to the subset that
1500      is available on both.  */
1501   unsigned int flags;
1502
1503   /* The ASE_* flag used for instructions that are available on 64-bit
1504      architectures but that are not included in FLAGS.  */
1505   unsigned int flags64;
1506
1507   /* The command-line options that turn the ASE on and off.  */
1508   int option_on;
1509   int option_off;
1510
1511   /* The minimum required architecture revisions for MIPS32, MIPS64,
1512      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1513   int mips32_rev;
1514   int mips64_rev;
1515   int micromips32_rev;
1516   int micromips64_rev;
1517 };
1518
1519 /* A table of all supported ASEs.  */
1520 static const struct mips_ase mips_ases[] = {
1521   { "dsp", ASE_DSP, ASE_DSP64,
1522     OPTION_DSP, OPTION_NO_DSP,
1523     2, 2, 2, 2 },
1524
1525   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1526     OPTION_DSPR2, OPTION_NO_DSPR2,
1527     2, 2, 2, 2 },
1528
1529   { "eva", ASE_EVA, 0,
1530     OPTION_EVA, OPTION_NO_EVA,
1531     2, 2, 2, 2 },
1532
1533   { "mcu", ASE_MCU, 0,
1534     OPTION_MCU, OPTION_NO_MCU,
1535     2, 2, 2, 2 },
1536
1537   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1538   { "mdmx", ASE_MDMX, 0,
1539     OPTION_MDMX, OPTION_NO_MDMX,
1540     -1, 1, -1, -1 },
1541
1542   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1543   { "mips3d", ASE_MIPS3D, 0,
1544     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1545     2, 1, -1, -1 },
1546
1547   { "mt", ASE_MT, 0,
1548     OPTION_MT, OPTION_NO_MT,
1549     2, 2, -1, -1 },
1550
1551   { "smartmips", ASE_SMARTMIPS, 0,
1552     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1553     1, -1, -1, -1 },
1554
1555   { "virt", ASE_VIRT, ASE_VIRT64,
1556     OPTION_VIRT, OPTION_NO_VIRT,
1557     2, 2, 2, 2 }
1558 };
1559
1560 /* The set of ASEs that require -mfp64.  */
1561 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1562
1563 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1564 static const unsigned int mips_ase_groups[] = {
1565   ASE_DSP | ASE_DSPR2
1566 };
1567 \f
1568 /* Pseudo-op table.
1569
1570    The following pseudo-ops from the Kane and Heinrich MIPS book
1571    should be defined here, but are currently unsupported: .alias,
1572    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1573
1574    The following pseudo-ops from the Kane and Heinrich MIPS book are
1575    specific to the type of debugging information being generated, and
1576    should be defined by the object format: .aent, .begin, .bend,
1577    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1578    .vreg.
1579
1580    The following pseudo-ops from the Kane and Heinrich MIPS book are
1581    not MIPS CPU specific, but are also not specific to the object file
1582    format.  This file is probably the best place to define them, but
1583    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1584
1585 static const pseudo_typeS mips_pseudo_table[] =
1586 {
1587   /* MIPS specific pseudo-ops.  */
1588   {"option", s_option, 0},
1589   {"set", s_mipsset, 0},
1590   {"rdata", s_change_sec, 'r'},
1591   {"sdata", s_change_sec, 's'},
1592   {"livereg", s_ignore, 0},
1593   {"abicalls", s_abicalls, 0},
1594   {"cpload", s_cpload, 0},
1595   {"cpsetup", s_cpsetup, 0},
1596   {"cplocal", s_cplocal, 0},
1597   {"cprestore", s_cprestore, 0},
1598   {"cpreturn", s_cpreturn, 0},
1599   {"dtprelword", s_dtprelword, 0},
1600   {"dtpreldword", s_dtpreldword, 0},
1601   {"tprelword", s_tprelword, 0},
1602   {"tpreldword", s_tpreldword, 0},
1603   {"gpvalue", s_gpvalue, 0},
1604   {"gpword", s_gpword, 0},
1605   {"gpdword", s_gpdword, 0},
1606   {"ehword", s_ehword, 0},
1607   {"cpadd", s_cpadd, 0},
1608   {"insn", s_insn, 0},
1609   {"nan", s_nan, 0},
1610
1611   /* Relatively generic pseudo-ops that happen to be used on MIPS
1612      chips.  */
1613   {"asciiz", stringer, 8 + 1},
1614   {"bss", s_change_sec, 'b'},
1615   {"err", s_err, 0},
1616   {"half", s_cons, 1},
1617   {"dword", s_cons, 3},
1618   {"weakext", s_mips_weakext, 0},
1619   {"origin", s_org, 0},
1620   {"repeat", s_rept, 0},
1621
1622   /* For MIPS this is non-standard, but we define it for consistency.  */
1623   {"sbss", s_change_sec, 'B'},
1624
1625   /* These pseudo-ops are defined in read.c, but must be overridden
1626      here for one reason or another.  */
1627   {"align", s_align, 0},
1628   {"byte", s_cons, 0},
1629   {"data", s_change_sec, 'd'},
1630   {"double", s_float_cons, 'd'},
1631   {"float", s_float_cons, 'f'},
1632   {"globl", s_mips_globl, 0},
1633   {"global", s_mips_globl, 0},
1634   {"hword", s_cons, 1},
1635   {"int", s_cons, 2},
1636   {"long", s_cons, 2},
1637   {"octa", s_cons, 4},
1638   {"quad", s_cons, 3},
1639   {"section", s_change_section, 0},
1640   {"short", s_cons, 1},
1641   {"single", s_float_cons, 'f'},
1642   {"stabd", s_mips_stab, 'd'},
1643   {"stabn", s_mips_stab, 'n'},
1644   {"stabs", s_mips_stab, 's'},
1645   {"text", s_change_sec, 't'},
1646   {"word", s_cons, 2},
1647
1648   { "extern", ecoff_directive_extern, 0},
1649
1650   { NULL, NULL, 0 },
1651 };
1652
1653 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1654 {
1655   /* These pseudo-ops should be defined by the object file format.
1656      However, a.out doesn't support them, so we have versions here.  */
1657   {"aent", s_mips_ent, 1},
1658   {"bgnb", s_ignore, 0},
1659   {"end", s_mips_end, 0},
1660   {"endb", s_ignore, 0},
1661   {"ent", s_mips_ent, 0},
1662   {"file", s_mips_file, 0},
1663   {"fmask", s_mips_mask, 'F'},
1664   {"frame", s_mips_frame, 0},
1665   {"loc", s_mips_loc, 0},
1666   {"mask", s_mips_mask, 'R'},
1667   {"verstamp", s_ignore, 0},
1668   { NULL, NULL, 0 },
1669 };
1670
1671 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1672    purpose of the `.dc.a' internal pseudo-op.  */
1673
1674 int
1675 mips_address_bytes (void)
1676 {
1677   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1678 }
1679
1680 extern void pop_insert (const pseudo_typeS *);
1681
1682 void
1683 mips_pop_insert (void)
1684 {
1685   pop_insert (mips_pseudo_table);
1686   if (! ECOFF_DEBUGGING)
1687     pop_insert (mips_nonecoff_pseudo_table);
1688 }
1689 \f
1690 /* Symbols labelling the current insn.  */
1691
1692 struct insn_label_list
1693 {
1694   struct insn_label_list *next;
1695   symbolS *label;
1696 };
1697
1698 static struct insn_label_list *free_insn_labels;
1699 #define label_list tc_segment_info_data.labels
1700
1701 static void mips_clear_insn_labels (void);
1702 static void mips_mark_labels (void);
1703 static void mips_compressed_mark_labels (void);
1704
1705 static inline void
1706 mips_clear_insn_labels (void)
1707 {
1708   register struct insn_label_list **pl;
1709   segment_info_type *si;
1710
1711   if (now_seg)
1712     {
1713       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1714         ;
1715       
1716       si = seg_info (now_seg);
1717       *pl = si->label_list;
1718       si->label_list = NULL;
1719     }
1720 }
1721
1722 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1723
1724 static inline void
1725 mips_mark_labels (void)
1726 {
1727   if (HAVE_CODE_COMPRESSION)
1728     mips_compressed_mark_labels ();
1729 }
1730 \f
1731 static char *expr_end;
1732
1733 /* Expressions which appear in macro instructions.  These are set by
1734    mips_ip and read by macro.  */
1735
1736 static expressionS imm_expr;
1737 static expressionS imm2_expr;
1738
1739 /* The relocatable field in an instruction and the relocs associated
1740    with it.  These variables are used for instructions like LUI and
1741    JAL as well as true offsets.  They are also used for address
1742    operands in macros.  */
1743
1744 static expressionS offset_expr;
1745 static bfd_reloc_code_real_type offset_reloc[3]
1746   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1747
1748 /* This is set to the resulting size of the instruction to be produced
1749    by mips16_ip if an explicit extension is used or by mips_ip if an
1750    explicit size is supplied.  */
1751
1752 static unsigned int forced_insn_length;
1753
1754 /* True if we are assembling an instruction.  All dot symbols defined during
1755    this time should be treated as code labels.  */
1756
1757 static bfd_boolean mips_assembling_insn;
1758
1759 /* The pdr segment for per procedure frame/regmask info.  Not used for
1760    ECOFF debugging.  */
1761
1762 static segT pdr_seg;
1763
1764 /* The default target format to use.  */
1765
1766 #if defined (TE_FreeBSD)
1767 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1768 #elif defined (TE_TMIPS)
1769 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1770 #else
1771 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1772 #endif
1773
1774 const char *
1775 mips_target_format (void)
1776 {
1777   switch (OUTPUT_FLAVOR)
1778     {
1779     case bfd_target_elf_flavour:
1780 #ifdef TE_VXWORKS
1781       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1782         return (target_big_endian
1783                 ? "elf32-bigmips-vxworks"
1784                 : "elf32-littlemips-vxworks");
1785 #endif
1786       return (target_big_endian
1787               ? (HAVE_64BIT_OBJECTS
1788                  ? ELF_TARGET ("elf64-", "big")
1789                  : (HAVE_NEWABI
1790                     ? ELF_TARGET ("elf32-n", "big")
1791                     : ELF_TARGET ("elf32-", "big")))
1792               : (HAVE_64BIT_OBJECTS
1793                  ? ELF_TARGET ("elf64-", "little")
1794                  : (HAVE_NEWABI
1795                     ? ELF_TARGET ("elf32-n", "little")
1796                     : ELF_TARGET ("elf32-", "little"))));
1797     default:
1798       abort ();
1799       return NULL;
1800     }
1801 }
1802
1803 /* Return the ISA revision that is currently in use, or 0 if we are
1804    generating code for MIPS V or below.  */
1805
1806 static int
1807 mips_isa_rev (void)
1808 {
1809   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1810     return 2;
1811
1812   /* microMIPS implies revision 2 or above.  */
1813   if (mips_opts.micromips)
1814     return 2;
1815
1816   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1817     return 1;
1818
1819   return 0;
1820 }
1821
1822 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1823
1824 static unsigned int
1825 mips_ase_mask (unsigned int flags)
1826 {
1827   unsigned int i;
1828
1829   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1830     if (flags & mips_ase_groups[i])
1831       flags |= mips_ase_groups[i];
1832   return flags;
1833 }
1834
1835 /* Check whether the current ISA supports ASE.  Issue a warning if
1836    appropriate.  */
1837
1838 static void
1839 mips_check_isa_supports_ase (const struct mips_ase *ase)
1840 {
1841   const char *base;
1842   int min_rev, size;
1843   static unsigned int warned_isa;
1844   static unsigned int warned_fp32;
1845
1846   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1847     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1848   else
1849     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1850   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1851       && (warned_isa & ase->flags) != ase->flags)
1852     {
1853       warned_isa |= ase->flags;
1854       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1855       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1856       if (min_rev < 0)
1857         as_warn (_("The %d-bit %s architecture does not support the"
1858                    " `%s' extension"), size, base, ase->name);
1859       else
1860         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1861                  ase->name, base, size, min_rev);
1862     }
1863   if ((ase->flags & FP64_ASES)
1864       && mips_opts.fp32
1865       && (warned_fp32 & ase->flags) != ase->flags)
1866     {
1867       warned_fp32 |= ase->flags;
1868       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1869     }
1870 }
1871
1872 /* Check all enabled ASEs to see whether they are supported by the
1873    chosen architecture.  */
1874
1875 static void
1876 mips_check_isa_supports_ases (void)
1877 {
1878   unsigned int i, mask;
1879
1880   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1881     {
1882       mask = mips_ase_mask (mips_ases[i].flags);
1883       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1884         mips_check_isa_supports_ase (&mips_ases[i]);
1885     }
1886 }
1887
1888 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1889    that were affected.  */
1890
1891 static unsigned int
1892 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1893 {
1894   unsigned int mask;
1895
1896   mask = mips_ase_mask (ase->flags);
1897   mips_opts.ase &= ~mask;
1898   if (enabled_p)
1899     mips_opts.ase |= ase->flags;
1900   return mask;
1901 }
1902
1903 /* Return the ASE called NAME, or null if none.  */
1904
1905 static const struct mips_ase *
1906 mips_lookup_ase (const char *name)
1907 {
1908   unsigned int i;
1909
1910   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1911     if (strcmp (name, mips_ases[i].name) == 0)
1912       return &mips_ases[i];
1913   return NULL;
1914 }
1915
1916 /* Return the length of a microMIPS instruction in bytes.  If bits of
1917    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1918    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1919    major opcode) will require further modifications to the opcode
1920    table.  */
1921
1922 static inline unsigned int
1923 micromips_insn_length (const struct mips_opcode *mo)
1924 {
1925   return (mo->mask >> 16) == 0 ? 2 : 4;
1926 }
1927
1928 /* Return the length of MIPS16 instruction OPCODE.  */
1929
1930 static inline unsigned int
1931 mips16_opcode_length (unsigned long opcode)
1932 {
1933   return (opcode >> 16) == 0 ? 2 : 4;
1934 }
1935
1936 /* Return the length of instruction INSN.  */
1937
1938 static inline unsigned int
1939 insn_length (const struct mips_cl_insn *insn)
1940 {
1941   if (mips_opts.micromips)
1942     return micromips_insn_length (insn->insn_mo);
1943   else if (mips_opts.mips16)
1944     return mips16_opcode_length (insn->insn_opcode);
1945   else
1946     return 4;
1947 }
1948
1949 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1950
1951 static void
1952 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1953 {
1954   size_t i;
1955
1956   insn->insn_mo = mo;
1957   insn->insn_opcode = mo->match;
1958   insn->frag = NULL;
1959   insn->where = 0;
1960   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1961     insn->fixp[i] = NULL;
1962   insn->fixed_p = (mips_opts.noreorder > 0);
1963   insn->noreorder_p = (mips_opts.noreorder > 0);
1964   insn->mips16_absolute_jump_p = 0;
1965   insn->complete_p = 0;
1966   insn->cleared_p = 0;
1967 }
1968
1969 /* Install UVAL as the value of OPERAND in INSN.  */
1970
1971 static inline void
1972 insn_insert_operand (struct mips_cl_insn *insn,
1973                      const struct mips_operand *operand, unsigned int uval)
1974 {
1975   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
1976 }
1977
1978 /* Record the current MIPS16/microMIPS mode in now_seg.  */
1979
1980 static void
1981 mips_record_compressed_mode (void)
1982 {
1983   segment_info_type *si;
1984
1985   si = seg_info (now_seg);
1986   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
1987     si->tc_segment_info_data.mips16 = mips_opts.mips16;
1988   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
1989     si->tc_segment_info_data.micromips = mips_opts.micromips;
1990 }
1991
1992 /* Read a standard MIPS instruction from BUF.  */
1993
1994 static unsigned long
1995 read_insn (char *buf)
1996 {
1997   if (target_big_endian)
1998     return bfd_getb32 ((bfd_byte *) buf);
1999   else
2000     return bfd_getl32 ((bfd_byte *) buf);
2001 }
2002
2003 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2004    the next byte.  */
2005
2006 static char *
2007 write_insn (char *buf, unsigned int insn)
2008 {
2009   md_number_to_chars (buf, insn, 4);
2010   return buf + 4;
2011 }
2012
2013 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2014    has length LENGTH.  */
2015
2016 static unsigned long
2017 read_compressed_insn (char *buf, unsigned int length)
2018 {
2019   unsigned long insn;
2020   unsigned int i;
2021
2022   insn = 0;
2023   for (i = 0; i < length; i += 2)
2024     {
2025       insn <<= 16;
2026       if (target_big_endian)
2027         insn |= bfd_getb16 ((char *) buf);
2028       else
2029         insn |= bfd_getl16 ((char *) buf);
2030       buf += 2;
2031     }
2032   return insn;
2033 }
2034
2035 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2036    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2037
2038 static char *
2039 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2040 {
2041   unsigned int i;
2042
2043   for (i = 0; i < length; i += 2)
2044     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2045   return buf + length;
2046 }
2047
2048 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2049
2050 static void
2051 install_insn (const struct mips_cl_insn *insn)
2052 {
2053   char *f = insn->frag->fr_literal + insn->where;
2054   if (HAVE_CODE_COMPRESSION)
2055     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2056   else
2057     write_insn (f, insn->insn_opcode);
2058   mips_record_compressed_mode ();
2059 }
2060
2061 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2062    and install the opcode in the new location.  */
2063
2064 static void
2065 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2066 {
2067   size_t i;
2068
2069   insn->frag = frag;
2070   insn->where = where;
2071   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2072     if (insn->fixp[i] != NULL)
2073       {
2074         insn->fixp[i]->fx_frag = frag;
2075         insn->fixp[i]->fx_where = where;
2076       }
2077   install_insn (insn);
2078 }
2079
2080 /* Add INSN to the end of the output.  */
2081
2082 static void
2083 add_fixed_insn (struct mips_cl_insn *insn)
2084 {
2085   char *f = frag_more (insn_length (insn));
2086   move_insn (insn, frag_now, f - frag_now->fr_literal);
2087 }
2088
2089 /* Start a variant frag and move INSN to the start of the variant part,
2090    marking it as fixed.  The other arguments are as for frag_var.  */
2091
2092 static void
2093 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2094                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2095 {
2096   frag_grow (max_chars);
2097   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2098   insn->fixed_p = 1;
2099   frag_var (rs_machine_dependent, max_chars, var,
2100             subtype, symbol, offset, NULL);
2101 }
2102
2103 /* Insert N copies of INSN into the history buffer, starting at
2104    position FIRST.  Neither FIRST nor N need to be clipped.  */
2105
2106 static void
2107 insert_into_history (unsigned int first, unsigned int n,
2108                      const struct mips_cl_insn *insn)
2109 {
2110   if (mips_relax.sequence != 2)
2111     {
2112       unsigned int i;
2113
2114       for (i = ARRAY_SIZE (history); i-- > first;)
2115         if (i >= first + n)
2116           history[i] = history[i - n];
2117         else
2118           history[i] = *insn;
2119     }
2120 }
2121
2122 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2123    the idea is to make it obvious at a glance that each errata is
2124    included.  */
2125
2126 static void
2127 init_vr4120_conflicts (void)
2128 {
2129 #define CONFLICT(FIRST, SECOND) \
2130     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2131
2132   /* Errata 21 - [D]DIV[U] after [D]MACC */
2133   CONFLICT (MACC, DIV);
2134   CONFLICT (DMACC, DIV);
2135
2136   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2137   CONFLICT (DMULT, DMULT);
2138   CONFLICT (DMULT, DMACC);
2139   CONFLICT (DMACC, DMULT);
2140   CONFLICT (DMACC, DMACC);
2141
2142   /* Errata 24 - MT{LO,HI} after [D]MACC */
2143   CONFLICT (MACC, MTHILO);
2144   CONFLICT (DMACC, MTHILO);
2145
2146   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2147      instruction is executed immediately after a MACC or DMACC
2148      instruction, the result of [either instruction] is incorrect."  */
2149   CONFLICT (MACC, MULT);
2150   CONFLICT (MACC, DMULT);
2151   CONFLICT (DMACC, MULT);
2152   CONFLICT (DMACC, DMULT);
2153
2154   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2155      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2156      DDIV or DDIVU instruction, the result of the MACC or
2157      DMACC instruction is incorrect.".  */
2158   CONFLICT (DMULT, MACC);
2159   CONFLICT (DMULT, DMACC);
2160   CONFLICT (DIV, MACC);
2161   CONFLICT (DIV, DMACC);
2162
2163 #undef CONFLICT
2164 }
2165
2166 struct regname {
2167   const char *name;
2168   unsigned int num;
2169 };
2170
2171 #define RTYPE_MASK      0x1ff00
2172 #define RTYPE_NUM       0x00100
2173 #define RTYPE_FPU       0x00200
2174 #define RTYPE_FCC       0x00400
2175 #define RTYPE_VEC       0x00800
2176 #define RTYPE_GP        0x01000
2177 #define RTYPE_CP0       0x02000
2178 #define RTYPE_PC        0x04000
2179 #define RTYPE_ACC       0x08000
2180 #define RTYPE_CCC       0x10000
2181 #define RNUM_MASK       0x000ff
2182 #define RWARN           0x80000
2183
2184 #define GENERIC_REGISTER_NUMBERS \
2185     {"$0",      RTYPE_NUM | 0},  \
2186     {"$1",      RTYPE_NUM | 1},  \
2187     {"$2",      RTYPE_NUM | 2},  \
2188     {"$3",      RTYPE_NUM | 3},  \
2189     {"$4",      RTYPE_NUM | 4},  \
2190     {"$5",      RTYPE_NUM | 5},  \
2191     {"$6",      RTYPE_NUM | 6},  \
2192     {"$7",      RTYPE_NUM | 7},  \
2193     {"$8",      RTYPE_NUM | 8},  \
2194     {"$9",      RTYPE_NUM | 9},  \
2195     {"$10",     RTYPE_NUM | 10}, \
2196     {"$11",     RTYPE_NUM | 11}, \
2197     {"$12",     RTYPE_NUM | 12}, \
2198     {"$13",     RTYPE_NUM | 13}, \
2199     {"$14",     RTYPE_NUM | 14}, \
2200     {"$15",     RTYPE_NUM | 15}, \
2201     {"$16",     RTYPE_NUM | 16}, \
2202     {"$17",     RTYPE_NUM | 17}, \
2203     {"$18",     RTYPE_NUM | 18}, \
2204     {"$19",     RTYPE_NUM | 19}, \
2205     {"$20",     RTYPE_NUM | 20}, \
2206     {"$21",     RTYPE_NUM | 21}, \
2207     {"$22",     RTYPE_NUM | 22}, \
2208     {"$23",     RTYPE_NUM | 23}, \
2209     {"$24",     RTYPE_NUM | 24}, \
2210     {"$25",     RTYPE_NUM | 25}, \
2211     {"$26",     RTYPE_NUM | 26}, \
2212     {"$27",     RTYPE_NUM | 27}, \
2213     {"$28",     RTYPE_NUM | 28}, \
2214     {"$29",     RTYPE_NUM | 29}, \
2215     {"$30",     RTYPE_NUM | 30}, \
2216     {"$31",     RTYPE_NUM | 31} 
2217
2218 #define FPU_REGISTER_NAMES       \
2219     {"$f0",     RTYPE_FPU | 0},  \
2220     {"$f1",     RTYPE_FPU | 1},  \
2221     {"$f2",     RTYPE_FPU | 2},  \
2222     {"$f3",     RTYPE_FPU | 3},  \
2223     {"$f4",     RTYPE_FPU | 4},  \
2224     {"$f5",     RTYPE_FPU | 5},  \
2225     {"$f6",     RTYPE_FPU | 6},  \
2226     {"$f7",     RTYPE_FPU | 7},  \
2227     {"$f8",     RTYPE_FPU | 8},  \
2228     {"$f9",     RTYPE_FPU | 9},  \
2229     {"$f10",    RTYPE_FPU | 10}, \
2230     {"$f11",    RTYPE_FPU | 11}, \
2231     {"$f12",    RTYPE_FPU | 12}, \
2232     {"$f13",    RTYPE_FPU | 13}, \
2233     {"$f14",    RTYPE_FPU | 14}, \
2234     {"$f15",    RTYPE_FPU | 15}, \
2235     {"$f16",    RTYPE_FPU | 16}, \
2236     {"$f17",    RTYPE_FPU | 17}, \
2237     {"$f18",    RTYPE_FPU | 18}, \
2238     {"$f19",    RTYPE_FPU | 19}, \
2239     {"$f20",    RTYPE_FPU | 20}, \
2240     {"$f21",    RTYPE_FPU | 21}, \
2241     {"$f22",    RTYPE_FPU | 22}, \
2242     {"$f23",    RTYPE_FPU | 23}, \
2243     {"$f24",    RTYPE_FPU | 24}, \
2244     {"$f25",    RTYPE_FPU | 25}, \
2245     {"$f26",    RTYPE_FPU | 26}, \
2246     {"$f27",    RTYPE_FPU | 27}, \
2247     {"$f28",    RTYPE_FPU | 28}, \
2248     {"$f29",    RTYPE_FPU | 29}, \
2249     {"$f30",    RTYPE_FPU | 30}, \
2250     {"$f31",    RTYPE_FPU | 31}
2251
2252 #define FPU_CONDITION_CODE_NAMES \
2253     {"$fcc0",   RTYPE_FCC | 0},  \
2254     {"$fcc1",   RTYPE_FCC | 1},  \
2255     {"$fcc2",   RTYPE_FCC | 2},  \
2256     {"$fcc3",   RTYPE_FCC | 3},  \
2257     {"$fcc4",   RTYPE_FCC | 4},  \
2258     {"$fcc5",   RTYPE_FCC | 5},  \
2259     {"$fcc6",   RTYPE_FCC | 6},  \
2260     {"$fcc7",   RTYPE_FCC | 7}
2261
2262 #define COPROC_CONDITION_CODE_NAMES         \
2263     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2264     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2265     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2266     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2267     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2268     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2269     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2270     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2271
2272 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2273     {"$a4",     RTYPE_GP | 8},  \
2274     {"$a5",     RTYPE_GP | 9},  \
2275     {"$a6",     RTYPE_GP | 10}, \
2276     {"$a7",     RTYPE_GP | 11}, \
2277     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2278     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2279     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2280     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2281     {"$t0",     RTYPE_GP | 12}, \
2282     {"$t1",     RTYPE_GP | 13}, \
2283     {"$t2",     RTYPE_GP | 14}, \
2284     {"$t3",     RTYPE_GP | 15}
2285
2286 #define O32_SYMBOLIC_REGISTER_NAMES \
2287     {"$t0",     RTYPE_GP | 8},  \
2288     {"$t1",     RTYPE_GP | 9},  \
2289     {"$t2",     RTYPE_GP | 10}, \
2290     {"$t3",     RTYPE_GP | 11}, \
2291     {"$t4",     RTYPE_GP | 12}, \
2292     {"$t5",     RTYPE_GP | 13}, \
2293     {"$t6",     RTYPE_GP | 14}, \
2294     {"$t7",     RTYPE_GP | 15}, \
2295     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2296     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2297     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2298     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2299
2300 /* Remaining symbolic register names */
2301 #define SYMBOLIC_REGISTER_NAMES \
2302     {"$zero",   RTYPE_GP | 0},  \
2303     {"$at",     RTYPE_GP | 1},  \
2304     {"$AT",     RTYPE_GP | 1},  \
2305     {"$v0",     RTYPE_GP | 2},  \
2306     {"$v1",     RTYPE_GP | 3},  \
2307     {"$a0",     RTYPE_GP | 4},  \
2308     {"$a1",     RTYPE_GP | 5},  \
2309     {"$a2",     RTYPE_GP | 6},  \
2310     {"$a3",     RTYPE_GP | 7},  \
2311     {"$s0",     RTYPE_GP | 16}, \
2312     {"$s1",     RTYPE_GP | 17}, \
2313     {"$s2",     RTYPE_GP | 18}, \
2314     {"$s3",     RTYPE_GP | 19}, \
2315     {"$s4",     RTYPE_GP | 20}, \
2316     {"$s5",     RTYPE_GP | 21}, \
2317     {"$s6",     RTYPE_GP | 22}, \
2318     {"$s7",     RTYPE_GP | 23}, \
2319     {"$t8",     RTYPE_GP | 24}, \
2320     {"$t9",     RTYPE_GP | 25}, \
2321     {"$k0",     RTYPE_GP | 26}, \
2322     {"$kt0",    RTYPE_GP | 26}, \
2323     {"$k1",     RTYPE_GP | 27}, \
2324     {"$kt1",    RTYPE_GP | 27}, \
2325     {"$gp",     RTYPE_GP | 28}, \
2326     {"$sp",     RTYPE_GP | 29}, \
2327     {"$s8",     RTYPE_GP | 30}, \
2328     {"$fp",     RTYPE_GP | 30}, \
2329     {"$ra",     RTYPE_GP | 31}
2330
2331 #define MIPS16_SPECIAL_REGISTER_NAMES \
2332     {"$pc",     RTYPE_PC | 0}
2333
2334 #define MDMX_VECTOR_REGISTER_NAMES \
2335     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2336     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2337     {"$v2",     RTYPE_VEC | 2},  \
2338     {"$v3",     RTYPE_VEC | 3},  \
2339     {"$v4",     RTYPE_VEC | 4},  \
2340     {"$v5",     RTYPE_VEC | 5},  \
2341     {"$v6",     RTYPE_VEC | 6},  \
2342     {"$v7",     RTYPE_VEC | 7},  \
2343     {"$v8",     RTYPE_VEC | 8},  \
2344     {"$v9",     RTYPE_VEC | 9},  \
2345     {"$v10",    RTYPE_VEC | 10}, \
2346     {"$v11",    RTYPE_VEC | 11}, \
2347     {"$v12",    RTYPE_VEC | 12}, \
2348     {"$v13",    RTYPE_VEC | 13}, \
2349     {"$v14",    RTYPE_VEC | 14}, \
2350     {"$v15",    RTYPE_VEC | 15}, \
2351     {"$v16",    RTYPE_VEC | 16}, \
2352     {"$v17",    RTYPE_VEC | 17}, \
2353     {"$v18",    RTYPE_VEC | 18}, \
2354     {"$v19",    RTYPE_VEC | 19}, \
2355     {"$v20",    RTYPE_VEC | 20}, \
2356     {"$v21",    RTYPE_VEC | 21}, \
2357     {"$v22",    RTYPE_VEC | 22}, \
2358     {"$v23",    RTYPE_VEC | 23}, \
2359     {"$v24",    RTYPE_VEC | 24}, \
2360     {"$v25",    RTYPE_VEC | 25}, \
2361     {"$v26",    RTYPE_VEC | 26}, \
2362     {"$v27",    RTYPE_VEC | 27}, \
2363     {"$v28",    RTYPE_VEC | 28}, \
2364     {"$v29",    RTYPE_VEC | 29}, \
2365     {"$v30",    RTYPE_VEC | 30}, \
2366     {"$v31",    RTYPE_VEC | 31}
2367
2368 #define MIPS_DSP_ACCUMULATOR_NAMES \
2369     {"$ac0",    RTYPE_ACC | 0}, \
2370     {"$ac1",    RTYPE_ACC | 1}, \
2371     {"$ac2",    RTYPE_ACC | 2}, \
2372     {"$ac3",    RTYPE_ACC | 3}
2373
2374 static const struct regname reg_names[] = {
2375   GENERIC_REGISTER_NUMBERS,
2376   FPU_REGISTER_NAMES,
2377   FPU_CONDITION_CODE_NAMES,
2378   COPROC_CONDITION_CODE_NAMES,
2379
2380   /* The $txx registers depends on the abi,
2381      these will be added later into the symbol table from
2382      one of the tables below once mips_abi is set after 
2383      parsing of arguments from the command line. */
2384   SYMBOLIC_REGISTER_NAMES,
2385
2386   MIPS16_SPECIAL_REGISTER_NAMES,
2387   MDMX_VECTOR_REGISTER_NAMES,
2388   MIPS_DSP_ACCUMULATOR_NAMES,
2389   {0, 0}
2390 };
2391
2392 static const struct regname reg_names_o32[] = {
2393   O32_SYMBOLIC_REGISTER_NAMES,
2394   {0, 0}
2395 };
2396
2397 static const struct regname reg_names_n32n64[] = {
2398   N32N64_SYMBOLIC_REGISTER_NAMES,
2399   {0, 0}
2400 };
2401
2402 /* Check if S points at a valid register specifier according to TYPES.
2403    If so, then return 1, advance S to consume the specifier and store
2404    the register's number in REGNOP, otherwise return 0.  */
2405
2406 static int
2407 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2408 {
2409   symbolS *symbolP;
2410   char *e;
2411   char save_c;
2412   int reg = -1;
2413
2414   /* Find end of name.  */
2415   e = *s;
2416   if (is_name_beginner (*e))
2417     ++e;
2418   while (is_part_of_name (*e))
2419     ++e;
2420
2421   /* Terminate name.  */
2422   save_c = *e;
2423   *e = '\0';
2424
2425   /* Look for a register symbol.  */
2426   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2427     {
2428       int r = S_GET_VALUE (symbolP);
2429       if (r & types)
2430         reg = r & RNUM_MASK;
2431       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2432         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2433         reg = (r & RNUM_MASK) - 2;
2434     }
2435   /* Else see if this is a register defined in an itbl entry.  */
2436   else if ((types & RTYPE_GP) && itbl_have_entries)
2437     {
2438       char *n = *s;
2439       unsigned long r;
2440
2441       if (*n == '$')
2442         ++n;
2443       if (itbl_get_reg_val (n, &r))
2444         reg = r & RNUM_MASK;
2445     }
2446
2447   /* Advance to next token if a register was recognised.  */
2448   if (reg >= 0)
2449     *s = e;
2450   else if (types & RWARN)
2451     as_warn (_("Unrecognized register name `%s'"), *s);
2452
2453   *e = save_c;
2454   if (regnop)
2455     *regnop = reg;
2456   return reg >= 0;
2457 }
2458
2459 /* Check if S points at a valid register list according to TYPES.
2460    If so, then return 1, advance S to consume the list and store
2461    the registers present on the list as a bitmask of ones in REGLISTP,
2462    otherwise return 0.  A valid list comprises a comma-separated
2463    enumeration of valid single registers and/or dash-separated
2464    contiguous register ranges as determined by their numbers.
2465
2466    As a special exception if one of s0-s7 registers is specified as
2467    the range's lower delimiter and s8 (fp) is its upper one, then no
2468    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2469    are selected; they have to be listed separately if needed.  */
2470
2471 static int
2472 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2473 {
2474   unsigned int reglist = 0;
2475   unsigned int lastregno;
2476   bfd_boolean ok = TRUE;
2477   unsigned int regmask;
2478   char *s_endlist = *s;
2479   char *s_reset = *s;
2480   unsigned int regno;
2481
2482   while (reg_lookup (s, types, &regno))
2483     {
2484       lastregno = regno;
2485       if (**s == '-')
2486         {
2487           (*s)++;
2488           ok = reg_lookup (s, types, &lastregno);
2489           if (ok && lastregno < regno)
2490             ok = FALSE;
2491           if (!ok)
2492             break;
2493         }
2494
2495       if (lastregno == FP && regno >= S0 && regno <= S7)
2496         {
2497           lastregno = S7;
2498           reglist |= 1 << FP;
2499         }
2500       regmask = 1 << lastregno;
2501       regmask = (regmask << 1) - 1;
2502       regmask ^= (1 << regno) - 1;
2503       reglist |= regmask;
2504
2505       s_endlist = *s;
2506       if (**s != ',')
2507         break;
2508       (*s)++;
2509     }
2510
2511   if (ok)
2512     *s = s_endlist;
2513   else
2514     *s = s_reset;
2515   if (reglistp)
2516     *reglistp = reglist;
2517   return ok && reglist != 0;
2518 }
2519
2520 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2521    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2522
2523 static bfd_boolean
2524 is_opcode_valid (const struct mips_opcode *mo)
2525 {
2526   int isa = mips_opts.isa;
2527   int ase = mips_opts.ase;
2528   int fp_s, fp_d;
2529   unsigned int i;
2530
2531   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2532     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2533       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2534         ase |= mips_ases[i].flags64;
2535
2536   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2537     return FALSE;
2538
2539   /* Check whether the instruction or macro requires single-precision or
2540      double-precision floating-point support.  Note that this information is
2541      stored differently in the opcode table for insns and macros.  */
2542   if (mo->pinfo == INSN_MACRO)
2543     {
2544       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2545       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2546     }
2547   else
2548     {
2549       fp_s = mo->pinfo & FP_S;
2550       fp_d = mo->pinfo & FP_D;
2551     }
2552
2553   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2554     return FALSE;
2555
2556   if (fp_s && mips_opts.soft_float)
2557     return FALSE;
2558
2559   return TRUE;
2560 }
2561
2562 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2563    selected ISA and architecture.  */
2564
2565 static bfd_boolean
2566 is_opcode_valid_16 (const struct mips_opcode *mo)
2567 {
2568   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2569 }
2570
2571 /* Return TRUE if the size of the microMIPS opcode MO matches one
2572    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2573
2574 static bfd_boolean
2575 is_size_valid (const struct mips_opcode *mo)
2576 {
2577   if (!mips_opts.micromips)
2578     return TRUE;
2579
2580   if (mips_opts.insn32)
2581     {
2582       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2583         return FALSE;
2584       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2585         return FALSE;
2586     }
2587   if (!forced_insn_length)
2588     return TRUE;
2589   if (mo->pinfo == INSN_MACRO)
2590     return FALSE;
2591   return forced_insn_length == micromips_insn_length (mo);
2592 }
2593
2594 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2595    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2596
2597    We don't accept macros in 16-bit delay slots to avoid a case where
2598    a macro expansion fails because it relies on a preceding 32-bit real
2599    instruction to have matched and does not handle the operands correctly.
2600    The only macros that may expand to 16-bit instructions are JAL that
2601    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2602    and BGT (that likewise cannot be placed in a delay slot) that decay to
2603    a NOP.  In all these cases the macros precede any corresponding real
2604    instruction definitions in the opcode table, so they will match in the
2605    second pass where the size of the delay slot is ignored and therefore
2606    produce correct code.  */
2607
2608 static bfd_boolean
2609 is_delay_slot_valid (const struct mips_opcode *mo)
2610 {
2611   if (!mips_opts.micromips)
2612     return TRUE;
2613
2614   if (mo->pinfo == INSN_MACRO)
2615     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2616   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2617       && micromips_insn_length (mo) != 4)
2618     return FALSE;
2619   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2620       && micromips_insn_length (mo) != 2)
2621     return FALSE;
2622
2623   return TRUE;
2624 }
2625
2626 /* For consistency checking, verify that all bits of OPCODE are
2627    specified either by the match/mask part of the instruction
2628    definition, or by the operand list.  INSN_BITS says which
2629    bits of the instruction are significant and DECODE_OPERAND
2630    provides the mips_operand description of each operand.  */
2631
2632 static int
2633 validate_mips_insn (const struct mips_opcode *opcode,
2634                     unsigned long insn_bits,
2635                     const struct mips_operand *(*decode_operand) (const char *))
2636 {
2637   const char *s;
2638   unsigned long used_bits, doubled, undefined;
2639   const struct mips_operand *operand;
2640
2641   if ((opcode->mask & opcode->match) != opcode->match)
2642     {
2643       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
2644               opcode->name, opcode->args);
2645       return 0;
2646     }
2647   used_bits = 0;
2648   for (s = opcode->args; *s; ++s)
2649     switch (*s)
2650       {
2651       case ',':
2652       case '(':
2653       case ')':
2654         break;
2655
2656       default:
2657         operand = decode_operand (s);
2658         if (!operand)
2659           {
2660             as_bad (_("internal: unknown operand type: %s %s"),
2661                     opcode->name, opcode->args);
2662             return 0;
2663           }
2664         used_bits |= ((1 << operand->size) - 1) << operand->lsb;
2665         if (operand->type == OP_MDMX_IMM_REG)
2666           /* Bit 5 is the format selector (OB vs QH).  The opcode table
2667              has separate entries for each format.  */
2668           used_bits &= ~(1 << (operand->lsb + 5));
2669         /* Skip prefix characters.  */
2670         if (*s == '+' || *s == 'm')
2671           ++s;
2672         break;
2673       }
2674   doubled = used_bits & opcode->mask & insn_bits;
2675   if (doubled)
2676     {
2677       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
2678                 " %s %s"), doubled, opcode->name, opcode->args);
2679       return 0;
2680     }
2681   used_bits |= opcode->mask;
2682   undefined = ~used_bits & insn_bits;
2683   if (undefined)
2684     {
2685       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
2686               undefined, opcode->name, opcode->args);
2687       return 0;
2688     }
2689   used_bits &= ~insn_bits;
2690   if (used_bits)
2691     {
2692       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
2693               used_bits, opcode->name, opcode->args);
2694       return 0;
2695     }
2696   return 1;
2697 }
2698
2699 /* The microMIPS version of validate_mips_insn.  */
2700
2701 static int
2702 validate_micromips_insn (const struct mips_opcode *opc)
2703 {
2704   unsigned long insn_bits;
2705   unsigned long major;
2706   unsigned int length;
2707
2708   length = micromips_insn_length (opc);
2709   if (length != 2 && length != 4)
2710     {
2711       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
2712                 "%s %s"), length, opc->name, opc->args);
2713       return 0;
2714     }
2715   major = opc->match >> (10 + 8 * (length - 2));
2716   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
2717       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
2718     {
2719       as_bad (_("Internal error: bad microMIPS opcode "
2720                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
2721       return 0;
2722     }
2723
2724   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
2725   insn_bits = 1 << 4 * length;
2726   insn_bits <<= 4 * length;
2727   insn_bits -= 1;
2728   return validate_mips_insn (opc, insn_bits, decode_micromips_operand);
2729 }
2730
2731 /* This function is called once, at assembler startup time.  It should set up
2732    all the tables, etc. that the MD part of the assembler will need.  */
2733
2734 void
2735 md_begin (void)
2736 {
2737   const char *retval = NULL;
2738   int i = 0;
2739   int broken = 0;
2740
2741   if (mips_pic != NO_PIC)
2742     {
2743       if (g_switch_seen && g_switch_value != 0)
2744         as_bad (_("-G may not be used in position-independent code"));
2745       g_switch_value = 0;
2746     }
2747
2748   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2749     as_warn (_("Could not set architecture and machine"));
2750
2751   op_hash = hash_new ();
2752
2753   for (i = 0; i < NUMOPCODES;)
2754     {
2755       const char *name = mips_opcodes[i].name;
2756
2757       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2758       if (retval != NULL)
2759         {
2760           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2761                    mips_opcodes[i].name, retval);
2762           /* Probably a memory allocation problem?  Give up now.  */
2763           as_fatal (_("Broken assembler.  No assembly attempted."));
2764         }
2765       do
2766         {
2767           if (mips_opcodes[i].pinfo != INSN_MACRO)
2768             {
2769               if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
2770                                        decode_mips_operand))
2771                 broken = 1;
2772               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2773                 {
2774                   create_insn (&nop_insn, mips_opcodes + i);
2775                   if (mips_fix_loongson2f_nop)
2776                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2777                   nop_insn.fixed_p = 1;
2778                 }
2779             }
2780           ++i;
2781         }
2782       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2783     }
2784
2785   mips16_op_hash = hash_new ();
2786
2787   i = 0;
2788   while (i < bfd_mips16_num_opcodes)
2789     {
2790       const char *name = mips16_opcodes[i].name;
2791
2792       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2793       if (retval != NULL)
2794         as_fatal (_("internal: can't hash `%s': %s"),
2795                   mips16_opcodes[i].name, retval);
2796       do
2797         {
2798           if (mips16_opcodes[i].pinfo != INSN_MACRO
2799               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2800                   != mips16_opcodes[i].match))
2801             {
2802               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2803                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2804               broken = 1;
2805             }
2806           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2807             {
2808               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2809               mips16_nop_insn.fixed_p = 1;
2810             }
2811           ++i;
2812         }
2813       while (i < bfd_mips16_num_opcodes
2814              && strcmp (mips16_opcodes[i].name, name) == 0);
2815     }
2816
2817   micromips_op_hash = hash_new ();
2818
2819   i = 0;
2820   while (i < bfd_micromips_num_opcodes)
2821     {
2822       const char *name = micromips_opcodes[i].name;
2823
2824       retval = hash_insert (micromips_op_hash, name,
2825                             (void *) &micromips_opcodes[i]);
2826       if (retval != NULL)
2827         as_fatal (_("internal: can't hash `%s': %s"),
2828                   micromips_opcodes[i].name, retval);
2829       do
2830         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2831           {
2832             struct mips_cl_insn *micromips_nop_insn;
2833
2834             if (!validate_micromips_insn (&micromips_opcodes[i]))
2835               broken = 1;
2836
2837             if (micromips_insn_length (micromips_opcodes + i) == 2)
2838               micromips_nop_insn = &micromips_nop16_insn;
2839             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2840               micromips_nop_insn = &micromips_nop32_insn;
2841             else
2842               continue;
2843
2844             if (micromips_nop_insn->insn_mo == NULL
2845                 && strcmp (name, "nop") == 0)
2846               {
2847                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2848                 micromips_nop_insn->fixed_p = 1;
2849               }
2850           }
2851       while (++i < bfd_micromips_num_opcodes
2852              && strcmp (micromips_opcodes[i].name, name) == 0);
2853     }
2854
2855   if (broken)
2856     as_fatal (_("Broken assembler.  No assembly attempted."));
2857
2858   /* We add all the general register names to the symbol table.  This
2859      helps us detect invalid uses of them.  */
2860   for (i = 0; reg_names[i].name; i++) 
2861     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2862                                      reg_names[i].num, /* & RNUM_MASK, */
2863                                      &zero_address_frag));
2864   if (HAVE_NEWABI)
2865     for (i = 0; reg_names_n32n64[i].name; i++) 
2866       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2867                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2868                                        &zero_address_frag));
2869   else
2870     for (i = 0; reg_names_o32[i].name; i++) 
2871       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2872                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2873                                        &zero_address_frag));
2874
2875   mips_no_prev_insn ();
2876
2877   mips_gprmask = 0;
2878   mips_cprmask[0] = 0;
2879   mips_cprmask[1] = 0;
2880   mips_cprmask[2] = 0;
2881   mips_cprmask[3] = 0;
2882
2883   /* set the default alignment for the text section (2**2) */
2884   record_alignment (text_section, 2);
2885
2886   bfd_set_gp_size (stdoutput, g_switch_value);
2887
2888   /* On a native system other than VxWorks, sections must be aligned
2889      to 16 byte boundaries.  When configured for an embedded ELF
2890      target, we don't bother.  */
2891   if (strncmp (TARGET_OS, "elf", 3) != 0
2892       && strncmp (TARGET_OS, "vxworks", 7) != 0)
2893     {
2894       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2895       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2896       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2897     }
2898
2899   /* Create a .reginfo section for register masks and a .mdebug
2900      section for debugging information.  */
2901   {
2902     segT seg;
2903     subsegT subseg;
2904     flagword flags;
2905     segT sec;
2906
2907     seg = now_seg;
2908     subseg = now_subseg;
2909
2910     /* The ABI says this section should be loaded so that the
2911        running program can access it.  However, we don't load it
2912        if we are configured for an embedded target */
2913     flags = SEC_READONLY | SEC_DATA;
2914     if (strncmp (TARGET_OS, "elf", 3) != 0)
2915       flags |= SEC_ALLOC | SEC_LOAD;
2916
2917     if (mips_abi != N64_ABI)
2918       {
2919         sec = subseg_new (".reginfo", (subsegT) 0);
2920
2921         bfd_set_section_flags (stdoutput, sec, flags);
2922         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2923
2924         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2925       }
2926     else
2927       {
2928         /* The 64-bit ABI uses a .MIPS.options section rather than
2929            .reginfo section.  */
2930         sec = subseg_new (".MIPS.options", (subsegT) 0);
2931         bfd_set_section_flags (stdoutput, sec, flags);
2932         bfd_set_section_alignment (stdoutput, sec, 3);
2933
2934         /* Set up the option header.  */
2935         {
2936           Elf_Internal_Options opthdr;
2937           char *f;
2938
2939           opthdr.kind = ODK_REGINFO;
2940           opthdr.size = (sizeof (Elf_External_Options)
2941                          + sizeof (Elf64_External_RegInfo));
2942           opthdr.section = 0;
2943           opthdr.info = 0;
2944           f = frag_more (sizeof (Elf_External_Options));
2945           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2946                                          (Elf_External_Options *) f);
2947
2948           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2949         }
2950       }
2951
2952     if (ECOFF_DEBUGGING)
2953       {
2954         sec = subseg_new (".mdebug", (subsegT) 0);
2955         (void) bfd_set_section_flags (stdoutput, sec,
2956                                       SEC_HAS_CONTENTS | SEC_READONLY);
2957         (void) bfd_set_section_alignment (stdoutput, sec, 2);
2958       }
2959     else if (mips_flag_pdr)
2960       {
2961         pdr_seg = subseg_new (".pdr", (subsegT) 0);
2962         (void) bfd_set_section_flags (stdoutput, pdr_seg,
2963                                       SEC_READONLY | SEC_RELOC
2964                                       | SEC_DEBUGGING);
2965         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2966       }
2967
2968     subseg_set (seg, subseg);
2969   }
2970
2971   if (! ECOFF_DEBUGGING)
2972     md_obj_begin ();
2973
2974   if (mips_fix_vr4120)
2975     init_vr4120_conflicts ();
2976 }
2977
2978 void
2979 md_mips_end (void)
2980 {
2981   mips_emit_delays ();
2982   if (! ECOFF_DEBUGGING)
2983     md_obj_end ();
2984 }
2985
2986 void
2987 md_assemble (char *str)
2988 {
2989   struct mips_cl_insn insn;
2990   bfd_reloc_code_real_type unused_reloc[3]
2991     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2992
2993   imm_expr.X_op = O_absent;
2994   imm2_expr.X_op = O_absent;
2995   offset_expr.X_op = O_absent;
2996   offset_reloc[0] = BFD_RELOC_UNUSED;
2997   offset_reloc[1] = BFD_RELOC_UNUSED;
2998   offset_reloc[2] = BFD_RELOC_UNUSED;
2999
3000   mips_mark_labels ();
3001   mips_assembling_insn = TRUE;
3002
3003   if (mips_opts.mips16)
3004     mips16_ip (str, &insn);
3005   else
3006     {
3007       mips_ip (str, &insn);
3008       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3009             str, insn.insn_opcode));
3010     }
3011
3012   if (insn_error)
3013     as_bad ("%s `%s'", insn_error, str);
3014   else if (insn.insn_mo->pinfo == INSN_MACRO)
3015     {
3016       macro_start ();
3017       if (mips_opts.mips16)
3018         mips16_macro (&insn);
3019       else
3020         macro (&insn, str);
3021       macro_end ();
3022     }
3023   else
3024     {
3025       if (offset_expr.X_op != O_absent)
3026         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3027       else
3028         append_insn (&insn, NULL, unused_reloc, FALSE);
3029     }
3030
3031   mips_assembling_insn = FALSE;
3032 }
3033
3034 /* Convenience functions for abstracting away the differences between
3035    MIPS16 and non-MIPS16 relocations.  */
3036
3037 static inline bfd_boolean
3038 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3039 {
3040   switch (reloc)
3041     {
3042     case BFD_RELOC_MIPS16_JMP:
3043     case BFD_RELOC_MIPS16_GPREL:
3044     case BFD_RELOC_MIPS16_GOT16:
3045     case BFD_RELOC_MIPS16_CALL16:
3046     case BFD_RELOC_MIPS16_HI16_S:
3047     case BFD_RELOC_MIPS16_HI16:
3048     case BFD_RELOC_MIPS16_LO16:
3049       return TRUE;
3050
3051     default:
3052       return FALSE;
3053     }
3054 }
3055
3056 static inline bfd_boolean
3057 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3058 {
3059   switch (reloc)
3060     {
3061     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3062     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3063     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3064     case BFD_RELOC_MICROMIPS_GPREL16:
3065     case BFD_RELOC_MICROMIPS_JMP:
3066     case BFD_RELOC_MICROMIPS_HI16:
3067     case BFD_RELOC_MICROMIPS_HI16_S:
3068     case BFD_RELOC_MICROMIPS_LO16:
3069     case BFD_RELOC_MICROMIPS_LITERAL:
3070     case BFD_RELOC_MICROMIPS_GOT16:
3071     case BFD_RELOC_MICROMIPS_CALL16:
3072     case BFD_RELOC_MICROMIPS_GOT_HI16:
3073     case BFD_RELOC_MICROMIPS_GOT_LO16:
3074     case BFD_RELOC_MICROMIPS_CALL_HI16:
3075     case BFD_RELOC_MICROMIPS_CALL_LO16:
3076     case BFD_RELOC_MICROMIPS_SUB:
3077     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3078     case BFD_RELOC_MICROMIPS_GOT_OFST:
3079     case BFD_RELOC_MICROMIPS_GOT_DISP:
3080     case BFD_RELOC_MICROMIPS_HIGHEST:
3081     case BFD_RELOC_MICROMIPS_HIGHER:
3082     case BFD_RELOC_MICROMIPS_SCN_DISP:
3083     case BFD_RELOC_MICROMIPS_JALR:
3084       return TRUE;
3085
3086     default:
3087       return FALSE;
3088     }
3089 }
3090
3091 static inline bfd_boolean
3092 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3093 {
3094   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3095 }
3096
3097 static inline bfd_boolean
3098 got16_reloc_p (bfd_reloc_code_real_type reloc)
3099 {
3100   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3101           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3102 }
3103
3104 static inline bfd_boolean
3105 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3106 {
3107   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3108           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3109 }
3110
3111 static inline bfd_boolean
3112 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3113 {
3114   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3115           || reloc == BFD_RELOC_MICROMIPS_LO16);
3116 }
3117
3118 static inline bfd_boolean
3119 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3120 {
3121   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3122 }
3123
3124 static inline bfd_boolean
3125 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3126 {
3127   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3128           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3129 }
3130
3131 /* Return true if RELOC is a PC-relative relocation that does not have
3132    full address range.  */
3133
3134 static inline bfd_boolean
3135 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3136 {
3137   switch (reloc)
3138     {
3139     case BFD_RELOC_16_PCREL_S2:
3140     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3141     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3142     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3143       return TRUE;
3144
3145     case BFD_RELOC_32_PCREL:
3146       return HAVE_64BIT_ADDRESSES;
3147
3148     default:
3149       return FALSE;
3150     }
3151 }
3152
3153 /* Return true if the given relocation might need a matching %lo().
3154    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3155    need a matching %lo() when applied to local symbols.  */
3156
3157 static inline bfd_boolean
3158 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3159 {
3160   return (HAVE_IN_PLACE_ADDENDS
3161           && (hi16_reloc_p (reloc)
3162               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3163                  all GOT16 relocations evaluate to "G".  */
3164               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3165 }
3166
3167 /* Return the type of %lo() reloc needed by RELOC, given that
3168    reloc_needs_lo_p.  */
3169
3170 static inline bfd_reloc_code_real_type
3171 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3172 {
3173   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3174           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3175              : BFD_RELOC_LO16));
3176 }
3177
3178 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3179    relocation.  */
3180
3181 static inline bfd_boolean
3182 fixup_has_matching_lo_p (fixS *fixp)
3183 {
3184   return (fixp->fx_next != NULL
3185           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3186           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3187           && fixp->fx_offset == fixp->fx_next->fx_offset);
3188 }
3189
3190 /* This function returns true if modifying a register requires a
3191    delay.  */
3192
3193 static int
3194 reg_needs_delay (unsigned int reg)
3195 {
3196   unsigned long prev_pinfo;
3197
3198   prev_pinfo = history[0].insn_mo->pinfo;
3199   if (! mips_opts.noreorder
3200       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3201            && ! gpr_interlocks)
3202           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3203               && ! cop_interlocks)))
3204     {
3205       /* A load from a coprocessor or from memory.  All load delays
3206          delay the use of general register rt for one instruction.  */
3207       /* Itbl support may require additional care here.  */
3208       know (prev_pinfo & INSN_WRITE_GPR_T);
3209       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3210         return 1;
3211     }
3212
3213   return 0;
3214 }
3215
3216 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3217    says whether the labels refer to text or data.  */
3218
3219 static void
3220 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3221 {
3222   struct insn_label_list *l;
3223   valueT val;
3224
3225   for (l = labels; l != NULL; l = l->next)
3226     {
3227       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3228       symbol_set_frag (l->label, frag_now);
3229       val = (valueT) frag_now_fix ();
3230       /* MIPS16/microMIPS text labels are stored as odd.  */
3231       if (text_p && HAVE_CODE_COMPRESSION)
3232         ++val;
3233       S_SET_VALUE (l->label, val);
3234     }
3235 }
3236
3237 /* Move all labels in insn_labels to the current insertion point
3238    and treat them as text labels.  */
3239
3240 static void
3241 mips_move_text_labels (void)
3242 {
3243   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3244 }
3245
3246 static bfd_boolean
3247 s_is_linkonce (symbolS *sym, segT from_seg)
3248 {
3249   bfd_boolean linkonce = FALSE;
3250   segT symseg = S_GET_SEGMENT (sym);
3251
3252   if (symseg != from_seg && !S_IS_LOCAL (sym))
3253     {
3254       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3255         linkonce = TRUE;
3256       /* The GNU toolchain uses an extension for ELF: a section
3257          beginning with the magic string .gnu.linkonce is a
3258          linkonce section.  */
3259       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3260                    sizeof ".gnu.linkonce" - 1) == 0)
3261         linkonce = TRUE;
3262     }
3263   return linkonce;
3264 }
3265
3266 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3267    linker to handle them specially, such as generating jalx instructions
3268    when needed.  We also make them odd for the duration of the assembly,
3269    in order to generate the right sort of code.  We will make them even
3270    in the adjust_symtab routine, while leaving them marked.  This is
3271    convenient for the debugger and the disassembler.  The linker knows
3272    to make them odd again.  */
3273
3274 static void
3275 mips_compressed_mark_label (symbolS *label)
3276 {
3277   gas_assert (HAVE_CODE_COMPRESSION);
3278
3279   if (mips_opts.mips16)
3280     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3281   else
3282     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3283   if ((S_GET_VALUE (label) & 1) == 0
3284       /* Don't adjust the address if the label is global or weak, or
3285          in a link-once section, since we'll be emitting symbol reloc
3286          references to it which will be patched up by the linker, and
3287          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3288       && !S_IS_WEAK (label)
3289       && !S_IS_EXTERNAL (label)
3290       && !s_is_linkonce (label, now_seg))
3291     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3292 }
3293
3294 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3295
3296 static void
3297 mips_compressed_mark_labels (void)
3298 {
3299   struct insn_label_list *l;
3300
3301   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3302     mips_compressed_mark_label (l->label);
3303 }
3304
3305 /* End the current frag.  Make it a variant frag and record the
3306    relaxation info.  */
3307
3308 static void
3309 relax_close_frag (void)
3310 {
3311   mips_macro_warning.first_frag = frag_now;
3312   frag_var (rs_machine_dependent, 0, 0,
3313             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3314             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3315
3316   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3317   mips_relax.first_fixup = 0;
3318 }
3319
3320 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3321    See the comment above RELAX_ENCODE for more details.  */
3322
3323 static void
3324 relax_start (symbolS *symbol)
3325 {
3326   gas_assert (mips_relax.sequence == 0);
3327   mips_relax.sequence = 1;
3328   mips_relax.symbol = symbol;
3329 }
3330
3331 /* Start generating the second version of a relaxable sequence.
3332    See the comment above RELAX_ENCODE for more details.  */
3333
3334 static void
3335 relax_switch (void)
3336 {
3337   gas_assert (mips_relax.sequence == 1);
3338   mips_relax.sequence = 2;
3339 }
3340
3341 /* End the current relaxable sequence.  */
3342
3343 static void
3344 relax_end (void)
3345 {
3346   gas_assert (mips_relax.sequence == 2);
3347   relax_close_frag ();
3348   mips_relax.sequence = 0;
3349 }
3350
3351 /* Return true if IP is a delayed branch or jump.  */
3352
3353 static inline bfd_boolean
3354 delayed_branch_p (const struct mips_cl_insn *ip)
3355 {
3356   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3357                                 | INSN_COND_BRANCH_DELAY
3358                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3359 }
3360
3361 /* Return true if IP is a compact branch or jump.  */
3362
3363 static inline bfd_boolean
3364 compact_branch_p (const struct mips_cl_insn *ip)
3365 {
3366   if (mips_opts.mips16)
3367     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3368                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3369   else
3370     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3371                                    | INSN2_COND_BRANCH)) != 0;
3372 }
3373
3374 /* Return true if IP is an unconditional branch or jump.  */
3375
3376 static inline bfd_boolean
3377 uncond_branch_p (const struct mips_cl_insn *ip)
3378 {
3379   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3380           || (mips_opts.mips16
3381               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3382               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3383 }
3384
3385 /* Return true if IP is a branch-likely instruction.  */
3386
3387 static inline bfd_boolean
3388 branch_likely_p (const struct mips_cl_insn *ip)
3389 {
3390   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3391 }
3392
3393 /* Return the type of nop that should be used to fill the delay slot
3394    of delayed branch IP.  */
3395
3396 static struct mips_cl_insn *
3397 get_delay_slot_nop (const struct mips_cl_insn *ip)
3398 {
3399   if (mips_opts.micromips
3400       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3401     return &micromips_nop32_insn;
3402   return NOP_INSN;
3403 }
3404
3405 /* Return the mask of core registers that IP reads or writes.  */
3406
3407 static unsigned int
3408 gpr_mod_mask (const struct mips_cl_insn *ip)
3409 {
3410   unsigned long pinfo2;
3411   unsigned int mask;
3412
3413   mask = 0;
3414   pinfo2 = ip->insn_mo->pinfo2;
3415   if (mips_opts.micromips)
3416     {
3417       if (pinfo2 & INSN2_MOD_GPR_MD)
3418         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3419       if (pinfo2 & INSN2_MOD_GPR_MF)
3420         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3421       if (pinfo2 & INSN2_MOD_SP)
3422         mask |= 1 << SP;
3423     }
3424   return mask;
3425 }
3426
3427 /* Return the mask of core registers that IP reads.  */
3428
3429 static unsigned int
3430 gpr_read_mask (const struct mips_cl_insn *ip)
3431 {
3432   unsigned long pinfo, pinfo2;
3433   unsigned int mask;
3434
3435   mask = gpr_mod_mask (ip);
3436   pinfo = ip->insn_mo->pinfo;
3437   pinfo2 = ip->insn_mo->pinfo2;
3438   if (mips_opts.mips16)
3439     {
3440       if (pinfo & MIPS16_INSN_READ_X)
3441         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3442       if (pinfo & MIPS16_INSN_READ_Y)
3443         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3444       if (pinfo & MIPS16_INSN_READ_T)
3445         mask |= 1 << TREG;
3446       if (pinfo & MIPS16_INSN_READ_SP)
3447         mask |= 1 << SP;
3448       if (pinfo & MIPS16_INSN_READ_31)
3449         mask |= 1 << RA;
3450       if (pinfo & MIPS16_INSN_READ_Z)
3451         mask |= 1 << (mips16_to_32_reg_map
3452                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3453       if (pinfo & MIPS16_INSN_READ_GPR_X)
3454         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3455     }
3456   else
3457     {
3458       if (pinfo2 & INSN2_READ_GPR_D)
3459         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3460       if (pinfo & INSN_READ_GPR_T)
3461         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3462       if (pinfo & INSN_READ_GPR_S)
3463         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3464       if (pinfo2 & INSN2_READ_GP)
3465         mask |= 1 << GP;
3466       if (pinfo2 & INSN2_READ_GPR_31)
3467         mask |= 1 << RA;
3468       if (pinfo2 & INSN2_READ_GPR_Z)
3469         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3470     }
3471   if (mips_opts.micromips)
3472     {
3473       if (pinfo2 & INSN2_READ_GPR_MC)
3474         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3475       if (pinfo2 & INSN2_READ_GPR_ME)
3476         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3477       if (pinfo2 & INSN2_READ_GPR_MG)
3478         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3479       if (pinfo2 & INSN2_READ_GPR_MJ)
3480         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3481       if (pinfo2 & INSN2_READ_GPR_MMN)
3482         {
3483           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3484           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3485         }
3486       if (pinfo2 & INSN2_READ_GPR_MP)
3487         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3488       if (pinfo2 & INSN2_READ_GPR_MQ)
3489         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3490     }
3491   /* Don't include register 0.  */
3492   return mask & ~1;
3493 }
3494
3495 /* Return the mask of core registers that IP writes.  */
3496
3497 static unsigned int
3498 gpr_write_mask (const struct mips_cl_insn *ip)
3499 {
3500   unsigned long pinfo, pinfo2;
3501   unsigned int mask;
3502
3503   mask = gpr_mod_mask (ip);
3504   pinfo = ip->insn_mo->pinfo;
3505   pinfo2 = ip->insn_mo->pinfo2;
3506   if (mips_opts.mips16)
3507     {
3508       if (pinfo & MIPS16_INSN_WRITE_X)
3509         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3510       if (pinfo & MIPS16_INSN_WRITE_Y)
3511         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3512       if (pinfo & MIPS16_INSN_WRITE_Z)
3513         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3514       if (pinfo & MIPS16_INSN_WRITE_T)
3515         mask |= 1 << TREG;
3516       if (pinfo & MIPS16_INSN_WRITE_SP)
3517         mask |= 1 << SP;
3518       if (pinfo & MIPS16_INSN_WRITE_31)
3519         mask |= 1 << RA;
3520       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3521         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3522     }
3523   else
3524     {
3525       if (pinfo & INSN_WRITE_GPR_D)
3526         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3527       if (pinfo & INSN_WRITE_GPR_T)
3528         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3529       if (pinfo & INSN_WRITE_GPR_S)
3530         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3531       if (pinfo & INSN_WRITE_GPR_31)
3532         mask |= 1 << RA;
3533       if (pinfo2 & INSN2_WRITE_GPR_Z)
3534         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3535     }
3536   if (mips_opts.micromips)
3537     {
3538       if (pinfo2 & INSN2_WRITE_GPR_MB)
3539         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3540       if (pinfo2 & INSN2_WRITE_GPR_MH)
3541         {
3542           mask |= 1 << micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
3543           mask |= 1 << micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
3544         }
3545       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3546         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3547       if (pinfo2 & INSN2_WRITE_GPR_MP)
3548         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3549     }
3550   /* Don't include register 0.  */
3551   return mask & ~1;
3552 }
3553
3554 /* Return the mask of floating-point registers that IP reads.  */
3555
3556 static unsigned int
3557 fpr_read_mask (const struct mips_cl_insn *ip)
3558 {
3559   unsigned long pinfo, pinfo2;
3560   unsigned int mask;
3561
3562   mask = 0;
3563   pinfo = ip->insn_mo->pinfo;
3564   pinfo2 = ip->insn_mo->pinfo2;
3565   if (!mips_opts.mips16)
3566     {
3567       if (pinfo2 & INSN2_READ_FPR_D)
3568         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3569       if (pinfo & INSN_READ_FPR_S)
3570         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3571       if (pinfo & INSN_READ_FPR_T)
3572         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3573       if (pinfo & INSN_READ_FPR_R)
3574         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3575       if (pinfo2 & INSN2_READ_FPR_Z)
3576         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3577     }
3578   /* Conservatively treat all operands to an FP_D instruction are doubles.
3579      (This is overly pessimistic for things like cvt.d.s.)  */
3580   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3581     mask |= mask << 1;
3582   return mask;
3583 }
3584
3585 /* Return the mask of floating-point registers that IP writes.  */
3586
3587 static unsigned int
3588 fpr_write_mask (const struct mips_cl_insn *ip)
3589 {
3590   unsigned long pinfo, pinfo2;
3591   unsigned int mask;
3592
3593   mask = 0;
3594   pinfo = ip->insn_mo->pinfo;
3595   pinfo2 = ip->insn_mo->pinfo2;
3596   if (!mips_opts.mips16)
3597     {
3598       if (pinfo & INSN_WRITE_FPR_D)
3599         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3600       if (pinfo & INSN_WRITE_FPR_S)
3601         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3602       if (pinfo & INSN_WRITE_FPR_T)
3603         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3604       if (pinfo2 & INSN2_WRITE_FPR_Z)
3605         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3606     }
3607   /* Conservatively treat all operands to an FP_D instruction are doubles.
3608      (This is overly pessimistic for things like cvt.s.d.)  */
3609   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3610     mask |= mask << 1;
3611   return mask;
3612 }
3613
3614 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
3615    Check whether that is allowed.  */
3616
3617 static bfd_boolean
3618 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
3619 {
3620   const char *s = insn->name;
3621
3622   if (insn->pinfo == INSN_MACRO)
3623     /* Let a macro pass, we'll catch it later when it is expanded.  */
3624     return TRUE;
3625
3626   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
3627     {
3628       /* Allow odd registers for single-precision ops.  */
3629       switch (insn->pinfo & (FP_S | FP_D))
3630         {
3631         case FP_S:
3632         case 0:
3633           return TRUE;
3634         case FP_D:
3635           return FALSE;
3636         default:
3637           break;
3638         }
3639
3640       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
3641       s = strchr (insn->name, '.');
3642       if (s != NULL && opnum == 2)
3643         s = strchr (s + 1, '.');
3644       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
3645     }
3646
3647   /* Single-precision coprocessor loads and moves are OK too.  */
3648   if ((insn->pinfo & FP_S)
3649       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
3650                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
3651     return TRUE;
3652
3653   return FALSE;
3654 }
3655
3656 /* Report that user-supplied argument ARGNUM for INSN was VAL, but should
3657    have been in the range [MIN_VAL, MAX_VAL].  PRINT_HEX says whether
3658    this operand is normally printed in hex or decimal.  */
3659
3660 static void
3661 report_bad_range (struct mips_cl_insn *insn, int argnum,
3662                   offsetT val, int min_val, int max_val,
3663                   bfd_boolean print_hex)
3664 {
3665   if (print_hex && val >= 0)
3666     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3667               " was 0x%lx."),
3668             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3669   else if (print_hex)
3670     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3671               " was %ld."),
3672             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3673   else
3674     as_bad (_("Operand %d of `%s' must be in the range [%d, %d],"
3675               " was %ld."),
3676             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3677 }
3678
3679 /* Report an invalid combination of position and size operands for a bitfield
3680    operation.  POS and SIZE are the values that were given.  */
3681
3682 static void
3683 report_bad_field (offsetT pos, offsetT size)
3684 {
3685   as_bad (_("Invalid field specification (position %ld, size %ld)"),
3686           (unsigned long) pos, (unsigned long) size);
3687 }
3688
3689 /* Information about an instruction argument that we're trying to match.  */
3690 struct mips_arg_info
3691 {
3692   /* The instruction so far.  */
3693   struct mips_cl_insn *insn;
3694
3695   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
3696   int opnum;
3697
3698   /* The 1-based argument number, for error reporting.  This does not
3699      count elided optional registers, etc..  */
3700   int argnum;
3701
3702   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
3703   unsigned int last_regno;
3704
3705   /* If the first operand was an OP_REG, this is the register that it
3706      specified, otherwise it is ILLEGAL_REG.  */
3707   unsigned int dest_regno;
3708
3709   /* The value of the last OP_INT operand.  Only used for OP_MSB,
3710      where it gives the lsb position.  */
3711   unsigned int last_op_int;
3712
3713   /* If true, match routines should silently reject invalid arguments.
3714      If false, match routines can accept invalid arguments as long as
3715      they report an appropriate error.  They still have the option of
3716      silently rejecting arguments, in which case a generic "Invalid operands"
3717      style of error will be used instead.  */
3718   bfd_boolean soft_match;
3719
3720   /* If true, the OP_INT match routine should treat plain symbolic operands
3721      as if a relocation operator like %lo(...) had been used.  This is only
3722      ever true if the operand can be relocated.  */
3723   bfd_boolean allow_nonconst;
3724
3725   /* When true, the OP_INT match routine should allow unsigned N-bit
3726      arguments to be used where a signed N-bit operand is expected.  */
3727   bfd_boolean lax_max;
3728
3729   /* When true, the OP_REG match routine should assume that another operand
3730      appears after this one.  It should fail the match if the register it
3731      sees is at the end of the argument list.  */
3732   bfd_boolean optional_reg;
3733
3734   /* True if a reference to the current AT register was seen.  */
3735   bfd_boolean seen_at;
3736 };
3737
3738 /* Match a constant integer at S for ARG.  Return null if the match failed.
3739    Otherwise return the end of the matched string and store the constant value
3740    in *VALUE.  In the latter case, use FALLBACK as the value if the match
3741    succeeded with an error.  */
3742
3743 static char *
3744 match_const_int (struct mips_arg_info *arg, char *s, offsetT *value,
3745                  offsetT fallback)
3746 {
3747   expressionS ex;
3748   bfd_reloc_code_real_type r[3];
3749   int num_relocs;
3750
3751   num_relocs = my_getSmallExpression (&ex, r, s);
3752   if (*s == '(' && ex.X_op == O_register)
3753     {
3754       /* Assume that the constant has been elided and that S is a base
3755          register.  The rest of the match will fail if the assumption
3756          turns out to be wrong.  */
3757       *value = 0;
3758       return s;
3759     }
3760
3761   if (num_relocs == 0 && ex.X_op == O_constant)
3762     *value = ex.X_add_number;
3763   else
3764     {
3765       /* If we got a register rather than an expression, the default
3766          "Invalid operands" style of error seems more appropriate.  */
3767       if (arg->soft_match || ex.X_op == O_register)
3768         return 0;
3769       as_bad (_("Operand %d of `%s' must be constant"),
3770               arg->argnum, arg->insn->insn_mo->name);
3771       *value = fallback;
3772     }
3773   return expr_end;
3774 }
3775
3776 /* Return the RTYPE_* flags for a register operand of type TYPE that
3777    appears in instruction OPCODE.  */
3778
3779 static unsigned int
3780 convert_reg_type (const struct mips_opcode *opcode,
3781                   enum mips_reg_operand_type type)
3782 {
3783   switch (type)
3784     {
3785     case OP_REG_GP:
3786       return RTYPE_NUM | RTYPE_GP;
3787
3788     case OP_REG_FP:
3789       /* Allow vector register names for MDMX if the instruction is a 64-bit
3790          FPR load, store or move (including moves to and from GPRs).  */
3791       if ((mips_opts.ase & ASE_MDMX)
3792           && (opcode->pinfo & FP_D)
3793           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
3794                                | INSN_COPROC_MEMORY_DELAY
3795                                | INSN_LOAD_COPROC_DELAY
3796                                | INSN_LOAD_MEMORY_DELAY
3797                                | INSN_STORE_MEMORY)))
3798         return RTYPE_FPU | RTYPE_VEC;
3799       return RTYPE_FPU;
3800
3801     case OP_REG_CCC:
3802       if (opcode->pinfo & (FP_D | FP_S))
3803         return RTYPE_CCC | RTYPE_FCC;
3804       return RTYPE_CCC;
3805
3806     case OP_REG_VEC:
3807       if (opcode->membership & INSN_5400)
3808         return RTYPE_FPU;
3809       return RTYPE_FPU | RTYPE_VEC;
3810
3811     case OP_REG_ACC:
3812       return RTYPE_ACC;
3813
3814     case OP_REG_COPRO:
3815       if (opcode->name[strlen (opcode->name) - 1] == '0')
3816         return RTYPE_NUM | RTYPE_CP0;
3817       return RTYPE_NUM;
3818
3819     case OP_REG_HW:
3820       return RTYPE_NUM;
3821     }
3822   abort ();
3823 }
3824
3825 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
3826
3827 static void
3828 check_regno (struct mips_arg_info *arg,
3829              enum mips_reg_operand_type type, unsigned int regno)
3830 {
3831   if (AT && type == OP_REG_GP && regno == AT)
3832     arg->seen_at = TRUE;
3833
3834   if (type == OP_REG_FP
3835       && (regno & 1) != 0
3836       && HAVE_32BIT_FPRS
3837       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
3838     as_warn (_("Float register should be even, was %d"), regno);
3839
3840   if (type == OP_REG_CCC)
3841     {
3842       const char *name;
3843       size_t length;
3844
3845       name = arg->insn->insn_mo->name;
3846       length = strlen (name);
3847       if ((regno & 1) != 0
3848           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
3849               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
3850         as_warn (_("Condition code register should be even for %s, was %d"),
3851                  name, regno);
3852
3853       if ((regno & 3) != 0
3854           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
3855         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
3856                  name, regno);
3857     }
3858 }
3859
3860 /* OP_INT matcher.  */
3861
3862 static char *
3863 match_int_operand (struct mips_arg_info *arg,
3864                    const struct mips_operand *operand_base, char *s)
3865 {
3866   const struct mips_int_operand *operand;
3867   unsigned int uval, mask;
3868   int min_val, max_val, factor;
3869   offsetT sval;
3870   bfd_boolean print_hex;
3871
3872   operand = (const struct mips_int_operand *) operand_base;
3873   factor = 1 << operand->shift;
3874   mask = (1 << operand_base->size) - 1;
3875   max_val = (operand->max_val + operand->bias) << operand->shift;
3876   min_val = max_val - (mask << operand->shift);
3877   if (arg->lax_max)
3878     max_val = mask << operand->shift;
3879
3880   if (operand_base->lsb == 0
3881       && operand_base->size == 16
3882       && operand->shift == 0
3883       && operand->bias == 0
3884       && (operand->max_val == 32767 || operand->max_val == 65535))
3885     {
3886       /* The operand can be relocated.  */
3887       offset_reloc[0] = BFD_RELOC_LO16;
3888       offset_reloc[1] = BFD_RELOC_UNUSED;
3889       offset_reloc[2] = BFD_RELOC_UNUSED;
3890       if (my_getSmallExpression (&offset_expr, offset_reloc, s) > 0)
3891         /* Relocation operators were used.  Accept the arguent and
3892            leave the relocation value in offset_expr and offset_relocs
3893            for the caller to process.  */
3894         return expr_end;
3895       if (*s == '(' && offset_expr.X_op == O_register)
3896         /* Assume that the constant has been elided and that S is a base
3897            register.  The rest of the match will fail if the assumption
3898            turns out to be wrong.  */
3899         sval = 0;
3900       else
3901         {
3902           s = expr_end;
3903           if (offset_expr.X_op != O_constant)
3904             /* If non-constant operands are allowed then leave them for
3905                the caller to process, otherwise fail the match.  */
3906             return arg->allow_nonconst ? s : 0;
3907           sval = offset_expr.X_add_number;
3908         }
3909       /* Clear the global state; we're going to install the operand
3910          ourselves.  */
3911       offset_reloc[0] = BFD_RELOC_UNUSED;
3912       offset_expr.X_op = O_absent;
3913     }
3914   else
3915     {
3916       s = match_const_int (arg, s, &sval, min_val);
3917       if (!s)
3918         return 0;
3919     }
3920
3921   arg->last_op_int = sval;
3922
3923   /* Check the range.  If there's a problem, record the lowest acceptable
3924      value in arg->last_op_int in order to prevent an unhelpful error
3925      from OP_MSB too.
3926
3927      Bit counts have traditionally been printed in hex by the disassembler
3928      but printed as decimal in error messages.  Only resort to hex if
3929      the operand is bigger than 6 bits.  */
3930   print_hex = operand->print_hex && operand_base->size > 6;
3931   if (sval < min_val || sval > max_val)
3932     {
3933       if (arg->soft_match)
3934         return 0;
3935       report_bad_range (arg->insn, arg->argnum, sval, min_val, max_val,
3936                         print_hex);
3937       arg->last_op_int = min_val;
3938     }
3939   else if (sval % factor)
3940     {
3941       if (arg->soft_match)
3942         return 0;
3943       as_bad (print_hex && sval >= 0
3944               ? _("Operand %d of `%s' must be a factor of %d, was 0x%lx.")
3945               : _("Operand %d of `%s' must be a factor of %d, was %ld."),
3946               arg->argnum, arg->insn->insn_mo->name, factor,
3947               (unsigned long) sval);
3948       arg->last_op_int = min_val;
3949     }
3950
3951   uval = (unsigned int) sval >> operand->shift;
3952   uval -= operand->bias;
3953
3954   /* Handle -mfix-cn63xxp1.  */
3955   if (arg->opnum == 1
3956       && mips_fix_cn63xxp1
3957       && !mips_opts.micromips
3958       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
3959     switch (uval)
3960       {
3961       case 5:
3962       case 25:
3963       case 26:
3964       case 27:
3965       case 28:
3966       case 29:
3967       case 30:
3968       case 31:
3969         /* These are ok.  */
3970         break;
3971
3972       default:
3973         /* The rest must be changed to 28.  */
3974         uval = 28;
3975         break;
3976       }
3977
3978   insn_insert_operand (arg->insn, operand_base, uval);
3979   return s;
3980 }
3981
3982 /* OP_MAPPED_INT matcher.  */
3983
3984 static char *
3985 match_mapped_int_operand (struct mips_arg_info *arg,
3986                           const struct mips_operand *operand_base, char *s)
3987 {
3988   const struct mips_mapped_int_operand *operand;
3989   unsigned int uval, num_vals;
3990   offsetT sval;
3991
3992   operand = (const struct mips_mapped_int_operand *) operand_base;
3993   s = match_const_int (arg, s, &sval, operand->int_map[0]);
3994   if (!s)
3995     return 0;
3996
3997   num_vals = 1 << operand_base->size;
3998   for (uval = 0; uval < num_vals; uval++)
3999     if (operand->int_map[uval] == sval)
4000       break;
4001   if (uval == num_vals)
4002     return 0;
4003
4004   insn_insert_operand (arg->insn, operand_base, uval);
4005   return s;
4006 }
4007
4008 /* OP_MSB matcher.  */
4009
4010 static char *
4011 match_msb_operand (struct mips_arg_info *arg,
4012                    const struct mips_operand *operand_base, char *s)
4013 {
4014   const struct mips_msb_operand *operand;
4015   int min_val, max_val, max_high;
4016   offsetT size, sval, high;
4017
4018   operand = (const struct mips_msb_operand *) operand_base;
4019   min_val = operand->bias;
4020   max_val = min_val + (1 << operand_base->size) - 1;
4021   max_high = operand->opsize;
4022
4023   s = match_const_int (arg, s, &size, 1);
4024   if (!s)
4025     return 0;
4026
4027   high = size + arg->last_op_int;
4028   sval = operand->add_lsb ? high : size;
4029
4030   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4031     {
4032       if (arg->soft_match)
4033         return 0;
4034       report_bad_field (arg->last_op_int, size);
4035       sval = min_val;
4036     }
4037   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4038   return s;
4039 }
4040
4041 /* OP_REG matcher.  */
4042
4043 static char *
4044 match_reg_operand (struct mips_arg_info *arg,
4045                    const struct mips_operand *operand_base, char *s)
4046 {
4047   const struct mips_reg_operand *operand;
4048   unsigned int regno, uval, num_vals, types;
4049
4050   operand = (const struct mips_reg_operand *) operand_base;
4051   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4052   if (!reg_lookup (&s, types, &regno))
4053     return 0;
4054
4055   SKIP_SPACE_TABS (s);
4056   if (arg->optional_reg && *s == 0)
4057     return 0;
4058
4059   if (operand->reg_map)
4060     {
4061       num_vals = 1 << operand->root.size;
4062       for (uval = 0; uval < num_vals; uval++)
4063         if (operand->reg_map[uval] == regno)
4064           break;
4065       if (num_vals == uval)
4066         return 0;
4067     }
4068   else
4069     uval = regno;
4070
4071   check_regno (arg, operand->reg_type, regno);
4072   arg->last_regno = regno;
4073   if (arg->opnum == 1)
4074     arg->dest_regno = regno;
4075   insn_insert_operand (arg->insn, operand_base, uval);
4076   return s;
4077 }
4078
4079 /* OP_REG_PAIR matcher.  */
4080
4081 static char *
4082 match_reg_pair_operand (struct mips_arg_info *arg,
4083                         const struct mips_operand *operand_base, char *s)
4084 {
4085   const struct mips_reg_pair_operand *operand;
4086   unsigned int regno1, regno2, uval, num_vals, types;
4087
4088   operand = (const struct mips_reg_pair_operand *) operand_base;
4089   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4090
4091   if (!reg_lookup (&s, types, &regno1))
4092     return 0;
4093
4094   SKIP_SPACE_TABS (s);
4095   if (*s++ != ',')
4096     return 0;
4097   arg->argnum += 1;
4098
4099   if (!reg_lookup (&s, types, &regno2))
4100     return 0;
4101
4102   num_vals = 1 << operand_base->size;
4103   for (uval = 0; uval < num_vals; uval++)
4104     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4105       break;
4106   if (uval == num_vals)
4107     return 0;
4108
4109   check_regno (arg, operand->reg_type, regno1);
4110   check_regno (arg, operand->reg_type, regno2);
4111   insn_insert_operand (arg->insn, operand_base, uval);
4112   return s;
4113 }
4114
4115 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4116
4117 static char *
4118 match_pcrel_operand (char *s)
4119 {
4120   my_getExpression (&offset_expr, s);
4121   return expr_end;
4122 }
4123
4124 /* OP_PERF_REG matcher.  */
4125
4126 static char *
4127 match_perf_reg_operand (struct mips_arg_info *arg,
4128                         const struct mips_operand *operand, char *s)
4129 {
4130   offsetT sval;
4131
4132   s = match_const_int (arg, s, &sval, 0);
4133   if (!s)
4134     return 0;
4135
4136   if (sval != 0
4137       && (sval != 1
4138           || (mips_opts.arch == CPU_R5900
4139               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4140                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4141     {
4142       if (arg->soft_match)
4143         return 0;
4144       as_bad (_("Invalid performance register (%ld)"), (unsigned long) sval);
4145     }
4146
4147   insn_insert_operand (arg->insn, operand, sval);
4148   return s;
4149 }
4150
4151 /* OP_ADDIUSP matcher.  */
4152
4153 static char *
4154 match_addiusp_operand (struct mips_arg_info *arg,
4155                        const struct mips_operand *operand, char *s)
4156 {
4157   offsetT sval;
4158   unsigned int uval;
4159
4160   s = match_const_int (arg, s, &sval, -256);
4161   if (!s)
4162     return 0;
4163
4164   if (sval % 4)
4165     return 0;
4166
4167   sval /= 4;
4168   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4169     return 0;
4170
4171   uval = (unsigned int) sval;
4172   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4173   insn_insert_operand (arg->insn, operand, uval);
4174   return s;
4175 }
4176
4177 /* OP_CLO_CLZ_DEST matcher.  */
4178
4179 static char *
4180 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4181                             const struct mips_operand *operand, char *s)
4182 {
4183   unsigned int regno;
4184
4185   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
4186     return 0;
4187
4188   check_regno (arg, OP_REG_GP, regno);
4189   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4190   return s;
4191 }
4192
4193 /* OP_LWM_SWM_LIST matcher.  */
4194
4195 static char *
4196 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4197                             const struct mips_operand *operand, char *s)
4198 {
4199   unsigned int reglist, sregs, ra;
4200
4201   if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
4202     return 0;
4203
4204   if (operand->size == 2)
4205     {
4206       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4207
4208          s0, ra
4209          s0, s1, ra, s2, s3
4210          s0-s2, ra
4211
4212          and any permutations of these.  */
4213       if ((reglist & 0xfff1ffff) != 0x80010000)
4214         return 0;
4215
4216       sregs = (reglist >> 17) & 7;
4217       ra = 0;
4218     }
4219   else
4220     {
4221       /* The list must include at least one of ra and s0-sN,
4222          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4223          which are $23 and $30 respectively.)  E.g.:
4224
4225          ra
4226          s0
4227          ra, s0, s1, s2
4228          s0-s8
4229          s0-s5, ra
4230
4231          and any permutations of these.  */
4232       if ((reglist & 0x3f00ffff) != 0)
4233         return 0;
4234
4235       ra = (reglist >> 27) & 0x10;
4236       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4237     }
4238   sregs += 1;
4239   if ((sregs & -sregs) != sregs)
4240     return 0;
4241
4242   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4243   return s;
4244 }
4245
4246 /* OP_ENTRY_EXIT_LIST matcher.  */
4247
4248 static char *
4249 match_entry_exit_operand (struct mips_arg_info *arg,
4250                           const struct mips_operand *operand, char *s)
4251 {
4252   unsigned int mask;
4253   bfd_boolean is_exit;
4254
4255   /* The format is the same for both ENTRY and EXIT, but the constraints
4256      are different.  */
4257   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4258   mask = (is_exit ? 7 << 3 : 0);
4259   for (;;)
4260     {
4261       unsigned int regno1, regno2;
4262       bfd_boolean is_freg;
4263
4264       if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno1))
4265         is_freg = FALSE;
4266       else if (reg_lookup (&s, RTYPE_FPU, &regno1))
4267         is_freg = TRUE;
4268       else
4269         return 0;
4270
4271       SKIP_SPACE_TABS (s);
4272       if (*s == '-')
4273         {
4274           ++s;
4275           SKIP_SPACE_TABS (s);
4276           if (!reg_lookup (&s, (is_freg ? RTYPE_FPU
4277                                 : RTYPE_GP | RTYPE_NUM), &regno2))
4278             return 0;
4279           SKIP_SPACE_TABS (s);
4280         }
4281       else
4282         regno2 = regno1;
4283
4284       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4285         {
4286           mask &= ~(7 << 3);
4287           mask |= (5 + regno2) << 3;
4288         }
4289       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4290         mask |= (regno2 - 3) << 3;
4291       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4292         mask |= (regno2 - 15) << 1;
4293       else if (regno1 == RA && regno2 == RA)
4294         mask |= 1;
4295       else
4296         return 0;
4297
4298       if (!*s)
4299         break;
4300       if (*s != ',')
4301         return 0;
4302       arg->argnum += 1;
4303       ++s;
4304       SKIP_SPACE_TABS (s);
4305     }
4306   insn_insert_operand (arg->insn, operand, mask);
4307   return s;
4308 }
4309
4310 /* OP_SAVE_RESTORE_LIST matcher.  */
4311
4312 static char *
4313 match_save_restore_list_operand (struct mips_arg_info *arg, char *s)
4314 {
4315   unsigned int opcode, args, statics, sregs;
4316   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4317   expressionS value;
4318   offsetT frame_size;
4319   const char *error;
4320
4321   error = 0;
4322   opcode = arg->insn->insn_opcode;
4323   frame_size = 0;
4324   num_frame_sizes = 0;
4325   args = 0;
4326   statics = 0;
4327   sregs = 0;
4328   for (;;)
4329     {
4330       unsigned int regno1, regno2;
4331
4332       my_getExpression (&value, s);
4333       if (value.X_op == O_constant)
4334         {
4335           /* Handle the frame size.  */
4336           num_frame_sizes += 1;
4337           frame_size = value.X_add_number;
4338           s = expr_end;
4339           SKIP_SPACE_TABS (s);
4340         }
4341       else
4342         {
4343           if (!reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno1))
4344             return 0;
4345
4346           SKIP_SPACE_TABS (s);
4347           if (*s == '-')
4348             {
4349               ++s;
4350               SKIP_SPACE_TABS (s);
4351               if (!reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &regno2)
4352                   || regno2 < regno1)
4353                 return 0;
4354               SKIP_SPACE_TABS (s);
4355             }
4356           else
4357             regno2 = regno1;
4358
4359           while (regno1 <= regno2)
4360             {
4361               if (regno1 >= 4 && regno1 <= 7)
4362                 {
4363                   if (num_frame_sizes == 0)
4364                     /* args $a0-$a3 */
4365                     args |= 1 << (regno1 - 4);
4366                   else
4367                     /* statics $a0-$a3 */
4368                     statics |= 1 << (regno1 - 4);
4369                 }
4370               else if (regno1 >= 16 && regno1 <= 23)
4371                 /* $s0-$s7 */
4372                 sregs |= 1 << (regno1 - 16);
4373               else if (regno1 == 30)
4374                 /* $s8 */
4375                 sregs |= 1 << 8;
4376               else if (regno1 == 31)
4377                 /* Add $ra to insn.  */
4378                 opcode |= 0x40;
4379               else
4380                 return 0;
4381               regno1 += 1;
4382               if (regno1 == 24)
4383                 regno1 = 30;
4384             }
4385         }
4386       if (!*s)
4387         break;
4388       if (*s != ',')
4389         return 0;
4390       arg->argnum += 1;
4391       ++s;
4392       SKIP_SPACE_TABS (s);
4393     }
4394
4395   /* Encode args/statics combination.  */
4396   if (args & statics)
4397     return 0;
4398   else if (args == 0xf)
4399     /* All $a0-$a3 are args.  */
4400     opcode |= MIPS16_ALL_ARGS << 16;
4401   else if (statics == 0xf)
4402     /* All $a0-$a3 are statics.  */
4403     opcode |= MIPS16_ALL_STATICS << 16;
4404   else
4405     {
4406       /* Count arg registers.  */
4407       num_args = 0;
4408       while (args & 0x1)
4409         {
4410           args >>= 1;
4411           num_args += 1;
4412         }
4413       if (args != 0)
4414         return 0;
4415
4416       /* Count static registers.  */
4417       num_statics = 0;
4418       while (statics & 0x8)
4419         {
4420           statics = (statics << 1) & 0xf;
4421           num_statics += 1;
4422         }
4423       if (statics != 0)
4424         return 0;
4425
4426       /* Encode args/statics.  */
4427       opcode |= ((num_args << 2) | num_statics) << 16;
4428     }
4429
4430   /* Encode $s0/$s1.  */
4431   if (sregs & (1 << 0))         /* $s0 */
4432     opcode |= 0x20;
4433   if (sregs & (1 << 1))         /* $s1 */
4434     opcode |= 0x10;
4435   sregs >>= 2;
4436
4437   /* Encode $s2-$s8. */
4438   num_sregs = 0;
4439   while (sregs & 1)
4440     {
4441       sregs >>= 1;
4442       num_sregs += 1;
4443     }
4444   if (sregs != 0)
4445     return 0;
4446   opcode |= num_sregs << 24;
4447
4448   /* Encode frame size.  */
4449   if (num_frame_sizes == 0)
4450     error = _("Missing frame size");
4451   else if (num_frame_sizes > 1)
4452     error = _("Frame size specified twice");
4453   else if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
4454     error = _("Invalid frame size");
4455   else if (frame_size != 128 || (opcode >> 16) != 0)
4456     {
4457       frame_size /= 8;
4458       opcode |= (((frame_size & 0xf0) << 16)
4459                  | (frame_size & 0x0f));
4460     }
4461
4462   if (error)
4463     {
4464       if (arg->soft_match)
4465         return 0;
4466       as_bad (error);
4467     }
4468
4469   /* Finally build the instruction.  */
4470   if ((opcode >> 16) != 0 || frame_size == 0)
4471     opcode |= MIPS16_EXTEND;
4472   arg->insn->insn_opcode = opcode;
4473   return s;
4474 }
4475
4476 /* OP_MDMX_IMM_REG matcher.  */
4477
4478 static char *
4479 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
4480                             const struct mips_operand *operand, char *s)
4481 {
4482   unsigned int regno, uval, types;
4483   bfd_boolean is_qh;
4484   const struct mips_opcode *opcode;
4485
4486   /* The mips_opcode records whether this is an octobyte or quadhalf
4487      instruction.  Start out with that bit in place.  */
4488   opcode = arg->insn->insn_mo;
4489   uval = mips_extract_operand (operand, opcode->match);
4490   is_qh = (uval != 0);
4491
4492   types = convert_reg_type (arg->insn->insn_mo, OP_REG_VEC);
4493   if (reg_lookup (&s, types, &regno))
4494     {
4495       if ((opcode->membership & INSN_5400)
4496           && strcmp (opcode->name, "rzu.ob") == 0)
4497         {
4498           if (arg->soft_match)
4499             return 0;
4500           as_bad (_("Operand %d of `%s' must be an immediate"),
4501                   arg->argnum, opcode->name);
4502         }
4503
4504       /* Check whether this is a vector register or a broadcast of
4505          a single element.  */
4506       SKIP_SPACE_TABS (s);
4507       if (*s == '[')
4508         {
4509           /* Read the element number.  */
4510           expressionS value;
4511
4512           ++s;
4513           SKIP_SPACE_TABS (s);
4514           my_getExpression (&value, s);
4515           s = expr_end;
4516           if (value.X_op != O_constant
4517               || value.X_add_number < 0
4518               || value.X_add_number > (is_qh ? 3 : 7))
4519             {
4520               if (arg->soft_match)
4521                 return 0;
4522               as_bad (_("Invalid element selector"));
4523               value.X_add_number = 0;
4524             }
4525           uval |= (unsigned int) value.X_add_number << (is_qh ? 2 : 1) << 5;
4526           SKIP_SPACE_TABS (s);
4527           if (*s == ']')
4528             ++s;
4529           else
4530             {
4531               if (arg->soft_match)
4532                 return 0;
4533               as_bad (_("Expecting ']' found '%s'"), s);
4534             }
4535         }
4536       else
4537         {
4538           /* A full vector.  */
4539           if ((opcode->membership & INSN_5400)
4540               && (strcmp (opcode->name, "sll.ob") == 0
4541                   || strcmp (opcode->name, "srl.ob") == 0))
4542             {
4543               if (arg->soft_match)
4544                 return 0;
4545               as_bad (_("Operand %d of `%s' must be scalar"),
4546                       arg->argnum, opcode->name);
4547             }
4548
4549           if (is_qh)
4550             uval |= MDMX_FMTSEL_VEC_QH << 5;
4551           else
4552             uval |= MDMX_FMTSEL_VEC_OB << 5;
4553         }
4554       check_regno (arg, OP_REG_FP, regno);
4555       uval |= regno;
4556     }
4557   else
4558     {
4559       offsetT sval;
4560
4561       s = match_const_int (arg, s, &sval, 0);
4562       if (!s)
4563         return 0;
4564       if (sval < 0 || sval > 31)
4565         {
4566           if (arg->soft_match)
4567             return 0;
4568           report_bad_range (arg->insn, arg->argnum, sval, 0, 31, FALSE);
4569         }
4570       uval |= (sval & 31);
4571       if (is_qh)
4572         uval |= MDMX_FMTSEL_IMM_QH << 5;
4573       else
4574         uval |= MDMX_FMTSEL_IMM_OB << 5;
4575     }
4576   insn_insert_operand (arg->insn, operand, uval);
4577   return s;
4578 }
4579
4580 /* OP_PC matcher.  */
4581
4582 static char *
4583 match_pc_operand (char *s)
4584 {
4585   if (strncmp (s, "$pc", 3) != 0)
4586     return 0;
4587   s += 3;
4588   SKIP_SPACE_TABS (s);
4589   return s;
4590 }
4591
4592 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
4593    register that we need to match.  */
4594
4595 static char *
4596 match_tied_reg_operand (struct mips_arg_info *arg, char *s,
4597                         unsigned int other_regno)
4598 {
4599   unsigned int regno;
4600
4601   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno)
4602       || regno != other_regno)
4603     return 0;
4604   SKIP_SPACE_TABS (s);
4605   if (arg->optional_reg && *s == 0)
4606     return 0;
4607   return s;
4608 }
4609
4610 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
4611    of the argument text if the match is successful, otherwise return null.  */
4612
4613 static char *
4614 match_operand (struct mips_arg_info *arg,
4615                const struct mips_operand *operand, char *s)
4616 {
4617   switch (operand->type)
4618     {
4619     case OP_INT:
4620       return match_int_operand (arg, operand, s);
4621
4622     case OP_MAPPED_INT:
4623       return match_mapped_int_operand (arg, operand, s);
4624
4625     case OP_MSB:
4626       return match_msb_operand (arg, operand, s);
4627
4628     case OP_REG:
4629       return match_reg_operand (arg, operand, s);
4630
4631     case OP_REG_PAIR:
4632       return match_reg_pair_operand (arg, operand, s);
4633
4634     case OP_PCREL:
4635       return match_pcrel_operand (s);
4636
4637     case OP_PERF_REG:
4638       return match_perf_reg_operand (arg, operand, s);
4639
4640     case OP_ADDIUSP_INT:
4641       return match_addiusp_operand (arg, operand, s);
4642
4643     case OP_CLO_CLZ_DEST:
4644       return match_clo_clz_dest_operand (arg, operand, s);
4645
4646     case OP_LWM_SWM_LIST:
4647       return match_lwm_swm_list_operand (arg, operand, s);
4648
4649     case OP_ENTRY_EXIT_LIST:
4650       return match_entry_exit_operand (arg, operand, s);
4651
4652     case OP_SAVE_RESTORE_LIST:
4653       return match_save_restore_list_operand (arg, s);
4654
4655     case OP_MDMX_IMM_REG:
4656       return match_mdmx_imm_reg_operand (arg, operand, s);
4657
4658     case OP_REPEAT_DEST_REG:
4659       return match_tied_reg_operand (arg, s, arg->dest_regno);
4660
4661     case OP_REPEAT_PREV_REG:
4662       return match_tied_reg_operand (arg, s, arg->last_regno);
4663
4664     case OP_PC:
4665       return match_pc_operand (s);
4666     }
4667   abort ();
4668 }
4669
4670 /* ARG is the state after successfully matching an instruction.
4671    Issue any queued-up warnings.  */
4672
4673 static void
4674 check_completed_insn (struct mips_arg_info *arg)
4675 {
4676   if (arg->seen_at)
4677     {
4678       if (AT == ATREG)
4679         as_warn (_("Used $at without \".set noat\""));
4680       else
4681         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
4682     }
4683 }
4684
4685 /* Classify an instruction according to the FIX_VR4120_* enumeration.
4686    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
4687    by VR4120 errata.  */
4688
4689 static unsigned int
4690 classify_vr4120_insn (const char *name)
4691 {
4692   if (strncmp (name, "macc", 4) == 0)
4693     return FIX_VR4120_MACC;
4694   if (strncmp (name, "dmacc", 5) == 0)
4695     return FIX_VR4120_DMACC;
4696   if (strncmp (name, "mult", 4) == 0)
4697     return FIX_VR4120_MULT;
4698   if (strncmp (name, "dmult", 5) == 0)
4699     return FIX_VR4120_DMULT;
4700   if (strstr (name, "div"))
4701     return FIX_VR4120_DIV;
4702   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
4703     return FIX_VR4120_MTHILO;
4704   return NUM_FIX_VR4120_CLASSES;
4705 }
4706
4707 #define INSN_ERET  0x42000018
4708 #define INSN_DERET 0x4200001f
4709
4710 /* Return the number of instructions that must separate INSN1 and INSN2,
4711    where INSN1 is the earlier instruction.  Return the worst-case value
4712    for any INSN2 if INSN2 is null.  */
4713
4714 static unsigned int
4715 insns_between (const struct mips_cl_insn *insn1,
4716                const struct mips_cl_insn *insn2)
4717 {
4718   unsigned long pinfo1, pinfo2;
4719   unsigned int mask;
4720
4721   /* This function needs to know which pinfo flags are set for INSN2
4722      and which registers INSN2 uses.  The former is stored in PINFO2 and
4723      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
4724      will have every flag set and INSN2_USES_GPR will always return true.  */
4725   pinfo1 = insn1->insn_mo->pinfo;
4726   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
4727
4728 #define INSN2_USES_GPR(REG) \
4729   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
4730
4731   /* For most targets, write-after-read dependencies on the HI and LO
4732      registers must be separated by at least two instructions.  */
4733   if (!hilo_interlocks)
4734     {
4735       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
4736         return 2;
4737       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
4738         return 2;
4739     }
4740
4741   /* If we're working around r7000 errata, there must be two instructions
4742      between an mfhi or mflo and any instruction that uses the result.  */
4743   if (mips_7000_hilo_fix
4744       && !mips_opts.micromips
4745       && MF_HILO_INSN (pinfo1)
4746       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
4747     return 2;
4748
4749   /* If we're working around 24K errata, one instruction is required
4750      if an ERET or DERET is followed by a branch instruction.  */
4751   if (mips_fix_24k && !mips_opts.micromips)
4752     {
4753       if (insn1->insn_opcode == INSN_ERET
4754           || insn1->insn_opcode == INSN_DERET)
4755         {
4756           if (insn2 == NULL
4757               || insn2->insn_opcode == INSN_ERET
4758               || insn2->insn_opcode == INSN_DERET
4759               || delayed_branch_p (insn2))
4760             return 1;
4761         }
4762     }
4763
4764   /* If working around VR4120 errata, check for combinations that need
4765      a single intervening instruction.  */
4766   if (mips_fix_vr4120 && !mips_opts.micromips)
4767     {
4768       unsigned int class1, class2;
4769
4770       class1 = classify_vr4120_insn (insn1->insn_mo->name);
4771       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
4772         {
4773           if (insn2 == NULL)
4774             return 1;
4775           class2 = classify_vr4120_insn (insn2->insn_mo->name);
4776           if (vr4120_conflicts[class1] & (1 << class2))
4777             return 1;
4778         }
4779     }
4780
4781   if (!HAVE_CODE_COMPRESSION)
4782     {
4783       /* Check for GPR or coprocessor load delays.  All such delays
4784          are on the RT register.  */
4785       /* Itbl support may require additional care here.  */
4786       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
4787           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
4788         {
4789           know (pinfo1 & INSN_WRITE_GPR_T);
4790           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
4791             return 1;
4792         }
4793
4794       /* Check for generic coprocessor hazards.
4795
4796          This case is not handled very well.  There is no special
4797          knowledge of CP0 handling, and the coprocessors other than
4798          the floating point unit are not distinguished at all.  */
4799       /* Itbl support may require additional care here. FIXME!
4800          Need to modify this to include knowledge about
4801          user specified delays!  */
4802       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
4803                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
4804         {
4805           /* Handle cases where INSN1 writes to a known general coprocessor
4806              register.  There must be a one instruction delay before INSN2
4807              if INSN2 reads that register, otherwise no delay is needed.  */
4808           mask = fpr_write_mask (insn1);
4809           if (mask != 0)
4810             {
4811               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
4812                 return 1;
4813             }
4814           else
4815             {
4816               /* Read-after-write dependencies on the control registers
4817                  require a two-instruction gap.  */
4818               if ((pinfo1 & INSN_WRITE_COND_CODE)
4819                   && (pinfo2 & INSN_READ_COND_CODE))
4820                 return 2;
4821
4822               /* We don't know exactly what INSN1 does.  If INSN2 is
4823                  also a coprocessor instruction, assume there must be
4824                  a one instruction gap.  */
4825               if (pinfo2 & INSN_COP)
4826                 return 1;
4827             }
4828         }
4829
4830       /* Check for read-after-write dependencies on the coprocessor
4831          control registers in cases where INSN1 does not need a general
4832          coprocessor delay.  This means that INSN1 is a floating point
4833          comparison instruction.  */
4834       /* Itbl support may require additional care here.  */
4835       else if (!cop_interlocks
4836                && (pinfo1 & INSN_WRITE_COND_CODE)
4837                && (pinfo2 & INSN_READ_COND_CODE))
4838         return 1;
4839     }
4840
4841 #undef INSN2_USES_GPR
4842
4843   return 0;
4844 }
4845
4846 /* Return the number of nops that would be needed to work around the
4847    VR4130 mflo/mfhi errata if instruction INSN immediately followed
4848    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
4849    that are contained within the first IGNORE instructions of HIST.  */
4850
4851 static int
4852 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
4853                  const struct mips_cl_insn *insn)
4854 {
4855   int i, j;
4856   unsigned int mask;
4857
4858   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
4859      are not affected by the errata.  */
4860   if (insn != 0
4861       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
4862           || strcmp (insn->insn_mo->name, "mtlo") == 0
4863           || strcmp (insn->insn_mo->name, "mthi") == 0))
4864     return 0;
4865
4866   /* Search for the first MFLO or MFHI.  */
4867   for (i = 0; i < MAX_VR4130_NOPS; i++)
4868     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
4869       {
4870         /* Extract the destination register.  */
4871         mask = gpr_write_mask (&hist[i]);
4872
4873         /* No nops are needed if INSN reads that register.  */
4874         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
4875           return 0;
4876
4877         /* ...or if any of the intervening instructions do.  */
4878         for (j = 0; j < i; j++)
4879           if (gpr_read_mask (&hist[j]) & mask)
4880             return 0;
4881
4882         if (i >= ignore)
4883           return MAX_VR4130_NOPS - i;
4884       }
4885   return 0;
4886 }
4887
4888 #define BASE_REG_EQ(INSN1, INSN2)       \
4889   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
4890       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
4891
4892 /* Return the minimum alignment for this store instruction.  */
4893
4894 static int
4895 fix_24k_align_to (const struct mips_opcode *mo)
4896 {
4897   if (strcmp (mo->name, "sh") == 0)
4898     return 2;
4899
4900   if (strcmp (mo->name, "swc1") == 0
4901       || strcmp (mo->name, "swc2") == 0
4902       || strcmp (mo->name, "sw") == 0
4903       || strcmp (mo->name, "sc") == 0
4904       || strcmp (mo->name, "s.s") == 0)
4905     return 4;
4906
4907   if (strcmp (mo->name, "sdc1") == 0
4908       || strcmp (mo->name, "sdc2") == 0
4909       || strcmp (mo->name, "s.d") == 0)
4910     return 8;
4911
4912   /* sb, swl, swr */
4913   return 1;
4914 }
4915
4916 struct fix_24k_store_info
4917   {
4918     /* Immediate offset, if any, for this store instruction.  */
4919     short off;
4920     /* Alignment required by this store instruction.  */
4921     int align_to;
4922     /* True for register offsets.  */
4923     int register_offset;
4924   };
4925
4926 /* Comparison function used by qsort.  */
4927
4928 static int
4929 fix_24k_sort (const void *a, const void *b)
4930 {
4931   const struct fix_24k_store_info *pos1 = a;
4932   const struct fix_24k_store_info *pos2 = b;
4933
4934   return (pos1->off - pos2->off);
4935 }
4936
4937 /* INSN is a store instruction.  Try to record the store information
4938    in STINFO.  Return false if the information isn't known.  */
4939
4940 static bfd_boolean
4941 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
4942                            const struct mips_cl_insn *insn)
4943 {
4944   /* The instruction must have a known offset.  */
4945   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
4946     return FALSE;
4947
4948   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
4949   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
4950   return TRUE;
4951 }
4952
4953 /* Return the number of nops that would be needed to work around the 24k
4954    "lost data on stores during refill" errata if instruction INSN
4955    immediately followed the 2 instructions described by HIST.
4956    Ignore hazards that are contained within the first IGNORE
4957    instructions of HIST.
4958
4959    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
4960    for the data cache refills and store data. The following describes
4961    the scenario where the store data could be lost.
4962
4963    * A data cache miss, due to either a load or a store, causing fill
4964      data to be supplied by the memory subsystem
4965    * The first three doublewords of fill data are returned and written
4966      into the cache
4967    * A sequence of four stores occurs in consecutive cycles around the
4968      final doubleword of the fill:
4969    * Store A
4970    * Store B
4971    * Store C
4972    * Zero, One or more instructions
4973    * Store D
4974
4975    The four stores A-D must be to different doublewords of the line that
4976    is being filled. The fourth instruction in the sequence above permits
4977    the fill of the final doubleword to be transferred from the FSB into
4978    the cache. In the sequence above, the stores may be either integer
4979    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
4980    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
4981    different doublewords on the line. If the floating point unit is
4982    running in 1:2 mode, it is not possible to create the sequence above
4983    using only floating point store instructions.
4984
4985    In this case, the cache line being filled is incorrectly marked
4986    invalid, thereby losing the data from any store to the line that
4987    occurs between the original miss and the completion of the five
4988    cycle sequence shown above.
4989
4990    The workarounds are:
4991
4992    * Run the data cache in write-through mode.
4993    * Insert a non-store instruction between
4994      Store A and Store B or Store B and Store C.  */
4995   
4996 static int
4997 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
4998               const struct mips_cl_insn *insn)
4999 {
5000   struct fix_24k_store_info pos[3];
5001   int align, i, base_offset;
5002
5003   if (ignore >= 2)
5004     return 0;
5005
5006   /* If the previous instruction wasn't a store, there's nothing to
5007      worry about.  */
5008   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5009     return 0;
5010
5011   /* If the instructions after the previous one are unknown, we have
5012      to assume the worst.  */
5013   if (!insn)
5014     return 1;
5015
5016   /* Check whether we are dealing with three consecutive stores.  */
5017   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5018       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5019     return 0;
5020
5021   /* If we don't know the relationship between the store addresses,
5022      assume the worst.  */
5023   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5024       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5025     return 1;
5026
5027   if (!fix_24k_record_store_info (&pos[0], insn)
5028       || !fix_24k_record_store_info (&pos[1], &hist[0])
5029       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5030     return 1;
5031
5032   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5033
5034   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5035      X bytes and such that the base register + X is known to be aligned
5036      to align bytes.  */
5037
5038   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5039     align = 8;
5040   else
5041     {
5042       align = pos[0].align_to;
5043       base_offset = pos[0].off;
5044       for (i = 1; i < 3; i++)
5045         if (align < pos[i].align_to)
5046           {
5047             align = pos[i].align_to;
5048             base_offset = pos[i].off;
5049           }
5050       for (i = 0; i < 3; i++)
5051         pos[i].off -= base_offset;
5052     }
5053
5054   pos[0].off &= ~align + 1;
5055   pos[1].off &= ~align + 1;
5056   pos[2].off &= ~align + 1;
5057
5058   /* If any two stores write to the same chunk, they also write to the
5059      same doubleword.  The offsets are still sorted at this point.  */
5060   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5061     return 0;
5062
5063   /* A range of at least 9 bytes is needed for the stores to be in
5064      non-overlapping doublewords.  */
5065   if (pos[2].off - pos[0].off <= 8)
5066     return 0;
5067
5068   if (pos[2].off - pos[1].off >= 24
5069       || pos[1].off - pos[0].off >= 24
5070       || pos[2].off - pos[0].off >= 32)
5071     return 0;
5072
5073   return 1;
5074 }
5075
5076 /* Return the number of nops that would be needed if instruction INSN
5077    immediately followed the MAX_NOPS instructions given by HIST,
5078    where HIST[0] is the most recent instruction.  Ignore hazards
5079    between INSN and the first IGNORE instructions in HIST.
5080
5081    If INSN is null, return the worse-case number of nops for any
5082    instruction.  */
5083
5084 static int
5085 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5086                const struct mips_cl_insn *insn)
5087 {
5088   int i, nops, tmp_nops;
5089
5090   nops = 0;
5091   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5092     {
5093       tmp_nops = insns_between (hist + i, insn) - i;
5094       if (tmp_nops > nops)
5095         nops = tmp_nops;
5096     }
5097
5098   if (mips_fix_vr4130 && !mips_opts.micromips)
5099     {
5100       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5101       if (tmp_nops > nops)
5102         nops = tmp_nops;
5103     }
5104
5105   if (mips_fix_24k && !mips_opts.micromips)
5106     {
5107       tmp_nops = nops_for_24k (ignore, hist, insn);
5108       if (tmp_nops > nops)
5109         nops = tmp_nops;
5110     }
5111
5112   return nops;
5113 }
5114
5115 /* The variable arguments provide NUM_INSNS extra instructions that
5116    might be added to HIST.  Return the largest number of nops that
5117    would be needed after the extended sequence, ignoring hazards
5118    in the first IGNORE instructions.  */
5119
5120 static int
5121 nops_for_sequence (int num_insns, int ignore,
5122                    const struct mips_cl_insn *hist, ...)
5123 {
5124   va_list args;
5125   struct mips_cl_insn buffer[MAX_NOPS];
5126   struct mips_cl_insn *cursor;
5127   int nops;
5128
5129   va_start (args, hist);
5130   cursor = buffer + num_insns;
5131   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5132   while (cursor > buffer)
5133     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5134
5135   nops = nops_for_insn (ignore, buffer, NULL);
5136   va_end (args);
5137   return nops;
5138 }
5139
5140 /* Like nops_for_insn, but if INSN is a branch, take into account the
5141    worst-case delay for the branch target.  */
5142
5143 static int
5144 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5145                          const struct mips_cl_insn *insn)
5146 {
5147   int nops, tmp_nops;
5148
5149   nops = nops_for_insn (ignore, hist, insn);
5150   if (delayed_branch_p (insn))
5151     {
5152       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5153                                     hist, insn, get_delay_slot_nop (insn));
5154       if (tmp_nops > nops)
5155         nops = tmp_nops;
5156     }
5157   else if (compact_branch_p (insn))
5158     {
5159       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5160       if (tmp_nops > nops)
5161         nops = tmp_nops;
5162     }
5163   return nops;
5164 }
5165
5166 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5167
5168 static void
5169 fix_loongson2f_nop (struct mips_cl_insn * ip)
5170 {
5171   gas_assert (!HAVE_CODE_COMPRESSION);
5172   if (strcmp (ip->insn_mo->name, "nop") == 0)
5173     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5174 }
5175
5176 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5177                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5178
5179 static void
5180 fix_loongson2f_jump (struct mips_cl_insn * ip)
5181 {
5182   gas_assert (!HAVE_CODE_COMPRESSION);
5183   if (strcmp (ip->insn_mo->name, "j") == 0
5184       || strcmp (ip->insn_mo->name, "jr") == 0
5185       || strcmp (ip->insn_mo->name, "jalr") == 0)
5186     {
5187       int sreg;
5188       expressionS ep;
5189
5190       if (! mips_opts.at)
5191         return;
5192
5193       sreg = EXTRACT_OPERAND (0, RS, *ip);
5194       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5195         return;
5196
5197       ep.X_op = O_constant;
5198       ep.X_add_number = 0xcfff0000;
5199       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5200       ep.X_add_number = 0xffff;
5201       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5202       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5203     }
5204 }
5205
5206 static void
5207 fix_loongson2f (struct mips_cl_insn * ip)
5208 {
5209   if (mips_fix_loongson2f_nop)
5210     fix_loongson2f_nop (ip);
5211
5212   if (mips_fix_loongson2f_jump)
5213     fix_loongson2f_jump (ip);
5214 }
5215
5216 /* IP is a branch that has a delay slot, and we need to fill it
5217    automatically.   Return true if we can do that by swapping IP
5218    with the previous instruction.
5219    ADDRESS_EXPR is an operand of the instruction to be used with
5220    RELOC_TYPE.  */
5221
5222 static bfd_boolean
5223 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5224   bfd_reloc_code_real_type *reloc_type)
5225 {
5226   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5227   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
5228
5229   /* -O2 and above is required for this optimization.  */
5230   if (mips_optimize < 2)
5231     return FALSE;
5232
5233   /* If we have seen .set volatile or .set nomove, don't optimize.  */
5234   if (mips_opts.nomove)
5235     return FALSE;
5236
5237   /* We can't swap if the previous instruction's position is fixed.  */
5238   if (history[0].fixed_p)
5239     return FALSE;
5240
5241   /* If the previous previous insn was in a .set noreorder, we can't
5242      swap.  Actually, the MIPS assembler will swap in this situation.
5243      However, gcc configured -with-gnu-as will generate code like
5244
5245         .set    noreorder
5246         lw      $4,XXX
5247         .set    reorder
5248         INSN
5249         bne     $4,$0,foo
5250
5251      in which we can not swap the bne and INSN.  If gcc is not configured
5252      -with-gnu-as, it does not output the .set pseudo-ops.  */
5253   if (history[1].noreorder_p)
5254     return FALSE;
5255
5256   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
5257      This means that the previous instruction was a 4-byte one anyhow.  */
5258   if (mips_opts.mips16 && history[0].fixp[0])
5259     return FALSE;
5260
5261   /* If the branch is itself the target of a branch, we can not swap.
5262      We cheat on this; all we check for is whether there is a label on
5263      this instruction.  If there are any branches to anything other than
5264      a label, users must use .set noreorder.  */
5265   if (seg_info (now_seg)->label_list)
5266     return FALSE;
5267
5268   /* If the previous instruction is in a variant frag other than this
5269      branch's one, we cannot do the swap.  This does not apply to
5270      MIPS16 code, which uses variant frags for different purposes.  */
5271   if (!mips_opts.mips16
5272       && history[0].frag
5273       && history[0].frag->fr_type == rs_machine_dependent)
5274     return FALSE;
5275
5276   /* We do not swap with instructions that cannot architecturally
5277      be placed in a branch delay slot, such as SYNC or ERET.  We
5278      also refrain from swapping with a trap instruction, since it
5279      complicates trap handlers to have the trap instruction be in
5280      a delay slot.  */
5281   prev_pinfo = history[0].insn_mo->pinfo;
5282   if (prev_pinfo & INSN_NO_DELAY_SLOT)
5283     return FALSE;
5284
5285   /* Check for conflicts between the branch and the instructions
5286      before the candidate delay slot.  */
5287   if (nops_for_insn (0, history + 1, ip) > 0)
5288     return FALSE;
5289
5290   /* Check for conflicts between the swapped sequence and the
5291      target of the branch.  */
5292   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
5293     return FALSE;
5294
5295   /* If the branch reads a register that the previous
5296      instruction sets, we can not swap.  */
5297   gpr_read = gpr_read_mask (ip);
5298   prev_gpr_write = gpr_write_mask (&history[0]);
5299   if (gpr_read & prev_gpr_write)
5300     return FALSE;
5301
5302   /* If the branch writes a register that the previous
5303      instruction sets, we can not swap.  */
5304   gpr_write = gpr_write_mask (ip);
5305   if (gpr_write & prev_gpr_write)
5306     return FALSE;
5307
5308   /* If the branch writes a register that the previous
5309      instruction reads, we can not swap.  */
5310   prev_gpr_read = gpr_read_mask (&history[0]);
5311   if (gpr_write & prev_gpr_read)
5312     return FALSE;
5313
5314   /* If one instruction sets a condition code and the
5315      other one uses a condition code, we can not swap.  */
5316   pinfo = ip->insn_mo->pinfo;
5317   if ((pinfo & INSN_READ_COND_CODE)
5318       && (prev_pinfo & INSN_WRITE_COND_CODE))
5319     return FALSE;
5320   if ((pinfo & INSN_WRITE_COND_CODE)
5321       && (prev_pinfo & INSN_READ_COND_CODE))
5322     return FALSE;
5323
5324   /* If the previous instruction uses the PC, we can not swap.  */
5325   prev_pinfo2 = history[0].insn_mo->pinfo2;
5326   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
5327     return FALSE;
5328   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
5329     return FALSE;
5330
5331   /* If the previous instruction has an incorrect size for a fixed
5332      branch delay slot in microMIPS mode, we cannot swap.  */
5333   pinfo2 = ip->insn_mo->pinfo2;
5334   if (mips_opts.micromips
5335       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
5336       && insn_length (history) != 2)
5337     return FALSE;
5338   if (mips_opts.micromips
5339       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
5340       && insn_length (history) != 4)
5341     return FALSE;
5342
5343   /* On R5900 short loops need to be fixed by inserting a nop in
5344      the branch delay slots.
5345      A short loop can be terminated too early.  */
5346   if (mips_opts.arch == CPU_R5900
5347       /* Check if instruction has a parameter, ignore "j $31". */
5348       && (address_expr != NULL)
5349       /* Parameter must be 16 bit. */
5350       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
5351       /* Branch to same segment. */
5352       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
5353       /* Branch to same code fragment. */
5354       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
5355       /* Can only calculate branch offset if value is known. */
5356       && symbol_constant_p(address_expr->X_add_symbol)
5357       /* Check if branch is really conditional. */
5358       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
5359         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
5360         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
5361     {
5362       int distance;
5363       /* Check if loop is shorter than 6 instructions including
5364          branch and delay slot.  */
5365       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
5366       if (distance <= 20)
5367         {
5368           int i;
5369           int rv;
5370
5371           rv = FALSE;
5372           /* When the loop includes branches or jumps,
5373              it is not a short loop. */
5374           for (i = 0; i < (distance / 4); i++)
5375             {
5376               if ((history[i].cleared_p)
5377                   || delayed_branch_p(&history[i]))
5378                 {
5379                   rv = TRUE;
5380                   break;
5381                 }
5382             }
5383           if (rv == FALSE)
5384             {
5385               /* Insert nop after branch to fix short loop. */
5386               return FALSE;
5387             }
5388         }
5389     }
5390
5391   return TRUE;
5392 }
5393
5394 /* Decide how we should add IP to the instruction stream.
5395    ADDRESS_EXPR is an operand of the instruction to be used with
5396    RELOC_TYPE.  */
5397
5398 static enum append_method
5399 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
5400   bfd_reloc_code_real_type *reloc_type)
5401 {
5402   unsigned long pinfo;
5403
5404   /* The relaxed version of a macro sequence must be inherently
5405      hazard-free.  */
5406   if (mips_relax.sequence == 2)
5407     return APPEND_ADD;
5408
5409   /* We must not dabble with instructions in a ".set norerorder" block.  */
5410   if (mips_opts.noreorder)
5411     return APPEND_ADD;
5412
5413   /* Otherwise, it's our responsibility to fill branch delay slots.  */
5414   if (delayed_branch_p (ip))
5415     {
5416       if (!branch_likely_p (ip)
5417           && can_swap_branch_p (ip, address_expr, reloc_type))
5418         return APPEND_SWAP;
5419
5420       pinfo = ip->insn_mo->pinfo;
5421       if (mips_opts.mips16
5422           && ISA_SUPPORTS_MIPS16E
5423           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
5424         return APPEND_ADD_COMPACT;
5425
5426       return APPEND_ADD_WITH_NOP;
5427     }
5428
5429   return APPEND_ADD;
5430 }
5431
5432 /* IP is a MIPS16 instruction whose opcode we have just changed.
5433    Point IP->insn_mo to the new opcode's definition.  */
5434
5435 static void
5436 find_altered_mips16_opcode (struct mips_cl_insn *ip)
5437 {
5438   const struct mips_opcode *mo, *end;
5439
5440   end = &mips16_opcodes[bfd_mips16_num_opcodes];
5441   for (mo = ip->insn_mo; mo < end; mo++)
5442     if ((ip->insn_opcode & mo->mask) == mo->match)
5443       {
5444         ip->insn_mo = mo;
5445         return;
5446       }
5447   abort ();
5448 }
5449
5450 /* For microMIPS macros, we need to generate a local number label
5451    as the target of branches.  */
5452 #define MICROMIPS_LABEL_CHAR            '\037'
5453 static unsigned long micromips_target_label;
5454 static char micromips_target_name[32];
5455
5456 static char *
5457 micromips_label_name (void)
5458 {
5459   char *p = micromips_target_name;
5460   char symbol_name_temporary[24];
5461   unsigned long l;
5462   int i;
5463
5464   if (*p)
5465     return p;
5466
5467   i = 0;
5468   l = micromips_target_label;
5469 #ifdef LOCAL_LABEL_PREFIX
5470   *p++ = LOCAL_LABEL_PREFIX;
5471 #endif
5472   *p++ = 'L';
5473   *p++ = MICROMIPS_LABEL_CHAR;
5474   do
5475     {
5476       symbol_name_temporary[i++] = l % 10 + '0';
5477       l /= 10;
5478     }
5479   while (l != 0);
5480   while (i > 0)
5481     *p++ = symbol_name_temporary[--i];
5482   *p = '\0';
5483
5484   return micromips_target_name;
5485 }
5486
5487 static void
5488 micromips_label_expr (expressionS *label_expr)
5489 {
5490   label_expr->X_op = O_symbol;
5491   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
5492   label_expr->X_add_number = 0;
5493 }
5494
5495 static void
5496 micromips_label_inc (void)
5497 {
5498   micromips_target_label++;
5499   *micromips_target_name = '\0';
5500 }
5501
5502 static void
5503 micromips_add_label (void)
5504 {
5505   symbolS *s;
5506
5507   s = colon (micromips_label_name ());
5508   micromips_label_inc ();
5509   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
5510 }
5511
5512 /* If assembling microMIPS code, then return the microMIPS reloc
5513    corresponding to the requested one if any.  Otherwise return
5514    the reloc unchanged.  */
5515
5516 static bfd_reloc_code_real_type
5517 micromips_map_reloc (bfd_reloc_code_real_type reloc)
5518 {
5519   static const bfd_reloc_code_real_type relocs[][2] =
5520     {
5521       /* Keep sorted incrementally by the left-hand key.  */
5522       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
5523       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
5524       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
5525       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
5526       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
5527       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
5528       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
5529       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
5530       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
5531       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
5532       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
5533       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
5534       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
5535       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
5536       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
5537       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
5538       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
5539       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
5540       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
5541       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
5542       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
5543       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
5544       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
5545       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
5546       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
5547       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
5548       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
5549     };
5550   bfd_reloc_code_real_type r;
5551   size_t i;
5552
5553   if (!mips_opts.micromips)
5554     return reloc;
5555   for (i = 0; i < ARRAY_SIZE (relocs); i++)
5556     {
5557       r = relocs[i][0];
5558       if (r > reloc)
5559         return reloc;
5560       if (r == reloc)
5561         return relocs[i][1];
5562     }
5563   return reloc;
5564 }
5565
5566 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
5567    Return true on success, storing the resolved value in RESULT.  */
5568
5569 static bfd_boolean
5570 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
5571                  offsetT *result)
5572 {
5573   switch (reloc)
5574     {
5575     case BFD_RELOC_MIPS_HIGHEST:
5576     case BFD_RELOC_MICROMIPS_HIGHEST:
5577       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
5578       return TRUE;
5579
5580     case BFD_RELOC_MIPS_HIGHER:
5581     case BFD_RELOC_MICROMIPS_HIGHER:
5582       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
5583       return TRUE;
5584
5585     case BFD_RELOC_HI16_S:
5586     case BFD_RELOC_MICROMIPS_HI16_S:
5587     case BFD_RELOC_MIPS16_HI16_S:
5588       *result = ((operand + 0x8000) >> 16) & 0xffff;
5589       return TRUE;
5590
5591     case BFD_RELOC_HI16:
5592     case BFD_RELOC_MICROMIPS_HI16:
5593     case BFD_RELOC_MIPS16_HI16:
5594       *result = (operand >> 16) & 0xffff;
5595       return TRUE;
5596
5597     case BFD_RELOC_LO16:
5598     case BFD_RELOC_MICROMIPS_LO16:
5599     case BFD_RELOC_MIPS16_LO16:
5600       *result = operand & 0xffff;
5601       return TRUE;
5602
5603     case BFD_RELOC_UNUSED:
5604       *result = operand;
5605       return TRUE;
5606
5607     default:
5608       return FALSE;
5609     }
5610 }
5611
5612 /* Output an instruction.  IP is the instruction information.
5613    ADDRESS_EXPR is an operand of the instruction to be used with
5614    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
5615    a macro expansion.  */
5616
5617 static void
5618 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
5619              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
5620 {
5621   unsigned long prev_pinfo2, pinfo;
5622   bfd_boolean relaxed_branch = FALSE;
5623   enum append_method method;
5624   bfd_boolean relax32;
5625   int branch_disp;
5626
5627   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
5628     fix_loongson2f (ip);
5629
5630   file_ase_mips16 |= mips_opts.mips16;
5631   file_ase_micromips |= mips_opts.micromips;
5632
5633   prev_pinfo2 = history[0].insn_mo->pinfo2;
5634   pinfo = ip->insn_mo->pinfo;
5635
5636   if (mips_opts.micromips
5637       && !expansionp
5638       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
5639            && micromips_insn_length (ip->insn_mo) != 2)
5640           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
5641               && micromips_insn_length (ip->insn_mo) != 4)))
5642     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
5643              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
5644
5645   if (address_expr == NULL)
5646     ip->complete_p = 1;
5647   else if (reloc_type[0] <= BFD_RELOC_UNUSED
5648            && reloc_type[1] == BFD_RELOC_UNUSED
5649            && reloc_type[2] == BFD_RELOC_UNUSED
5650            && address_expr->X_op == O_constant)
5651     {
5652       switch (*reloc_type)
5653         {
5654         case BFD_RELOC_MIPS_JMP:
5655           {
5656             int shift;
5657
5658             shift = mips_opts.micromips ? 1 : 2;
5659             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5660               as_bad (_("jump to misaligned address (0x%lx)"),
5661                       (unsigned long) address_expr->X_add_number);
5662             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5663                                 & 0x3ffffff);
5664             ip->complete_p = 1;
5665           }
5666           break;
5667
5668         case BFD_RELOC_MIPS16_JMP:
5669           if ((address_expr->X_add_number & 3) != 0)
5670             as_bad (_("jump to misaligned address (0x%lx)"),
5671                     (unsigned long) address_expr->X_add_number);
5672           ip->insn_opcode |=
5673             (((address_expr->X_add_number & 0x7c0000) << 3)
5674                | ((address_expr->X_add_number & 0xf800000) >> 7)
5675                | ((address_expr->X_add_number & 0x3fffc) >> 2));
5676           ip->complete_p = 1;
5677           break;
5678
5679         case BFD_RELOC_16_PCREL_S2:
5680           {
5681             int shift;
5682
5683             shift = mips_opts.micromips ? 1 : 2;
5684             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5685               as_bad (_("branch to misaligned address (0x%lx)"),
5686                       (unsigned long) address_expr->X_add_number);
5687             if (!mips_relax_branch)
5688               {
5689                 if ((address_expr->X_add_number + (1 << (shift + 15)))
5690                     & ~((1 << (shift + 16)) - 1))
5691                   as_bad (_("branch address range overflow (0x%lx)"),
5692                           (unsigned long) address_expr->X_add_number);
5693                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5694                                     & 0xffff);
5695               }
5696           }
5697           break;
5698
5699         default:
5700           {
5701             offsetT value;
5702
5703             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
5704                                  &value))
5705               {
5706                 ip->insn_opcode |= value & 0xffff;
5707                 ip->complete_p = 1;
5708               }
5709           }
5710           break;
5711         }
5712     }
5713
5714   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
5715     {
5716       /* There are a lot of optimizations we could do that we don't.
5717          In particular, we do not, in general, reorder instructions.
5718          If you use gcc with optimization, it will reorder
5719          instructions and generally do much more optimization then we
5720          do here; repeating all that work in the assembler would only
5721          benefit hand written assembly code, and does not seem worth
5722          it.  */
5723       int nops = (mips_optimize == 0
5724                   ? nops_for_insn (0, history, NULL)
5725                   : nops_for_insn_or_target (0, history, ip));
5726       if (nops > 0)
5727         {
5728           fragS *old_frag;
5729           unsigned long old_frag_offset;
5730           int i;
5731
5732           old_frag = frag_now;
5733           old_frag_offset = frag_now_fix ();
5734
5735           for (i = 0; i < nops; i++)
5736             add_fixed_insn (NOP_INSN);
5737           insert_into_history (0, nops, NOP_INSN);
5738
5739           if (listing)
5740             {
5741               listing_prev_line ();
5742               /* We may be at the start of a variant frag.  In case we
5743                  are, make sure there is enough space for the frag
5744                  after the frags created by listing_prev_line.  The
5745                  argument to frag_grow here must be at least as large
5746                  as the argument to all other calls to frag_grow in
5747                  this file.  We don't have to worry about being in the
5748                  middle of a variant frag, because the variants insert
5749                  all needed nop instructions themselves.  */
5750               frag_grow (40);
5751             }
5752
5753           mips_move_text_labels ();
5754
5755 #ifndef NO_ECOFF_DEBUGGING
5756           if (ECOFF_DEBUGGING)
5757             ecoff_fix_loc (old_frag, old_frag_offset);
5758 #endif
5759         }
5760     }
5761   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
5762     {
5763       int nops;
5764
5765       /* Work out how many nops in prev_nop_frag are needed by IP,
5766          ignoring hazards generated by the first prev_nop_frag_since
5767          instructions.  */
5768       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
5769       gas_assert (nops <= prev_nop_frag_holds);
5770
5771       /* Enforce NOPS as a minimum.  */
5772       if (nops > prev_nop_frag_required)
5773         prev_nop_frag_required = nops;
5774
5775       if (prev_nop_frag_holds == prev_nop_frag_required)
5776         {
5777           /* Settle for the current number of nops.  Update the history
5778              accordingly (for the benefit of any future .set reorder code).  */
5779           prev_nop_frag = NULL;
5780           insert_into_history (prev_nop_frag_since,
5781                                prev_nop_frag_holds, NOP_INSN);
5782         }
5783       else
5784         {
5785           /* Allow this instruction to replace one of the nops that was
5786              tentatively added to prev_nop_frag.  */
5787           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
5788           prev_nop_frag_holds--;
5789           prev_nop_frag_since++;
5790         }
5791     }
5792
5793   method = get_append_method (ip, address_expr, reloc_type);
5794   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
5795
5796   dwarf2_emit_insn (0);
5797   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
5798      so "move" the instruction address accordingly.
5799
5800      Also, it doesn't seem appropriate for the assembler to reorder .loc
5801      entries.  If this instruction is a branch that we are going to swap
5802      with the previous instruction, the two instructions should be
5803      treated as a unit, and the debug information for both instructions
5804      should refer to the start of the branch sequence.  Using the
5805      current position is certainly wrong when swapping a 32-bit branch
5806      and a 16-bit delay slot, since the current position would then be
5807      in the middle of a branch.  */
5808   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
5809
5810   relax32 = (mips_relax_branch
5811              /* Don't try branch relaxation within .set nomacro, or within
5812                 .set noat if we use $at for PIC computations.  If it turns
5813                 out that the branch was out-of-range, we'll get an error.  */
5814              && !mips_opts.warn_about_macros
5815              && (mips_opts.at || mips_pic == NO_PIC)
5816              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
5817                 as they have no complementing branches.  */
5818              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
5819
5820   if (!HAVE_CODE_COMPRESSION
5821       && address_expr
5822       && relax32
5823       && *reloc_type == BFD_RELOC_16_PCREL_S2
5824       && delayed_branch_p (ip))
5825     {
5826       relaxed_branch = TRUE;
5827       add_relaxed_insn (ip, (relaxed_branch_length
5828                              (NULL, NULL,
5829                               uncond_branch_p (ip) ? -1
5830                               : branch_likely_p (ip) ? 1
5831                               : 0)), 4,
5832                         RELAX_BRANCH_ENCODE
5833                         (AT,
5834                          uncond_branch_p (ip),
5835                          branch_likely_p (ip),
5836                          pinfo & INSN_WRITE_GPR_31,
5837                          0),
5838                         address_expr->X_add_symbol,
5839                         address_expr->X_add_number);
5840       *reloc_type = BFD_RELOC_UNUSED;
5841     }
5842   else if (mips_opts.micromips
5843            && address_expr
5844            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
5845                || *reloc_type > BFD_RELOC_UNUSED)
5846            && (delayed_branch_p (ip) || compact_branch_p (ip))
5847            /* Don't try branch relaxation when users specify
5848               16-bit/32-bit instructions.  */
5849            && !forced_insn_length)
5850     {
5851       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
5852       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
5853       int uncond = uncond_branch_p (ip) ? -1 : 0;
5854       int compact = compact_branch_p (ip);
5855       int al = pinfo & INSN_WRITE_GPR_31;
5856       int length32;
5857
5858       gas_assert (address_expr != NULL);
5859       gas_assert (!mips_relax.sequence);
5860
5861       relaxed_branch = TRUE;
5862       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
5863       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
5864                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
5865                                                 relax32, 0, 0),
5866                         address_expr->X_add_symbol,
5867                         address_expr->X_add_number);
5868       *reloc_type = BFD_RELOC_UNUSED;
5869     }
5870   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
5871     {
5872       /* We need to set up a variant frag.  */
5873       gas_assert (address_expr != NULL);
5874       add_relaxed_insn (ip, 4, 0,
5875                         RELAX_MIPS16_ENCODE
5876                         (*reloc_type - BFD_RELOC_UNUSED,
5877                          forced_insn_length == 2, forced_insn_length == 4,
5878                          delayed_branch_p (&history[0]),
5879                          history[0].mips16_absolute_jump_p),
5880                         make_expr_symbol (address_expr), 0);
5881     }
5882   else if (mips_opts.mips16 && insn_length (ip) == 2)
5883     {
5884       if (!delayed_branch_p (ip))
5885         /* Make sure there is enough room to swap this instruction with
5886            a following jump instruction.  */
5887         frag_grow (6);
5888       add_fixed_insn (ip);
5889     }
5890   else
5891     {
5892       if (mips_opts.mips16
5893           && mips_opts.noreorder
5894           && delayed_branch_p (&history[0]))
5895         as_warn (_("extended instruction in delay slot"));
5896
5897       if (mips_relax.sequence)
5898         {
5899           /* If we've reached the end of this frag, turn it into a variant
5900              frag and record the information for the instructions we've
5901              written so far.  */
5902           if (frag_room () < 4)
5903             relax_close_frag ();
5904           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
5905         }
5906
5907       if (mips_relax.sequence != 2)
5908         {
5909           if (mips_macro_warning.first_insn_sizes[0] == 0)
5910             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
5911           mips_macro_warning.sizes[0] += insn_length (ip);
5912           mips_macro_warning.insns[0]++;
5913         }
5914       if (mips_relax.sequence != 1)
5915         {
5916           if (mips_macro_warning.first_insn_sizes[1] == 0)
5917             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
5918           mips_macro_warning.sizes[1] += insn_length (ip);
5919           mips_macro_warning.insns[1]++;
5920         }
5921
5922       if (mips_opts.mips16)
5923         {
5924           ip->fixed_p = 1;
5925           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
5926         }
5927       add_fixed_insn (ip);
5928     }
5929
5930   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
5931     {
5932       bfd_reloc_code_real_type final_type[3];
5933       reloc_howto_type *howto0;
5934       reloc_howto_type *howto;
5935       int i;
5936
5937       /* Perform any necessary conversion to microMIPS relocations
5938          and find out how many relocations there actually are.  */
5939       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
5940         final_type[i] = micromips_map_reloc (reloc_type[i]);
5941
5942       /* In a compound relocation, it is the final (outermost)
5943          operator that determines the relocated field.  */
5944       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
5945       if (!howto)
5946         abort ();
5947
5948       if (i > 1)
5949         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
5950       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
5951                                  bfd_get_reloc_size (howto),
5952                                  address_expr,
5953                                  howto0 && howto0->pc_relative,
5954                                  final_type[0]);
5955
5956       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
5957       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
5958         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
5959
5960       /* These relocations can have an addend that won't fit in
5961          4 octets for 64bit assembly.  */
5962       if (HAVE_64BIT_GPRS
5963           && ! howto->partial_inplace
5964           && (reloc_type[0] == BFD_RELOC_16
5965               || reloc_type[0] == BFD_RELOC_32
5966               || reloc_type[0] == BFD_RELOC_MIPS_JMP
5967               || reloc_type[0] == BFD_RELOC_GPREL16
5968               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
5969               || reloc_type[0] == BFD_RELOC_GPREL32
5970               || reloc_type[0] == BFD_RELOC_64
5971               || reloc_type[0] == BFD_RELOC_CTOR
5972               || reloc_type[0] == BFD_RELOC_MIPS_SUB
5973               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
5974               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
5975               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
5976               || reloc_type[0] == BFD_RELOC_MIPS_REL16
5977               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
5978               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
5979               || hi16_reloc_p (reloc_type[0])
5980               || lo16_reloc_p (reloc_type[0])))
5981         ip->fixp[0]->fx_no_overflow = 1;
5982
5983       /* These relocations can have an addend that won't fit in 2 octets.  */
5984       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
5985           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
5986         ip->fixp[0]->fx_no_overflow = 1;
5987
5988       if (mips_relax.sequence)
5989         {
5990           if (mips_relax.first_fixup == 0)
5991             mips_relax.first_fixup = ip->fixp[0];
5992         }
5993       else if (reloc_needs_lo_p (*reloc_type))
5994         {
5995           struct mips_hi_fixup *hi_fixup;
5996
5997           /* Reuse the last entry if it already has a matching %lo.  */
5998           hi_fixup = mips_hi_fixup_list;
5999           if (hi_fixup == 0
6000               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6001             {
6002               hi_fixup = ((struct mips_hi_fixup *)
6003                           xmalloc (sizeof (struct mips_hi_fixup)));
6004               hi_fixup->next = mips_hi_fixup_list;
6005               mips_hi_fixup_list = hi_fixup;
6006             }
6007           hi_fixup->fixp = ip->fixp[0];
6008           hi_fixup->seg = now_seg;
6009         }
6010
6011       /* Add fixups for the second and third relocations, if given.
6012          Note that the ABI allows the second relocation to be
6013          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6014          moment we only use RSS_UNDEF, but we could add support
6015          for the others if it ever becomes necessary.  */
6016       for (i = 1; i < 3; i++)
6017         if (reloc_type[i] != BFD_RELOC_UNUSED)
6018           {
6019             ip->fixp[i] = fix_new (ip->frag, ip->where,
6020                                    ip->fixp[0]->fx_size, NULL, 0,
6021                                    FALSE, final_type[i]);
6022
6023             /* Use fx_tcbit to mark compound relocs.  */
6024             ip->fixp[0]->fx_tcbit = 1;
6025             ip->fixp[i]->fx_tcbit = 1;
6026           }
6027     }
6028   install_insn (ip);
6029
6030   /* Update the register mask information.  */
6031   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6032   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6033
6034   switch (method)
6035     {
6036     case APPEND_ADD:
6037       insert_into_history (0, 1, ip);
6038       break;
6039
6040     case APPEND_ADD_WITH_NOP:
6041       {
6042         struct mips_cl_insn *nop;
6043
6044         insert_into_history (0, 1, ip);
6045         nop = get_delay_slot_nop (ip);
6046         add_fixed_insn (nop);
6047         insert_into_history (0, 1, nop);
6048         if (mips_relax.sequence)
6049           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6050       }
6051       break;
6052
6053     case APPEND_ADD_COMPACT:
6054       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6055       gas_assert (mips_opts.mips16);
6056       ip->insn_opcode |= 0x0080;
6057       find_altered_mips16_opcode (ip);
6058       install_insn (ip);
6059       insert_into_history (0, 1, ip);
6060       break;
6061
6062     case APPEND_SWAP:
6063       {
6064         struct mips_cl_insn delay = history[0];
6065         if (mips_opts.mips16)
6066           {
6067             know (delay.frag == ip->frag);
6068             move_insn (ip, delay.frag, delay.where);
6069             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6070           }
6071         else if (relaxed_branch || delay.frag != ip->frag)
6072           {
6073             /* Add the delay slot instruction to the end of the
6074                current frag and shrink the fixed part of the
6075                original frag.  If the branch occupies the tail of
6076                the latter, move it backwards to cover the gap.  */
6077             delay.frag->fr_fix -= branch_disp;
6078             if (delay.frag == ip->frag)
6079               move_insn (ip, ip->frag, ip->where - branch_disp);
6080             add_fixed_insn (&delay);
6081           }
6082         else
6083           {
6084             move_insn (&delay, ip->frag,
6085                        ip->where - branch_disp + insn_length (ip));
6086             move_insn (ip, history[0].frag, history[0].where);
6087           }
6088         history[0] = *ip;
6089         delay.fixed_p = 1;
6090         insert_into_history (0, 1, &delay);
6091       }
6092       break;
6093     }
6094
6095   /* If we have just completed an unconditional branch, clear the history.  */
6096   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6097       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6098     {
6099       unsigned int i;
6100
6101       mips_no_prev_insn ();
6102
6103       for (i = 0; i < ARRAY_SIZE (history); i++)
6104         history[i].cleared_p = 1;
6105     }
6106
6107   /* We need to emit a label at the end of branch-likely macros.  */
6108   if (emit_branch_likely_macro)
6109     {
6110       emit_branch_likely_macro = FALSE;
6111       micromips_add_label ();
6112     }
6113
6114   /* We just output an insn, so the next one doesn't have a label.  */
6115   mips_clear_insn_labels ();
6116 }
6117
6118 /* Forget that there was any previous instruction or label.
6119    When BRANCH is true, the branch history is also flushed.  */
6120
6121 static void
6122 mips_no_prev_insn (void)
6123 {
6124   prev_nop_frag = NULL;
6125   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6126   mips_clear_insn_labels ();
6127 }
6128
6129 /* This function must be called before we emit something other than
6130    instructions.  It is like mips_no_prev_insn except that it inserts
6131    any NOPS that might be needed by previous instructions.  */
6132
6133 void
6134 mips_emit_delays (void)
6135 {
6136   if (! mips_opts.noreorder)
6137     {
6138       int nops = nops_for_insn (0, history, NULL);
6139       if (nops > 0)
6140         {
6141           while (nops-- > 0)
6142             add_fixed_insn (NOP_INSN);
6143           mips_move_text_labels ();
6144         }
6145     }
6146   mips_no_prev_insn ();
6147 }
6148
6149 /* Start a (possibly nested) noreorder block.  */
6150
6151 static void
6152 start_noreorder (void)
6153 {
6154   if (mips_opts.noreorder == 0)
6155     {
6156       unsigned int i;
6157       int nops;
6158
6159       /* None of the instructions before the .set noreorder can be moved.  */
6160       for (i = 0; i < ARRAY_SIZE (history); i++)
6161         history[i].fixed_p = 1;
6162
6163       /* Insert any nops that might be needed between the .set noreorder
6164          block and the previous instructions.  We will later remove any
6165          nops that turn out not to be needed.  */
6166       nops = nops_for_insn (0, history, NULL);
6167       if (nops > 0)
6168         {
6169           if (mips_optimize != 0)
6170             {
6171               /* Record the frag which holds the nop instructions, so
6172                  that we can remove them if we don't need them.  */
6173               frag_grow (nops * NOP_INSN_SIZE);
6174               prev_nop_frag = frag_now;
6175               prev_nop_frag_holds = nops;
6176               prev_nop_frag_required = 0;
6177               prev_nop_frag_since = 0;
6178             }
6179
6180           for (; nops > 0; --nops)
6181             add_fixed_insn (NOP_INSN);
6182
6183           /* Move on to a new frag, so that it is safe to simply
6184              decrease the size of prev_nop_frag.  */
6185           frag_wane (frag_now);
6186           frag_new (0);
6187           mips_move_text_labels ();
6188         }
6189       mips_mark_labels ();
6190       mips_clear_insn_labels ();
6191     }
6192   mips_opts.noreorder++;
6193   mips_any_noreorder = 1;
6194 }
6195
6196 /* End a nested noreorder block.  */
6197
6198 static void
6199 end_noreorder (void)
6200 {
6201   mips_opts.noreorder--;
6202   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6203     {
6204       /* Commit to inserting prev_nop_frag_required nops and go back to
6205          handling nop insertion the .set reorder way.  */
6206       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6207                                 * NOP_INSN_SIZE);
6208       insert_into_history (prev_nop_frag_since,
6209                            prev_nop_frag_required, NOP_INSN);
6210       prev_nop_frag = NULL;
6211     }
6212 }
6213
6214 /* Set up global variables for the start of a new macro.  */
6215
6216 static void
6217 macro_start (void)
6218 {
6219   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
6220   memset (&mips_macro_warning.first_insn_sizes, 0,
6221           sizeof (mips_macro_warning.first_insn_sizes));
6222   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
6223   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
6224                                      && delayed_branch_p (&history[0]));
6225   switch (history[0].insn_mo->pinfo2
6226           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
6227     {
6228     case INSN2_BRANCH_DELAY_32BIT:
6229       mips_macro_warning.delay_slot_length = 4;
6230       break;
6231     case INSN2_BRANCH_DELAY_16BIT:
6232       mips_macro_warning.delay_slot_length = 2;
6233       break;
6234     default:
6235       mips_macro_warning.delay_slot_length = 0;
6236       break;
6237     }
6238   mips_macro_warning.first_frag = NULL;
6239 }
6240
6241 /* Given that a macro is longer than one instruction or of the wrong size,
6242    return the appropriate warning for it.  Return null if no warning is
6243    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
6244    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
6245    and RELAX_NOMACRO.  */
6246
6247 static const char *
6248 macro_warning (relax_substateT subtype)
6249 {
6250   if (subtype & RELAX_DELAY_SLOT)
6251     return _("Macro instruction expanded into multiple instructions"
6252              " in a branch delay slot");
6253   else if (subtype & RELAX_NOMACRO)
6254     return _("Macro instruction expanded into multiple instructions");
6255   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
6256                       | RELAX_DELAY_SLOT_SIZE_SECOND))
6257     return ((subtype & RELAX_DELAY_SLOT_16BIT)
6258             ? _("Macro instruction expanded into a wrong size instruction"
6259                 " in a 16-bit branch delay slot")
6260             : _("Macro instruction expanded into a wrong size instruction"
6261                 " in a 32-bit branch delay slot"));
6262   else
6263     return 0;
6264 }
6265
6266 /* Finish up a macro.  Emit warnings as appropriate.  */
6267
6268 static void
6269 macro_end (void)
6270 {
6271   /* Relaxation warning flags.  */
6272   relax_substateT subtype = 0;
6273
6274   /* Check delay slot size requirements.  */
6275   if (mips_macro_warning.delay_slot_length == 2)
6276     subtype |= RELAX_DELAY_SLOT_16BIT;
6277   if (mips_macro_warning.delay_slot_length != 0)
6278     {
6279       if (mips_macro_warning.delay_slot_length
6280           != mips_macro_warning.first_insn_sizes[0])
6281         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
6282       if (mips_macro_warning.delay_slot_length
6283           != mips_macro_warning.first_insn_sizes[1])
6284         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
6285     }
6286
6287   /* Check instruction count requirements.  */
6288   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
6289     {
6290       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
6291         subtype |= RELAX_SECOND_LONGER;
6292       if (mips_opts.warn_about_macros)
6293         subtype |= RELAX_NOMACRO;
6294       if (mips_macro_warning.delay_slot_p)
6295         subtype |= RELAX_DELAY_SLOT;
6296     }
6297
6298   /* If both alternatives fail to fill a delay slot correctly,
6299      emit the warning now.  */
6300   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
6301       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
6302     {
6303       relax_substateT s;
6304       const char *msg;
6305
6306       s = subtype & (RELAX_DELAY_SLOT_16BIT
6307                      | RELAX_DELAY_SLOT_SIZE_FIRST
6308                      | RELAX_DELAY_SLOT_SIZE_SECOND);
6309       msg = macro_warning (s);
6310       if (msg != NULL)
6311         as_warn ("%s", msg);
6312       subtype &= ~s;
6313     }
6314
6315   /* If both implementations are longer than 1 instruction, then emit the
6316      warning now.  */
6317   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
6318     {
6319       relax_substateT s;
6320       const char *msg;
6321
6322       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
6323       msg = macro_warning (s);
6324       if (msg != NULL)
6325         as_warn ("%s", msg);
6326       subtype &= ~s;
6327     }
6328
6329   /* If any flags still set, then one implementation might need a warning
6330      and the other either will need one of a different kind or none at all.
6331      Pass any remaining flags over to relaxation.  */
6332   if (mips_macro_warning.first_frag != NULL)
6333     mips_macro_warning.first_frag->fr_subtype |= subtype;
6334 }
6335
6336 /* Instruction operand formats used in macros that vary between
6337    standard MIPS and microMIPS code.  */
6338
6339 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
6340 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
6341 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
6342 static const char * const lui_fmt[2] = { "t,u", "s,u" };
6343 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
6344 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
6345 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
6346 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
6347
6348 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
6349 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
6350 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
6351 #define LUI_FMT (lui_fmt[mips_opts.micromips])
6352 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
6353 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
6354 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
6355 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
6356
6357 /* Read a macro's relocation codes from *ARGS and store them in *R.
6358    The first argument in *ARGS will be either the code for a single
6359    relocation or -1 followed by the three codes that make up a
6360    composite relocation.  */
6361
6362 static void
6363 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
6364 {
6365   int i, next;
6366
6367   next = va_arg (*args, int);
6368   if (next >= 0)
6369     r[0] = (bfd_reloc_code_real_type) next;
6370   else
6371     {
6372       for (i = 0; i < 3; i++)
6373         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
6374       /* This function is only used for 16-bit relocation fields.
6375          To make the macro code simpler, treat an unrelocated value
6376          in the same way as BFD_RELOC_LO16.  */
6377       if (r[0] == BFD_RELOC_UNUSED)
6378         r[0] = BFD_RELOC_LO16;
6379     }
6380 }
6381
6382 /* Build an instruction created by a macro expansion.  This is passed
6383    a pointer to the count of instructions created so far, an
6384    expression, the name of the instruction to build, an operand format
6385    string, and corresponding arguments.  */
6386
6387 static void
6388 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
6389 {
6390   const struct mips_opcode *mo = NULL;
6391   bfd_reloc_code_real_type r[3];
6392   const struct mips_opcode *amo;
6393   const struct mips_operand *operand;
6394   struct hash_control *hash;
6395   struct mips_cl_insn insn;
6396   va_list args;
6397   unsigned int uval;
6398
6399   va_start (args, fmt);
6400
6401   if (mips_opts.mips16)
6402     {
6403       mips16_macro_build (ep, name, fmt, &args);
6404       va_end (args);
6405       return;
6406     }
6407
6408   r[0] = BFD_RELOC_UNUSED;
6409   r[1] = BFD_RELOC_UNUSED;
6410   r[2] = BFD_RELOC_UNUSED;
6411   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
6412   amo = (struct mips_opcode *) hash_find (hash, name);
6413   gas_assert (amo);
6414   gas_assert (strcmp (name, amo->name) == 0);
6415
6416   do
6417     {
6418       /* Search until we get a match for NAME.  It is assumed here that
6419          macros will never generate MDMX, MIPS-3D, or MT instructions.
6420          We try to match an instruction that fulfils the branch delay
6421          slot instruction length requirement (if any) of the previous
6422          instruction.  While doing this we record the first instruction
6423          seen that matches all the other conditions and use it anyway
6424          if the requirement cannot be met; we will issue an appropriate
6425          warning later on.  */
6426       if (strcmp (fmt, amo->args) == 0
6427           && amo->pinfo != INSN_MACRO
6428           && is_opcode_valid (amo)
6429           && is_size_valid (amo))
6430         {
6431           if (is_delay_slot_valid (amo))
6432             {
6433               mo = amo;
6434               break;
6435             }
6436           else if (!mo)
6437             mo = amo;
6438         }
6439
6440       ++amo;
6441       gas_assert (amo->name);
6442     }
6443   while (strcmp (name, amo->name) == 0);
6444
6445   gas_assert (mo);
6446   create_insn (&insn, mo);
6447   for (; *fmt; ++fmt)
6448     {
6449       switch (*fmt)
6450         {
6451         case ',':
6452         case '(':
6453         case ')':
6454         case 'z':
6455           break;
6456
6457         case 'i':
6458         case 'j':
6459           macro_read_relocs (&args, r);
6460           gas_assert (*r == BFD_RELOC_GPREL16
6461                       || *r == BFD_RELOC_MIPS_HIGHER
6462                       || *r == BFD_RELOC_HI16_S
6463                       || *r == BFD_RELOC_LO16
6464                       || *r == BFD_RELOC_MIPS_GOT_OFST);
6465           break;
6466
6467         case 'o':
6468           macro_read_relocs (&args, r);
6469           break;
6470
6471         case 'u':
6472           macro_read_relocs (&args, r);
6473           gas_assert (ep != NULL
6474                       && (ep->X_op == O_constant
6475                           || (ep->X_op == O_symbol
6476                               && (*r == BFD_RELOC_MIPS_HIGHEST
6477                                   || *r == BFD_RELOC_HI16_S
6478                                   || *r == BFD_RELOC_HI16
6479                                   || *r == BFD_RELOC_GPREL16
6480                                   || *r == BFD_RELOC_MIPS_GOT_HI16
6481                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
6482           break;
6483
6484         case 'p':
6485           gas_assert (ep != NULL);
6486
6487           /*
6488            * This allows macro() to pass an immediate expression for
6489            * creating short branches without creating a symbol.
6490            *
6491            * We don't allow branch relaxation for these branches, as
6492            * they should only appear in ".set nomacro" anyway.
6493            */
6494           if (ep->X_op == O_constant)
6495             {
6496               /* For microMIPS we always use relocations for branches.
6497                  So we should not resolve immediate values.  */
6498               gas_assert (!mips_opts.micromips);
6499
6500               if ((ep->X_add_number & 3) != 0)
6501                 as_bad (_("branch to misaligned address (0x%lx)"),
6502                         (unsigned long) ep->X_add_number);
6503               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
6504                 as_bad (_("branch address range overflow (0x%lx)"),
6505                         (unsigned long) ep->X_add_number);
6506               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
6507               ep = NULL;
6508             }
6509           else
6510             *r = BFD_RELOC_16_PCREL_S2;
6511           break;
6512
6513         case 'a':
6514           gas_assert (ep != NULL);
6515           *r = BFD_RELOC_MIPS_JMP;
6516           break;
6517
6518         default:
6519           operand = (mips_opts.micromips
6520                      ? decode_micromips_operand (fmt)
6521                      : decode_mips_operand (fmt));
6522           if (!operand)
6523             abort ();
6524
6525           uval = va_arg (args, int);
6526           if (operand->type == OP_CLO_CLZ_DEST)
6527             uval |= (uval << 5);
6528           insn_insert_operand (&insn, operand, uval);
6529
6530           if (*fmt == '+' || *fmt == 'm')
6531             ++fmt;
6532           break;
6533         }
6534     }
6535   va_end (args);
6536   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6537
6538   append_insn (&insn, ep, r, TRUE);
6539 }
6540
6541 static void
6542 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
6543                     va_list *args)
6544 {
6545   struct mips_opcode *mo;
6546   struct mips_cl_insn insn;
6547   const struct mips_operand *operand;
6548   bfd_reloc_code_real_type r[3]
6549     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
6550
6551   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
6552   gas_assert (mo);
6553   gas_assert (strcmp (name, mo->name) == 0);
6554
6555   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
6556     {
6557       ++mo;
6558       gas_assert (mo->name);
6559       gas_assert (strcmp (name, mo->name) == 0);
6560     }
6561
6562   create_insn (&insn, mo);
6563   for (; *fmt; ++fmt)
6564     {
6565       int c;
6566
6567       c = *fmt;
6568       switch (c)
6569         {
6570         case ',':
6571         case '(':
6572         case ')':
6573           break;
6574
6575         case '0':
6576         case 'S':
6577         case 'P':
6578         case 'R':
6579           break;
6580
6581         case '<':
6582         case '>':
6583         case '4':
6584         case '5':
6585         case 'H':
6586         case 'W':
6587         case 'D':
6588         case 'j':
6589         case '8':
6590         case 'V':
6591         case 'C':
6592         case 'U':
6593         case 'k':
6594         case 'K':
6595         case 'p':
6596         case 'q':
6597           {
6598             offsetT value;
6599
6600             gas_assert (ep != NULL);
6601
6602             if (ep->X_op != O_constant)
6603               *r = (int) BFD_RELOC_UNUSED + c;
6604             else if (calculate_reloc (*r, ep->X_add_number, &value))
6605               {
6606                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
6607                 ep = NULL;
6608                 *r = BFD_RELOC_UNUSED;
6609               }
6610           }
6611           break;
6612
6613         default:
6614           operand = decode_mips16_operand (c, FALSE);
6615           if (!operand)
6616             abort ();
6617
6618           insn_insert_operand (&insn, operand, va_arg (args, int));
6619           break;
6620         }
6621     }
6622
6623   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6624
6625   append_insn (&insn, ep, r, TRUE);
6626 }
6627
6628 /*
6629  * Sign-extend 32-bit mode constants that have bit 31 set and all
6630  * higher bits unset.
6631  */
6632 static void
6633 normalize_constant_expr (expressionS *ex)
6634 {
6635   if (ex->X_op == O_constant
6636       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6637     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6638                         - 0x80000000);
6639 }
6640
6641 /*
6642  * Sign-extend 32-bit mode address offsets that have bit 31 set and
6643  * all higher bits unset.
6644  */
6645 static void
6646 normalize_address_expr (expressionS *ex)
6647 {
6648   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
6649         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
6650       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6651     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6652                         - 0x80000000);
6653 }
6654
6655 /*
6656  * Generate a "jalr" instruction with a relocation hint to the called
6657  * function.  This occurs in NewABI PIC code.
6658  */
6659 static void
6660 macro_build_jalr (expressionS *ep, int cprestore)
6661 {
6662   static const bfd_reloc_code_real_type jalr_relocs[2]
6663     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
6664   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
6665   const char *jalr;
6666   char *f = NULL;
6667
6668   if (MIPS_JALR_HINT_P (ep))
6669     {
6670       frag_grow (8);
6671       f = frag_more (0);
6672     }
6673   if (mips_opts.micromips)
6674     {
6675       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
6676               ? "jalr" : "jalrs");
6677       if (MIPS_JALR_HINT_P (ep)
6678           || mips_opts.insn32
6679           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6680         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
6681       else
6682         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
6683     }
6684   else
6685     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
6686   if (MIPS_JALR_HINT_P (ep))
6687     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
6688 }
6689
6690 /*
6691  * Generate a "lui" instruction.
6692  */
6693 static void
6694 macro_build_lui (expressionS *ep, int regnum)
6695 {
6696   gas_assert (! mips_opts.mips16);
6697
6698   if (ep->X_op != O_constant)
6699     {
6700       gas_assert (ep->X_op == O_symbol);
6701       /* _gp_disp is a special case, used from s_cpload.
6702          __gnu_local_gp is used if mips_no_shared.  */
6703       gas_assert (mips_pic == NO_PIC
6704               || (! HAVE_NEWABI
6705                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
6706               || (! mips_in_shared
6707                   && strcmp (S_GET_NAME (ep->X_add_symbol),
6708                              "__gnu_local_gp") == 0));
6709     }
6710
6711   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
6712 }
6713
6714 /* Generate a sequence of instructions to do a load or store from a constant
6715    offset off of a base register (breg) into/from a target register (treg),
6716    using AT if necessary.  */
6717 static void
6718 macro_build_ldst_constoffset (expressionS *ep, const char *op,
6719                               int treg, int breg, int dbl)
6720 {
6721   gas_assert (ep->X_op == O_constant);
6722
6723   /* Sign-extending 32-bit constants makes their handling easier.  */
6724   if (!dbl)
6725     normalize_constant_expr (ep);
6726
6727   /* Right now, this routine can only handle signed 32-bit constants.  */
6728   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
6729     as_warn (_("operand overflow"));
6730
6731   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
6732     {
6733       /* Signed 16-bit offset will fit in the op.  Easy!  */
6734       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6735     }
6736   else
6737     {
6738       /* 32-bit offset, need multiple instructions and AT, like:
6739            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
6740            addu     $tempreg,$tempreg,$breg
6741            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
6742          to handle the complete offset.  */
6743       macro_build_lui (ep, AT);
6744       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
6745       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
6746
6747       if (!mips_opts.at)
6748         as_bad (_("Macro used $at after \".set noat\""));
6749     }
6750 }
6751
6752 /*                      set_at()
6753  * Generates code to set the $at register to true (one)
6754  * if reg is less than the immediate expression.
6755  */
6756 static void
6757 set_at (int reg, int unsignedp)
6758 {
6759   if (imm_expr.X_op == O_constant
6760       && imm_expr.X_add_number >= -0x8000
6761       && imm_expr.X_add_number < 0x8000)
6762     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
6763                  AT, reg, BFD_RELOC_LO16);
6764   else
6765     {
6766       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6767       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
6768     }
6769 }
6770
6771 /* Count the leading zeroes by performing a binary chop. This is a
6772    bulky bit of source, but performance is a LOT better for the
6773    majority of values than a simple loop to count the bits:
6774        for (lcnt = 0; (lcnt < 32); lcnt++)
6775          if ((v) & (1 << (31 - lcnt)))
6776            break;
6777   However it is not code size friendly, and the gain will drop a bit
6778   on certain cached systems.
6779 */
6780 #define COUNT_TOP_ZEROES(v)             \
6781   (((v) & ~0xffff) == 0                 \
6782    ? ((v) & ~0xff) == 0                 \
6783      ? ((v) & ~0xf) == 0                \
6784        ? ((v) & ~0x3) == 0              \
6785          ? ((v) & ~0x1) == 0            \
6786            ? !(v)                       \
6787              ? 32                       \
6788              : 31                       \
6789            : 30                         \
6790          : ((v) & ~0x7) == 0            \
6791            ? 29                         \
6792            : 28                         \
6793        : ((v) & ~0x3f) == 0             \
6794          ? ((v) & ~0x1f) == 0           \
6795            ? 27                         \
6796            : 26                         \
6797          : ((v) & ~0x7f) == 0           \
6798            ? 25                         \
6799            : 24                         \
6800      : ((v) & ~0xfff) == 0              \
6801        ? ((v) & ~0x3ff) == 0            \
6802          ? ((v) & ~0x1ff) == 0          \
6803            ? 23                         \
6804            : 22                         \
6805          : ((v) & ~0x7ff) == 0          \
6806            ? 21                         \
6807            : 20                         \
6808        : ((v) & ~0x3fff) == 0           \
6809          ? ((v) & ~0x1fff) == 0         \
6810            ? 19                         \
6811            : 18                         \
6812          : ((v) & ~0x7fff) == 0         \
6813            ? 17                         \
6814            : 16                         \
6815    : ((v) & ~0xffffff) == 0             \
6816      ? ((v) & ~0xfffff) == 0            \
6817        ? ((v) & ~0x3ffff) == 0          \
6818          ? ((v) & ~0x1ffff) == 0        \
6819            ? 15                         \
6820            : 14                         \
6821          : ((v) & ~0x7ffff) == 0        \
6822            ? 13                         \
6823            : 12                         \
6824        : ((v) & ~0x3fffff) == 0         \
6825          ? ((v) & ~0x1fffff) == 0       \
6826            ? 11                         \
6827            : 10                         \
6828          : ((v) & ~0x7fffff) == 0       \
6829            ? 9                          \
6830            : 8                          \
6831      : ((v) & ~0xfffffff) == 0          \
6832        ? ((v) & ~0x3ffffff) == 0        \
6833          ? ((v) & ~0x1ffffff) == 0      \
6834            ? 7                          \
6835            : 6                          \
6836          : ((v) & ~0x7ffffff) == 0      \
6837            ? 5                          \
6838            : 4                          \
6839        : ((v) & ~0x3fffffff) == 0       \
6840          ? ((v) & ~0x1fffffff) == 0     \
6841            ? 3                          \
6842            : 2                          \
6843          : ((v) & ~0x7fffffff) == 0     \
6844            ? 1                          \
6845            : 0)
6846
6847 /*                      load_register()
6848  *  This routine generates the least number of instructions necessary to load
6849  *  an absolute expression value into a register.
6850  */
6851 static void
6852 load_register (int reg, expressionS *ep, int dbl)
6853 {
6854   int freg;
6855   expressionS hi32, lo32;
6856
6857   if (ep->X_op != O_big)
6858     {
6859       gas_assert (ep->X_op == O_constant);
6860
6861       /* Sign-extending 32-bit constants makes their handling easier.  */
6862       if (!dbl)
6863         normalize_constant_expr (ep);
6864
6865       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
6866         {
6867           /* We can handle 16 bit signed values with an addiu to
6868              $zero.  No need to ever use daddiu here, since $zero and
6869              the result are always correct in 32 bit mode.  */
6870           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6871           return;
6872         }
6873       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
6874         {
6875           /* We can handle 16 bit unsigned values with an ori to
6876              $zero.  */
6877           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6878           return;
6879         }
6880       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
6881         {
6882           /* 32 bit values require an lui.  */
6883           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6884           if ((ep->X_add_number & 0xffff) != 0)
6885             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6886           return;
6887         }
6888     }
6889
6890   /* The value is larger than 32 bits.  */
6891
6892   if (!dbl || HAVE_32BIT_GPRS)
6893     {
6894       char value[32];
6895
6896       sprintf_vma (value, ep->X_add_number);
6897       as_bad (_("Number (0x%s) larger than 32 bits"), value);
6898       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6899       return;
6900     }
6901
6902   if (ep->X_op != O_big)
6903     {
6904       hi32 = *ep;
6905       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6906       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6907       hi32.X_add_number &= 0xffffffff;
6908       lo32 = *ep;
6909       lo32.X_add_number &= 0xffffffff;
6910     }
6911   else
6912     {
6913       gas_assert (ep->X_add_number > 2);
6914       if (ep->X_add_number == 3)
6915         generic_bignum[3] = 0;
6916       else if (ep->X_add_number > 4)
6917         as_bad (_("Number larger than 64 bits"));
6918       lo32.X_op = O_constant;
6919       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
6920       hi32.X_op = O_constant;
6921       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
6922     }
6923
6924   if (hi32.X_add_number == 0)
6925     freg = 0;
6926   else
6927     {
6928       int shift, bit;
6929       unsigned long hi, lo;
6930
6931       if (hi32.X_add_number == (offsetT) 0xffffffff)
6932         {
6933           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
6934             {
6935               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6936               return;
6937             }
6938           if (lo32.X_add_number & 0x80000000)
6939             {
6940               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6941               if (lo32.X_add_number & 0xffff)
6942                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6943               return;
6944             }
6945         }
6946
6947       /* Check for 16bit shifted constant.  We know that hi32 is
6948          non-zero, so start the mask on the first bit of the hi32
6949          value.  */
6950       shift = 17;
6951       do
6952         {
6953           unsigned long himask, lomask;
6954
6955           if (shift < 32)
6956             {
6957               himask = 0xffff >> (32 - shift);
6958               lomask = (0xffff << shift) & 0xffffffff;
6959             }
6960           else
6961             {
6962               himask = 0xffff << (shift - 32);
6963               lomask = 0;
6964             }
6965           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6966               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6967             {
6968               expressionS tmp;
6969
6970               tmp.X_op = O_constant;
6971               if (shift < 32)
6972                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6973                                     | (lo32.X_add_number >> shift));
6974               else
6975                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
6976               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6977               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6978                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6979               return;
6980             }
6981           ++shift;
6982         }
6983       while (shift <= (64 - 16));
6984
6985       /* Find the bit number of the lowest one bit, and store the
6986          shifted value in hi/lo.  */
6987       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
6988       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
6989       if (lo != 0)
6990         {
6991           bit = 0;
6992           while ((lo & 1) == 0)
6993             {
6994               lo >>= 1;
6995               ++bit;
6996             }
6997           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
6998           hi >>= bit;
6999         }
7000       else
7001         {
7002           bit = 32;
7003           while ((hi & 1) == 0)
7004             {
7005               hi >>= 1;
7006               ++bit;
7007             }
7008           lo = hi;
7009           hi = 0;
7010         }
7011
7012       /* Optimize if the shifted value is a (power of 2) - 1.  */
7013       if ((hi == 0 && ((lo + 1) & lo) == 0)
7014           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
7015         {
7016           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
7017           if (shift != 0)
7018             {
7019               expressionS tmp;
7020
7021               /* This instruction will set the register to be all
7022                  ones.  */
7023               tmp.X_op = O_constant;
7024               tmp.X_add_number = (offsetT) -1;
7025               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7026               if (bit != 0)
7027                 {
7028                   bit += shift;
7029                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7030                                reg, reg, (bit >= 32) ? bit - 32 : bit);
7031                 }
7032               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
7033                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7034               return;
7035             }
7036         }
7037
7038       /* Sign extend hi32 before calling load_register, because we can
7039          generally get better code when we load a sign extended value.  */
7040       if ((hi32.X_add_number & 0x80000000) != 0)
7041         hi32.X_add_number |= ~(offsetT) 0xffffffff;
7042       load_register (reg, &hi32, 0);
7043       freg = reg;
7044     }
7045   if ((lo32.X_add_number & 0xffff0000) == 0)
7046     {
7047       if (freg != 0)
7048         {
7049           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
7050           freg = reg;
7051         }
7052     }
7053   else
7054     {
7055       expressionS mid16;
7056
7057       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
7058         {
7059           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7060           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
7061           return;
7062         }
7063
7064       if (freg != 0)
7065         {
7066           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
7067           freg = reg;
7068         }
7069       mid16 = lo32;
7070       mid16.X_add_number >>= 16;
7071       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7072       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7073       freg = reg;
7074     }
7075   if ((lo32.X_add_number & 0xffff) != 0)
7076     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7077 }
7078
7079 static inline void
7080 load_delay_nop (void)
7081 {
7082   if (!gpr_interlocks)
7083     macro_build (NULL, "nop", "");
7084 }
7085
7086 /* Load an address into a register.  */
7087
7088 static void
7089 load_address (int reg, expressionS *ep, int *used_at)
7090 {
7091   if (ep->X_op != O_constant
7092       && ep->X_op != O_symbol)
7093     {
7094       as_bad (_("expression too complex"));
7095       ep->X_op = O_constant;
7096     }
7097
7098   if (ep->X_op == O_constant)
7099     {
7100       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
7101       return;
7102     }
7103
7104   if (mips_pic == NO_PIC)
7105     {
7106       /* If this is a reference to a GP relative symbol, we want
7107            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
7108          Otherwise we want
7109            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
7110            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7111          If we have an addend, we always use the latter form.
7112
7113          With 64bit address space and a usable $at we want
7114            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7115            lui          $at,<sym>               (BFD_RELOC_HI16_S)
7116            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7117            daddiu       $at,<sym>               (BFD_RELOC_LO16)
7118            dsll32       $reg,0
7119            daddu        $reg,$reg,$at
7120
7121          If $at is already in use, we use a path which is suboptimal
7122          on superscalar processors.
7123            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7124            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7125            dsll         $reg,16
7126            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
7127            dsll         $reg,16
7128            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
7129
7130          For GP relative symbols in 64bit address space we can use
7131          the same sequence as in 32bit address space.  */
7132       if (HAVE_64BIT_SYMBOLS)
7133         {
7134           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7135               && !nopic_need_relax (ep->X_add_symbol, 1))
7136             {
7137               relax_start (ep->X_add_symbol);
7138               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7139                            mips_gp_register, BFD_RELOC_GPREL16);
7140               relax_switch ();
7141             }
7142
7143           if (*used_at == 0 && mips_opts.at)
7144             {
7145               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7146               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
7147               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7148                            BFD_RELOC_MIPS_HIGHER);
7149               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
7150               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
7151               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
7152               *used_at = 1;
7153             }
7154           else
7155             {
7156               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7157               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7158                            BFD_RELOC_MIPS_HIGHER);
7159               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7160               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
7161               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7162               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
7163             }
7164
7165           if (mips_relax.sequence)
7166             relax_end ();
7167         }
7168       else
7169         {
7170           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7171               && !nopic_need_relax (ep->X_add_symbol, 1))
7172             {
7173               relax_start (ep->X_add_symbol);
7174               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7175                            mips_gp_register, BFD_RELOC_GPREL16);
7176               relax_switch ();
7177             }
7178           macro_build_lui (ep, reg);
7179           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
7180                        reg, reg, BFD_RELOC_LO16);
7181           if (mips_relax.sequence)
7182             relax_end ();
7183         }
7184     }
7185   else if (!mips_big_got)
7186     {
7187       expressionS ex;
7188
7189       /* If this is a reference to an external symbol, we want
7190            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7191          Otherwise we want
7192            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7193            nop
7194            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7195          If there is a constant, it must be added in after.
7196
7197          If we have NewABI, we want
7198            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7199          unless we're referencing a global symbol with a non-zero
7200          offset, in which case cst must be added separately.  */
7201       if (HAVE_NEWABI)
7202         {
7203           if (ep->X_add_number)
7204             {
7205               ex.X_add_number = ep->X_add_number;
7206               ep->X_add_number = 0;
7207               relax_start (ep->X_add_symbol);
7208               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7209                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7210               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7211                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7212               ex.X_op = O_constant;
7213               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7214                            reg, reg, BFD_RELOC_LO16);
7215               ep->X_add_number = ex.X_add_number;
7216               relax_switch ();
7217             }
7218           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7219                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7220           if (mips_relax.sequence)
7221             relax_end ();
7222         }
7223       else
7224         {
7225           ex.X_add_number = ep->X_add_number;
7226           ep->X_add_number = 0;
7227           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7228                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7229           load_delay_nop ();
7230           relax_start (ep->X_add_symbol);
7231           relax_switch ();
7232           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7233                        BFD_RELOC_LO16);
7234           relax_end ();
7235
7236           if (ex.X_add_number != 0)
7237             {
7238               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7239                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7240               ex.X_op = O_constant;
7241               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7242                            reg, reg, BFD_RELOC_LO16);
7243             }
7244         }
7245     }
7246   else if (mips_big_got)
7247     {
7248       expressionS ex;
7249
7250       /* This is the large GOT case.  If this is a reference to an
7251          external symbol, we want
7252            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
7253            addu         $reg,$reg,$gp
7254            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
7255
7256          Otherwise, for a reference to a local symbol in old ABI, we want
7257            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7258            nop
7259            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7260          If there is a constant, it must be added in after.
7261
7262          In the NewABI, for local symbols, with or without offsets, we want:
7263            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7264            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7265       */
7266       if (HAVE_NEWABI)
7267         {
7268           ex.X_add_number = ep->X_add_number;
7269           ep->X_add_number = 0;
7270           relax_start (ep->X_add_symbol);
7271           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7272           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7273                        reg, reg, mips_gp_register);
7274           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7275                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7276           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7277             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7278           else if (ex.X_add_number)
7279             {
7280               ex.X_op = O_constant;
7281               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7282                            BFD_RELOC_LO16);
7283             }
7284
7285           ep->X_add_number = ex.X_add_number;
7286           relax_switch ();
7287           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7288                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7289           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7290                        BFD_RELOC_MIPS_GOT_OFST);
7291           relax_end ();
7292         }
7293       else
7294         {
7295           ex.X_add_number = ep->X_add_number;
7296           ep->X_add_number = 0;
7297           relax_start (ep->X_add_symbol);
7298           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7299           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7300                        reg, reg, mips_gp_register);
7301           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7302                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7303           relax_switch ();
7304           if (reg_needs_delay (mips_gp_register))
7305             {
7306               /* We need a nop before loading from $gp.  This special
7307                  check is required because the lui which starts the main
7308                  instruction stream does not refer to $gp, and so will not
7309                  insert the nop which may be required.  */
7310               macro_build (NULL, "nop", "");
7311             }
7312           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7313                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7314           load_delay_nop ();
7315           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7316                        BFD_RELOC_LO16);
7317           relax_end ();
7318
7319           if (ex.X_add_number != 0)
7320             {
7321               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7322                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7323               ex.X_op = O_constant;
7324               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7325                            BFD_RELOC_LO16);
7326             }
7327         }
7328     }
7329   else
7330     abort ();
7331
7332   if (!mips_opts.at && *used_at == 1)
7333     as_bad (_("Macro used $at after \".set noat\""));
7334 }
7335
7336 /* Move the contents of register SOURCE into register DEST.  */
7337
7338 static void
7339 move_register (int dest, int source)
7340 {
7341   /* Prefer to use a 16-bit microMIPS instruction unless the previous
7342      instruction specifically requires a 32-bit one.  */
7343   if (mips_opts.micromips
7344       && !mips_opts.insn32
7345       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7346     macro_build (NULL, "move", "mp,mj", dest, source);
7347   else
7348     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
7349                  dest, source, 0);
7350 }
7351
7352 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
7353    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
7354    The two alternatives are:
7355
7356    Global symbol                Local sybmol
7357    -------------                ------------
7358    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
7359    ...                          ...
7360    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
7361
7362    load_got_offset emits the first instruction and add_got_offset
7363    emits the second for a 16-bit offset or add_got_offset_hilo emits
7364    a sequence to add a 32-bit offset using a scratch register.  */
7365
7366 static void
7367 load_got_offset (int dest, expressionS *local)
7368 {
7369   expressionS global;
7370
7371   global = *local;
7372   global.X_add_number = 0;
7373
7374   relax_start (local->X_add_symbol);
7375   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7376                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7377   relax_switch ();
7378   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7379                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7380   relax_end ();
7381 }
7382
7383 static void
7384 add_got_offset (int dest, expressionS *local)
7385 {
7386   expressionS global;
7387
7388   global.X_op = O_constant;
7389   global.X_op_symbol = NULL;
7390   global.X_add_symbol = NULL;
7391   global.X_add_number = local->X_add_number;
7392
7393   relax_start (local->X_add_symbol);
7394   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
7395                dest, dest, BFD_RELOC_LO16);
7396   relax_switch ();
7397   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
7398   relax_end ();
7399 }
7400
7401 static void
7402 add_got_offset_hilo (int dest, expressionS *local, int tmp)
7403 {
7404   expressionS global;
7405   int hold_mips_optimize;
7406
7407   global.X_op = O_constant;
7408   global.X_op_symbol = NULL;
7409   global.X_add_symbol = NULL;
7410   global.X_add_number = local->X_add_number;
7411
7412   relax_start (local->X_add_symbol);
7413   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
7414   relax_switch ();
7415   /* Set mips_optimize around the lui instruction to avoid
7416      inserting an unnecessary nop after the lw.  */
7417   hold_mips_optimize = mips_optimize;
7418   mips_optimize = 2;
7419   macro_build_lui (&global, tmp);
7420   mips_optimize = hold_mips_optimize;
7421   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
7422   relax_end ();
7423
7424   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
7425 }
7426
7427 /* Emit a sequence of instructions to emulate a branch likely operation.
7428    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
7429    is its complementing branch with the original condition negated.
7430    CALL is set if the original branch specified the link operation.
7431    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
7432
7433    Code like this is produced in the noreorder mode:
7434
7435         BRNEG   <args>, 1f
7436          nop
7437         b       <sym>
7438          delay slot (executed only if branch taken)
7439     1:
7440
7441    or, if CALL is set:
7442
7443         BRNEG   <args>, 1f
7444          nop
7445         bal     <sym>
7446          delay slot (executed only if branch taken)
7447     1:
7448
7449    In the reorder mode the delay slot would be filled with a nop anyway,
7450    so code produced is simply:
7451
7452         BR      <args>, <sym>
7453          nop
7454
7455    This function is used when producing code for the microMIPS ASE that
7456    does not implement branch likely instructions in hardware.  */
7457
7458 static void
7459 macro_build_branch_likely (const char *br, const char *brneg,
7460                            int call, expressionS *ep, const char *fmt,
7461                            unsigned int sreg, unsigned int treg)
7462 {
7463   int noreorder = mips_opts.noreorder;
7464   expressionS expr1;
7465
7466   gas_assert (mips_opts.micromips);
7467   start_noreorder ();
7468   if (noreorder)
7469     {
7470       micromips_label_expr (&expr1);
7471       macro_build (&expr1, brneg, fmt, sreg, treg);
7472       macro_build (NULL, "nop", "");
7473       macro_build (ep, call ? "bal" : "b", "p");
7474
7475       /* Set to true so that append_insn adds a label.  */
7476       emit_branch_likely_macro = TRUE;
7477     }
7478   else
7479     {
7480       macro_build (ep, br, fmt, sreg, treg);
7481       macro_build (NULL, "nop", "");
7482     }
7483   end_noreorder ();
7484 }
7485
7486 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
7487    the condition code tested.  EP specifies the branch target.  */
7488
7489 static void
7490 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
7491 {
7492   const int call = 0;
7493   const char *brneg;
7494   const char *br;
7495
7496   switch (type)
7497     {
7498     case M_BC1FL:
7499       br = "bc1f";
7500       brneg = "bc1t";
7501       break;
7502     case M_BC1TL:
7503       br = "bc1t";
7504       brneg = "bc1f";
7505       break;
7506     case M_BC2FL:
7507       br = "bc2f";
7508       brneg = "bc2t";
7509       break;
7510     case M_BC2TL:
7511       br = "bc2t";
7512       brneg = "bc2f";
7513       break;
7514     default:
7515       abort ();
7516     }
7517   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
7518 }
7519
7520 /* Emit a two-argument branch macro specified by TYPE, using SREG as
7521    the register tested.  EP specifies the branch target.  */
7522
7523 static void
7524 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
7525 {
7526   const char *brneg = NULL;
7527   const char *br;
7528   int call = 0;
7529
7530   switch (type)
7531     {
7532     case M_BGEZ:
7533       br = "bgez";
7534       break;
7535     case M_BGEZL:
7536       br = mips_opts.micromips ? "bgez" : "bgezl";
7537       brneg = "bltz";
7538       break;
7539     case M_BGEZALL:
7540       gas_assert (mips_opts.micromips);
7541       br = mips_opts.insn32 ? "bgezal" : "bgezals";
7542       brneg = "bltz";
7543       call = 1;
7544       break;
7545     case M_BGTZ:
7546       br = "bgtz";
7547       break;
7548     case M_BGTZL:
7549       br = mips_opts.micromips ? "bgtz" : "bgtzl";
7550       brneg = "blez";
7551       break;
7552     case M_BLEZ:
7553       br = "blez";
7554       break;
7555     case M_BLEZL:
7556       br = mips_opts.micromips ? "blez" : "blezl";
7557       brneg = "bgtz";
7558       break;
7559     case M_BLTZ:
7560       br = "bltz";
7561       break;
7562     case M_BLTZL:
7563       br = mips_opts.micromips ? "bltz" : "bltzl";
7564       brneg = "bgez";
7565       break;
7566     case M_BLTZALL:
7567       gas_assert (mips_opts.micromips);
7568       br = mips_opts.insn32 ? "bltzal" : "bltzals";
7569       brneg = "bgez";
7570       call = 1;
7571       break;
7572     default:
7573       abort ();
7574     }
7575   if (mips_opts.micromips && brneg)
7576     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
7577   else
7578     macro_build (ep, br, "s,p", sreg);
7579 }
7580
7581 /* Emit a three-argument branch macro specified by TYPE, using SREG and
7582    TREG as the registers tested.  EP specifies the branch target.  */
7583
7584 static void
7585 macro_build_branch_rsrt (int type, expressionS *ep,
7586                          unsigned int sreg, unsigned int treg)
7587 {
7588   const char *brneg = NULL;
7589   const int call = 0;
7590   const char *br;
7591
7592   switch (type)
7593     {
7594     case M_BEQ:
7595     case M_BEQ_I:
7596       br = "beq";
7597       break;
7598     case M_BEQL:
7599     case M_BEQL_I:
7600       br = mips_opts.micromips ? "beq" : "beql";
7601       brneg = "bne";
7602       break;
7603     case M_BNE:
7604     case M_BNE_I:
7605       br = "bne";
7606       break;
7607     case M_BNEL:
7608     case M_BNEL_I:
7609       br = mips_opts.micromips ? "bne" : "bnel";
7610       brneg = "beq";
7611       break;
7612     default:
7613       abort ();
7614     }
7615   if (mips_opts.micromips && brneg)
7616     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
7617   else
7618     macro_build (ep, br, "s,t,p", sreg, treg);
7619 }
7620
7621 /* Return the high part that should be loaded in order to make the low
7622    part of VALUE accessible using an offset of OFFBITS bits.  */
7623
7624 static offsetT
7625 offset_high_part (offsetT value, unsigned int offbits)
7626 {
7627   offsetT bias;
7628   addressT low_mask;
7629
7630   if (offbits == 0)
7631     return value;
7632   bias = 1 << (offbits - 1);
7633   low_mask = bias * 2 - 1;
7634   return (value + bias) & ~low_mask;
7635 }
7636
7637 /* Return true if the value stored in offset_expr and offset_reloc
7638    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
7639    amount that the caller wants to add without inducing overflow
7640    and ALIGN is the known alignment of the value in bytes.  */
7641
7642 static bfd_boolean
7643 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
7644 {
7645   if (offbits == 16)
7646     {
7647       /* Accept any relocation operator if overflow isn't a concern.  */
7648       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
7649         return TRUE;
7650
7651       /* These relocations are guaranteed not to overflow in correct links.  */
7652       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
7653           || gprel16_reloc_p (*offset_reloc))
7654         return TRUE;
7655     }
7656   if (offset_expr.X_op == O_constant
7657       && offset_high_part (offset_expr.X_add_number, offbits) == 0
7658       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
7659     return TRUE;
7660   return FALSE;
7661 }
7662
7663 /*
7664  *                      Build macros
7665  *   This routine implements the seemingly endless macro or synthesized
7666  * instructions and addressing modes in the mips assembly language. Many
7667  * of these macros are simple and are similar to each other. These could
7668  * probably be handled by some kind of table or grammar approach instead of
7669  * this verbose method. Others are not simple macros but are more like
7670  * optimizing code generation.
7671  *   One interesting optimization is when several store macros appear
7672  * consecutively that would load AT with the upper half of the same address.
7673  * The ensuing load upper instructions are ommited. This implies some kind
7674  * of global optimization. We currently only optimize within a single macro.
7675  *   For many of the load and store macros if the address is specified as a
7676  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
7677  * first load register 'at' with zero and use it as the base register. The
7678  * mips assembler simply uses register $zero. Just one tiny optimization
7679  * we're missing.
7680  */
7681 static void
7682 macro (struct mips_cl_insn *ip, char *str)
7683 {
7684   unsigned int treg, sreg, dreg, breg;
7685   unsigned int tempreg;
7686   int mask;
7687   int used_at = 0;
7688   expressionS label_expr;
7689   expressionS expr1;
7690   expressionS *ep;
7691   const char *s;
7692   const char *s2;
7693   const char *fmt;
7694   int likely = 0;
7695   int coproc = 0;
7696   int offbits = 16;
7697   int call = 0;
7698   int jals = 0;
7699   int dbl = 0;
7700   int imm = 0;
7701   int ust = 0;
7702   int lp = 0;
7703   bfd_boolean large_offset;
7704   int off;
7705   int hold_mips_optimize;
7706   unsigned int align;
7707
7708   gas_assert (! mips_opts.mips16);
7709
7710   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
7711   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
7712   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
7713   mask = ip->insn_mo->mask;
7714
7715   label_expr.X_op = O_constant;
7716   label_expr.X_op_symbol = NULL;
7717   label_expr.X_add_symbol = NULL;
7718   label_expr.X_add_number = 0;
7719
7720   expr1.X_op = O_constant;
7721   expr1.X_op_symbol = NULL;
7722   expr1.X_add_symbol = NULL;
7723   expr1.X_add_number = 1;
7724   align = 1;
7725
7726   switch (mask)
7727     {
7728     case M_DABS:
7729       dbl = 1;
7730     case M_ABS:
7731       /*    bgez    $a0,1f
7732             move    v0,$a0
7733             sub     v0,$zero,$a0
7734          1:
7735        */
7736
7737       start_noreorder ();
7738
7739       if (mips_opts.micromips)
7740         micromips_label_expr (&label_expr);
7741       else
7742         label_expr.X_add_number = 8;
7743       macro_build (&label_expr, "bgez", "s,p", sreg);
7744       if (dreg == sreg)
7745         macro_build (NULL, "nop", "");
7746       else
7747         move_register (dreg, sreg);
7748       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
7749       if (mips_opts.micromips)
7750         micromips_add_label ();
7751
7752       end_noreorder ();
7753       break;
7754
7755     case M_ADD_I:
7756       s = "addi";
7757       s2 = "add";
7758       goto do_addi;
7759     case M_ADDU_I:
7760       s = "addiu";
7761       s2 = "addu";
7762       goto do_addi;
7763     case M_DADD_I:
7764       dbl = 1;
7765       s = "daddi";
7766       s2 = "dadd";
7767       if (!mips_opts.micromips)
7768         goto do_addi;
7769       if (imm_expr.X_op == O_constant
7770           && imm_expr.X_add_number >= -0x200
7771           && imm_expr.X_add_number < 0x200)
7772         {
7773           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
7774           break;
7775         }
7776       goto do_addi_i;
7777     case M_DADDU_I:
7778       dbl = 1;
7779       s = "daddiu";
7780       s2 = "daddu";
7781     do_addi:
7782       if (imm_expr.X_op == O_constant
7783           && imm_expr.X_add_number >= -0x8000
7784           && imm_expr.X_add_number < 0x8000)
7785         {
7786           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
7787           break;
7788         }
7789     do_addi_i:
7790       used_at = 1;
7791       load_register (AT, &imm_expr, dbl);
7792       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7793       break;
7794
7795     case M_AND_I:
7796       s = "andi";
7797       s2 = "and";
7798       goto do_bit;
7799     case M_OR_I:
7800       s = "ori";
7801       s2 = "or";
7802       goto do_bit;
7803     case M_NOR_I:
7804       s = "";
7805       s2 = "nor";
7806       goto do_bit;
7807     case M_XOR_I:
7808       s = "xori";
7809       s2 = "xor";
7810     do_bit:
7811       if (imm_expr.X_op == O_constant
7812           && imm_expr.X_add_number >= 0
7813           && imm_expr.X_add_number < 0x10000)
7814         {
7815           if (mask != M_NOR_I)
7816             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
7817           else
7818             {
7819               macro_build (&imm_expr, "ori", "t,r,i",
7820                            treg, sreg, BFD_RELOC_LO16);
7821               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
7822             }
7823           break;
7824         }
7825
7826       used_at = 1;
7827       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7828       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7829       break;
7830
7831     case M_BALIGN:
7832       switch (imm_expr.X_add_number)
7833         {
7834         case 0:
7835           macro_build (NULL, "nop", "");
7836           break;
7837         case 2:
7838           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
7839           break;
7840         case 1:
7841         case 3:
7842           macro_build (NULL, "balign", "t,s,2", treg, sreg,
7843                        (int) imm_expr.X_add_number);
7844           break;
7845         default:
7846           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
7847                   (unsigned long) imm_expr.X_add_number);
7848           break;
7849         }
7850       break;
7851
7852     case M_BC1FL:
7853     case M_BC1TL:
7854     case M_BC2FL:
7855     case M_BC2TL:
7856       gas_assert (mips_opts.micromips);
7857       macro_build_branch_ccl (mask, &offset_expr,
7858                               EXTRACT_OPERAND (1, BCC, *ip));
7859       break;
7860
7861     case M_BEQ_I:
7862     case M_BEQL_I:
7863     case M_BNE_I:
7864     case M_BNEL_I:
7865       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7866         treg = 0;
7867       else
7868         {
7869           treg = AT;
7870           used_at = 1;
7871           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
7872         }
7873       /* Fall through.  */
7874     case M_BEQL:
7875     case M_BNEL:
7876       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
7877       break;
7878
7879     case M_BGEL:
7880       likely = 1;
7881     case M_BGE:
7882       if (treg == 0)
7883         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
7884       else if (sreg == 0)
7885         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
7886       else
7887         {
7888           used_at = 1;
7889           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7890           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7891                                    &offset_expr, AT, ZERO);
7892         }
7893       break;
7894
7895     case M_BGEZL:
7896     case M_BGEZALL:
7897     case M_BGTZL:
7898     case M_BLEZL:
7899     case M_BLTZL:
7900     case M_BLTZALL:
7901       macro_build_branch_rs (mask, &offset_expr, sreg);
7902       break;
7903
7904     case M_BGTL_I:
7905       likely = 1;
7906     case M_BGT_I:
7907       /* Check for > max integer.  */
7908       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7909         {
7910         do_false:
7911           /* Result is always false.  */
7912           if (! likely)
7913             macro_build (NULL, "nop", "");
7914           else
7915             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
7916           break;
7917         }
7918       if (imm_expr.X_op != O_constant)
7919         as_bad (_("Unsupported large constant"));
7920       ++imm_expr.X_add_number;
7921       /* FALLTHROUGH */
7922     case M_BGE_I:
7923     case M_BGEL_I:
7924       if (mask == M_BGEL_I)
7925         likely = 1;
7926       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7927         {
7928           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
7929                                  &offset_expr, sreg);
7930           break;
7931         }
7932       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7933         {
7934           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
7935                                  &offset_expr, sreg);
7936           break;
7937         }
7938       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
7939         {
7940         do_true:
7941           /* result is always true */
7942           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
7943           macro_build (&offset_expr, "b", "p");
7944           break;
7945         }
7946       used_at = 1;
7947       set_at (sreg, 0);
7948       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7949                                &offset_expr, AT, ZERO);
7950       break;
7951
7952     case M_BGEUL:
7953       likely = 1;
7954     case M_BGEU:
7955       if (treg == 0)
7956         goto do_true;
7957       else if (sreg == 0)
7958         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7959                                  &offset_expr, ZERO, treg);
7960       else
7961         {
7962           used_at = 1;
7963           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7964           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7965                                    &offset_expr, AT, ZERO);
7966         }
7967       break;
7968
7969     case M_BGTUL_I:
7970       likely = 1;
7971     case M_BGTU_I:
7972       if (sreg == 0
7973           || (HAVE_32BIT_GPRS
7974               && imm_expr.X_op == O_constant
7975               && imm_expr.X_add_number == -1))
7976         goto do_false;
7977       if (imm_expr.X_op != O_constant)
7978         as_bad (_("Unsupported large constant"));
7979       ++imm_expr.X_add_number;
7980       /* FALLTHROUGH */
7981     case M_BGEU_I:
7982     case M_BGEUL_I:
7983       if (mask == M_BGEUL_I)
7984         likely = 1;
7985       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7986         goto do_true;
7987       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7988         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7989                                  &offset_expr, sreg, ZERO);
7990       else
7991         {
7992           used_at = 1;
7993           set_at (sreg, 1);
7994           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7995                                    &offset_expr, AT, ZERO);
7996         }
7997       break;
7998
7999     case M_BGTL:
8000       likely = 1;
8001     case M_BGT:
8002       if (treg == 0)
8003         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
8004       else if (sreg == 0)
8005         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
8006       else
8007         {
8008           used_at = 1;
8009           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8010           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8011                                    &offset_expr, AT, ZERO);
8012         }
8013       break;
8014
8015     case M_BGTUL:
8016       likely = 1;
8017     case M_BGTU:
8018       if (treg == 0)
8019         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8020                                  &offset_expr, sreg, ZERO);
8021       else if (sreg == 0)
8022         goto do_false;
8023       else
8024         {
8025           used_at = 1;
8026           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8027           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8028                                    &offset_expr, AT, ZERO);
8029         }
8030       break;
8031
8032     case M_BLEL:
8033       likely = 1;
8034     case M_BLE:
8035       if (treg == 0)
8036         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8037       else if (sreg == 0)
8038         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
8039       else
8040         {
8041           used_at = 1;
8042           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8043           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8044                                    &offset_expr, AT, ZERO);
8045         }
8046       break;
8047
8048     case M_BLEL_I:
8049       likely = 1;
8050     case M_BLE_I:
8051       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8052         goto do_true;
8053       if (imm_expr.X_op != O_constant)
8054         as_bad (_("Unsupported large constant"));
8055       ++imm_expr.X_add_number;
8056       /* FALLTHROUGH */
8057     case M_BLT_I:
8058     case M_BLTL_I:
8059       if (mask == M_BLTL_I)
8060         likely = 1;
8061       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8062         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8063       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8064         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8065       else
8066         {
8067           used_at = 1;
8068           set_at (sreg, 0);
8069           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8070                                    &offset_expr, AT, ZERO);
8071         }
8072       break;
8073
8074     case M_BLEUL:
8075       likely = 1;
8076     case M_BLEU:
8077       if (treg == 0)
8078         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8079                                  &offset_expr, sreg, ZERO);
8080       else if (sreg == 0)
8081         goto do_true;
8082       else
8083         {
8084           used_at = 1;
8085           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8086           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8087                                    &offset_expr, AT, ZERO);
8088         }
8089       break;
8090
8091     case M_BLEUL_I:
8092       likely = 1;
8093     case M_BLEU_I:
8094       if (sreg == 0
8095           || (HAVE_32BIT_GPRS
8096               && imm_expr.X_op == O_constant
8097               && imm_expr.X_add_number == -1))
8098         goto do_true;
8099       if (imm_expr.X_op != O_constant)
8100         as_bad (_("Unsupported large constant"));
8101       ++imm_expr.X_add_number;
8102       /* FALLTHROUGH */
8103     case M_BLTU_I:
8104     case M_BLTUL_I:
8105       if (mask == M_BLTUL_I)
8106         likely = 1;
8107       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8108         goto do_false;
8109       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8110         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8111                                  &offset_expr, sreg, ZERO);
8112       else
8113         {
8114           used_at = 1;
8115           set_at (sreg, 1);
8116           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8117                                    &offset_expr, AT, ZERO);
8118         }
8119       break;
8120
8121     case M_BLTL:
8122       likely = 1;
8123     case M_BLT:
8124       if (treg == 0)
8125         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8126       else if (sreg == 0)
8127         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
8128       else
8129         {
8130           used_at = 1;
8131           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
8132           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8133                                    &offset_expr, AT, ZERO);
8134         }
8135       break;
8136
8137     case M_BLTUL:
8138       likely = 1;
8139     case M_BLTU:
8140       if (treg == 0)
8141         goto do_false;
8142       else if (sreg == 0)
8143         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8144                                  &offset_expr, ZERO, treg);
8145       else
8146         {
8147           used_at = 1;
8148           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
8149           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8150                                    &offset_expr, AT, ZERO);
8151         }
8152       break;
8153
8154     case M_DEXT:
8155       {
8156         /* Use unsigned arithmetic.  */
8157         addressT pos;
8158         addressT size;
8159
8160         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8161           {
8162             as_bad (_("Unsupported large constant"));
8163             pos = size = 1;
8164           }
8165         else
8166           {
8167             pos = imm_expr.X_add_number;
8168             size = imm2_expr.X_add_number;
8169           }
8170
8171         if (pos > 63)
8172           {
8173             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8174             pos = 1;
8175           }
8176         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8177           {
8178             report_bad_field (pos, size);
8179             size = 1;
8180           }
8181
8182         if (size <= 32 && pos < 32)
8183           {
8184             s = "dext";
8185             fmt = "t,r,+A,+C";
8186           }
8187         else if (size <= 32)
8188           {
8189             s = "dextu";
8190             fmt = "t,r,+E,+H";
8191           }
8192         else
8193           {
8194             s = "dextm";
8195             fmt = "t,r,+A,+G";
8196           }
8197         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8198                      (int) (size - 1));
8199       }
8200       break;
8201
8202     case M_DINS:
8203       {
8204         /* Use unsigned arithmetic.  */
8205         addressT pos;
8206         addressT size;
8207
8208         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8209           {
8210             as_bad (_("Unsupported large constant"));
8211             pos = size = 1;
8212           }
8213         else
8214           {
8215             pos = imm_expr.X_add_number;
8216             size = imm2_expr.X_add_number;
8217           }
8218
8219         if (pos > 63)
8220           {
8221             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8222             pos = 1;
8223           }
8224         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8225           {
8226             report_bad_field (pos, size);
8227             size = 1;
8228           }
8229
8230         if (pos < 32 && (pos + size - 1) < 32)
8231           {
8232             s = "dins";
8233             fmt = "t,r,+A,+B";
8234           }
8235         else if (pos >= 32)
8236           {
8237             s = "dinsu";
8238             fmt = "t,r,+E,+F";
8239           }
8240         else
8241           {
8242             s = "dinsm";
8243             fmt = "t,r,+A,+F";
8244           }
8245         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8246                      (int) (pos + size - 1));
8247       }
8248       break;
8249
8250     case M_DDIV_3:
8251       dbl = 1;
8252     case M_DIV_3:
8253       s = "mflo";
8254       goto do_div3;
8255     case M_DREM_3:
8256       dbl = 1;
8257     case M_REM_3:
8258       s = "mfhi";
8259     do_div3:
8260       if (treg == 0)
8261         {
8262           as_warn (_("Divide by zero."));
8263           if (mips_trap)
8264             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8265           else
8266             macro_build (NULL, "break", BRK_FMT, 7);
8267           break;
8268         }
8269
8270       start_noreorder ();
8271       if (mips_trap)
8272         {
8273           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8274           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8275         }
8276       else
8277         {
8278           if (mips_opts.micromips)
8279             micromips_label_expr (&label_expr);
8280           else
8281             label_expr.X_add_number = 8;
8282           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8283           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8284           macro_build (NULL, "break", BRK_FMT, 7);
8285           if (mips_opts.micromips)
8286             micromips_add_label ();
8287         }
8288       expr1.X_add_number = -1;
8289       used_at = 1;
8290       load_register (AT, &expr1, dbl);
8291       if (mips_opts.micromips)
8292         micromips_label_expr (&label_expr);
8293       else
8294         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
8295       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
8296       if (dbl)
8297         {
8298           expr1.X_add_number = 1;
8299           load_register (AT, &expr1, dbl);
8300           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
8301         }
8302       else
8303         {
8304           expr1.X_add_number = 0x80000000;
8305           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
8306         }
8307       if (mips_trap)
8308         {
8309           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
8310           /* We want to close the noreorder block as soon as possible, so
8311              that later insns are available for delay slot filling.  */
8312           end_noreorder ();
8313         }
8314       else
8315         {
8316           if (mips_opts.micromips)
8317             micromips_label_expr (&label_expr);
8318           else
8319             label_expr.X_add_number = 8;
8320           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
8321           macro_build (NULL, "nop", "");
8322
8323           /* We want to close the noreorder block as soon as possible, so
8324              that later insns are available for delay slot filling.  */
8325           end_noreorder ();
8326
8327           macro_build (NULL, "break", BRK_FMT, 6);
8328         }
8329       if (mips_opts.micromips)
8330         micromips_add_label ();
8331       macro_build (NULL, s, MFHL_FMT, dreg);
8332       break;
8333
8334     case M_DIV_3I:
8335       s = "div";
8336       s2 = "mflo";
8337       goto do_divi;
8338     case M_DIVU_3I:
8339       s = "divu";
8340       s2 = "mflo";
8341       goto do_divi;
8342     case M_REM_3I:
8343       s = "div";
8344       s2 = "mfhi";
8345       goto do_divi;
8346     case M_REMU_3I:
8347       s = "divu";
8348       s2 = "mfhi";
8349       goto do_divi;
8350     case M_DDIV_3I:
8351       dbl = 1;
8352       s = "ddiv";
8353       s2 = "mflo";
8354       goto do_divi;
8355     case M_DDIVU_3I:
8356       dbl = 1;
8357       s = "ddivu";
8358       s2 = "mflo";
8359       goto do_divi;
8360     case M_DREM_3I:
8361       dbl = 1;
8362       s = "ddiv";
8363       s2 = "mfhi";
8364       goto do_divi;
8365     case M_DREMU_3I:
8366       dbl = 1;
8367       s = "ddivu";
8368       s2 = "mfhi";
8369     do_divi:
8370       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8371         {
8372           as_warn (_("Divide by zero."));
8373           if (mips_trap)
8374             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8375           else
8376             macro_build (NULL, "break", BRK_FMT, 7);
8377           break;
8378         }
8379       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8380         {
8381           if (strcmp (s2, "mflo") == 0)
8382             move_register (dreg, sreg);
8383           else
8384             move_register (dreg, ZERO);
8385           break;
8386         }
8387       if (imm_expr.X_op == O_constant
8388           && imm_expr.X_add_number == -1
8389           && s[strlen (s) - 1] != 'u')
8390         {
8391           if (strcmp (s2, "mflo") == 0)
8392             {
8393               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
8394             }
8395           else
8396             move_register (dreg, ZERO);
8397           break;
8398         }
8399
8400       used_at = 1;
8401       load_register (AT, &imm_expr, dbl);
8402       macro_build (NULL, s, "z,s,t", sreg, AT);
8403       macro_build (NULL, s2, MFHL_FMT, dreg);
8404       break;
8405
8406     case M_DIVU_3:
8407       s = "divu";
8408       s2 = "mflo";
8409       goto do_divu3;
8410     case M_REMU_3:
8411       s = "divu";
8412       s2 = "mfhi";
8413       goto do_divu3;
8414     case M_DDIVU_3:
8415       s = "ddivu";
8416       s2 = "mflo";
8417       goto do_divu3;
8418     case M_DREMU_3:
8419       s = "ddivu";
8420       s2 = "mfhi";
8421     do_divu3:
8422       start_noreorder ();
8423       if (mips_trap)
8424         {
8425           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8426           macro_build (NULL, s, "z,s,t", sreg, treg);
8427           /* We want to close the noreorder block as soon as possible, so
8428              that later insns are available for delay slot filling.  */
8429           end_noreorder ();
8430         }
8431       else
8432         {
8433           if (mips_opts.micromips)
8434             micromips_label_expr (&label_expr);
8435           else
8436             label_expr.X_add_number = 8;
8437           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8438           macro_build (NULL, s, "z,s,t", sreg, treg);
8439
8440           /* We want to close the noreorder block as soon as possible, so
8441              that later insns are available for delay slot filling.  */
8442           end_noreorder ();
8443           macro_build (NULL, "break", BRK_FMT, 7);
8444           if (mips_opts.micromips)
8445             micromips_add_label ();
8446         }
8447       macro_build (NULL, s2, MFHL_FMT, dreg);
8448       break;
8449
8450     case M_DLCA_AB:
8451       dbl = 1;
8452     case M_LCA_AB:
8453       call = 1;
8454       goto do_la;
8455     case M_DLA_AB:
8456       dbl = 1;
8457     case M_LA_AB:
8458     do_la:
8459       /* Load the address of a symbol into a register.  If breg is not
8460          zero, we then add a base register to it.  */
8461
8462       if (dbl && HAVE_32BIT_GPRS)
8463         as_warn (_("dla used to load 32-bit register"));
8464
8465       if (!dbl && HAVE_64BIT_OBJECTS)
8466         as_warn (_("la used to load 64-bit address"));
8467
8468       if (small_offset_p (0, align, 16))
8469         {
8470           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
8471                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8472           break;
8473         }
8474
8475       if (mips_opts.at && (treg == breg))
8476         {
8477           tempreg = AT;
8478           used_at = 1;
8479         }
8480       else
8481         {
8482           tempreg = treg;
8483         }
8484
8485       if (offset_expr.X_op != O_symbol
8486           && offset_expr.X_op != O_constant)
8487         {
8488           as_bad (_("Expression too complex"));
8489           offset_expr.X_op = O_constant;
8490         }
8491
8492       if (offset_expr.X_op == O_constant)
8493         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
8494       else if (mips_pic == NO_PIC)
8495         {
8496           /* If this is a reference to a GP relative symbol, we want
8497                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
8498              Otherwise we want
8499                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8500                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8501              If we have a constant, we need two instructions anyhow,
8502              so we may as well always use the latter form.
8503
8504              With 64bit address space and a usable $at we want
8505                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8506                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8507                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8508                daddiu   $at,<sym>               (BFD_RELOC_LO16)
8509                dsll32   $tempreg,0
8510                daddu    $tempreg,$tempreg,$at
8511
8512              If $at is already in use, we use a path which is suboptimal
8513              on superscalar processors.
8514                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8515                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8516                dsll     $tempreg,16
8517                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8518                dsll     $tempreg,16
8519                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
8520
8521              For GP relative symbols in 64bit address space we can use
8522              the same sequence as in 32bit address space.  */
8523           if (HAVE_64BIT_SYMBOLS)
8524             {
8525               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8526                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8527                 {
8528                   relax_start (offset_expr.X_add_symbol);
8529                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8530                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8531                   relax_switch ();
8532                 }
8533
8534               if (used_at == 0 && mips_opts.at)
8535                 {
8536                   macro_build (&offset_expr, "lui", LUI_FMT,
8537                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8538                   macro_build (&offset_expr, "lui", LUI_FMT,
8539                                AT, BFD_RELOC_HI16_S);
8540                   macro_build (&offset_expr, "daddiu", "t,r,j",
8541                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8542                   macro_build (&offset_expr, "daddiu", "t,r,j",
8543                                AT, AT, BFD_RELOC_LO16);
8544                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8545                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8546                   used_at = 1;
8547                 }
8548               else
8549                 {
8550                   macro_build (&offset_expr, "lui", LUI_FMT,
8551                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8552                   macro_build (&offset_expr, "daddiu", "t,r,j",
8553                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8554                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8555                   macro_build (&offset_expr, "daddiu", "t,r,j",
8556                                tempreg, tempreg, BFD_RELOC_HI16_S);
8557                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8558                   macro_build (&offset_expr, "daddiu", "t,r,j",
8559                                tempreg, tempreg, BFD_RELOC_LO16);
8560                 }
8561
8562               if (mips_relax.sequence)
8563                 relax_end ();
8564             }
8565           else
8566             {
8567               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8568                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8569                 {
8570                   relax_start (offset_expr.X_add_symbol);
8571                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8572                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8573                   relax_switch ();
8574                 }
8575               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8576                 as_bad (_("Offset too large"));
8577               macro_build_lui (&offset_expr, tempreg);
8578               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8579                            tempreg, tempreg, BFD_RELOC_LO16);
8580               if (mips_relax.sequence)
8581                 relax_end ();
8582             }
8583         }
8584       else if (!mips_big_got && !HAVE_NEWABI)
8585         {
8586           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8587
8588           /* If this is a reference to an external symbol, and there
8589              is no constant, we want
8590                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8591              or for lca or if tempreg is PIC_CALL_REG
8592                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8593              For a local symbol, we want
8594                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8595                nop
8596                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8597
8598              If we have a small constant, and this is a reference to
8599              an external symbol, we want
8600                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8601                nop
8602                addiu    $tempreg,$tempreg,<constant>
8603              For a local symbol, we want the same instruction
8604              sequence, but we output a BFD_RELOC_LO16 reloc on the
8605              addiu instruction.
8606
8607              If we have a large constant, and this is a reference to
8608              an external symbol, we want
8609                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8610                lui      $at,<hiconstant>
8611                addiu    $at,$at,<loconstant>
8612                addu     $tempreg,$tempreg,$at
8613              For a local symbol, we want the same instruction
8614              sequence, but we output a BFD_RELOC_LO16 reloc on the
8615              addiu instruction.
8616            */
8617
8618           if (offset_expr.X_add_number == 0)
8619             {
8620               if (mips_pic == SVR4_PIC
8621                   && breg == 0
8622                   && (call || tempreg == PIC_CALL_REG))
8623                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
8624
8625               relax_start (offset_expr.X_add_symbol);
8626               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8627                            lw_reloc_type, mips_gp_register);
8628               if (breg != 0)
8629                 {
8630                   /* We're going to put in an addu instruction using
8631                      tempreg, so we may as well insert the nop right
8632                      now.  */
8633                   load_delay_nop ();
8634                 }
8635               relax_switch ();
8636               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8637                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
8638               load_delay_nop ();
8639               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8640                            tempreg, tempreg, BFD_RELOC_LO16);
8641               relax_end ();
8642               /* FIXME: If breg == 0, and the next instruction uses
8643                  $tempreg, then if this variant case is used an extra
8644                  nop will be generated.  */
8645             }
8646           else if (offset_expr.X_add_number >= -0x8000
8647                    && offset_expr.X_add_number < 0x8000)
8648             {
8649               load_got_offset (tempreg, &offset_expr);
8650               load_delay_nop ();
8651               add_got_offset (tempreg, &offset_expr);
8652             }
8653           else
8654             {
8655               expr1.X_add_number = offset_expr.X_add_number;
8656               offset_expr.X_add_number =
8657                 SEXT_16BIT (offset_expr.X_add_number);
8658               load_got_offset (tempreg, &offset_expr);
8659               offset_expr.X_add_number = expr1.X_add_number;
8660               /* If we are going to add in a base register, and the
8661                  target register and the base register are the same,
8662                  then we are using AT as a temporary register.  Since
8663                  we want to load the constant into AT, we add our
8664                  current AT (from the global offset table) and the
8665                  register into the register now, and pretend we were
8666                  not using a base register.  */
8667               if (breg == treg)
8668                 {
8669                   load_delay_nop ();
8670                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8671                                treg, AT, breg);
8672                   breg = 0;
8673                   tempreg = treg;
8674                 }
8675               add_got_offset_hilo (tempreg, &offset_expr, AT);
8676               used_at = 1;
8677             }
8678         }
8679       else if (!mips_big_got && HAVE_NEWABI)
8680         {
8681           int add_breg_early = 0;
8682
8683           /* If this is a reference to an external, and there is no
8684              constant, or local symbol (*), with or without a
8685              constant, we want
8686                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8687              or for lca or if tempreg is PIC_CALL_REG
8688                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8689
8690              If we have a small constant, and this is a reference to
8691              an external symbol, we want
8692                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8693                addiu    $tempreg,$tempreg,<constant>
8694
8695              If we have a large constant, and this is a reference to
8696              an external symbol, we want
8697                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8698                lui      $at,<hiconstant>
8699                addiu    $at,$at,<loconstant>
8700                addu     $tempreg,$tempreg,$at
8701
8702              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
8703              local symbols, even though it introduces an additional
8704              instruction.  */
8705
8706           if (offset_expr.X_add_number)
8707             {
8708               expr1.X_add_number = offset_expr.X_add_number;
8709               offset_expr.X_add_number = 0;
8710
8711               relax_start (offset_expr.X_add_symbol);
8712               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8713                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8714
8715               if (expr1.X_add_number >= -0x8000
8716                   && expr1.X_add_number < 0x8000)
8717                 {
8718                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8719                                tempreg, tempreg, BFD_RELOC_LO16);
8720                 }
8721               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8722                 {
8723                   /* If we are going to add in a base register, and the
8724                      target register and the base register are the same,
8725                      then we are using AT as a temporary register.  Since
8726                      we want to load the constant into AT, we add our
8727                      current AT (from the global offset table) and the
8728                      register into the register now, and pretend we were
8729                      not using a base register.  */
8730                   if (breg != treg)
8731                     dreg = tempreg;
8732                   else
8733                     {
8734                       gas_assert (tempreg == AT);
8735                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8736                                    treg, AT, breg);
8737                       dreg = treg;
8738                       add_breg_early = 1;
8739                     }
8740
8741                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8742                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8743                                dreg, dreg, AT);
8744
8745                   used_at = 1;
8746                 }
8747               else
8748                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8749
8750               relax_switch ();
8751               offset_expr.X_add_number = expr1.X_add_number;
8752
8753               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8754                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8755               if (add_breg_early)
8756                 {
8757                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8758                                treg, tempreg, breg);
8759                   breg = 0;
8760                   tempreg = treg;
8761                 }
8762               relax_end ();
8763             }
8764           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
8765             {
8766               relax_start (offset_expr.X_add_symbol);
8767               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8768                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
8769               relax_switch ();
8770               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8771                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8772               relax_end ();
8773             }
8774           else
8775             {
8776               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8777                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8778             }
8779         }
8780       else if (mips_big_got && !HAVE_NEWABI)
8781         {
8782           int gpdelay;
8783           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8784           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8785           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8786
8787           /* This is the large GOT case.  If this is a reference to an
8788              external symbol, and there is no constant, we want
8789                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8790                addu     $tempreg,$tempreg,$gp
8791                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8792              or for lca or if tempreg is PIC_CALL_REG
8793                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8794                addu     $tempreg,$tempreg,$gp
8795                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8796              For a local symbol, we want
8797                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8798                nop
8799                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8800
8801              If we have a small constant, and this is a reference to
8802              an external symbol, we want
8803                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8804                addu     $tempreg,$tempreg,$gp
8805                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8806                nop
8807                addiu    $tempreg,$tempreg,<constant>
8808              For a local symbol, we want
8809                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8810                nop
8811                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
8812
8813              If we have a large constant, and this is a reference to
8814              an external symbol, we want
8815                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8816                addu     $tempreg,$tempreg,$gp
8817                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8818                lui      $at,<hiconstant>
8819                addiu    $at,$at,<loconstant>
8820                addu     $tempreg,$tempreg,$at
8821              For a local symbol, we want
8822                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8823                lui      $at,<hiconstant>
8824                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
8825                addu     $tempreg,$tempreg,$at
8826           */
8827
8828           expr1.X_add_number = offset_expr.X_add_number;
8829           offset_expr.X_add_number = 0;
8830           relax_start (offset_expr.X_add_symbol);
8831           gpdelay = reg_needs_delay (mips_gp_register);
8832           if (expr1.X_add_number == 0 && breg == 0
8833               && (call || tempreg == PIC_CALL_REG))
8834             {
8835               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8836               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8837             }
8838           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8839           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8840                        tempreg, tempreg, mips_gp_register);
8841           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8842                        tempreg, lw_reloc_type, tempreg);
8843           if (expr1.X_add_number == 0)
8844             {
8845               if (breg != 0)
8846                 {
8847                   /* We're going to put in an addu instruction using
8848                      tempreg, so we may as well insert the nop right
8849                      now.  */
8850                   load_delay_nop ();
8851                 }
8852             }
8853           else if (expr1.X_add_number >= -0x8000
8854                    && expr1.X_add_number < 0x8000)
8855             {
8856               load_delay_nop ();
8857               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8858                            tempreg, tempreg, BFD_RELOC_LO16);
8859             }
8860           else
8861             {
8862               /* If we are going to add in a base register, and the
8863                  target register and the base register are the same,
8864                  then we are using AT as a temporary register.  Since
8865                  we want to load the constant into AT, we add our
8866                  current AT (from the global offset table) and the
8867                  register into the register now, and pretend we were
8868                  not using a base register.  */
8869               if (breg != treg)
8870                 dreg = tempreg;
8871               else
8872                 {
8873                   gas_assert (tempreg == AT);
8874                   load_delay_nop ();
8875                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8876                                treg, AT, breg);
8877                   dreg = treg;
8878                 }
8879
8880               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8881               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8882
8883               used_at = 1;
8884             }
8885           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
8886           relax_switch ();
8887
8888           if (gpdelay)
8889             {
8890               /* This is needed because this instruction uses $gp, but
8891                  the first instruction on the main stream does not.  */
8892               macro_build (NULL, "nop", "");
8893             }
8894
8895           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8896                        local_reloc_type, mips_gp_register);
8897           if (expr1.X_add_number >= -0x8000
8898               && expr1.X_add_number < 0x8000)
8899             {
8900               load_delay_nop ();
8901               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8902                            tempreg, tempreg, BFD_RELOC_LO16);
8903               /* FIXME: If add_number is 0, and there was no base
8904                  register, the external symbol case ended with a load,
8905                  so if the symbol turns out to not be external, and
8906                  the next instruction uses tempreg, an unnecessary nop
8907                  will be inserted.  */
8908             }
8909           else
8910             {
8911               if (breg == treg)
8912                 {
8913                   /* We must add in the base register now, as in the
8914                      external symbol case.  */
8915                   gas_assert (tempreg == AT);
8916                   load_delay_nop ();
8917                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8918                                treg, AT, breg);
8919                   tempreg = treg;
8920                   /* We set breg to 0 because we have arranged to add
8921                      it in in both cases.  */
8922                   breg = 0;
8923                 }
8924
8925               macro_build_lui (&expr1, AT);
8926               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8927                            AT, AT, BFD_RELOC_LO16);
8928               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8929                            tempreg, tempreg, AT);
8930               used_at = 1;
8931             }
8932           relax_end ();
8933         }
8934       else if (mips_big_got && HAVE_NEWABI)
8935         {
8936           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8937           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8938           int add_breg_early = 0;
8939
8940           /* This is the large GOT case.  If this is a reference to an
8941              external symbol, and there is no constant, we want
8942                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8943                add      $tempreg,$tempreg,$gp
8944                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8945              or for lca or if tempreg is PIC_CALL_REG
8946                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8947                add      $tempreg,$tempreg,$gp
8948                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8949
8950              If we have a small constant, and this is a reference to
8951              an external symbol, we want
8952                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8953                add      $tempreg,$tempreg,$gp
8954                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8955                addi     $tempreg,$tempreg,<constant>
8956
8957              If we have a large constant, and this is a reference to
8958              an external symbol, we want
8959                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8960                addu     $tempreg,$tempreg,$gp
8961                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8962                lui      $at,<hiconstant>
8963                addi     $at,$at,<loconstant>
8964                add      $tempreg,$tempreg,$at
8965
8966              If we have NewABI, and we know it's a local symbol, we want
8967                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8968                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8969              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8970
8971           relax_start (offset_expr.X_add_symbol);
8972
8973           expr1.X_add_number = offset_expr.X_add_number;
8974           offset_expr.X_add_number = 0;
8975
8976           if (expr1.X_add_number == 0 && breg == 0
8977               && (call || tempreg == PIC_CALL_REG))
8978             {
8979               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8980               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8981             }
8982           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8983           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8984                        tempreg, tempreg, mips_gp_register);
8985           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8986                        tempreg, lw_reloc_type, tempreg);
8987
8988           if (expr1.X_add_number == 0)
8989             ;
8990           else if (expr1.X_add_number >= -0x8000
8991                    && expr1.X_add_number < 0x8000)
8992             {
8993               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8994                            tempreg, tempreg, BFD_RELOC_LO16);
8995             }
8996           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8997             {
8998               /* If we are going to add in a base register, and the
8999                  target register and the base register are the same,
9000                  then we are using AT as a temporary register.  Since
9001                  we want to load the constant into AT, we add our
9002                  current AT (from the global offset table) and the
9003                  register into the register now, and pretend we were
9004                  not using a base register.  */
9005               if (breg != treg)
9006                 dreg = tempreg;
9007               else
9008                 {
9009                   gas_assert (tempreg == AT);
9010                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9011                                treg, AT, breg);
9012                   dreg = treg;
9013                   add_breg_early = 1;
9014                 }
9015
9016               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9017               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9018
9019               used_at = 1;
9020             }
9021           else
9022             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9023
9024           relax_switch ();
9025           offset_expr.X_add_number = expr1.X_add_number;
9026           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9027                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9028           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9029                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
9030           if (add_breg_early)
9031             {
9032               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9033                            treg, tempreg, breg);
9034               breg = 0;
9035               tempreg = treg;
9036             }
9037           relax_end ();
9038         }
9039       else
9040         abort ();
9041
9042       if (breg != 0)
9043         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
9044       break;
9045
9046     case M_MSGSND:
9047       gas_assert (!mips_opts.micromips);
9048       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
9049       break;
9050
9051     case M_MSGLD:
9052       gas_assert (!mips_opts.micromips);
9053       macro_build (NULL, "c2", "C", 0x02);
9054       break;
9055
9056     case M_MSGLD_T:
9057       gas_assert (!mips_opts.micromips);
9058       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
9059       break;
9060
9061     case M_MSGWAIT:
9062       gas_assert (!mips_opts.micromips);
9063       macro_build (NULL, "c2", "C", 3);
9064       break;
9065
9066     case M_MSGWAIT_T:
9067       gas_assert (!mips_opts.micromips);
9068       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
9069       break;
9070
9071     case M_J_A:
9072       /* The j instruction may not be used in PIC code, since it
9073          requires an absolute address.  We convert it to a b
9074          instruction.  */
9075       if (mips_pic == NO_PIC)
9076         macro_build (&offset_expr, "j", "a");
9077       else
9078         macro_build (&offset_expr, "b", "p");
9079       break;
9080
9081       /* The jal instructions must be handled as macros because when
9082          generating PIC code they expand to multi-instruction
9083          sequences.  Normally they are simple instructions.  */
9084     case M_JALS_1:
9085       dreg = RA;
9086       /* Fall through.  */
9087     case M_JALS_2:
9088       gas_assert (mips_opts.micromips);
9089       if (mips_opts.insn32)
9090         {
9091           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9092           break;
9093         }
9094       jals = 1;
9095       goto jal;
9096     case M_JAL_1:
9097       dreg = RA;
9098       /* Fall through.  */
9099     case M_JAL_2:
9100     jal:
9101       if (mips_pic == NO_PIC)
9102         {
9103           s = jals ? "jalrs" : "jalr";
9104           if (mips_opts.micromips
9105               && !mips_opts.insn32
9106               && dreg == RA
9107               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9108             macro_build (NULL, s, "mj", sreg);
9109           else
9110             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9111         }
9112       else
9113         {
9114           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
9115                            && mips_cprestore_offset >= 0);
9116
9117           if (sreg != PIC_CALL_REG)
9118             as_warn (_("MIPS PIC call to register other than $25"));
9119
9120           s = ((mips_opts.micromips
9121                 && !mips_opts.insn32
9122                 && (!mips_opts.noreorder || cprestore))
9123                ? "jalrs" : "jalr");
9124           if (mips_opts.micromips
9125               && !mips_opts.insn32
9126               && dreg == RA
9127               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9128             macro_build (NULL, s, "mj", sreg);
9129           else
9130             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9131           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
9132             {
9133               if (mips_cprestore_offset < 0)
9134                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9135               else
9136                 {
9137                   if (!mips_frame_reg_valid)
9138                     {
9139                       as_warn (_("No .frame pseudo-op used in PIC code"));
9140                       /* Quiet this warning.  */
9141                       mips_frame_reg_valid = 1;
9142                     }
9143                   if (!mips_cprestore_valid)
9144                     {
9145                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9146                       /* Quiet this warning.  */
9147                       mips_cprestore_valid = 1;
9148                     }
9149                   if (mips_opts.noreorder)
9150                     macro_build (NULL, "nop", "");
9151                   expr1.X_add_number = mips_cprestore_offset;
9152                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9153                                                 mips_gp_register,
9154                                                 mips_frame_reg,
9155                                                 HAVE_64BIT_ADDRESSES);
9156                 }
9157             }
9158         }
9159
9160       break;
9161
9162     case M_JALS_A:
9163       gas_assert (mips_opts.micromips);
9164       if (mips_opts.insn32)
9165         {
9166           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9167           break;
9168         }
9169       jals = 1;
9170       /* Fall through.  */
9171     case M_JAL_A:
9172       if (mips_pic == NO_PIC)
9173         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
9174       else if (mips_pic == SVR4_PIC)
9175         {
9176           /* If this is a reference to an external symbol, and we are
9177              using a small GOT, we want
9178                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
9179                nop
9180                jalr     $ra,$25
9181                nop
9182                lw       $gp,cprestore($sp)
9183              The cprestore value is set using the .cprestore
9184              pseudo-op.  If we are using a big GOT, we want
9185                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
9186                addu     $25,$25,$gp
9187                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
9188                nop
9189                jalr     $ra,$25
9190                nop
9191                lw       $gp,cprestore($sp)
9192              If the symbol is not external, we want
9193                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9194                nop
9195                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
9196                jalr     $ra,$25
9197                nop
9198                lw $gp,cprestore($sp)
9199
9200              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
9201              sequences above, minus nops, unless the symbol is local,
9202              which enables us to use GOT_PAGE/GOT_OFST (big got) or
9203              GOT_DISP.  */
9204           if (HAVE_NEWABI)
9205             {
9206               if (!mips_big_got)
9207                 {
9208                   relax_start (offset_expr.X_add_symbol);
9209                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9210                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9211                                mips_gp_register);
9212                   relax_switch ();
9213                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9214                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
9215                                mips_gp_register);
9216                   relax_end ();
9217                 }
9218               else
9219                 {
9220                   relax_start (offset_expr.X_add_symbol);
9221                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9222                                BFD_RELOC_MIPS_CALL_HI16);
9223                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9224                                PIC_CALL_REG, mips_gp_register);
9225                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9226                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9227                                PIC_CALL_REG);
9228                   relax_switch ();
9229                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9230                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
9231                                mips_gp_register);
9232                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9233                                PIC_CALL_REG, PIC_CALL_REG,
9234                                BFD_RELOC_MIPS_GOT_OFST);
9235                   relax_end ();
9236                 }
9237
9238               macro_build_jalr (&offset_expr, 0);
9239             }
9240           else
9241             {
9242               relax_start (offset_expr.X_add_symbol);
9243               if (!mips_big_got)
9244                 {
9245                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9246                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9247                                mips_gp_register);
9248                   load_delay_nop ();
9249                   relax_switch ();
9250                 }
9251               else
9252                 {
9253                   int gpdelay;
9254
9255                   gpdelay = reg_needs_delay (mips_gp_register);
9256                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9257                                BFD_RELOC_MIPS_CALL_HI16);
9258                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9259                                PIC_CALL_REG, mips_gp_register);
9260                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9261                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9262                                PIC_CALL_REG);
9263                   load_delay_nop ();
9264                   relax_switch ();
9265                   if (gpdelay)
9266                     macro_build (NULL, "nop", "");
9267                 }
9268               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9269                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
9270                            mips_gp_register);
9271               load_delay_nop ();
9272               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9273                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
9274               relax_end ();
9275               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
9276
9277               if (mips_cprestore_offset < 0)
9278                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9279               else
9280                 {
9281                   if (!mips_frame_reg_valid)
9282                     {
9283                       as_warn (_("No .frame pseudo-op used in PIC code"));
9284                       /* Quiet this warning.  */
9285                       mips_frame_reg_valid = 1;
9286                     }
9287                   if (!mips_cprestore_valid)
9288                     {
9289                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9290                       /* Quiet this warning.  */
9291                       mips_cprestore_valid = 1;
9292                     }
9293                   if (mips_opts.noreorder)
9294                     macro_build (NULL, "nop", "");
9295                   expr1.X_add_number = mips_cprestore_offset;
9296                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9297                                                 mips_gp_register,
9298                                                 mips_frame_reg,
9299                                                 HAVE_64BIT_ADDRESSES);
9300                 }
9301             }
9302         }
9303       else if (mips_pic == VXWORKS_PIC)
9304         as_bad (_("Non-PIC jump used in PIC library"));
9305       else
9306         abort ();
9307
9308       break;
9309
9310     case M_LBUE_AB:
9311       s = "lbue";
9312       fmt = "t,+j(b)";
9313       offbits = 9;
9314       goto ld_st;
9315     case M_LHUE_AB:
9316       s = "lhue";
9317       fmt = "t,+j(b)";
9318       offbits = 9;
9319       goto ld_st;
9320     case M_LBE_AB:
9321       s = "lbe";
9322       fmt = "t,+j(b)";
9323       offbits = 9;
9324       goto ld_st;
9325     case M_LHE_AB:
9326       s = "lhe";
9327       fmt = "t,+j(b)";
9328       offbits = 9;
9329       goto ld_st;
9330     case M_LLE_AB:
9331       s = "lle";
9332       fmt = "t,+j(b)";
9333       offbits = 9;
9334       goto ld_st;
9335     case M_LWE_AB:
9336       s = "lwe";
9337       fmt = "t,+j(b)";
9338       offbits = 9;
9339       goto ld_st;
9340     case M_LWLE_AB:
9341       s = "lwle";
9342       fmt = "t,+j(b)";
9343       offbits = 9;
9344       goto ld_st;
9345     case M_LWRE_AB:
9346       s = "lwre";
9347       fmt = "t,+j(b)";
9348       offbits = 9;
9349       goto ld_st;
9350     case M_SBE_AB:
9351       s = "sbe";
9352       fmt = "t,+j(b)";
9353       offbits = 9;
9354       goto ld_st;
9355     case M_SCE_AB:
9356       s = "sce";
9357       fmt = "t,+j(b)";
9358       offbits = 9;
9359       goto ld_st;
9360     case M_SHE_AB:
9361       s = "she";
9362       fmt = "t,+j(b)";
9363       offbits = 9;
9364       goto ld_st;
9365     case M_SWE_AB:
9366       s = "swe";
9367       fmt = "t,+j(b)";
9368       offbits = 9;
9369       goto ld_st;
9370     case M_SWLE_AB:
9371       s = "swle";
9372       fmt = "t,+j(b)";
9373       offbits = 9;
9374       goto ld_st;
9375     case M_SWRE_AB:
9376       s = "swre";
9377       fmt = "t,+j(b)";
9378       offbits = 9;
9379       goto ld_st;
9380     case M_ACLR_AB:
9381       s = "aclr";
9382       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9383       fmt = "\\,~(b)";
9384       offbits = 12;
9385       goto ld_st;
9386     case M_ASET_AB:
9387       s = "aset";
9388       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9389       fmt = "\\,~(b)";
9390       offbits = 12;
9391       goto ld_st;
9392     case M_LB_AB:
9393       s = "lb";
9394       fmt = "t,o(b)";
9395       goto ld;
9396     case M_LBU_AB:
9397       s = "lbu";
9398       fmt = "t,o(b)";
9399       goto ld;
9400     case M_LH_AB:
9401       s = "lh";
9402       fmt = "t,o(b)";
9403       goto ld;
9404     case M_LHU_AB:
9405       s = "lhu";
9406       fmt = "t,o(b)";
9407       goto ld;
9408     case M_LW_AB:
9409       s = "lw";
9410       fmt = "t,o(b)";
9411       goto ld;
9412     case M_LWC0_AB:
9413       gas_assert (!mips_opts.micromips);
9414       s = "lwc0";
9415       fmt = "E,o(b)";
9416       /* Itbl support may require additional care here.  */
9417       coproc = 1;
9418       goto ld_st;
9419     case M_LWC1_AB:
9420       s = "lwc1";
9421       fmt = "T,o(b)";
9422       /* Itbl support may require additional care here.  */
9423       coproc = 1;
9424       goto ld_st;
9425     case M_LWC2_AB:
9426       s = "lwc2";
9427       fmt = COP12_FMT;
9428       offbits = (mips_opts.micromips ? 12 : 16);
9429       /* Itbl support may require additional care here.  */
9430       coproc = 1;
9431       goto ld_st;
9432     case M_LWC3_AB:
9433       gas_assert (!mips_opts.micromips);
9434       s = "lwc3";
9435       fmt = "E,o(b)";
9436       /* Itbl support may require additional care here.  */
9437       coproc = 1;
9438       goto ld_st;
9439     case M_LWL_AB:
9440       s = "lwl";
9441       fmt = MEM12_FMT;
9442       offbits = (mips_opts.micromips ? 12 : 16);
9443       goto ld_st;
9444     case M_LWR_AB:
9445       s = "lwr";
9446       fmt = MEM12_FMT;
9447       offbits = (mips_opts.micromips ? 12 : 16);
9448       goto ld_st;
9449     case M_LDC1_AB:
9450       s = "ldc1";
9451       fmt = "T,o(b)";
9452       /* Itbl support may require additional care here.  */
9453       coproc = 1;
9454       goto ld_st;
9455     case M_LDC2_AB:
9456       s = "ldc2";
9457       fmt = COP12_FMT;
9458       offbits = (mips_opts.micromips ? 12 : 16);
9459       /* Itbl support may require additional care here.  */
9460       coproc = 1;
9461       goto ld_st;
9462     case M_LQC2_AB:
9463       s = "lqc2";
9464       fmt = "E,o(b)";
9465       /* Itbl support may require additional care here.  */
9466       coproc = 1;
9467       goto ld_st;
9468     case M_LDC3_AB:
9469       s = "ldc3";
9470       fmt = "E,o(b)";
9471       /* Itbl support may require additional care here.  */
9472       coproc = 1;
9473       goto ld_st;
9474     case M_LDL_AB:
9475       s = "ldl";
9476       fmt = MEM12_FMT;
9477       offbits = (mips_opts.micromips ? 12 : 16);
9478       goto ld_st;
9479     case M_LDR_AB:
9480       s = "ldr";
9481       fmt = MEM12_FMT;
9482       offbits = (mips_opts.micromips ? 12 : 16);
9483       goto ld_st;
9484     case M_LL_AB:
9485       s = "ll";
9486       fmt = MEM12_FMT;
9487       offbits = (mips_opts.micromips ? 12 : 16);
9488       goto ld;
9489     case M_LLD_AB:
9490       s = "lld";
9491       fmt = MEM12_FMT;
9492       offbits = (mips_opts.micromips ? 12 : 16);
9493       goto ld;
9494     case M_LWU_AB:
9495       s = "lwu";
9496       fmt = MEM12_FMT;
9497       offbits = (mips_opts.micromips ? 12 : 16);
9498       goto ld;
9499     case M_LWP_AB:
9500       gas_assert (mips_opts.micromips);
9501       s = "lwp";
9502       fmt = "t,~(b)";
9503       offbits = 12;
9504       lp = 1;
9505       goto ld;
9506     case M_LDP_AB:
9507       gas_assert (mips_opts.micromips);
9508       s = "ldp";
9509       fmt = "t,~(b)";
9510       offbits = 12;
9511       lp = 1;
9512       goto ld;
9513     case M_LWM_AB:
9514       gas_assert (mips_opts.micromips);
9515       s = "lwm";
9516       fmt = "n,~(b)";
9517       offbits = 12;
9518       goto ld_st;
9519     case M_LDM_AB:
9520       gas_assert (mips_opts.micromips);
9521       s = "ldm";
9522       fmt = "n,~(b)";
9523       offbits = 12;
9524       goto ld_st;
9525
9526     ld:
9527       /* We don't want to use $0 as tempreg.  */
9528       if (breg == treg + lp || treg + lp == ZERO)
9529         goto ld_st;
9530       else
9531         tempreg = treg + lp;
9532       goto ld_noat;
9533
9534     case M_SB_AB:
9535       s = "sb";
9536       fmt = "t,o(b)";
9537       goto ld_st;
9538     case M_SH_AB:
9539       s = "sh";
9540       fmt = "t,o(b)";
9541       goto ld_st;
9542     case M_SW_AB:
9543       s = "sw";
9544       fmt = "t,o(b)";
9545       goto ld_st;
9546     case M_SWC0_AB:
9547       gas_assert (!mips_opts.micromips);
9548       s = "swc0";
9549       fmt = "E,o(b)";
9550       /* Itbl support may require additional care here.  */
9551       coproc = 1;
9552       goto ld_st;
9553     case M_SWC1_AB:
9554       s = "swc1";
9555       fmt = "T,o(b)";
9556       /* Itbl support may require additional care here.  */
9557       coproc = 1;
9558       goto ld_st;
9559     case M_SWC2_AB:
9560       s = "swc2";
9561       fmt = COP12_FMT;
9562       offbits = (mips_opts.micromips ? 12 : 16);
9563       /* Itbl support may require additional care here.  */
9564       coproc = 1;
9565       goto ld_st;
9566     case M_SWC3_AB:
9567       gas_assert (!mips_opts.micromips);
9568       s = "swc3";
9569       fmt = "E,o(b)";
9570       /* Itbl support may require additional care here.  */
9571       coproc = 1;
9572       goto ld_st;
9573     case M_SWL_AB:
9574       s = "swl";
9575       fmt = MEM12_FMT;
9576       offbits = (mips_opts.micromips ? 12 : 16);
9577       goto ld_st;
9578     case M_SWR_AB:
9579       s = "swr";
9580       fmt = MEM12_FMT;
9581       offbits = (mips_opts.micromips ? 12 : 16);
9582       goto ld_st;
9583     case M_SC_AB:
9584       s = "sc";
9585       fmt = MEM12_FMT;
9586       offbits = (mips_opts.micromips ? 12 : 16);
9587       goto ld_st;
9588     case M_SCD_AB:
9589       s = "scd";
9590       fmt = MEM12_FMT;
9591       offbits = (mips_opts.micromips ? 12 : 16);
9592       goto ld_st;
9593     case M_CACHE_AB:
9594       s = "cache";
9595       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
9596       offbits = (mips_opts.micromips ? 12 : 16);
9597       goto ld_st;
9598     case M_CACHEE_AB:
9599       s = "cachee";
9600       fmt = "k,+j(b)";
9601       offbits = 9;
9602       goto ld_st;
9603     case M_PREF_AB:
9604       s = "pref";
9605       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
9606       offbits = (mips_opts.micromips ? 12 : 16);
9607       goto ld_st;
9608     case M_PREFE_AB:
9609       s = "prefe";
9610       fmt = "k,+j(b)";
9611       offbits = 9;
9612       goto ld_st;
9613     case M_SDC1_AB:
9614       s = "sdc1";
9615       fmt = "T,o(b)";
9616       coproc = 1;
9617       /* Itbl support may require additional care here.  */
9618       goto ld_st;
9619     case M_SDC2_AB:
9620       s = "sdc2";
9621       fmt = COP12_FMT;
9622       offbits = (mips_opts.micromips ? 12 : 16);
9623       /* Itbl support may require additional care here.  */
9624       coproc = 1;
9625       goto ld_st;
9626     case M_SQC2_AB:
9627       s = "sqc2";
9628       fmt = "E,o(b)";
9629       /* Itbl support may require additional care here.  */
9630       coproc = 1;
9631       goto ld_st;
9632     case M_SDC3_AB:
9633       gas_assert (!mips_opts.micromips);
9634       s = "sdc3";
9635       fmt = "E,o(b)";
9636       /* Itbl support may require additional care here.  */
9637       coproc = 1;
9638       goto ld_st;
9639     case M_SDL_AB:
9640       s = "sdl";
9641       fmt = MEM12_FMT;
9642       offbits = (mips_opts.micromips ? 12 : 16);
9643       goto ld_st;
9644     case M_SDR_AB:
9645       s = "sdr";
9646       fmt = MEM12_FMT;
9647       offbits = (mips_opts.micromips ? 12 : 16);
9648       goto ld_st;
9649     case M_SWP_AB:
9650       gas_assert (mips_opts.micromips);
9651       s = "swp";
9652       fmt = "t,~(b)";
9653       offbits = 12;
9654       goto ld_st;
9655     case M_SDP_AB:
9656       gas_assert (mips_opts.micromips);
9657       s = "sdp";
9658       fmt = "t,~(b)";
9659       offbits = 12;
9660       goto ld_st;
9661     case M_SWM_AB:
9662       gas_assert (mips_opts.micromips);
9663       s = "swm";
9664       fmt = "n,~(b)";
9665       offbits = 12;
9666       goto ld_st;
9667     case M_SDM_AB:
9668       gas_assert (mips_opts.micromips);
9669       s = "sdm";
9670       fmt = "n,~(b)";
9671       offbits = 12;
9672
9673     ld_st:
9674       tempreg = AT;
9675     ld_noat:
9676       if (small_offset_p (0, align, 16))
9677         {
9678           /* The first case exists for M_LD_AB and M_SD_AB, which are
9679              macros for o32 but which should act like normal instructions
9680              otherwise.  */
9681           if (offbits == 16)
9682             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
9683                          offset_reloc[1], offset_reloc[2], breg);
9684           else if (small_offset_p (0, align, offbits))
9685             {
9686               if (offbits == 0)
9687                 macro_build (NULL, s, fmt, treg, breg);
9688               else
9689                 macro_build (NULL, s, fmt, treg,
9690                              (int) offset_expr.X_add_number, breg);
9691             }
9692           else
9693             {
9694               if (tempreg == AT)
9695                 used_at = 1;
9696               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9697                            tempreg, breg, -1, offset_reloc[0],
9698                            offset_reloc[1], offset_reloc[2]);
9699               if (offbits == 0)
9700                 macro_build (NULL, s, fmt, treg, tempreg);
9701               else
9702                 macro_build (NULL, s, fmt, treg, 0, tempreg);
9703             }
9704           break;
9705         }
9706
9707       if (tempreg == AT)
9708         used_at = 1;
9709
9710       if (offset_expr.X_op != O_constant
9711           && offset_expr.X_op != O_symbol)
9712         {
9713           as_bad (_("Expression too complex"));
9714           offset_expr.X_op = O_constant;
9715         }
9716
9717       if (HAVE_32BIT_ADDRESSES
9718           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9719         {
9720           char value [32];
9721
9722           sprintf_vma (value, offset_expr.X_add_number);
9723           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9724         }
9725
9726       /* A constant expression in PIC code can be handled just as it
9727          is in non PIC code.  */
9728       if (offset_expr.X_op == O_constant)
9729         {
9730           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
9731                                                  offbits == 0 ? 16 : offbits);
9732           offset_expr.X_add_number -= expr1.X_add_number;
9733
9734           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
9735           if (breg != 0)
9736             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9737                          tempreg, tempreg, breg);
9738           if (offbits == 0)
9739             {
9740               if (offset_expr.X_add_number != 0)
9741                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
9742                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
9743               macro_build (NULL, s, fmt, treg, tempreg);
9744             }
9745           else if (offbits == 16)
9746             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9747           else
9748             macro_build (NULL, s, fmt, treg,
9749                          (int) offset_expr.X_add_number, tempreg);
9750         }
9751       else if (offbits != 16)
9752         {
9753           /* The offset field is too narrow to be used for a low-part
9754              relocation, so load the whole address into the auxillary
9755              register.  */
9756           load_address (tempreg, &offset_expr, &used_at);
9757           if (breg != 0)
9758             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9759                          tempreg, tempreg, breg);
9760           if (offbits == 0)
9761             macro_build (NULL, s, fmt, treg, tempreg);
9762           else
9763             macro_build (NULL, s, fmt, treg, 0, tempreg);
9764         }
9765       else if (mips_pic == NO_PIC)
9766         {
9767           /* If this is a reference to a GP relative symbol, and there
9768              is no base register, we want
9769                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9770              Otherwise, if there is no base register, we want
9771                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9772                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9773              If we have a constant, we need two instructions anyhow,
9774              so we always use the latter form.
9775
9776              If we have a base register, and this is a reference to a
9777              GP relative symbol, we want
9778                addu     $tempreg,$breg,$gp
9779                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9780              Otherwise we want
9781                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9782                addu     $tempreg,$tempreg,$breg
9783                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9784              With a constant we always use the latter case.
9785
9786              With 64bit address space and no base register and $at usable,
9787              we want
9788                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9789                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9790                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9791                dsll32   $tempreg,0
9792                daddu    $tempreg,$at
9793                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9794              If we have a base register, we want
9795                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9796                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9797                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9798                daddu    $at,$breg
9799                dsll32   $tempreg,0
9800                daddu    $tempreg,$at
9801                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9802
9803              Without $at we can't generate the optimal path for superscalar
9804              processors here since this would require two temporary registers.
9805                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9806                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9807                dsll     $tempreg,16
9808                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9809                dsll     $tempreg,16
9810                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9811              If we have a base register, we want
9812                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9813                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9814                dsll     $tempreg,16
9815                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9816                dsll     $tempreg,16
9817                daddu    $tempreg,$tempreg,$breg
9818                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9819
9820              For GP relative symbols in 64bit address space we can use
9821              the same sequence as in 32bit address space.  */
9822           if (HAVE_64BIT_SYMBOLS)
9823             {
9824               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9825                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9826                 {
9827                   relax_start (offset_expr.X_add_symbol);
9828                   if (breg == 0)
9829                     {
9830                       macro_build (&offset_expr, s, fmt, treg,
9831                                    BFD_RELOC_GPREL16, mips_gp_register);
9832                     }
9833                   else
9834                     {
9835                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9836                                    tempreg, breg, mips_gp_register);
9837                       macro_build (&offset_expr, s, fmt, treg,
9838                                    BFD_RELOC_GPREL16, tempreg);
9839                     }
9840                   relax_switch ();
9841                 }
9842
9843               if (used_at == 0 && mips_opts.at)
9844                 {
9845                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9846                                BFD_RELOC_MIPS_HIGHEST);
9847                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
9848                                BFD_RELOC_HI16_S);
9849                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9850                                tempreg, BFD_RELOC_MIPS_HIGHER);
9851                   if (breg != 0)
9852                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
9853                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9854                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9855                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
9856                                tempreg);
9857                   used_at = 1;
9858                 }
9859               else
9860                 {
9861                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9862                                BFD_RELOC_MIPS_HIGHEST);
9863                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9864                                tempreg, BFD_RELOC_MIPS_HIGHER);
9865                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9866                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9867                                tempreg, BFD_RELOC_HI16_S);
9868                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9869                   if (breg != 0)
9870                     macro_build (NULL, "daddu", "d,v,t",
9871                                  tempreg, tempreg, breg);
9872                   macro_build (&offset_expr, s, fmt, treg,
9873                                BFD_RELOC_LO16, tempreg);
9874                 }
9875
9876               if (mips_relax.sequence)
9877                 relax_end ();
9878               break;
9879             }
9880
9881           if (breg == 0)
9882             {
9883               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9884                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9885                 {
9886                   relax_start (offset_expr.X_add_symbol);
9887                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
9888                                mips_gp_register);
9889                   relax_switch ();
9890                 }
9891               macro_build_lui (&offset_expr, tempreg);
9892               macro_build (&offset_expr, s, fmt, treg,
9893                            BFD_RELOC_LO16, tempreg);
9894               if (mips_relax.sequence)
9895                 relax_end ();
9896             }
9897           else
9898             {
9899               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9900                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9901                 {
9902                   relax_start (offset_expr.X_add_symbol);
9903                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9904                                tempreg, breg, mips_gp_register);
9905                   macro_build (&offset_expr, s, fmt, treg,
9906                                BFD_RELOC_GPREL16, tempreg);
9907                   relax_switch ();
9908                 }
9909               macro_build_lui (&offset_expr, tempreg);
9910               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9911                            tempreg, tempreg, breg);
9912               macro_build (&offset_expr, s, fmt, treg,
9913                            BFD_RELOC_LO16, tempreg);
9914               if (mips_relax.sequence)
9915                 relax_end ();
9916             }
9917         }
9918       else if (!mips_big_got)
9919         {
9920           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9921
9922           /* If this is a reference to an external symbol, we want
9923                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9924                nop
9925                <op>     $treg,0($tempreg)
9926              Otherwise we want
9927                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9928                nop
9929                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9930                <op>     $treg,0($tempreg)
9931
9932              For NewABI, we want
9933                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9934                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
9935
9936              If there is a base register, we add it to $tempreg before
9937              the <op>.  If there is a constant, we stick it in the
9938              <op> instruction.  We don't handle constants larger than
9939              16 bits, because we have no way to load the upper 16 bits
9940              (actually, we could handle them for the subset of cases
9941              in which we are not using $at).  */
9942           gas_assert (offset_expr.X_op == O_symbol);
9943           if (HAVE_NEWABI)
9944             {
9945               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9946                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9947               if (breg != 0)
9948                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9949                              tempreg, tempreg, breg);
9950               macro_build (&offset_expr, s, fmt, treg,
9951                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
9952               break;
9953             }
9954           expr1.X_add_number = offset_expr.X_add_number;
9955           offset_expr.X_add_number = 0;
9956           if (expr1.X_add_number < -0x8000
9957               || expr1.X_add_number >= 0x8000)
9958             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9959           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9960                        lw_reloc_type, mips_gp_register);
9961           load_delay_nop ();
9962           relax_start (offset_expr.X_add_symbol);
9963           relax_switch ();
9964           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9965                        tempreg, BFD_RELOC_LO16);
9966           relax_end ();
9967           if (breg != 0)
9968             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9969                          tempreg, tempreg, breg);
9970           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9971         }
9972       else if (mips_big_got && !HAVE_NEWABI)
9973         {
9974           int gpdelay;
9975
9976           /* If this is a reference to an external symbol, we want
9977                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9978                addu     $tempreg,$tempreg,$gp
9979                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9980                <op>     $treg,0($tempreg)
9981              Otherwise we want
9982                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9983                nop
9984                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9985                <op>     $treg,0($tempreg)
9986              If there is a base register, we add it to $tempreg before
9987              the <op>.  If there is a constant, we stick it in the
9988              <op> instruction.  We don't handle constants larger than
9989              16 bits, because we have no way to load the upper 16 bits
9990              (actually, we could handle them for the subset of cases
9991              in which we are not using $at).  */
9992           gas_assert (offset_expr.X_op == O_symbol);
9993           expr1.X_add_number = offset_expr.X_add_number;
9994           offset_expr.X_add_number = 0;
9995           if (expr1.X_add_number < -0x8000
9996               || expr1.X_add_number >= 0x8000)
9997             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9998           gpdelay = reg_needs_delay (mips_gp_register);
9999           relax_start (offset_expr.X_add_symbol);
10000           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10001                        BFD_RELOC_MIPS_GOT_HI16);
10002           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10003                        mips_gp_register);
10004           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10005                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10006           relax_switch ();
10007           if (gpdelay)
10008             macro_build (NULL, "nop", "");
10009           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10010                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10011           load_delay_nop ();
10012           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10013                        tempreg, BFD_RELOC_LO16);
10014           relax_end ();
10015
10016           if (breg != 0)
10017             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10018                          tempreg, tempreg, breg);
10019           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10020         }
10021       else if (mips_big_got && HAVE_NEWABI)
10022         {
10023           /* If this is a reference to an external symbol, we want
10024                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10025                add      $tempreg,$tempreg,$gp
10026                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10027                <op>     $treg,<ofst>($tempreg)
10028              Otherwise, for local symbols, we want:
10029                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10030                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
10031           gas_assert (offset_expr.X_op == O_symbol);
10032           expr1.X_add_number = offset_expr.X_add_number;
10033           offset_expr.X_add_number = 0;
10034           if (expr1.X_add_number < -0x8000
10035               || expr1.X_add_number >= 0x8000)
10036             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10037           relax_start (offset_expr.X_add_symbol);
10038           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10039                        BFD_RELOC_MIPS_GOT_HI16);
10040           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10041                        mips_gp_register);
10042           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10043                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10044           if (breg != 0)
10045             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10046                          tempreg, tempreg, breg);
10047           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10048
10049           relax_switch ();
10050           offset_expr.X_add_number = expr1.X_add_number;
10051           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10052                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10053           if (breg != 0)
10054             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10055                          tempreg, tempreg, breg);
10056           macro_build (&offset_expr, s, fmt, treg,
10057                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
10058           relax_end ();
10059         }
10060       else
10061         abort ();
10062
10063       break;
10064
10065     case M_JRADDIUSP:
10066       gas_assert (mips_opts.micromips);
10067       gas_assert (mips_opts.insn32);
10068       start_noreorder ();
10069       macro_build (NULL, "jr", "s", RA);
10070       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
10071       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
10072       end_noreorder ();
10073       break;
10074
10075     case M_JRC:
10076       gas_assert (mips_opts.micromips);
10077       gas_assert (mips_opts.insn32);
10078       macro_build (NULL, "jr", "s", sreg);
10079       if (mips_opts.noreorder)
10080         macro_build (NULL, "nop", "");
10081       break;
10082
10083     case M_LI:
10084     case M_LI_S:
10085       load_register (treg, &imm_expr, 0);
10086       break;
10087
10088     case M_DLI:
10089       load_register (treg, &imm_expr, 1);
10090       break;
10091
10092     case M_LI_SS:
10093       if (imm_expr.X_op == O_constant)
10094         {
10095           used_at = 1;
10096           load_register (AT, &imm_expr, 0);
10097           macro_build (NULL, "mtc1", "t,G", AT, treg);
10098           break;
10099         }
10100       else
10101         {
10102           gas_assert (offset_expr.X_op == O_symbol
10103                       && strcmp (segment_name (S_GET_SEGMENT
10104                                                (offset_expr.X_add_symbol)),
10105                                  ".lit4") == 0
10106                       && offset_expr.X_add_number == 0);
10107           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
10108                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
10109           break;
10110         }
10111
10112     case M_LI_D:
10113       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
10114          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
10115          order 32 bits of the value and the low order 32 bits are either
10116          zero or in OFFSET_EXPR.  */
10117       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10118         {
10119           if (HAVE_64BIT_GPRS)
10120             load_register (treg, &imm_expr, 1);
10121           else
10122             {
10123               int hreg, lreg;
10124
10125               if (target_big_endian)
10126                 {
10127                   hreg = treg;
10128                   lreg = treg + 1;
10129                 }
10130               else
10131                 {
10132                   hreg = treg + 1;
10133                   lreg = treg;
10134                 }
10135
10136               if (hreg <= 31)
10137                 load_register (hreg, &imm_expr, 0);
10138               if (lreg <= 31)
10139                 {
10140                   if (offset_expr.X_op == O_absent)
10141                     move_register (lreg, 0);
10142                   else
10143                     {
10144                       gas_assert (offset_expr.X_op == O_constant);
10145                       load_register (lreg, &offset_expr, 0);
10146                     }
10147                 }
10148             }
10149           break;
10150         }
10151
10152       /* We know that sym is in the .rdata section.  First we get the
10153          upper 16 bits of the address.  */
10154       if (mips_pic == NO_PIC)
10155         {
10156           macro_build_lui (&offset_expr, AT);
10157           used_at = 1;
10158         }
10159       else
10160         {
10161           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10162                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10163           used_at = 1;
10164         }
10165
10166       /* Now we load the register(s).  */
10167       if (HAVE_64BIT_GPRS)
10168         {
10169           used_at = 1;
10170           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10171         }
10172       else
10173         {
10174           used_at = 1;
10175           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10176           if (treg != RA)
10177             {
10178               /* FIXME: How in the world do we deal with the possible
10179                  overflow here?  */
10180               offset_expr.X_add_number += 4;
10181               macro_build (&offset_expr, "lw", "t,o(b)",
10182                            treg + 1, BFD_RELOC_LO16, AT);
10183             }
10184         }
10185       break;
10186
10187     case M_LI_DD:
10188       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
10189          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
10190          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
10191          the value and the low order 32 bits are either zero or in
10192          OFFSET_EXPR.  */
10193       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10194         {
10195           used_at = 1;
10196           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
10197           if (HAVE_64BIT_FPRS)
10198             {
10199               gas_assert (HAVE_64BIT_GPRS);
10200               macro_build (NULL, "dmtc1", "t,S", AT, treg);
10201             }
10202           else
10203             {
10204               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
10205               if (offset_expr.X_op == O_absent)
10206                 macro_build (NULL, "mtc1", "t,G", 0, treg);
10207               else
10208                 {
10209                   gas_assert (offset_expr.X_op == O_constant);
10210                   load_register (AT, &offset_expr, 0);
10211                   macro_build (NULL, "mtc1", "t,G", AT, treg);
10212                 }
10213             }
10214           break;
10215         }
10216
10217       gas_assert (offset_expr.X_op == O_symbol
10218                   && offset_expr.X_add_number == 0);
10219       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
10220       if (strcmp (s, ".lit8") == 0)
10221         {
10222           breg = mips_gp_register;
10223           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
10224           offset_reloc[1] = BFD_RELOC_UNUSED;
10225           offset_reloc[2] = BFD_RELOC_UNUSED;
10226         }
10227       else
10228         {
10229           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
10230           used_at = 1;
10231           if (mips_pic != NO_PIC)
10232             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10233                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
10234           else
10235             {
10236               /* FIXME: This won't work for a 64 bit address.  */
10237               macro_build_lui (&offset_expr, AT);
10238             }
10239
10240           breg = AT;
10241           offset_reloc[0] = BFD_RELOC_LO16;
10242           offset_reloc[1] = BFD_RELOC_UNUSED;
10243           offset_reloc[2] = BFD_RELOC_UNUSED;
10244         }
10245       align = 8;
10246       /* Fall through */
10247
10248     case M_L_DAB:
10249       /*
10250        * The MIPS assembler seems to check for X_add_number not
10251        * being double aligned and generating:
10252        *        lui     at,%hi(foo+1)
10253        *        addu    at,at,v1
10254        *        addiu   at,at,%lo(foo+1)
10255        *        lwc1    f2,0(at)
10256        *        lwc1    f3,4(at)
10257        * But, the resulting address is the same after relocation so why
10258        * generate the extra instruction?
10259        */
10260       /* Itbl support may require additional care here.  */
10261       coproc = 1;
10262       fmt = "T,o(b)";
10263       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10264         {
10265           s = "ldc1";
10266           goto ld_st;
10267         }
10268       s = "lwc1";
10269       goto ldd_std;
10270
10271     case M_S_DAB:
10272       gas_assert (!mips_opts.micromips);
10273       /* Itbl support may require additional care here.  */
10274       coproc = 1;
10275       fmt = "T,o(b)";
10276       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10277         {
10278           s = "sdc1";
10279           goto ld_st;
10280         }
10281       s = "swc1";
10282       goto ldd_std;
10283
10284     case M_LQ_AB:
10285       fmt = "t,o(b)";
10286       s = "lq";
10287       goto ld;
10288
10289     case M_SQ_AB:
10290       fmt = "t,o(b)";
10291       s = "sq";
10292       goto ld_st;
10293
10294     case M_LD_AB:
10295       fmt = "t,o(b)";
10296       if (HAVE_64BIT_GPRS)
10297         {
10298           s = "ld";
10299           goto ld;
10300         }
10301       s = "lw";
10302       goto ldd_std;
10303
10304     case M_SD_AB:
10305       fmt = "t,o(b)";
10306       if (HAVE_64BIT_GPRS)
10307         {
10308           s = "sd";
10309           goto ld_st;
10310         }
10311       s = "sw";
10312
10313     ldd_std:
10314       /* Even on a big endian machine $fn comes before $fn+1.  We have
10315          to adjust when loading from memory.  We set coproc if we must
10316          load $fn+1 first.  */
10317       /* Itbl support may require additional care here.  */
10318       if (!target_big_endian)
10319         coproc = 0;
10320
10321       if (small_offset_p (0, align, 16))
10322         {
10323           ep = &offset_expr;
10324           if (!small_offset_p (4, align, 16))
10325             {
10326               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
10327                            -1, offset_reloc[0], offset_reloc[1],
10328                            offset_reloc[2]);
10329               expr1.X_add_number = 0;
10330               ep = &expr1;
10331               breg = AT;
10332               used_at = 1;
10333               offset_reloc[0] = BFD_RELOC_LO16;
10334               offset_reloc[1] = BFD_RELOC_UNUSED;
10335               offset_reloc[2] = BFD_RELOC_UNUSED;
10336             }
10337           if (strcmp (s, "lw") == 0 && treg == breg)
10338             {
10339               ep->X_add_number += 4;
10340               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
10341                            offset_reloc[1], offset_reloc[2], breg);
10342               ep->X_add_number -= 4;
10343               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
10344                            offset_reloc[1], offset_reloc[2], breg);
10345             }
10346           else
10347             {
10348               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
10349                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10350                            breg);
10351               ep->X_add_number += 4;
10352               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
10353                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10354                            breg);
10355             }
10356           break;
10357         }
10358
10359       if (offset_expr.X_op != O_symbol
10360           && offset_expr.X_op != O_constant)
10361         {
10362           as_bad (_("Expression too complex"));
10363           offset_expr.X_op = O_constant;
10364         }
10365
10366       if (HAVE_32BIT_ADDRESSES
10367           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10368         {
10369           char value [32];
10370
10371           sprintf_vma (value, offset_expr.X_add_number);
10372           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10373         }
10374
10375       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
10376         {
10377           /* If this is a reference to a GP relative symbol, we want
10378                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
10379                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
10380              If we have a base register, we use this
10381                addu     $at,$breg,$gp
10382                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
10383                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
10384              If this is not a GP relative symbol, we want
10385                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10386                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10387                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10388              If there is a base register, we add it to $at after the
10389              lui instruction.  If there is a constant, we always use
10390              the last case.  */
10391           if (offset_expr.X_op == O_symbol
10392               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10393               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10394             {
10395               relax_start (offset_expr.X_add_symbol);
10396               if (breg == 0)
10397                 {
10398                   tempreg = mips_gp_register;
10399                 }
10400               else
10401                 {
10402                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10403                                AT, breg, mips_gp_register);
10404                   tempreg = AT;
10405                   used_at = 1;
10406                 }
10407
10408               /* Itbl support may require additional care here.  */
10409               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10410                            BFD_RELOC_GPREL16, tempreg);
10411               offset_expr.X_add_number += 4;
10412
10413               /* Set mips_optimize to 2 to avoid inserting an
10414                  undesired nop.  */
10415               hold_mips_optimize = mips_optimize;
10416               mips_optimize = 2;
10417               /* Itbl support may require additional care here.  */
10418               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10419                            BFD_RELOC_GPREL16, tempreg);
10420               mips_optimize = hold_mips_optimize;
10421
10422               relax_switch ();
10423
10424               offset_expr.X_add_number -= 4;
10425             }
10426           used_at = 1;
10427           if (offset_high_part (offset_expr.X_add_number, 16)
10428               != offset_high_part (offset_expr.X_add_number + 4, 16))
10429             {
10430               load_address (AT, &offset_expr, &used_at);
10431               offset_expr.X_op = O_constant;
10432               offset_expr.X_add_number = 0;
10433             }
10434           else
10435             macro_build_lui (&offset_expr, AT);
10436           if (breg != 0)
10437             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10438           /* Itbl support may require additional care here.  */
10439           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10440                        BFD_RELOC_LO16, AT);
10441           /* FIXME: How do we handle overflow here?  */
10442           offset_expr.X_add_number += 4;
10443           /* Itbl support may require additional care here.  */
10444           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10445                        BFD_RELOC_LO16, AT);
10446           if (mips_relax.sequence)
10447             relax_end ();
10448         }
10449       else if (!mips_big_got)
10450         {
10451           /* If this is a reference to an external symbol, we want
10452                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10453                nop
10454                <op>     $treg,0($at)
10455                <op>     $treg+1,4($at)
10456              Otherwise we want
10457                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10458                nop
10459                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10460                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10461              If there is a base register we add it to $at before the
10462              lwc1 instructions.  If there is a constant we include it
10463              in the lwc1 instructions.  */
10464           used_at = 1;
10465           expr1.X_add_number = offset_expr.X_add_number;
10466           if (expr1.X_add_number < -0x8000
10467               || expr1.X_add_number >= 0x8000 - 4)
10468             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10469           load_got_offset (AT, &offset_expr);
10470           load_delay_nop ();
10471           if (breg != 0)
10472             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10473
10474           /* Set mips_optimize to 2 to avoid inserting an undesired
10475              nop.  */
10476           hold_mips_optimize = mips_optimize;
10477           mips_optimize = 2;
10478
10479           /* Itbl support may require additional care here.  */
10480           relax_start (offset_expr.X_add_symbol);
10481           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10482                        BFD_RELOC_LO16, AT);
10483           expr1.X_add_number += 4;
10484           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10485                        BFD_RELOC_LO16, AT);
10486           relax_switch ();
10487           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10488                        BFD_RELOC_LO16, AT);
10489           offset_expr.X_add_number += 4;
10490           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10491                        BFD_RELOC_LO16, AT);
10492           relax_end ();
10493
10494           mips_optimize = hold_mips_optimize;
10495         }
10496       else if (mips_big_got)
10497         {
10498           int gpdelay;
10499
10500           /* If this is a reference to an external symbol, we want
10501                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
10502                addu     $at,$at,$gp
10503                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
10504                nop
10505                <op>     $treg,0($at)
10506                <op>     $treg+1,4($at)
10507              Otherwise we want
10508                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10509                nop
10510                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10511                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10512              If there is a base register we add it to $at before the
10513              lwc1 instructions.  If there is a constant we include it
10514              in the lwc1 instructions.  */
10515           used_at = 1;
10516           expr1.X_add_number = offset_expr.X_add_number;
10517           offset_expr.X_add_number = 0;
10518           if (expr1.X_add_number < -0x8000
10519               || expr1.X_add_number >= 0x8000 - 4)
10520             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10521           gpdelay = reg_needs_delay (mips_gp_register);
10522           relax_start (offset_expr.X_add_symbol);
10523           macro_build (&offset_expr, "lui", LUI_FMT,
10524                        AT, BFD_RELOC_MIPS_GOT_HI16);
10525           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10526                        AT, AT, mips_gp_register);
10527           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10528                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
10529           load_delay_nop ();
10530           if (breg != 0)
10531             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10532           /* Itbl support may require additional care here.  */
10533           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10534                        BFD_RELOC_LO16, AT);
10535           expr1.X_add_number += 4;
10536
10537           /* Set mips_optimize to 2 to avoid inserting an undesired
10538              nop.  */
10539           hold_mips_optimize = mips_optimize;
10540           mips_optimize = 2;
10541           /* Itbl support may require additional care here.  */
10542           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10543                        BFD_RELOC_LO16, AT);
10544           mips_optimize = hold_mips_optimize;
10545           expr1.X_add_number -= 4;
10546
10547           relax_switch ();
10548           offset_expr.X_add_number = expr1.X_add_number;
10549           if (gpdelay)
10550             macro_build (NULL, "nop", "");
10551           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10552                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10553           load_delay_nop ();
10554           if (breg != 0)
10555             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10556           /* Itbl support may require additional care here.  */
10557           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10558                        BFD_RELOC_LO16, AT);
10559           offset_expr.X_add_number += 4;
10560
10561           /* Set mips_optimize to 2 to avoid inserting an undesired
10562              nop.  */
10563           hold_mips_optimize = mips_optimize;
10564           mips_optimize = 2;
10565           /* Itbl support may require additional care here.  */
10566           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10567                        BFD_RELOC_LO16, AT);
10568           mips_optimize = hold_mips_optimize;
10569           relax_end ();
10570         }
10571       else
10572         abort ();
10573
10574       break;
10575         
10576     case M_SAA_AB:
10577       s = "saa";
10578       offbits = 0;
10579       fmt = "t,(b)";
10580       goto ld_st;
10581     case M_SAAD_AB:
10582       s = "saad";
10583       offbits = 0;
10584       fmt = "t,(b)";
10585       goto ld_st;
10586
10587    /* New code added to support COPZ instructions.
10588       This code builds table entries out of the macros in mip_opcodes.
10589       R4000 uses interlocks to handle coproc delays.
10590       Other chips (like the R3000) require nops to be inserted for delays.
10591
10592       FIXME: Currently, we require that the user handle delays.
10593       In order to fill delay slots for non-interlocked chips,
10594       we must have a way to specify delays based on the coprocessor.
10595       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
10596       What are the side-effects of the cop instruction?
10597       What cache support might we have and what are its effects?
10598       Both coprocessor & memory require delays. how long???
10599       What registers are read/set/modified?
10600
10601       If an itbl is provided to interpret cop instructions,
10602       this knowledge can be encoded in the itbl spec.  */
10603
10604     case M_COP0:
10605       s = "c0";
10606       goto copz;
10607     case M_COP1:
10608       s = "c1";
10609       goto copz;
10610     case M_COP2:
10611       s = "c2";
10612       goto copz;
10613     case M_COP3:
10614       s = "c3";
10615     copz:
10616       gas_assert (!mips_opts.micromips);
10617       /* For now we just do C (same as Cz).  The parameter will be
10618          stored in insn_opcode by mips_ip.  */
10619       macro_build (NULL, s, "C", (int) ip->insn_opcode);
10620       break;
10621
10622     case M_MOVE:
10623       move_register (dreg, sreg);
10624       break;
10625
10626     case M_MOVEP:
10627       gas_assert (mips_opts.micromips);
10628       gas_assert (mips_opts.insn32);
10629       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
10630       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
10631       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
10632       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
10633       move_register (dreg, sreg);
10634       move_register (breg, treg);
10635       break;
10636
10637     case M_DMUL:
10638       dbl = 1;
10639     case M_MUL:
10640       if (mips_opts.arch == CPU_R5900)
10641         {
10642           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
10643         }
10644       else
10645         {
10646       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
10647       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10648         }
10649       break;
10650
10651     case M_DMUL_I:
10652       dbl = 1;
10653     case M_MUL_I:
10654       /* The MIPS assembler some times generates shifts and adds.  I'm
10655          not trying to be that fancy. GCC should do this for us
10656          anyway.  */
10657       used_at = 1;
10658       load_register (AT, &imm_expr, dbl);
10659       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
10660       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10661       break;
10662
10663     case M_DMULO_I:
10664       dbl = 1;
10665     case M_MULO_I:
10666       imm = 1;
10667       goto do_mulo;
10668
10669     case M_DMULO:
10670       dbl = 1;
10671     case M_MULO:
10672     do_mulo:
10673       start_noreorder ();
10674       used_at = 1;
10675       if (imm)
10676         load_register (AT, &imm_expr, dbl);
10677       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
10678       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10679       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
10680       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10681       if (mips_trap)
10682         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
10683       else
10684         {
10685           if (mips_opts.micromips)
10686             micromips_label_expr (&label_expr);
10687           else
10688             label_expr.X_add_number = 8;
10689           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
10690           macro_build (NULL, "nop", "");
10691           macro_build (NULL, "break", BRK_FMT, 6);
10692           if (mips_opts.micromips)
10693             micromips_add_label ();
10694         }
10695       end_noreorder ();
10696       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10697       break;
10698
10699     case M_DMULOU_I:
10700       dbl = 1;
10701     case M_MULOU_I:
10702       imm = 1;
10703       goto do_mulou;
10704
10705     case M_DMULOU:
10706       dbl = 1;
10707     case M_MULOU:
10708     do_mulou:
10709       start_noreorder ();
10710       used_at = 1;
10711       if (imm)
10712         load_register (AT, &imm_expr, dbl);
10713       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
10714                    sreg, imm ? AT : treg);
10715       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10716       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10717       if (mips_trap)
10718         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
10719       else
10720         {
10721           if (mips_opts.micromips)
10722             micromips_label_expr (&label_expr);
10723           else
10724             label_expr.X_add_number = 8;
10725           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
10726           macro_build (NULL, "nop", "");
10727           macro_build (NULL, "break", BRK_FMT, 6);
10728           if (mips_opts.micromips)
10729             micromips_add_label ();
10730         }
10731       end_noreorder ();
10732       break;
10733
10734     case M_DROL:
10735       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10736         {
10737           if (dreg == sreg)
10738             {
10739               tempreg = AT;
10740               used_at = 1;
10741             }
10742           else
10743             {
10744               tempreg = dreg;
10745             }
10746           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
10747           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
10748           break;
10749         }
10750       used_at = 1;
10751       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10752       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
10753       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
10754       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10755       break;
10756
10757     case M_ROL:
10758       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10759         {
10760           if (dreg == sreg)
10761             {
10762               tempreg = AT;
10763               used_at = 1;
10764             }
10765           else
10766             {
10767               tempreg = dreg;
10768             }
10769           macro_build (NULL, "negu", "d,w", tempreg, treg);
10770           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
10771           break;
10772         }
10773       used_at = 1;
10774       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10775       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
10776       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
10777       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10778       break;
10779
10780     case M_DROL_I:
10781       {
10782         unsigned int rot;
10783         char *l;
10784         char *rr;
10785
10786         if (imm_expr.X_op != O_constant)
10787           as_bad (_("Improper rotate count"));
10788         rot = imm_expr.X_add_number & 0x3f;
10789         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10790           {
10791             rot = (64 - rot) & 0x3f;
10792             if (rot >= 32)
10793               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10794             else
10795               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10796             break;
10797           }
10798         if (rot == 0)
10799           {
10800             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10801             break;
10802           }
10803         l = (rot < 0x20) ? "dsll" : "dsll32";
10804         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10805         rot &= 0x1f;
10806         used_at = 1;
10807         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10808         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10809         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10810       }
10811       break;
10812
10813     case M_ROL_I:
10814       {
10815         unsigned int rot;
10816
10817         if (imm_expr.X_op != O_constant)
10818           as_bad (_("Improper rotate count"));
10819         rot = imm_expr.X_add_number & 0x1f;
10820         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10821           {
10822             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10823             break;
10824           }
10825         if (rot == 0)
10826           {
10827             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10828             break;
10829           }
10830         used_at = 1;
10831         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10832         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10833         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10834       }
10835       break;
10836
10837     case M_DROR:
10838       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10839         {
10840           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
10841           break;
10842         }
10843       used_at = 1;
10844       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10845       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
10846       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
10847       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10848       break;
10849
10850     case M_ROR:
10851       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10852         {
10853           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
10854           break;
10855         }
10856       used_at = 1;
10857       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10858       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
10859       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
10860       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10861       break;
10862
10863     case M_DROR_I:
10864       {
10865         unsigned int rot;
10866         char *l;
10867         char *rr;
10868
10869         if (imm_expr.X_op != O_constant)
10870           as_bad (_("Improper rotate count"));
10871         rot = imm_expr.X_add_number & 0x3f;
10872         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10873           {
10874             if (rot >= 32)
10875               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10876             else
10877               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10878             break;
10879           }
10880         if (rot == 0)
10881           {
10882             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10883             break;
10884           }
10885         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
10886         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
10887         rot &= 0x1f;
10888         used_at = 1;
10889         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
10890         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10891         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10892       }
10893       break;
10894
10895     case M_ROR_I:
10896       {
10897         unsigned int rot;
10898
10899         if (imm_expr.X_op != O_constant)
10900           as_bad (_("Improper rotate count"));
10901         rot = imm_expr.X_add_number & 0x1f;
10902         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10903           {
10904             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
10905             break;
10906           }
10907         if (rot == 0)
10908           {
10909             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10910             break;
10911           }
10912         used_at = 1;
10913         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
10914         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10915         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10916       }
10917       break;
10918
10919     case M_SEQ:
10920       if (sreg == 0)
10921         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
10922       else if (treg == 0)
10923         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10924       else
10925         {
10926           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10927           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10928         }
10929       break;
10930
10931     case M_SEQ_I:
10932       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10933         {
10934           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10935           break;
10936         }
10937       if (sreg == 0)
10938         {
10939           as_warn (_("Instruction %s: result is always false"),
10940                    ip->insn_mo->name);
10941           move_register (dreg, 0);
10942           break;
10943         }
10944       if (CPU_HAS_SEQ (mips_opts.arch)
10945           && -512 <= imm_expr.X_add_number
10946           && imm_expr.X_add_number < 512)
10947         {
10948           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
10949                        (int) imm_expr.X_add_number);
10950           break;
10951         }
10952       if (imm_expr.X_op == O_constant
10953           && imm_expr.X_add_number >= 0
10954           && imm_expr.X_add_number < 0x10000)
10955         {
10956           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10957         }
10958       else if (imm_expr.X_op == O_constant
10959                && imm_expr.X_add_number > -0x8000
10960                && imm_expr.X_add_number < 0)
10961         {
10962           imm_expr.X_add_number = -imm_expr.X_add_number;
10963           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10964                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10965         }
10966       else if (CPU_HAS_SEQ (mips_opts.arch))
10967         {
10968           used_at = 1;
10969           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10970           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10971           break;
10972         }
10973       else
10974         {
10975           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10976           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10977           used_at = 1;
10978         }
10979       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10980       break;
10981
10982     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
10983       s = "slt";
10984       goto sge;
10985     case M_SGEU:
10986       s = "sltu";
10987     sge:
10988       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
10989       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10990       break;
10991
10992     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
10993     case M_SGEU_I:
10994       if (imm_expr.X_op == O_constant
10995           && imm_expr.X_add_number >= -0x8000
10996           && imm_expr.X_add_number < 0x8000)
10997         {
10998           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
10999                        dreg, sreg, BFD_RELOC_LO16);
11000         }
11001       else
11002         {
11003           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11004           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
11005                        dreg, sreg, AT);
11006           used_at = 1;
11007         }
11008       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11009       break;
11010
11011     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
11012       s = "slt";
11013       goto sgt;
11014     case M_SGTU:
11015       s = "sltu";
11016     sgt:
11017       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11018       break;
11019
11020     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
11021       s = "slt";
11022       goto sgti;
11023     case M_SGTU_I:
11024       s = "sltu";
11025     sgti:
11026       used_at = 1;
11027       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11028       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11029       break;
11030
11031     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
11032       s = "slt";
11033       goto sle;
11034     case M_SLEU:
11035       s = "sltu";
11036     sle:
11037       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11038       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11039       break;
11040
11041     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
11042       s = "slt";
11043       goto slei;
11044     case M_SLEU_I:
11045       s = "sltu";
11046     slei:
11047       used_at = 1;
11048       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11049       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11050       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11051       break;
11052
11053     case M_SLT_I:
11054       if (imm_expr.X_op == O_constant
11055           && imm_expr.X_add_number >= -0x8000
11056           && imm_expr.X_add_number < 0x8000)
11057         {
11058           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11059           break;
11060         }
11061       used_at = 1;
11062       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11063       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
11064       break;
11065
11066     case M_SLTU_I:
11067       if (imm_expr.X_op == O_constant
11068           && imm_expr.X_add_number >= -0x8000
11069           && imm_expr.X_add_number < 0x8000)
11070         {
11071           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
11072                        BFD_RELOC_LO16);
11073           break;
11074         }
11075       used_at = 1;
11076       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11077       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
11078       break;
11079
11080     case M_SNE:
11081       if (sreg == 0)
11082         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
11083       else if (treg == 0)
11084         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11085       else
11086         {
11087           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
11088           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11089         }
11090       break;
11091
11092     case M_SNE_I:
11093       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11094         {
11095           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11096           break;
11097         }
11098       if (sreg == 0)
11099         {
11100           as_warn (_("Instruction %s: result is always true"),
11101                    ip->insn_mo->name);
11102           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
11103                        dreg, 0, BFD_RELOC_LO16);
11104           break;
11105         }
11106       if (CPU_HAS_SEQ (mips_opts.arch)
11107           && -512 <= imm_expr.X_add_number
11108           && imm_expr.X_add_number < 512)
11109         {
11110           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
11111                        (int) imm_expr.X_add_number);
11112           break;
11113         }
11114       if (imm_expr.X_op == O_constant
11115           && imm_expr.X_add_number >= 0
11116           && imm_expr.X_add_number < 0x10000)
11117         {
11118           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
11119         }
11120       else if (imm_expr.X_op == O_constant
11121                && imm_expr.X_add_number > -0x8000
11122                && imm_expr.X_add_number < 0)
11123         {
11124           imm_expr.X_add_number = -imm_expr.X_add_number;
11125           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11126                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11127         }
11128       else if (CPU_HAS_SEQ (mips_opts.arch))
11129         {
11130           used_at = 1;
11131           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11132           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
11133           break;
11134         }
11135       else
11136         {
11137           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11138           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11139           used_at = 1;
11140         }
11141       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11142       break;
11143
11144     case M_SUB_I:
11145       s = "addi";
11146       s2 = "sub";
11147       goto do_subi;
11148     case M_SUBU_I:
11149       s = "addiu";
11150       s2 = "subu";
11151       goto do_subi;
11152     case M_DSUB_I:
11153       dbl = 1;
11154       s = "daddi";
11155       s2 = "dsub";
11156       if (!mips_opts.micromips)
11157         goto do_subi;
11158       if (imm_expr.X_op == O_constant
11159           && imm_expr.X_add_number > -0x200
11160           && imm_expr.X_add_number <= 0x200)
11161         {
11162           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
11163           break;
11164         }
11165       goto do_subi_i;
11166     case M_DSUBU_I:
11167       dbl = 1;
11168       s = "daddiu";
11169       s2 = "dsubu";
11170     do_subi:
11171       if (imm_expr.X_op == O_constant
11172           && imm_expr.X_add_number > -0x8000
11173           && imm_expr.X_add_number <= 0x8000)
11174         {
11175           imm_expr.X_add_number = -imm_expr.X_add_number;
11176           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11177           break;
11178         }
11179     do_subi_i:
11180       used_at = 1;
11181       load_register (AT, &imm_expr, dbl);
11182       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
11183       break;
11184
11185     case M_TEQ_I:
11186       s = "teq";
11187       goto trap;
11188     case M_TGE_I:
11189       s = "tge";
11190       goto trap;
11191     case M_TGEU_I:
11192       s = "tgeu";
11193       goto trap;
11194     case M_TLT_I:
11195       s = "tlt";
11196       goto trap;
11197     case M_TLTU_I:
11198       s = "tltu";
11199       goto trap;
11200     case M_TNE_I:
11201       s = "tne";
11202     trap:
11203       used_at = 1;
11204       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11205       macro_build (NULL, s, "s,t", sreg, AT);
11206       break;
11207
11208     case M_TRUNCWS:
11209     case M_TRUNCWD:
11210       gas_assert (!mips_opts.micromips);
11211       gas_assert (mips_opts.isa == ISA_MIPS1);
11212       used_at = 1;
11213       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
11214       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
11215
11216       /*
11217        * Is the double cfc1 instruction a bug in the mips assembler;
11218        * or is there a reason for it?
11219        */
11220       start_noreorder ();
11221       macro_build (NULL, "cfc1", "t,G", treg, RA);
11222       macro_build (NULL, "cfc1", "t,G", treg, RA);
11223       macro_build (NULL, "nop", "");
11224       expr1.X_add_number = 3;
11225       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
11226       expr1.X_add_number = 2;
11227       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
11228       macro_build (NULL, "ctc1", "t,G", AT, RA);
11229       macro_build (NULL, "nop", "");
11230       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
11231                    dreg, sreg);
11232       macro_build (NULL, "ctc1", "t,G", treg, RA);
11233       macro_build (NULL, "nop", "");
11234       end_noreorder ();
11235       break;
11236
11237     case M_ULH_AB:
11238       s = "lb";
11239       s2 = "lbu";
11240       off = 1;
11241       goto uld_st;
11242     case M_ULHU_AB:
11243       s = "lbu";
11244       s2 = "lbu";
11245       off = 1;
11246       goto uld_st;
11247     case M_ULW_AB:
11248       s = "lwl";
11249       s2 = "lwr";
11250       offbits = (mips_opts.micromips ? 12 : 16);
11251       off = 3;
11252       goto uld_st;
11253     case M_ULD_AB:
11254       s = "ldl";
11255       s2 = "ldr";
11256       offbits = (mips_opts.micromips ? 12 : 16);
11257       off = 7;
11258       goto uld_st;
11259     case M_USH_AB:
11260       s = "sb";
11261       s2 = "sb";
11262       off = 1;
11263       ust = 1;
11264       goto uld_st;
11265     case M_USW_AB:
11266       s = "swl";
11267       s2 = "swr";
11268       offbits = (mips_opts.micromips ? 12 : 16);
11269       off = 3;
11270       ust = 1;
11271       goto uld_st;
11272     case M_USD_AB:
11273       s = "sdl";
11274       s2 = "sdr";
11275       offbits = (mips_opts.micromips ? 12 : 16);
11276       off = 7;
11277       ust = 1;
11278
11279     uld_st:
11280       large_offset = !small_offset_p (off, align, offbits);
11281       ep = &offset_expr;
11282       expr1.X_add_number = 0;
11283       if (large_offset)
11284         {
11285           used_at = 1;
11286           tempreg = AT;
11287           if (small_offset_p (0, align, 16))
11288             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
11289                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11290           else
11291             {
11292               load_address (tempreg, ep, &used_at);
11293               if (breg != 0)
11294                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11295                              tempreg, tempreg, breg);
11296             }
11297           offset_reloc[0] = BFD_RELOC_LO16;
11298           offset_reloc[1] = BFD_RELOC_UNUSED;
11299           offset_reloc[2] = BFD_RELOC_UNUSED;
11300           breg = tempreg;
11301           tempreg = treg;
11302           ep = &expr1;
11303         }
11304       else if (!ust && treg == breg)
11305         {
11306           used_at = 1;
11307           tempreg = AT;
11308         }
11309       else
11310         tempreg = treg;
11311
11312       if (off == 1)
11313         goto ulh_sh;
11314
11315       if (!target_big_endian)
11316         ep->X_add_number += off;
11317       if (offbits == 12)
11318         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
11319       else
11320         macro_build (ep, s, "t,o(b)", tempreg, -1,
11321                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11322
11323       if (!target_big_endian)
11324         ep->X_add_number -= off;
11325       else
11326         ep->X_add_number += off;
11327       if (offbits == 12)
11328         macro_build (NULL, s2, "t,~(b)",
11329                      tempreg, (int) ep->X_add_number, breg);
11330       else
11331         macro_build (ep, s2, "t,o(b)", tempreg, -1,
11332                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11333
11334       /* If necessary, move the result in tempreg to the final destination.  */
11335       if (!ust && treg != tempreg)
11336         {
11337           /* Protect second load's delay slot.  */
11338           load_delay_nop ();
11339           move_register (treg, tempreg);
11340         }
11341       break;
11342
11343     ulh_sh:
11344       used_at = 1;
11345       if (target_big_endian == ust)
11346         ep->X_add_number += off;
11347       tempreg = ust || large_offset ? treg : AT;
11348       macro_build (ep, s, "t,o(b)", tempreg, -1,
11349                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11350
11351       /* For halfword transfers we need a temporary register to shuffle
11352          bytes.  Unfortunately for M_USH_A we have none available before
11353          the next store as AT holds the base address.  We deal with this
11354          case by clobbering TREG and then restoring it as with ULH.  */
11355       tempreg = ust == large_offset ? treg : AT;
11356       if (ust)
11357         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
11358
11359       if (target_big_endian == ust)
11360         ep->X_add_number -= off;
11361       else
11362         ep->X_add_number += off;
11363       macro_build (ep, s2, "t,o(b)", tempreg, -1,
11364                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11365
11366       /* For M_USH_A re-retrieve the LSB.  */
11367       if (ust && large_offset)
11368         {
11369           if (target_big_endian)
11370             ep->X_add_number += off;
11371           else
11372             ep->X_add_number -= off;
11373           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
11374                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
11375         }
11376       /* For ULH and M_USH_A OR the LSB in.  */
11377       if (!ust || large_offset)
11378         {
11379           tempreg = !large_offset ? AT : treg;
11380           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
11381           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
11382         }
11383       break;
11384
11385     default:
11386       /* FIXME: Check if this is one of the itbl macros, since they
11387          are added dynamically.  */
11388       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
11389       break;
11390     }
11391   if (!mips_opts.at && used_at)
11392     as_bad (_("Macro used $at after \".set noat\""));
11393 }
11394
11395 /* Implement macros in mips16 mode.  */
11396
11397 static void
11398 mips16_macro (struct mips_cl_insn *ip)
11399 {
11400   int mask;
11401   int xreg, yreg, zreg, tmp;
11402   expressionS expr1;
11403   int dbl;
11404   const char *s, *s2, *s3;
11405
11406   mask = ip->insn_mo->mask;
11407
11408   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
11409   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
11410   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
11411
11412   expr1.X_op = O_constant;
11413   expr1.X_op_symbol = NULL;
11414   expr1.X_add_symbol = NULL;
11415   expr1.X_add_number = 1;
11416
11417   dbl = 0;
11418
11419   switch (mask)
11420     {
11421     default:
11422       abort ();
11423
11424     case M_DDIV_3:
11425       dbl = 1;
11426     case M_DIV_3:
11427       s = "mflo";
11428       goto do_div3;
11429     case M_DREM_3:
11430       dbl = 1;
11431     case M_REM_3:
11432       s = "mfhi";
11433     do_div3:
11434       start_noreorder ();
11435       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
11436       expr1.X_add_number = 2;
11437       macro_build (&expr1, "bnez", "x,p", yreg);
11438       macro_build (NULL, "break", "6", 7);
11439
11440       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
11441          since that causes an overflow.  We should do that as well,
11442          but I don't see how to do the comparisons without a temporary
11443          register.  */
11444       end_noreorder ();
11445       macro_build (NULL, s, "x", zreg);
11446       break;
11447
11448     case M_DIVU_3:
11449       s = "divu";
11450       s2 = "mflo";
11451       goto do_divu3;
11452     case M_REMU_3:
11453       s = "divu";
11454       s2 = "mfhi";
11455       goto do_divu3;
11456     case M_DDIVU_3:
11457       s = "ddivu";
11458       s2 = "mflo";
11459       goto do_divu3;
11460     case M_DREMU_3:
11461       s = "ddivu";
11462       s2 = "mfhi";
11463     do_divu3:
11464       start_noreorder ();
11465       macro_build (NULL, s, "0,x,y", xreg, yreg);
11466       expr1.X_add_number = 2;
11467       macro_build (&expr1, "bnez", "x,p", yreg);
11468       macro_build (NULL, "break", "6", 7);
11469       end_noreorder ();
11470       macro_build (NULL, s2, "x", zreg);
11471       break;
11472
11473     case M_DMUL:
11474       dbl = 1;
11475     case M_MUL:
11476       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
11477       macro_build (NULL, "mflo", "x", zreg);
11478       break;
11479
11480     case M_DSUBU_I:
11481       dbl = 1;
11482       goto do_subu;
11483     case M_SUBU_I:
11484     do_subu:
11485       if (imm_expr.X_op != O_constant)
11486         as_bad (_("Unsupported large constant"));
11487       imm_expr.X_add_number = -imm_expr.X_add_number;
11488       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
11489       break;
11490
11491     case M_SUBU_I_2:
11492       if (imm_expr.X_op != O_constant)
11493         as_bad (_("Unsupported large constant"));
11494       imm_expr.X_add_number = -imm_expr.X_add_number;
11495       macro_build (&imm_expr, "addiu", "x,k", xreg);
11496       break;
11497
11498     case M_DSUBU_I_2:
11499       if (imm_expr.X_op != O_constant)
11500         as_bad (_("Unsupported large constant"));
11501       imm_expr.X_add_number = -imm_expr.X_add_number;
11502       macro_build (&imm_expr, "daddiu", "y,j", yreg);
11503       break;
11504
11505     case M_BEQ:
11506       s = "cmp";
11507       s2 = "bteqz";
11508       goto do_branch;
11509     case M_BNE:
11510       s = "cmp";
11511       s2 = "btnez";
11512       goto do_branch;
11513     case M_BLT:
11514       s = "slt";
11515       s2 = "btnez";
11516       goto do_branch;
11517     case M_BLTU:
11518       s = "sltu";
11519       s2 = "btnez";
11520       goto do_branch;
11521     case M_BLE:
11522       s = "slt";
11523       s2 = "bteqz";
11524       goto do_reverse_branch;
11525     case M_BLEU:
11526       s = "sltu";
11527       s2 = "bteqz";
11528       goto do_reverse_branch;
11529     case M_BGE:
11530       s = "slt";
11531       s2 = "bteqz";
11532       goto do_branch;
11533     case M_BGEU:
11534       s = "sltu";
11535       s2 = "bteqz";
11536       goto do_branch;
11537     case M_BGT:
11538       s = "slt";
11539       s2 = "btnez";
11540       goto do_reverse_branch;
11541     case M_BGTU:
11542       s = "sltu";
11543       s2 = "btnez";
11544
11545     do_reverse_branch:
11546       tmp = xreg;
11547       xreg = yreg;
11548       yreg = tmp;
11549
11550     do_branch:
11551       macro_build (NULL, s, "x,y", xreg, yreg);
11552       macro_build (&offset_expr, s2, "p");
11553       break;
11554
11555     case M_BEQ_I:
11556       s = "cmpi";
11557       s2 = "bteqz";
11558       s3 = "x,U";
11559       goto do_branch_i;
11560     case M_BNE_I:
11561       s = "cmpi";
11562       s2 = "btnez";
11563       s3 = "x,U";
11564       goto do_branch_i;
11565     case M_BLT_I:
11566       s = "slti";
11567       s2 = "btnez";
11568       s3 = "x,8";
11569       goto do_branch_i;
11570     case M_BLTU_I:
11571       s = "sltiu";
11572       s2 = "btnez";
11573       s3 = "x,8";
11574       goto do_branch_i;
11575     case M_BLE_I:
11576       s = "slti";
11577       s2 = "btnez";
11578       s3 = "x,8";
11579       goto do_addone_branch_i;
11580     case M_BLEU_I:
11581       s = "sltiu";
11582       s2 = "btnez";
11583       s3 = "x,8";
11584       goto do_addone_branch_i;
11585     case M_BGE_I:
11586       s = "slti";
11587       s2 = "bteqz";
11588       s3 = "x,8";
11589       goto do_branch_i;
11590     case M_BGEU_I:
11591       s = "sltiu";
11592       s2 = "bteqz";
11593       s3 = "x,8";
11594       goto do_branch_i;
11595     case M_BGT_I:
11596       s = "slti";
11597       s2 = "bteqz";
11598       s3 = "x,8";
11599       goto do_addone_branch_i;
11600     case M_BGTU_I:
11601       s = "sltiu";
11602       s2 = "bteqz";
11603       s3 = "x,8";
11604
11605     do_addone_branch_i:
11606       if (imm_expr.X_op != O_constant)
11607         as_bad (_("Unsupported large constant"));
11608       ++imm_expr.X_add_number;
11609
11610     do_branch_i:
11611       macro_build (&imm_expr, s, s3, xreg);
11612       macro_build (&offset_expr, s2, "p");
11613       break;
11614
11615     case M_ABS:
11616       expr1.X_add_number = 0;
11617       macro_build (&expr1, "slti", "x,8", yreg);
11618       if (xreg != yreg)
11619         move_register (xreg, yreg);
11620       expr1.X_add_number = 2;
11621       macro_build (&expr1, "bteqz", "p");
11622       macro_build (NULL, "neg", "x,w", xreg, xreg);
11623     }
11624 }
11625
11626 /* Assemble an instruction into its binary format.  If the instruction
11627    is a macro, set imm_expr, imm2_expr and offset_expr to the values
11628    associated with "I", "+I" and "A" operands respectively.  Otherwise
11629    store the value of the relocatable field (if any) in offset_expr.
11630    In both cases set offset_reloc to the relocation operators applied
11631    to offset_expr.  */
11632
11633 static void
11634 mips_ip (char *str, struct mips_cl_insn *ip)
11635 {
11636   bfd_boolean wrong_delay_slot_insns = FALSE;
11637   bfd_boolean need_delay_slot_ok = TRUE;
11638   struct mips_opcode *firstinsn = NULL;
11639   const struct mips_opcode *past;
11640   struct hash_control *hash;
11641   char *s;
11642   const char *args;
11643   char c = 0;
11644   struct mips_opcode *insn;
11645   char *argsStart;
11646   long opend;
11647   char *name;
11648   char *dot;
11649   long end;
11650   const struct mips_operand *operand;
11651   struct mips_arg_info arg;
11652
11653   insn_error = NULL;
11654
11655   if (mips_opts.micromips)
11656     {
11657       hash = micromips_op_hash;
11658       past = &micromips_opcodes[bfd_micromips_num_opcodes];
11659     }
11660   else
11661     {
11662       hash = op_hash;
11663       past = &mips_opcodes[NUMOPCODES];
11664     }
11665   forced_insn_length = 0;
11666   insn = NULL;
11667
11668   /* We first try to match an instruction up to a space or to the end.  */
11669   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
11670     continue;
11671
11672   /* Make a copy of the instruction so that we can fiddle with it.  */
11673   name = alloca (end + 1);
11674   memcpy (name, str, end);
11675   name[end] = '\0';
11676
11677   for (;;)
11678     {
11679       insn = (struct mips_opcode *) hash_find (hash, name);
11680
11681       if (insn != NULL || !mips_opts.micromips)
11682         break;
11683       if (forced_insn_length)
11684         break;
11685
11686       /* See if there's an instruction size override suffix,
11687          either `16' or `32', at the end of the mnemonic proper,
11688          that defines the operation, i.e. before the first `.'
11689          character if any.  Strip it and retry.  */
11690       dot = strchr (name, '.');
11691       opend = dot != NULL ? dot - name : end;
11692       if (opend < 3)
11693         break;
11694       if (name[opend - 2] == '1' && name[opend - 1] == '6')
11695         forced_insn_length = 2;
11696       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11697         forced_insn_length = 4;
11698       else
11699         break;
11700       memcpy (name + opend - 2, name + opend, end - opend + 1);
11701     }
11702   if (insn == NULL)
11703     {
11704       insn_error = _("Unrecognized opcode");
11705       return;
11706     }
11707
11708   /* For microMIPS instructions placed in a fixed-length branch delay slot
11709      we make up to two passes over the relevant fragment of the opcode
11710      table.  First we try instructions that meet the delay slot's length
11711      requirement.  If none matched, then we retry with the remaining ones
11712      and if one matches, then we use it and then issue an appropriate
11713      warning later on.  */
11714   argsStart = s = str + end;
11715   for (;;)
11716     {
11717       bfd_boolean delay_slot_ok;
11718       bfd_boolean size_ok;
11719       bfd_boolean ok;
11720       bfd_boolean more_alts;
11721
11722       gas_assert (strcmp (insn->name, name) == 0);
11723
11724       ok = is_opcode_valid (insn);
11725       size_ok = is_size_valid (insn);
11726       delay_slot_ok = is_delay_slot_valid (insn);
11727       if (!delay_slot_ok && !wrong_delay_slot_insns)
11728         {
11729           firstinsn = insn;
11730           wrong_delay_slot_insns = TRUE;
11731         }
11732       more_alts = (insn + 1 < past
11733                    && strcmp (insn[0].name, insn[1].name) == 0);
11734       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11735         {
11736           static char buf[256];
11737
11738           if (more_alts)
11739             {
11740               ++insn;
11741               continue;
11742             }
11743           if (wrong_delay_slot_insns && need_delay_slot_ok)
11744             {
11745               gas_assert (firstinsn);
11746               need_delay_slot_ok = FALSE;
11747               past = insn + 1;
11748               insn = firstinsn;
11749               continue;
11750             }
11751
11752           if (insn_error)
11753             return;
11754
11755           if (!ok)
11756             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11757                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11758                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11759           else if (mips_opts.insn32)
11760             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
11761           else
11762             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11763                      8 * forced_insn_length);
11764           insn_error = buf;
11765
11766           return;
11767         }
11768
11769       imm_expr.X_op = O_absent;
11770       imm2_expr.X_op = O_absent;
11771       offset_expr.X_op = O_absent;
11772       offset_reloc[0] = BFD_RELOC_UNUSED;
11773       offset_reloc[1] = BFD_RELOC_UNUSED;
11774       offset_reloc[2] = BFD_RELOC_UNUSED;
11775
11776       create_insn (ip, insn);
11777       insn_error = NULL;
11778       memset (&arg, 0, sizeof (arg));
11779       arg.insn = ip;
11780       arg.argnum = 1;
11781       arg.last_regno = ILLEGAL_REG;
11782       arg.dest_regno = ILLEGAL_REG;
11783       arg.soft_match = (more_alts
11784                         || (wrong_delay_slot_insns && need_delay_slot_ok));
11785       for (args = insn->args;; ++args)
11786         {
11787           SKIP_SPACE_TABS (s);
11788           if (*s == 0)
11789             {
11790               /* Handle unary instructions in which only one operand is given.
11791                  The source is then the same as the destination.  */
11792               if (arg.opnum == 1 && *args == ',')
11793                 switch (args[1])
11794                   {
11795                   case 'r':
11796                   case 'v':
11797                   case 'w':
11798                   case 'W':
11799                   case 'V':
11800                     arg.argnum = 1;
11801                     s = argsStart;
11802                     continue;
11803                   }
11804
11805               /* Treat elided base registers as $0.  */
11806               if (strcmp (args, "(b)") == 0)
11807                 args += 3;
11808
11809               /* Fail the match if there were too few operands.  */
11810               if (*args)
11811                 break;
11812
11813               /* Successful match.  */
11814               if (arg.dest_regno == arg.last_regno
11815                   && strncmp (ip->insn_mo->name, "jalr", 4) == 0)
11816                 {
11817                   if (arg.opnum == 2)
11818                     as_bad (_("Source and destination must be different"));
11819                   else if (arg.last_regno == 31)
11820                     as_bad (_("A destination register must be supplied"));
11821                 }
11822               check_completed_insn (&arg);
11823               return;
11824             }
11825
11826           /* Fail the match if the line has too many operands.   */
11827           if (*args == 0)
11828             break;
11829
11830           /* Handle characters that need to match exactly.  */
11831           if (*args == '(' || *args == ')' || *args == ',')
11832             {
11833               if (*s != *args)
11834                 break;
11835               if (*s == ',')
11836                 arg.argnum += 1;
11837               ++s;
11838               continue;
11839             }
11840
11841           /* Handle special macro operands.  Work out the properties of
11842              other operands.  */
11843           arg.opnum += 1;
11844           arg.optional_reg = FALSE;
11845           arg.lax_max = FALSE;
11846           switch (*args)
11847             {
11848             case '+':
11849               switch (args[1])
11850                 {
11851                 case '1':
11852                 case '2':
11853                 case '3':
11854                 case '4':
11855                 case 'B':
11856                 case 'C':
11857                 case 'F':
11858                 case 'G':
11859                 case 'H':
11860                 case 'J':
11861                 case 'Q':
11862                 case 'S':
11863                 case 's':
11864                   /* If these integer forms come last, there is no other
11865                      form of the instruction that could match.  Prefer to
11866                      give detailed error messages where possible.  */
11867                   if (args[2] == 0)
11868                     arg.soft_match = FALSE;
11869                   break;
11870
11871                 case 'I':
11872                   /* "+I" is like "I", except that imm2_expr is used.  */
11873                   my_getExpression (&imm2_expr, s);
11874                   if (imm2_expr.X_op != O_big
11875                       && imm2_expr.X_op != O_constant)
11876                   insn_error = _("absolute expression required");
11877                   if (HAVE_32BIT_GPRS)
11878                     normalize_constant_expr (&imm2_expr);
11879                   s = expr_end;
11880                   ++args;
11881                   continue;
11882
11883                 case 'i':
11884                   *offset_reloc = BFD_RELOC_MIPS_JMP;
11885                   break;
11886                 }
11887               break;
11888
11889             case '\'':
11890             case ':':
11891             case '@':
11892             case '^':
11893             case '$':
11894             case '\\':
11895             case '%':
11896             case '|':
11897             case '0':
11898             case '1':
11899             case '2':
11900             case '3':
11901             case '4':
11902             case '5':
11903             case '6':
11904             case '8':
11905             case 'B':
11906             case 'C':
11907             case 'J':
11908             case 'O':
11909             case 'P':
11910             case 'Q':
11911             case 'c':
11912             case 'h':
11913             case 'q':
11914               /* If these integer forms come last, there is no other
11915                  form of the instruction that could match.  Prefer to
11916                  give detailed error messages where possible.  */
11917               if (args[1] == 0)
11918                 arg.soft_match = FALSE;
11919               break;
11920
11921             case 'r':
11922             case 'v':
11923             case 'w':
11924             case 'W':
11925             case 'V':
11926               /* We have already matched a comma by this point, so the register
11927                  is only optional if there is another operand to come.  */
11928               gas_assert (arg.opnum == 2);
11929               arg.optional_reg = (args[1] == ',');
11930               break;
11931
11932             case 'I':
11933               my_getExpression (&imm_expr, s);
11934               if (imm_expr.X_op != O_big
11935                   && imm_expr.X_op != O_constant)
11936                 insn_error = _("absolute expression required");
11937               if (HAVE_32BIT_GPRS)
11938                 normalize_constant_expr (&imm_expr);
11939               s = expr_end;
11940               continue;
11941
11942             case 'A':
11943               my_getSmallExpression (&offset_expr, offset_reloc, s);
11944               if (offset_expr.X_op == O_register)
11945                 {
11946                   /* Assume that the offset has been elided and that what
11947                      we saw was a base register.  The match will fail later
11948                      if that assumption turns out to be wrong.  */
11949                   offset_expr.X_op = O_constant;
11950                   offset_expr.X_add_number = 0;
11951                 }
11952               else
11953                 {
11954                   normalize_address_expr (&offset_expr);
11955                   s = expr_end;
11956                 }
11957               continue;
11958
11959             case 'F':
11960             case 'L':
11961             case 'f':
11962             case 'l':
11963               {
11964                 int f64;
11965                 int using_gprs;
11966                 char *save_in;
11967                 char *err;
11968                 unsigned char temp[8];
11969                 int len;
11970                 unsigned int length;
11971                 segT seg;
11972                 subsegT subseg;
11973                 char *p;
11974
11975                 /* These only appear as the last operand in an
11976                    instruction, and every instruction that accepts
11977                    them in any variant accepts them in all variants.
11978                    This means we don't have to worry about backing out
11979                    any changes if the instruction does not match.
11980
11981                    The difference between them is the size of the
11982                    floating point constant and where it goes.  For 'F'
11983                    and 'L' the constant is 64 bits; for 'f' and 'l' it
11984                    is 32 bits.  Where the constant is placed is based
11985                    on how the MIPS assembler does things:
11986                     F -- .rdata
11987                     L -- .lit8
11988                     f -- immediate value
11989                     l -- .lit4
11990
11991                     The .lit4 and .lit8 sections are only used if
11992                     permitted by the -G argument.
11993
11994                     The code below needs to know whether the target register
11995                     is 32 or 64 bits wide.  It relies on the fact 'f' and
11996                     'F' are used with GPR-based instructions and 'l' and
11997                     'L' are used with FPR-based instructions.  */
11998
11999                 f64 = *args == 'F' || *args == 'L';
12000                 using_gprs = *args == 'F' || *args == 'f';
12001
12002                 save_in = input_line_pointer;
12003                 input_line_pointer = s;
12004                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12005                 length = len;
12006                 s = input_line_pointer;
12007                 input_line_pointer = save_in;
12008                 if (err != NULL && *err != '\0')
12009                   {
12010                     as_bad (_("Bad floating point constant: %s"), err);
12011                     memset (temp, '\0', sizeof temp);
12012                     length = f64 ? 8 : 4;
12013                   }
12014
12015                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12016
12017                 if (*args == 'f'
12018                     || (*args == 'l'
12019                         && (g_switch_value < 4
12020                             || (temp[0] == 0 && temp[1] == 0)
12021                             || (temp[2] == 0 && temp[3] == 0))))
12022                   {
12023                     imm_expr.X_op = O_constant;
12024                     if (!target_big_endian)
12025                       imm_expr.X_add_number = bfd_getl32 (temp);
12026                     else
12027                       imm_expr.X_add_number = bfd_getb32 (temp);
12028                   }
12029                 else if (length > 4
12030                          && !mips_disable_float_construction
12031                          /* Constants can only be constructed in GPRs and
12032                             copied to FPRs if the GPRs are at least as wide
12033                             as the FPRs.  Force the constant into memory if
12034                             we are using 64-bit FPRs but the GPRs are only
12035                             32 bits wide.  */
12036                          && (using_gprs
12037                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12038                          && ((temp[0] == 0 && temp[1] == 0)
12039                              || (temp[2] == 0 && temp[3] == 0))
12040                          && ((temp[4] == 0 && temp[5] == 0)
12041                              || (temp[6] == 0 && temp[7] == 0)))
12042                   {
12043                     /* The value is simple enough to load with a couple of
12044                        instructions.  If using 32-bit registers, set
12045                        imm_expr to the high order 32 bits and offset_expr to
12046                        the low order 32 bits.  Otherwise, set imm_expr to
12047                        the entire 64 bit constant.  */
12048                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12049                       {
12050                         imm_expr.X_op = O_constant;
12051                         offset_expr.X_op = O_constant;
12052                         if (!target_big_endian)
12053                           {
12054                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12055                             offset_expr.X_add_number = bfd_getl32 (temp);
12056                           }
12057                         else
12058                           {
12059                             imm_expr.X_add_number = bfd_getb32 (temp);
12060                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12061                           }
12062                         if (offset_expr.X_add_number == 0)
12063                           offset_expr.X_op = O_absent;
12064                       }
12065                     else
12066                       {
12067                         imm_expr.X_op = O_constant;
12068                         if (!target_big_endian)
12069                           imm_expr.X_add_number = bfd_getl64 (temp);
12070                         else
12071                           imm_expr.X_add_number = bfd_getb64 (temp);
12072                       }
12073                   }
12074                 else
12075                   {
12076                     const char *newname;
12077                     segT new_seg;
12078
12079                     /* Switch to the right section.  */
12080                     seg = now_seg;
12081                     subseg = now_subseg;
12082                     switch (*args)
12083                       {
12084                       default: /* unused default case avoids warnings.  */
12085                       case 'L':
12086                         newname = RDATA_SECTION_NAME;
12087                         if (g_switch_value >= 8)
12088                           newname = ".lit8";
12089                         break;
12090                       case 'F':
12091                         newname = RDATA_SECTION_NAME;
12092                         break;
12093                       case 'l':
12094                         gas_assert (g_switch_value >= 4);
12095                         newname = ".lit4";
12096                         break;
12097                       }
12098                     new_seg = subseg_new (newname, (subsegT) 0);
12099                     bfd_set_section_flags (stdoutput, new_seg,
12100                                            (SEC_ALLOC
12101                                             | SEC_LOAD
12102                                             | SEC_READONLY
12103                                             | SEC_DATA));
12104                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12105                     if (strncmp (TARGET_OS, "elf", 3) != 0)
12106                       record_alignment (new_seg, 4);
12107                     else
12108                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12109                     if (seg == now_seg)
12110                       as_bad (_("Can't use floating point insn in this section"));
12111
12112                     /* Set the argument to the current address in the
12113                        section.  */
12114                     offset_expr.X_op = O_symbol;
12115                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12116                     offset_expr.X_add_number = 0;
12117
12118                     /* Put the floating point number into the section.  */
12119                     p = frag_more ((int) length);
12120                     memcpy (p, temp, length);
12121
12122                     /* Switch back to the original section.  */
12123                     subseg_set (seg, subseg);
12124                   }
12125               }
12126               continue;
12127
12128               /* ??? This is the traditional behavior, but is flaky if
12129                  there are alternative versions of the same instruction
12130                  for different subarchitectures.  The next alternative
12131                  might not be suitable.  */
12132             case 'j':
12133               /* For compatibility with older assemblers, we accept
12134                  0x8000-0xffff as signed 16-bit numbers when only
12135                  signed numbers are allowed.  */
12136               arg.lax_max = !more_alts;
12137             case 'i':
12138               /* Only accept non-constant operands if this is the
12139                  final alternative.  Later alternatives might include
12140                  a macro implementation.  */
12141               arg.allow_nonconst = !more_alts;
12142               break;
12143
12144             case 'u':
12145               /* There are no macro implementations for out-of-range values.  */
12146               arg.allow_nonconst = TRUE;
12147               break;
12148
12149             case 'o':
12150               /* There should always be a macro implementation.  */
12151               arg.allow_nonconst = FALSE;
12152               break;
12153
12154             case 'p':
12155               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12156               break;
12157
12158             case 'a':
12159               *offset_reloc = BFD_RELOC_MIPS_JMP;
12160               break;
12161
12162             case 'm':
12163               gas_assert (mips_opts.micromips);
12164               c = args[1];
12165               switch (c)
12166                 {
12167                 case 't':
12168                 case 'c':
12169                 case 'e':
12170                   /* We have already matched a comma by this point,
12171                      so the register is only optional if there is another
12172                      operand to come.  */
12173                   gas_assert (arg.opnum == 2);
12174                   arg.optional_reg = (args[2] == ',');
12175                   break;
12176
12177                 case 'D':
12178                 case 'E':
12179                   if (!forced_insn_length)
12180                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12181                   else if (c == 'D')
12182                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12183                   else
12184                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12185                   break;
12186                 }
12187               break;
12188             }
12189
12190           operand = (mips_opts.micromips
12191                      ? decode_micromips_operand (args)
12192                      : decode_mips_operand (args));
12193           if (!operand)
12194             abort ();
12195
12196           s = match_operand (&arg, operand, s);
12197           if (!s && arg.optional_reg)
12198             {
12199               /* Assume that the register has been elided and is the
12200                  same as the first operand.  */
12201               arg.optional_reg = FALSE;
12202               arg.argnum = 1;
12203               s = argsStart;
12204               SKIP_SPACE_TABS (s);
12205               s = match_operand (&arg, operand, s);
12206             }
12207           if (!s)
12208             break;
12209
12210           /* Skip prefixes.  */
12211           if (*args == '+' || *args == 'm')
12212             args++;
12213
12214           continue;
12215         }
12216       /* Args don't match.  */
12217       s = argsStart;
12218       insn_error = _("Illegal operands");
12219       if (more_alts)
12220         {
12221           ++insn;
12222           continue;
12223         }
12224       if (wrong_delay_slot_insns && need_delay_slot_ok)
12225         {
12226           gas_assert (firstinsn);
12227           need_delay_slot_ok = FALSE;
12228           past = insn + 1;
12229           insn = firstinsn;
12230           continue;
12231         }
12232       return;
12233     }
12234 }
12235
12236 /* As for mips_ip, but used when assembling MIPS16 code.
12237    Also set forced_insn_length to the resulting instruction size in
12238    bytes if the user explicitly requested a small or extended instruction.  */
12239
12240 static void
12241 mips16_ip (char *str, struct mips_cl_insn *ip)
12242 {
12243   char *s;
12244   const char *args;
12245   struct mips_opcode *insn;
12246   char *argsstart;
12247   size_t i;
12248   const struct mips_operand *operand;
12249   const struct mips_operand *ext_operand;
12250   struct mips_arg_info arg;
12251
12252   insn_error = NULL;
12253
12254   forced_insn_length = 0;
12255
12256   for (s = str; ISLOWER (*s); ++s)
12257     ;
12258   switch (*s)
12259     {
12260     case '\0':
12261       break;
12262
12263     case ' ':
12264       *s++ = '\0';
12265       break;
12266
12267     case '.':
12268       if (s[1] == 't' && s[2] == ' ')
12269         {
12270           *s = '\0';
12271           forced_insn_length = 2;
12272           s += 3;
12273           break;
12274         }
12275       else if (s[1] == 'e' && s[2] == ' ')
12276         {
12277           *s = '\0';
12278           forced_insn_length = 4;
12279           s += 3;
12280           break;
12281         }
12282       /* Fall through.  */
12283     default:
12284       insn_error = _("unknown opcode");
12285       return;
12286     }
12287
12288   if (mips_opts.noautoextend && !forced_insn_length)
12289     forced_insn_length = 2;
12290
12291   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
12292     {
12293       insn_error = _("unrecognized opcode");
12294       return;
12295     }
12296
12297   argsstart = s;
12298   for (;;)
12299     {
12300       bfd_boolean ok;
12301       bfd_boolean more_alts;
12302       char relax_char;
12303
12304       gas_assert (strcmp (insn->name, str) == 0);
12305
12306       ok = is_opcode_valid_16 (insn);
12307       more_alts = (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
12308                    && strcmp (insn[0].name, insn[1].name) == 0);
12309       if (! ok)
12310         {
12311           if (more_alts)
12312             {
12313               ++insn;
12314               continue;
12315             }
12316           else
12317             {
12318               if (!insn_error)
12319                 {
12320                   static char buf[100];
12321                   sprintf (buf,
12322                            _("Opcode not supported on this processor: %s (%s)"),
12323                            mips_cpu_info_from_arch (mips_opts.arch)->name,
12324                            mips_cpu_info_from_isa (mips_opts.isa)->name);
12325                   insn_error = buf;
12326                 }
12327               return;
12328             }
12329         }
12330
12331       create_insn (ip, insn);
12332       imm_expr.X_op = O_absent;
12333       imm2_expr.X_op = O_absent;
12334       offset_expr.X_op = O_absent;
12335       offset_reloc[0] = BFD_RELOC_UNUSED;
12336       offset_reloc[1] = BFD_RELOC_UNUSED;
12337       offset_reloc[2] = BFD_RELOC_UNUSED;
12338       relax_char = 0;
12339
12340       memset (&arg, 0, sizeof (arg));
12341       arg.insn = ip;
12342       arg.argnum = 1;
12343       arg.last_regno = ILLEGAL_REG;
12344       arg.dest_regno = ILLEGAL_REG;
12345       arg.soft_match = more_alts;
12346       relax_char = 0;
12347       for (args = insn->args; 1; ++args)
12348         {
12349           int c;
12350
12351           SKIP_SPACE_TABS (s);
12352           if (*s == 0)
12353             {
12354               offsetT value;
12355
12356               /* Handle unary instructions in which only one operand is given.
12357                  The source is then the same as the destination.  */
12358               if (arg.opnum == 1 && *args == ',')
12359                 switch (args[1])
12360                   {
12361                   case 'v':
12362                   case 'w':
12363                     arg.argnum = 1;
12364                     s = argsstart;
12365                     continue;
12366                   }
12367
12368               /* Fail the match if there were too few operands.  */
12369               if (*args)
12370                 break;
12371
12372               /* Successful match.  Stuff the immediate value in now, if
12373                  we can.  */
12374               if (insn->pinfo == INSN_MACRO)
12375                 {
12376                   gas_assert (relax_char == 0);
12377                   gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
12378                 }
12379               else if (relax_char
12380                        && offset_expr.X_op == O_constant
12381                        && calculate_reloc (*offset_reloc,
12382                                            offset_expr.X_add_number,
12383                                            &value))
12384                 {
12385                   mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
12386                                 forced_insn_length, &ip->insn_opcode);
12387                   offset_expr.X_op = O_absent;
12388                   *offset_reloc = BFD_RELOC_UNUSED;
12389                 }
12390               else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
12391                 {
12392                   if (forced_insn_length == 2)
12393                     as_bad (_("invalid unextended operand value"));
12394                   forced_insn_length = 4;
12395                   ip->insn_opcode |= MIPS16_EXTEND;
12396                 }
12397               else if (relax_char)
12398                 *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
12399
12400               check_completed_insn (&arg);
12401               return;
12402             }
12403
12404           /* Fail the match if the line has too many operands.   */
12405           if (*args == 0)
12406             break;
12407
12408           /* Handle characters that need to match exactly.  */
12409           if (*args == '(' || *args == ')' || *args == ',')
12410             {
12411               if (*s != *args)
12412                 break;
12413               if (*s == ',')
12414                 arg.argnum += 1;
12415               ++s;
12416               continue;
12417             }
12418
12419           arg.opnum += 1;
12420           arg.optional_reg = FALSE;
12421           c = *args;
12422           switch (c)
12423             {
12424             case 'v':
12425             case 'w':
12426               arg.optional_reg = (args[1] == ',');
12427               break;
12428
12429             case 'p':
12430             case 'q':
12431             case 'A':
12432             case 'B':
12433             case 'E':
12434               relax_char = c;
12435               break;
12436
12437             case 'I':
12438               my_getExpression (&imm_expr, s);
12439               if (imm_expr.X_op != O_big
12440                   && imm_expr.X_op != O_constant)
12441                 insn_error = _("absolute expression required");
12442               if (HAVE_32BIT_GPRS)
12443                 normalize_constant_expr (&imm_expr);
12444               s = expr_end;
12445               continue;
12446
12447             case 'a':
12448             case 'i':
12449               *offset_reloc = BFD_RELOC_MIPS16_JMP;
12450               ip->insn_opcode <<= 16;
12451               break;
12452             }
12453
12454           operand = decode_mips16_operand (c, FALSE);
12455           if (!operand)
12456             abort ();
12457
12458           /* '6' is a special case.  It is used for BREAK and SDBBP,
12459              whose operands are only meaningful to the software that decodes
12460              them.  This means that there is no architectural reason why
12461              they cannot be prefixed by EXTEND, but in practice,
12462              exception handlers will only look at the instruction
12463              itself.  We therefore allow '6' to be extended when
12464              disassembling but not when assembling.  */
12465           if (operand->type != OP_PCREL && c != '6')
12466             {
12467               ext_operand = decode_mips16_operand (c, TRUE);
12468               if (operand != ext_operand)
12469                 {
12470                   /* Parse the expression, allowing relocation operators.  */
12471                   i = my_getSmallExpression (&offset_expr, offset_reloc, s);
12472                   s = expr_end;
12473
12474                   if (offset_expr.X_op == O_register)
12475                     {
12476                       /* Handle elided offsets, which are equivalent to 0.  */
12477                       if (*s == '(')
12478                         {
12479                           offset_expr.X_op = O_constant;
12480                           offset_expr.X_add_number = 0;
12481                           relax_char = c;
12482                           continue;
12483                         }
12484                       /* Fail the match.  */
12485                       break;
12486                     }
12487                   /* '8' is used for SLTI(U) and has traditionally not
12488                      been allowed to take relocation operators.  */
12489                   if (i > 0 && (ext_operand->size != 16 || c == '8'))
12490                     break;
12491                   relax_char = c;
12492                   continue;
12493                 }
12494             }
12495
12496           s = match_operand (&arg, operand, s);
12497           if (!s && arg.optional_reg)
12498             {
12499               /* Assume that the register has been elided and is the
12500                  same as the first operand.  */
12501               arg.optional_reg = FALSE;
12502               arg.argnum = 1;
12503               s = argsstart;
12504               SKIP_SPACE_TABS (s);
12505               s = match_operand (&arg, operand, s);
12506             }
12507           if (!s)
12508             break;
12509           continue;
12510         }
12511
12512       /* Args don't match.  */
12513       if (more_alts)
12514         {
12515           ++insn;
12516           s = argsstart;
12517           continue;
12518         }
12519
12520       insn_error = _("illegal operands");
12521
12522       return;
12523     }
12524 }
12525
12526 /* This structure holds information we know about a mips16 immediate
12527    argument type.  */
12528
12529 struct mips16_immed_operand
12530 {
12531   /* The type code used in the argument string in the opcode table.  */
12532   int type;
12533   /* The number of bits in the short form of the opcode.  */
12534   int nbits;
12535   /* The number of bits in the extended form of the opcode.  */
12536   int extbits;
12537   /* The amount by which the short form is shifted when it is used;
12538      for example, the sw instruction has a shift count of 2.  */
12539   int shift;
12540   /* The amount by which the short form is shifted when it is stored
12541      into the instruction code.  */
12542   int op_shift;
12543   /* Non-zero if the short form is unsigned.  */
12544   int unsp;
12545   /* Non-zero if the extended form is unsigned.  */
12546   int extu;
12547   /* Non-zero if the value is PC relative.  */
12548   int pcrel;
12549 };
12550
12551 /* The mips16 immediate operand types.  */
12552
12553 static const struct mips16_immed_operand mips16_immed_operands[] =
12554 {
12555   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12556   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12557   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12558   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12559   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
12560   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
12561   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
12562   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
12563   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
12564   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
12565   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
12566   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
12567   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
12568   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
12569   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
12570   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
12571   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12572   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12573   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
12574   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
12575   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
12576 };
12577
12578 #define MIPS16_NUM_IMMED \
12579   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
12580
12581 /* Marshal immediate value VAL for an extended MIPS16 instruction.
12582    NBITS is the number of significant bits in VAL.  */
12583
12584 static unsigned long
12585 mips16_immed_extend (offsetT val, unsigned int nbits)
12586 {
12587   int extval;
12588   if (nbits == 16)
12589     {
12590       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
12591       val &= 0x1f;
12592     }
12593   else if (nbits == 15)
12594     {
12595       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
12596       val &= 0xf;
12597     }
12598   else
12599     {
12600       extval = ((val & 0x1f) << 6) | (val & 0x20);
12601       val = 0;
12602     }
12603   return (extval << 16) | val;
12604 }
12605
12606 /* Install immediate value VAL into MIPS16 instruction *INSN,
12607    extending it if necessary.  The instruction in *INSN may
12608    already be extended.
12609
12610    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
12611    if none.  In the former case, VAL is a 16-bit number with no
12612    defined signedness.
12613
12614    TYPE is the type of the immediate field.  USER_INSN_LENGTH
12615    is the length that the user requested, or 0 if none.  */
12616
12617 static void
12618 mips16_immed (char *file, unsigned int line, int type,
12619               bfd_reloc_code_real_type reloc, offsetT val,
12620               unsigned int user_insn_length, unsigned long *insn)
12621 {
12622   const struct mips16_immed_operand *op;
12623   int mintiny, maxtiny;
12624
12625   op = mips16_immed_operands;
12626   while (op->type != type)
12627     {
12628       ++op;
12629       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
12630     }
12631
12632   if (op->unsp)
12633     {
12634       if (type == '<' || type == '>' || type == '[' || type == ']')
12635         {
12636           mintiny = 1;
12637           maxtiny = 1 << op->nbits;
12638         }
12639       else
12640         {
12641           mintiny = 0;
12642           maxtiny = (1 << op->nbits) - 1;
12643         }
12644       if (reloc != BFD_RELOC_UNUSED)
12645         val &= 0xffff;
12646     }
12647   else
12648     {
12649       mintiny = - (1 << (op->nbits - 1));
12650       maxtiny = (1 << (op->nbits - 1)) - 1;
12651       if (reloc != BFD_RELOC_UNUSED)
12652         val = SEXT_16BIT (val);
12653     }
12654
12655   /* Branch offsets have an implicit 0 in the lowest bit.  */
12656   if (type == 'p' || type == 'q')
12657     val /= 2;
12658
12659   if ((val & ((1 << op->shift) - 1)) != 0
12660       || val < (mintiny << op->shift)
12661       || val > (maxtiny << op->shift))
12662     {
12663       /* We need an extended instruction.  */
12664       if (user_insn_length == 2)
12665         as_bad_where (file, line, _("invalid unextended operand value"));
12666       else
12667         *insn |= MIPS16_EXTEND;
12668     }
12669   else if (user_insn_length == 4)
12670     {
12671       /* The operand doesn't force an unextended instruction to be extended.
12672          Warn if the user wanted an extended instruction anyway.  */
12673       *insn |= MIPS16_EXTEND;
12674       as_warn_where (file, line,
12675                      _("extended operand requested but not required"));
12676     }
12677
12678   if (mips16_opcode_length (*insn) == 2)
12679     {
12680       int insnval;
12681
12682       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
12683       insnval <<= op->op_shift;
12684       *insn |= insnval;
12685     }
12686   else
12687     {
12688       long minext, maxext;
12689
12690       if (reloc == BFD_RELOC_UNUSED)
12691         {
12692           if (op->extu)
12693             {
12694               minext = 0;
12695               maxext = (1 << op->extbits) - 1;
12696             }
12697           else
12698             {
12699               minext = - (1 << (op->extbits - 1));
12700               maxext = (1 << (op->extbits - 1)) - 1;
12701             }
12702           if (val < minext || val > maxext)
12703             as_bad_where (file, line,
12704                           _("operand value out of range for instruction"));
12705         }
12706
12707       *insn |= mips16_immed_extend (val, op->extbits);
12708     }
12709 }
12710 \f
12711 struct percent_op_match
12712 {
12713   const char *str;
12714   bfd_reloc_code_real_type reloc;
12715 };
12716
12717 static const struct percent_op_match mips_percent_op[] =
12718 {
12719   {"%lo", BFD_RELOC_LO16},
12720   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
12721   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
12722   {"%call16", BFD_RELOC_MIPS_CALL16},
12723   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
12724   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
12725   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
12726   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
12727   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
12728   {"%got", BFD_RELOC_MIPS_GOT16},
12729   {"%gp_rel", BFD_RELOC_GPREL16},
12730   {"%half", BFD_RELOC_16},
12731   {"%highest", BFD_RELOC_MIPS_HIGHEST},
12732   {"%higher", BFD_RELOC_MIPS_HIGHER},
12733   {"%neg", BFD_RELOC_MIPS_SUB},
12734   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
12735   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
12736   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
12737   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
12738   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
12739   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
12740   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
12741   {"%hi", BFD_RELOC_HI16_S}
12742 };
12743
12744 static const struct percent_op_match mips16_percent_op[] =
12745 {
12746   {"%lo", BFD_RELOC_MIPS16_LO16},
12747   {"%gprel", BFD_RELOC_MIPS16_GPREL},
12748   {"%got", BFD_RELOC_MIPS16_GOT16},
12749   {"%call16", BFD_RELOC_MIPS16_CALL16},
12750   {"%hi", BFD_RELOC_MIPS16_HI16_S},
12751   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
12752   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
12753   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
12754   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
12755   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
12756   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
12757   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
12758 };
12759
12760
12761 /* Return true if *STR points to a relocation operator.  When returning true,
12762    move *STR over the operator and store its relocation code in *RELOC.
12763    Leave both *STR and *RELOC alone when returning false.  */
12764
12765 static bfd_boolean
12766 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
12767 {
12768   const struct percent_op_match *percent_op;
12769   size_t limit, i;
12770
12771   if (mips_opts.mips16)
12772     {
12773       percent_op = mips16_percent_op;
12774       limit = ARRAY_SIZE (mips16_percent_op);
12775     }
12776   else
12777     {
12778       percent_op = mips_percent_op;
12779       limit = ARRAY_SIZE (mips_percent_op);
12780     }
12781
12782   for (i = 0; i < limit; i++)
12783     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
12784       {
12785         int len = strlen (percent_op[i].str);
12786
12787         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
12788           continue;
12789
12790         *str += strlen (percent_op[i].str);
12791         *reloc = percent_op[i].reloc;
12792
12793         /* Check whether the output BFD supports this relocation.
12794            If not, issue an error and fall back on something safe.  */
12795         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
12796           {
12797             as_bad (_("relocation %s isn't supported by the current ABI"),
12798                     percent_op[i].str);
12799             *reloc = BFD_RELOC_UNUSED;
12800           }
12801         return TRUE;
12802       }
12803   return FALSE;
12804 }
12805
12806
12807 /* Parse string STR as a 16-bit relocatable operand.  Store the
12808    expression in *EP and the relocations in the array starting
12809    at RELOC.  Return the number of relocation operators used.
12810
12811    On exit, EXPR_END points to the first character after the expression.  */
12812
12813 static size_t
12814 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
12815                        char *str)
12816 {
12817   bfd_reloc_code_real_type reversed_reloc[3];
12818   size_t reloc_index, i;
12819   int crux_depth, str_depth;
12820   char *crux;
12821
12822   /* Search for the start of the main expression, recoding relocations
12823      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
12824      of the main expression and with CRUX_DEPTH containing the number
12825      of open brackets at that point.  */
12826   reloc_index = -1;
12827   str_depth = 0;
12828   do
12829     {
12830       reloc_index++;
12831       crux = str;
12832       crux_depth = str_depth;
12833
12834       /* Skip over whitespace and brackets, keeping count of the number
12835          of brackets.  */
12836       while (*str == ' ' || *str == '\t' || *str == '(')
12837         if (*str++ == '(')
12838           str_depth++;
12839     }
12840   while (*str == '%'
12841          && reloc_index < (HAVE_NEWABI ? 3 : 1)
12842          && parse_relocation (&str, &reversed_reloc[reloc_index]));
12843
12844   my_getExpression (ep, crux);
12845   str = expr_end;
12846
12847   /* Match every open bracket.  */
12848   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
12849     if (*str++ == ')')
12850       crux_depth--;
12851
12852   if (crux_depth > 0)
12853     as_bad (_("unclosed '('"));
12854
12855   expr_end = str;
12856
12857   if (reloc_index != 0)
12858     {
12859       prev_reloc_op_frag = frag_now;
12860       for (i = 0; i < reloc_index; i++)
12861         reloc[i] = reversed_reloc[reloc_index - 1 - i];
12862     }
12863
12864   return reloc_index;
12865 }
12866
12867 static void
12868 my_getExpression (expressionS *ep, char *str)
12869 {
12870   char *save_in;
12871
12872   save_in = input_line_pointer;
12873   input_line_pointer = str;
12874   expression (ep);
12875   expr_end = input_line_pointer;
12876   input_line_pointer = save_in;
12877 }
12878
12879 char *
12880 md_atof (int type, char *litP, int *sizeP)
12881 {
12882   return ieee_md_atof (type, litP, sizeP, target_big_endian);
12883 }
12884
12885 void
12886 md_number_to_chars (char *buf, valueT val, int n)
12887 {
12888   if (target_big_endian)
12889     number_to_chars_bigendian (buf, val, n);
12890   else
12891     number_to_chars_littleendian (buf, val, n);
12892 }
12893 \f
12894 static int support_64bit_objects(void)
12895 {
12896   const char **list, **l;
12897   int yes;
12898
12899   list = bfd_target_list ();
12900   for (l = list; *l != NULL; l++)
12901     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
12902         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
12903       break;
12904   yes = (*l != NULL);
12905   free (list);
12906   return yes;
12907 }
12908
12909 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
12910    NEW_VALUE.  Warn if another value was already specified.  Note:
12911    we have to defer parsing the -march and -mtune arguments in order
12912    to handle 'from-abi' correctly, since the ABI might be specified
12913    in a later argument.  */
12914
12915 static void
12916 mips_set_option_string (const char **string_ptr, const char *new_value)
12917 {
12918   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
12919     as_warn (_("A different %s was already specified, is now %s"),
12920              string_ptr == &mips_arch_string ? "-march" : "-mtune",
12921              new_value);
12922
12923   *string_ptr = new_value;
12924 }
12925
12926 int
12927 md_parse_option (int c, char *arg)
12928 {
12929   unsigned int i;
12930
12931   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
12932     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
12933       {
12934         file_ase_explicit |= mips_set_ase (&mips_ases[i],
12935                                            c == mips_ases[i].option_on);
12936         return 1;
12937       }
12938
12939   switch (c)
12940     {
12941     case OPTION_CONSTRUCT_FLOATS:
12942       mips_disable_float_construction = 0;
12943       break;
12944
12945     case OPTION_NO_CONSTRUCT_FLOATS:
12946       mips_disable_float_construction = 1;
12947       break;
12948
12949     case OPTION_TRAP:
12950       mips_trap = 1;
12951       break;
12952
12953     case OPTION_BREAK:
12954       mips_trap = 0;
12955       break;
12956
12957     case OPTION_EB:
12958       target_big_endian = 1;
12959       break;
12960
12961     case OPTION_EL:
12962       target_big_endian = 0;
12963       break;
12964
12965     case 'O':
12966       if (arg == NULL)
12967         mips_optimize = 1;
12968       else if (arg[0] == '0')
12969         mips_optimize = 0;
12970       else if (arg[0] == '1')
12971         mips_optimize = 1;
12972       else
12973         mips_optimize = 2;
12974       break;
12975
12976     case 'g':
12977       if (arg == NULL)
12978         mips_debug = 2;
12979       else
12980         mips_debug = atoi (arg);
12981       break;
12982
12983     case OPTION_MIPS1:
12984       file_mips_isa = ISA_MIPS1;
12985       break;
12986
12987     case OPTION_MIPS2:
12988       file_mips_isa = ISA_MIPS2;
12989       break;
12990
12991     case OPTION_MIPS3:
12992       file_mips_isa = ISA_MIPS3;
12993       break;
12994
12995     case OPTION_MIPS4:
12996       file_mips_isa = ISA_MIPS4;
12997       break;
12998
12999     case OPTION_MIPS5:
13000       file_mips_isa = ISA_MIPS5;
13001       break;
13002
13003     case OPTION_MIPS32:
13004       file_mips_isa = ISA_MIPS32;
13005       break;
13006
13007     case OPTION_MIPS32R2:
13008       file_mips_isa = ISA_MIPS32R2;
13009       break;
13010
13011     case OPTION_MIPS64R2:
13012       file_mips_isa = ISA_MIPS64R2;
13013       break;
13014
13015     case OPTION_MIPS64:
13016       file_mips_isa = ISA_MIPS64;
13017       break;
13018
13019     case OPTION_MTUNE:
13020       mips_set_option_string (&mips_tune_string, arg);
13021       break;
13022
13023     case OPTION_MARCH:
13024       mips_set_option_string (&mips_arch_string, arg);
13025       break;
13026
13027     case OPTION_M4650:
13028       mips_set_option_string (&mips_arch_string, "4650");
13029       mips_set_option_string (&mips_tune_string, "4650");
13030       break;
13031
13032     case OPTION_NO_M4650:
13033       break;
13034
13035     case OPTION_M4010:
13036       mips_set_option_string (&mips_arch_string, "4010");
13037       mips_set_option_string (&mips_tune_string, "4010");
13038       break;
13039
13040     case OPTION_NO_M4010:
13041       break;
13042
13043     case OPTION_M4100:
13044       mips_set_option_string (&mips_arch_string, "4100");
13045       mips_set_option_string (&mips_tune_string, "4100");
13046       break;
13047
13048     case OPTION_NO_M4100:
13049       break;
13050
13051     case OPTION_M3900:
13052       mips_set_option_string (&mips_arch_string, "3900");
13053       mips_set_option_string (&mips_tune_string, "3900");
13054       break;
13055
13056     case OPTION_NO_M3900:
13057       break;
13058
13059     case OPTION_MICROMIPS:
13060       if (mips_opts.mips16 == 1)
13061         {
13062           as_bad (_("-mmicromips cannot be used with -mips16"));
13063           return 0;
13064         }
13065       mips_opts.micromips = 1;
13066       mips_no_prev_insn ();
13067       break;
13068
13069     case OPTION_NO_MICROMIPS:
13070       mips_opts.micromips = 0;
13071       mips_no_prev_insn ();
13072       break;
13073
13074     case OPTION_MIPS16:
13075       if (mips_opts.micromips == 1)
13076         {
13077           as_bad (_("-mips16 cannot be used with -micromips"));
13078           return 0;
13079         }
13080       mips_opts.mips16 = 1;
13081       mips_no_prev_insn ();
13082       break;
13083
13084     case OPTION_NO_MIPS16:
13085       mips_opts.mips16 = 0;
13086       mips_no_prev_insn ();
13087       break;
13088
13089     case OPTION_FIX_24K:
13090       mips_fix_24k = 1;
13091       break;
13092
13093     case OPTION_NO_FIX_24K:
13094       mips_fix_24k = 0;
13095       break;
13096
13097     case OPTION_FIX_LOONGSON2F_JUMP:
13098       mips_fix_loongson2f_jump = TRUE;
13099       break;
13100
13101     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13102       mips_fix_loongson2f_jump = FALSE;
13103       break;
13104
13105     case OPTION_FIX_LOONGSON2F_NOP:
13106       mips_fix_loongson2f_nop = TRUE;
13107       break;
13108
13109     case OPTION_NO_FIX_LOONGSON2F_NOP:
13110       mips_fix_loongson2f_nop = FALSE;
13111       break;
13112
13113     case OPTION_FIX_VR4120:
13114       mips_fix_vr4120 = 1;
13115       break;
13116
13117     case OPTION_NO_FIX_VR4120:
13118       mips_fix_vr4120 = 0;
13119       break;
13120
13121     case OPTION_FIX_VR4130:
13122       mips_fix_vr4130 = 1;
13123       break;
13124
13125     case OPTION_NO_FIX_VR4130:
13126       mips_fix_vr4130 = 0;
13127       break;
13128
13129     case OPTION_FIX_CN63XXP1:
13130       mips_fix_cn63xxp1 = TRUE;
13131       break;
13132
13133     case OPTION_NO_FIX_CN63XXP1:
13134       mips_fix_cn63xxp1 = FALSE;
13135       break;
13136
13137     case OPTION_RELAX_BRANCH:
13138       mips_relax_branch = 1;
13139       break;
13140
13141     case OPTION_NO_RELAX_BRANCH:
13142       mips_relax_branch = 0;
13143       break;
13144
13145     case OPTION_INSN32:
13146       mips_opts.insn32 = TRUE;
13147       break;
13148
13149     case OPTION_NO_INSN32:
13150       mips_opts.insn32 = FALSE;
13151       break;
13152
13153     case OPTION_MSHARED:
13154       mips_in_shared = TRUE;
13155       break;
13156
13157     case OPTION_MNO_SHARED:
13158       mips_in_shared = FALSE;
13159       break;
13160
13161     case OPTION_MSYM32:
13162       mips_opts.sym32 = TRUE;
13163       break;
13164
13165     case OPTION_MNO_SYM32:
13166       mips_opts.sym32 = FALSE;
13167       break;
13168
13169       /* When generating ELF code, we permit -KPIC and -call_shared to
13170          select SVR4_PIC, and -non_shared to select no PIC.  This is
13171          intended to be compatible with Irix 5.  */
13172     case OPTION_CALL_SHARED:
13173       mips_pic = SVR4_PIC;
13174       mips_abicalls = TRUE;
13175       break;
13176
13177     case OPTION_CALL_NONPIC:
13178       mips_pic = NO_PIC;
13179       mips_abicalls = TRUE;
13180       break;
13181
13182     case OPTION_NON_SHARED:
13183       mips_pic = NO_PIC;
13184       mips_abicalls = FALSE;
13185       break;
13186
13187       /* The -xgot option tells the assembler to use 32 bit offsets
13188          when accessing the got in SVR4_PIC mode.  It is for Irix
13189          compatibility.  */
13190     case OPTION_XGOT:
13191       mips_big_got = 1;
13192       break;
13193
13194     case 'G':
13195       g_switch_value = atoi (arg);
13196       g_switch_seen = 1;
13197       break;
13198
13199       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13200          and -mabi=64.  */
13201     case OPTION_32:
13202       mips_abi = O32_ABI;
13203       break;
13204
13205     case OPTION_N32:
13206       mips_abi = N32_ABI;
13207       break;
13208
13209     case OPTION_64:
13210       mips_abi = N64_ABI;
13211       if (!support_64bit_objects())
13212         as_fatal (_("No compiled in support for 64 bit object file format"));
13213       break;
13214
13215     case OPTION_GP32:
13216       file_mips_gp32 = 1;
13217       break;
13218
13219     case OPTION_GP64:
13220       file_mips_gp32 = 0;
13221       break;
13222
13223     case OPTION_FP32:
13224       file_mips_fp32 = 1;
13225       break;
13226
13227     case OPTION_FP64:
13228       file_mips_fp32 = 0;
13229       break;
13230
13231     case OPTION_SINGLE_FLOAT:
13232       file_mips_single_float = 1;
13233       break;
13234
13235     case OPTION_DOUBLE_FLOAT:
13236       file_mips_single_float = 0;
13237       break;
13238
13239     case OPTION_SOFT_FLOAT:
13240       file_mips_soft_float = 1;
13241       break;
13242
13243     case OPTION_HARD_FLOAT:
13244       file_mips_soft_float = 0;
13245       break;
13246
13247     case OPTION_MABI:
13248       if (strcmp (arg, "32") == 0)
13249         mips_abi = O32_ABI;
13250       else if (strcmp (arg, "o64") == 0)
13251         mips_abi = O64_ABI;
13252       else if (strcmp (arg, "n32") == 0)
13253         mips_abi = N32_ABI;
13254       else if (strcmp (arg, "64") == 0)
13255         {
13256           mips_abi = N64_ABI;
13257           if (! support_64bit_objects())
13258             as_fatal (_("No compiled in support for 64 bit object file "
13259                         "format"));
13260         }
13261       else if (strcmp (arg, "eabi") == 0)
13262         mips_abi = EABI_ABI;
13263       else
13264         {
13265           as_fatal (_("invalid abi -mabi=%s"), arg);
13266           return 0;
13267         }
13268       break;
13269
13270     case OPTION_M7000_HILO_FIX:
13271       mips_7000_hilo_fix = TRUE;
13272       break;
13273
13274     case OPTION_MNO_7000_HILO_FIX:
13275       mips_7000_hilo_fix = FALSE;
13276       break;
13277
13278     case OPTION_MDEBUG:
13279       mips_flag_mdebug = TRUE;
13280       break;
13281
13282     case OPTION_NO_MDEBUG:
13283       mips_flag_mdebug = FALSE;
13284       break;
13285
13286     case OPTION_PDR:
13287       mips_flag_pdr = TRUE;
13288       break;
13289
13290     case OPTION_NO_PDR:
13291       mips_flag_pdr = FALSE;
13292       break;
13293
13294     case OPTION_MVXWORKS_PIC:
13295       mips_pic = VXWORKS_PIC;
13296       break;
13297
13298     case OPTION_NAN:
13299       if (strcmp (arg, "2008") == 0)
13300         mips_flag_nan2008 = TRUE;
13301       else if (strcmp (arg, "legacy") == 0)
13302         mips_flag_nan2008 = FALSE;
13303       else
13304         {
13305           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13306           return 0;
13307         }
13308       break;
13309
13310     default:
13311       return 0;
13312     }
13313
13314     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13315
13316   return 1;
13317 }
13318 \f
13319 /* Set up globals to generate code for the ISA or processor
13320    described by INFO.  */
13321
13322 static void
13323 mips_set_architecture (const struct mips_cpu_info *info)
13324 {
13325   if (info != 0)
13326     {
13327       file_mips_arch = info->cpu;
13328       mips_opts.arch = info->cpu;
13329       mips_opts.isa = info->isa;
13330     }
13331 }
13332
13333
13334 /* Likewise for tuning.  */
13335
13336 static void
13337 mips_set_tune (const struct mips_cpu_info *info)
13338 {
13339   if (info != 0)
13340     mips_tune = info->cpu;
13341 }
13342
13343
13344 void
13345 mips_after_parse_args (void)
13346 {
13347   const struct mips_cpu_info *arch_info = 0;
13348   const struct mips_cpu_info *tune_info = 0;
13349
13350   /* GP relative stuff not working for PE */
13351   if (strncmp (TARGET_OS, "pe", 2) == 0)
13352     {
13353       if (g_switch_seen && g_switch_value != 0)
13354         as_bad (_("-G not supported in this configuration."));
13355       g_switch_value = 0;
13356     }
13357
13358   if (mips_abi == NO_ABI)
13359     mips_abi = MIPS_DEFAULT_ABI;
13360
13361   /* The following code determines the architecture and register size.
13362      Similar code was added to GCC 3.3 (see override_options() in
13363      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13364      as much as possible.  */
13365
13366   if (mips_arch_string != 0)
13367     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13368
13369   if (file_mips_isa != ISA_UNKNOWN)
13370     {
13371       /* Handle -mipsN.  At this point, file_mips_isa contains the
13372          ISA level specified by -mipsN, while arch_info->isa contains
13373          the -march selection (if any).  */
13374       if (arch_info != 0)
13375         {
13376           /* -march takes precedence over -mipsN, since it is more descriptive.
13377              There's no harm in specifying both as long as the ISA levels
13378              are the same.  */
13379           if (file_mips_isa != arch_info->isa)
13380             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13381                     mips_cpu_info_from_isa (file_mips_isa)->name,
13382                     mips_cpu_info_from_isa (arch_info->isa)->name);
13383         }
13384       else
13385         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13386     }
13387
13388   if (arch_info == 0)
13389     {
13390       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13391       gas_assert (arch_info);
13392     }
13393
13394   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13395     as_bad (_("-march=%s is not compatible with the selected ABI"),
13396             arch_info->name);
13397
13398   mips_set_architecture (arch_info);
13399
13400   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13401   if (mips_tune_string != 0)
13402     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13403
13404   if (tune_info == 0)
13405     mips_set_tune (arch_info);
13406   else
13407     mips_set_tune (tune_info);
13408
13409   if (file_mips_gp32 >= 0)
13410     {
13411       /* The user specified the size of the integer registers.  Make sure
13412          it agrees with the ABI and ISA.  */
13413       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13414         as_bad (_("-mgp64 used with a 32-bit processor"));
13415       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13416         as_bad (_("-mgp32 used with a 64-bit ABI"));
13417       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13418         as_bad (_("-mgp64 used with a 32-bit ABI"));
13419     }
13420   else
13421     {
13422       /* Infer the integer register size from the ABI and processor.
13423          Restrict ourselves to 32-bit registers if that's all the
13424          processor has, or if the ABI cannot handle 64-bit registers.  */
13425       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13426                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13427     }
13428
13429   switch (file_mips_fp32)
13430     {
13431     default:
13432     case -1:
13433       /* No user specified float register size.
13434          ??? GAS treats single-float processors as though they had 64-bit
13435          float registers (although it complains when double-precision
13436          instructions are used).  As things stand, saying they have 32-bit
13437          registers would lead to spurious "register must be even" messages.
13438          So here we assume float registers are never smaller than the
13439          integer ones.  */
13440       if (file_mips_gp32 == 0)
13441         /* 64-bit integer registers implies 64-bit float registers.  */
13442         file_mips_fp32 = 0;
13443       else if ((mips_opts.ase & FP64_ASES)
13444                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13445         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13446         file_mips_fp32 = 0;
13447       else
13448         /* 32-bit float registers.  */
13449         file_mips_fp32 = 1;
13450       break;
13451
13452     /* The user specified the size of the float registers.  Check if it
13453        agrees with the ABI and ISA.  */
13454     case 0:
13455       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13456         as_bad (_("-mfp64 used with a 32-bit fpu"));
13457       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13458                && !ISA_HAS_MXHC1 (mips_opts.isa))
13459         as_warn (_("-mfp64 used with a 32-bit ABI"));
13460       break;
13461     case 1:
13462       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13463         as_warn (_("-mfp32 used with a 64-bit ABI"));
13464       break;
13465     }
13466
13467   /* End of GCC-shared inference code.  */
13468
13469   /* This flag is set when we have a 64-bit capable CPU but use only
13470      32-bit wide registers.  Note that EABI does not use it.  */
13471   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13472       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13473           || mips_abi == O32_ABI))
13474     mips_32bitmode = 1;
13475
13476   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13477     as_bad (_("trap exception not supported at ISA 1"));
13478
13479   /* If the selected architecture includes support for ASEs, enable
13480      generation of code for them.  */
13481   if (mips_opts.mips16 == -1)
13482     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13483   if (mips_opts.micromips == -1)
13484     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13485
13486   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13487      ASEs from being selected implicitly.  */
13488   if (file_mips_fp32 == 1)
13489     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13490
13491   /* If the user didn't explicitly select or deselect a particular ASE,
13492      use the default setting for the CPU.  */
13493   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13494
13495   file_mips_isa = mips_opts.isa;
13496   file_ase = mips_opts.ase;
13497   mips_opts.gp32 = file_mips_gp32;
13498   mips_opts.fp32 = file_mips_fp32;
13499   mips_opts.soft_float = file_mips_soft_float;
13500   mips_opts.single_float = file_mips_single_float;
13501
13502   mips_check_isa_supports_ases ();
13503
13504   if (mips_flag_mdebug < 0)
13505     mips_flag_mdebug = 0;
13506 }
13507 \f
13508 void
13509 mips_init_after_args (void)
13510 {
13511   /* initialize opcodes */
13512   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
13513   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
13514 }
13515
13516 long
13517 md_pcrel_from (fixS *fixP)
13518 {
13519   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
13520   switch (fixP->fx_r_type)
13521     {
13522     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13523     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13524       /* Return the address of the delay slot.  */
13525       return addr + 2;
13526
13527     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13528     case BFD_RELOC_MICROMIPS_JMP:
13529     case BFD_RELOC_16_PCREL_S2:
13530     case BFD_RELOC_MIPS_JMP:
13531       /* Return the address of the delay slot.  */
13532       return addr + 4;
13533
13534     case BFD_RELOC_32_PCREL:
13535       return addr;
13536
13537     default:
13538       /* We have no relocation type for PC relative MIPS16 instructions.  */
13539       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
13540         as_bad_where (fixP->fx_file, fixP->fx_line,
13541                       _("PC relative MIPS16 instruction references a different section"));
13542       return addr;
13543     }
13544 }
13545
13546 /* This is called before the symbol table is processed.  In order to
13547    work with gcc when using mips-tfile, we must keep all local labels.
13548    However, in other cases, we want to discard them.  If we were
13549    called with -g, but we didn't see any debugging information, it may
13550    mean that gcc is smuggling debugging information through to
13551    mips-tfile, in which case we must generate all local labels.  */
13552
13553 void
13554 mips_frob_file_before_adjust (void)
13555 {
13556 #ifndef NO_ECOFF_DEBUGGING
13557   if (ECOFF_DEBUGGING
13558       && mips_debug != 0
13559       && ! ecoff_debugging_seen)
13560     flag_keep_locals = 1;
13561 #endif
13562 }
13563
13564 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
13565    the corresponding LO16 reloc.  This is called before md_apply_fix and
13566    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
13567    relocation operators.
13568
13569    For our purposes, a %lo() expression matches a %got() or %hi()
13570    expression if:
13571
13572       (a) it refers to the same symbol; and
13573       (b) the offset applied in the %lo() expression is no lower than
13574           the offset applied in the %got() or %hi().
13575
13576    (b) allows us to cope with code like:
13577
13578         lui     $4,%hi(foo)
13579         lh      $4,%lo(foo+2)($4)
13580
13581    ...which is legal on RELA targets, and has a well-defined behaviour
13582    if the user knows that adding 2 to "foo" will not induce a carry to
13583    the high 16 bits.
13584
13585    When several %lo()s match a particular %got() or %hi(), we use the
13586    following rules to distinguish them:
13587
13588      (1) %lo()s with smaller offsets are a better match than %lo()s with
13589          higher offsets.
13590
13591      (2) %lo()s with no matching %got() or %hi() are better than those
13592          that already have a matching %got() or %hi().
13593
13594      (3) later %lo()s are better than earlier %lo()s.
13595
13596    These rules are applied in order.
13597
13598    (1) means, among other things, that %lo()s with identical offsets are
13599    chosen if they exist.
13600
13601    (2) means that we won't associate several high-part relocations with
13602    the same low-part relocation unless there's no alternative.  Having
13603    several high parts for the same low part is a GNU extension; this rule
13604    allows careful users to avoid it.
13605
13606    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
13607    with the last high-part relocation being at the front of the list.
13608    It therefore makes sense to choose the last matching low-part
13609    relocation, all other things being equal.  It's also easier
13610    to code that way.  */
13611
13612 void
13613 mips_frob_file (void)
13614 {
13615   struct mips_hi_fixup *l;
13616   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
13617
13618   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
13619     {
13620       segment_info_type *seginfo;
13621       bfd_boolean matched_lo_p;
13622       fixS **hi_pos, **lo_pos, **pos;
13623
13624       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
13625
13626       /* If a GOT16 relocation turns out to be against a global symbol,
13627          there isn't supposed to be a matching LO.  Ignore %gots against
13628          constants; we'll report an error for those later.  */
13629       if (got16_reloc_p (l->fixp->fx_r_type)
13630           && !(l->fixp->fx_addsy
13631                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
13632         continue;
13633
13634       /* Check quickly whether the next fixup happens to be a matching %lo.  */
13635       if (fixup_has_matching_lo_p (l->fixp))
13636         continue;
13637
13638       seginfo = seg_info (l->seg);
13639
13640       /* Set HI_POS to the position of this relocation in the chain.
13641          Set LO_POS to the position of the chosen low-part relocation.
13642          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
13643          relocation that matches an immediately-preceding high-part
13644          relocation.  */
13645       hi_pos = NULL;
13646       lo_pos = NULL;
13647       matched_lo_p = FALSE;
13648       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
13649
13650       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
13651         {
13652           if (*pos == l->fixp)
13653             hi_pos = pos;
13654
13655           if ((*pos)->fx_r_type == looking_for_rtype
13656               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
13657               && (*pos)->fx_offset >= l->fixp->fx_offset
13658               && (lo_pos == NULL
13659                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
13660                   || (!matched_lo_p
13661                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
13662             lo_pos = pos;
13663
13664           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
13665                           && fixup_has_matching_lo_p (*pos));
13666         }
13667
13668       /* If we found a match, remove the high-part relocation from its
13669          current position and insert it before the low-part relocation.
13670          Make the offsets match so that fixup_has_matching_lo_p()
13671          will return true.
13672
13673          We don't warn about unmatched high-part relocations since some
13674          versions of gcc have been known to emit dead "lui ...%hi(...)"
13675          instructions.  */
13676       if (lo_pos != NULL)
13677         {
13678           l->fixp->fx_offset = (*lo_pos)->fx_offset;
13679           if (l->fixp->fx_next != *lo_pos)
13680             {
13681               *hi_pos = l->fixp->fx_next;
13682               l->fixp->fx_next = *lo_pos;
13683               *lo_pos = l->fixp;
13684             }
13685         }
13686     }
13687 }
13688
13689 int
13690 mips_force_relocation (fixS *fixp)
13691 {
13692   if (generic_force_reloc (fixp))
13693     return 1;
13694
13695   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
13696      so that the linker relaxation can update targets.  */
13697   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13698       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13699       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
13700     return 1;
13701
13702   return 0;
13703 }
13704
13705 /* Read the instruction associated with RELOC from BUF.  */
13706
13707 static unsigned int
13708 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
13709 {
13710   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13711     return read_compressed_insn (buf, 4);
13712   else
13713     return read_insn (buf);
13714 }
13715
13716 /* Write instruction INSN to BUF, given that it has been relocated
13717    by RELOC.  */
13718
13719 static void
13720 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
13721                   unsigned long insn)
13722 {
13723   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13724     write_compressed_insn (buf, insn, 4);
13725   else
13726     write_insn (buf, insn);
13727 }
13728
13729 /* Apply a fixup to the object file.  */
13730
13731 void
13732 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
13733 {
13734   char *buf;
13735   unsigned long insn;
13736   reloc_howto_type *howto;
13737
13738   /* We ignore generic BFD relocations we don't know about.  */
13739   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
13740   if (! howto)
13741     return;
13742
13743   gas_assert (fixP->fx_size == 2
13744               || fixP->fx_size == 4
13745               || fixP->fx_r_type == BFD_RELOC_16
13746               || fixP->fx_r_type == BFD_RELOC_64
13747               || fixP->fx_r_type == BFD_RELOC_CTOR
13748               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
13749               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
13750               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
13751               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
13752               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
13753
13754   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
13755
13756   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
13757               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13758               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13759               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
13760               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
13761
13762   /* Don't treat parts of a composite relocation as done.  There are two
13763      reasons for this:
13764
13765      (1) The second and third parts will be against 0 (RSS_UNDEF) but
13766          should nevertheless be emitted if the first part is.
13767
13768      (2) In normal usage, composite relocations are never assembly-time
13769          constants.  The easiest way of dealing with the pathological
13770          exceptions is to generate a relocation against STN_UNDEF and
13771          leave everything up to the linker.  */
13772   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
13773     fixP->fx_done = 1;
13774
13775   switch (fixP->fx_r_type)
13776     {
13777     case BFD_RELOC_MIPS_TLS_GD:
13778     case BFD_RELOC_MIPS_TLS_LDM:
13779     case BFD_RELOC_MIPS_TLS_DTPREL32:
13780     case BFD_RELOC_MIPS_TLS_DTPREL64:
13781     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
13782     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
13783     case BFD_RELOC_MIPS_TLS_GOTTPREL:
13784     case BFD_RELOC_MIPS_TLS_TPREL32:
13785     case BFD_RELOC_MIPS_TLS_TPREL64:
13786     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
13787     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
13788     case BFD_RELOC_MICROMIPS_TLS_GD:
13789     case BFD_RELOC_MICROMIPS_TLS_LDM:
13790     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
13791     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
13792     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
13793     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
13794     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
13795     case BFD_RELOC_MIPS16_TLS_GD:
13796     case BFD_RELOC_MIPS16_TLS_LDM:
13797     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
13798     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
13799     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
13800     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
13801     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
13802       if (!fixP->fx_addsy)
13803         {
13804           as_bad_where (fixP->fx_file, fixP->fx_line,
13805                         _("TLS relocation against a constant"));
13806           break;
13807         }
13808       S_SET_THREAD_LOCAL (fixP->fx_addsy);
13809       /* fall through */
13810
13811     case BFD_RELOC_MIPS_JMP:
13812     case BFD_RELOC_MIPS_SHIFT5:
13813     case BFD_RELOC_MIPS_SHIFT6:
13814     case BFD_RELOC_MIPS_GOT_DISP:
13815     case BFD_RELOC_MIPS_GOT_PAGE:
13816     case BFD_RELOC_MIPS_GOT_OFST:
13817     case BFD_RELOC_MIPS_SUB:
13818     case BFD_RELOC_MIPS_INSERT_A:
13819     case BFD_RELOC_MIPS_INSERT_B:
13820     case BFD_RELOC_MIPS_DELETE:
13821     case BFD_RELOC_MIPS_HIGHEST:
13822     case BFD_RELOC_MIPS_HIGHER:
13823     case BFD_RELOC_MIPS_SCN_DISP:
13824     case BFD_RELOC_MIPS_REL16:
13825     case BFD_RELOC_MIPS_RELGOT:
13826     case BFD_RELOC_MIPS_JALR:
13827     case BFD_RELOC_HI16:
13828     case BFD_RELOC_HI16_S:
13829     case BFD_RELOC_LO16:
13830     case BFD_RELOC_GPREL16:
13831     case BFD_RELOC_MIPS_LITERAL:
13832     case BFD_RELOC_MIPS_CALL16:
13833     case BFD_RELOC_MIPS_GOT16:
13834     case BFD_RELOC_GPREL32:
13835     case BFD_RELOC_MIPS_GOT_HI16:
13836     case BFD_RELOC_MIPS_GOT_LO16:
13837     case BFD_RELOC_MIPS_CALL_HI16:
13838     case BFD_RELOC_MIPS_CALL_LO16:
13839     case BFD_RELOC_MIPS16_GPREL:
13840     case BFD_RELOC_MIPS16_GOT16:
13841     case BFD_RELOC_MIPS16_CALL16:
13842     case BFD_RELOC_MIPS16_HI16:
13843     case BFD_RELOC_MIPS16_HI16_S:
13844     case BFD_RELOC_MIPS16_LO16:
13845     case BFD_RELOC_MIPS16_JMP:
13846     case BFD_RELOC_MICROMIPS_JMP:
13847     case BFD_RELOC_MICROMIPS_GOT_DISP:
13848     case BFD_RELOC_MICROMIPS_GOT_PAGE:
13849     case BFD_RELOC_MICROMIPS_GOT_OFST:
13850     case BFD_RELOC_MICROMIPS_SUB:
13851     case BFD_RELOC_MICROMIPS_HIGHEST:
13852     case BFD_RELOC_MICROMIPS_HIGHER:
13853     case BFD_RELOC_MICROMIPS_SCN_DISP:
13854     case BFD_RELOC_MICROMIPS_JALR:
13855     case BFD_RELOC_MICROMIPS_HI16:
13856     case BFD_RELOC_MICROMIPS_HI16_S:
13857     case BFD_RELOC_MICROMIPS_LO16:
13858     case BFD_RELOC_MICROMIPS_GPREL16:
13859     case BFD_RELOC_MICROMIPS_LITERAL:
13860     case BFD_RELOC_MICROMIPS_CALL16:
13861     case BFD_RELOC_MICROMIPS_GOT16:
13862     case BFD_RELOC_MICROMIPS_GOT_HI16:
13863     case BFD_RELOC_MICROMIPS_GOT_LO16:
13864     case BFD_RELOC_MICROMIPS_CALL_HI16:
13865     case BFD_RELOC_MICROMIPS_CALL_LO16:
13866     case BFD_RELOC_MIPS_EH:
13867       if (fixP->fx_done)
13868         {
13869           offsetT value;
13870
13871           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
13872             {
13873               insn = read_reloc_insn (buf, fixP->fx_r_type);
13874               if (mips16_reloc_p (fixP->fx_r_type))
13875                 insn |= mips16_immed_extend (value, 16);
13876               else
13877                 insn |= (value & 0xffff);
13878               write_reloc_insn (buf, fixP->fx_r_type, insn);
13879             }
13880           else
13881             as_bad_where (fixP->fx_file, fixP->fx_line,
13882                           _("Unsupported constant in relocation"));
13883         }
13884       break;
13885
13886     case BFD_RELOC_64:
13887       /* This is handled like BFD_RELOC_32, but we output a sign
13888          extended value if we are only 32 bits.  */
13889       if (fixP->fx_done)
13890         {
13891           if (8 <= sizeof (valueT))
13892             md_number_to_chars (buf, *valP, 8);
13893           else
13894             {
13895               valueT hiv;
13896
13897               if ((*valP & 0x80000000) != 0)
13898                 hiv = 0xffffffff;
13899               else
13900                 hiv = 0;
13901               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
13902               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
13903             }
13904         }
13905       break;
13906
13907     case BFD_RELOC_RVA:
13908     case BFD_RELOC_32:
13909     case BFD_RELOC_32_PCREL:
13910     case BFD_RELOC_16:
13911       /* If we are deleting this reloc entry, we must fill in the
13912          value now.  This can happen if we have a .word which is not
13913          resolved when it appears but is later defined.  */
13914       if (fixP->fx_done)
13915         md_number_to_chars (buf, *valP, fixP->fx_size);
13916       break;
13917
13918     case BFD_RELOC_16_PCREL_S2:
13919       if ((*valP & 0x3) != 0)
13920         as_bad_where (fixP->fx_file, fixP->fx_line,
13921                       _("Branch to misaligned address (%lx)"), (long) *valP);
13922
13923       /* We need to save the bits in the instruction since fixup_segment()
13924          might be deleting the relocation entry (i.e., a branch within
13925          the current segment).  */
13926       if (! fixP->fx_done)
13927         break;
13928
13929       /* Update old instruction data.  */
13930       insn = read_insn (buf);
13931
13932       if (*valP + 0x20000 <= 0x3ffff)
13933         {
13934           insn |= (*valP >> 2) & 0xffff;
13935           write_insn (buf, insn);
13936         }
13937       else if (mips_pic == NO_PIC
13938                && fixP->fx_done
13939                && fixP->fx_frag->fr_address >= text_section->vma
13940                && (fixP->fx_frag->fr_address
13941                    < text_section->vma + bfd_get_section_size (text_section))
13942                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
13943                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
13944                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
13945         {
13946           /* The branch offset is too large.  If this is an
13947              unconditional branch, and we are not generating PIC code,
13948              we can convert it to an absolute jump instruction.  */
13949           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
13950             insn = 0x0c000000;  /* jal */
13951           else
13952             insn = 0x08000000;  /* j */
13953           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
13954           fixP->fx_done = 0;
13955           fixP->fx_addsy = section_symbol (text_section);
13956           *valP += md_pcrel_from (fixP);
13957           write_insn (buf, insn);
13958         }
13959       else
13960         {
13961           /* If we got here, we have branch-relaxation disabled,
13962              and there's nothing we can do to fix this instruction
13963              without turning it into a longer sequence.  */
13964           as_bad_where (fixP->fx_file, fixP->fx_line,
13965                         _("Branch out of range"));
13966         }
13967       break;
13968
13969     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13970     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13971     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13972       /* We adjust the offset back to even.  */
13973       if ((*valP & 0x1) != 0)
13974         --(*valP);
13975
13976       if (! fixP->fx_done)
13977         break;
13978
13979       /* Should never visit here, because we keep the relocation.  */
13980       abort ();
13981       break;
13982
13983     case BFD_RELOC_VTABLE_INHERIT:
13984       fixP->fx_done = 0;
13985       if (fixP->fx_addsy
13986           && !S_IS_DEFINED (fixP->fx_addsy)
13987           && !S_IS_WEAK (fixP->fx_addsy))
13988         S_SET_WEAK (fixP->fx_addsy);
13989       break;
13990
13991     case BFD_RELOC_VTABLE_ENTRY:
13992       fixP->fx_done = 0;
13993       break;
13994
13995     default:
13996       abort ();
13997     }
13998
13999   /* Remember value for tc_gen_reloc.  */
14000   fixP->fx_addnumber = *valP;
14001 }
14002
14003 static symbolS *
14004 get_symbol (void)
14005 {
14006   int c;
14007   char *name;
14008   symbolS *p;
14009
14010   name = input_line_pointer;
14011   c = get_symbol_end ();
14012   p = (symbolS *) symbol_find_or_make (name);
14013   *input_line_pointer = c;
14014   return p;
14015 }
14016
14017 /* Align the current frag to a given power of two.  If a particular
14018    fill byte should be used, FILL points to an integer that contains
14019    that byte, otherwise FILL is null.
14020
14021    This function used to have the comment:
14022
14023       The MIPS assembler also automatically adjusts any preceding label.
14024
14025    The implementation therefore applied the adjustment to a maximum of
14026    one label.  However, other label adjustments are applied to batches
14027    of labels, and adjusting just one caused problems when new labels
14028    were added for the sake of debugging or unwind information.
14029    We therefore adjust all preceding labels (given as LABELS) instead.  */
14030
14031 static void
14032 mips_align (int to, int *fill, struct insn_label_list *labels)
14033 {
14034   mips_emit_delays ();
14035   mips_record_compressed_mode ();
14036   if (fill == NULL && subseg_text_p (now_seg))
14037     frag_align_code (to, 0);
14038   else
14039     frag_align (to, fill ? *fill : 0, 0);
14040   record_alignment (now_seg, to);
14041   mips_move_labels (labels, FALSE);
14042 }
14043
14044 /* Align to a given power of two.  .align 0 turns off the automatic
14045    alignment used by the data creating pseudo-ops.  */
14046
14047 static void
14048 s_align (int x ATTRIBUTE_UNUSED)
14049 {
14050   int temp, fill_value, *fill_ptr;
14051   long max_alignment = 28;
14052
14053   /* o Note that the assembler pulls down any immediately preceding label
14054        to the aligned address.
14055      o It's not documented but auto alignment is reinstated by
14056        a .align pseudo instruction.
14057      o Note also that after auto alignment is turned off the mips assembler
14058        issues an error on attempt to assemble an improperly aligned data item.
14059        We don't.  */
14060
14061   temp = get_absolute_expression ();
14062   if (temp > max_alignment)
14063     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14064   else if (temp < 0)
14065     {
14066       as_warn (_("Alignment negative: 0 assumed."));
14067       temp = 0;
14068     }
14069   if (*input_line_pointer == ',')
14070     {
14071       ++input_line_pointer;
14072       fill_value = get_absolute_expression ();
14073       fill_ptr = &fill_value;
14074     }
14075   else
14076     fill_ptr = 0;
14077   if (temp)
14078     {
14079       segment_info_type *si = seg_info (now_seg);
14080       struct insn_label_list *l = si->label_list;
14081       /* Auto alignment should be switched on by next section change.  */
14082       auto_align = 1;
14083       mips_align (temp, fill_ptr, l);
14084     }
14085   else
14086     {
14087       auto_align = 0;
14088     }
14089
14090   demand_empty_rest_of_line ();
14091 }
14092
14093 static void
14094 s_change_sec (int sec)
14095 {
14096   segT seg;
14097
14098   /* The ELF backend needs to know that we are changing sections, so
14099      that .previous works correctly.  We could do something like check
14100      for an obj_section_change_hook macro, but that might be confusing
14101      as it would not be appropriate to use it in the section changing
14102      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14103      This should be cleaner, somehow.  */
14104   obj_elf_section_change_hook ();
14105
14106   mips_emit_delays ();
14107
14108   switch (sec)
14109     {
14110     case 't':
14111       s_text (0);
14112       break;
14113     case 'd':
14114       s_data (0);
14115       break;
14116     case 'b':
14117       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14118       demand_empty_rest_of_line ();
14119       break;
14120
14121     case 'r':
14122       seg = subseg_new (RDATA_SECTION_NAME,
14123                         (subsegT) get_absolute_expression ());
14124       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14125                                               | SEC_READONLY | SEC_RELOC
14126                                               | SEC_DATA));
14127       if (strncmp (TARGET_OS, "elf", 3) != 0)
14128         record_alignment (seg, 4);
14129       demand_empty_rest_of_line ();
14130       break;
14131
14132     case 's':
14133       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14134       bfd_set_section_flags (stdoutput, seg,
14135                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14136       if (strncmp (TARGET_OS, "elf", 3) != 0)
14137         record_alignment (seg, 4);
14138       demand_empty_rest_of_line ();
14139       break;
14140
14141     case 'B':
14142       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14143       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14144       if (strncmp (TARGET_OS, "elf", 3) != 0)
14145         record_alignment (seg, 4);
14146       demand_empty_rest_of_line ();
14147       break;
14148     }
14149
14150   auto_align = 1;
14151 }
14152
14153 void
14154 s_change_section (int ignore ATTRIBUTE_UNUSED)
14155 {
14156   char *section_name;
14157   char c;
14158   char next_c = 0;
14159   int section_type;
14160   int section_flag;
14161   int section_entry_size;
14162   int section_alignment;
14163
14164   section_name = input_line_pointer;
14165   c = get_symbol_end ();
14166   if (c)
14167     next_c = *(input_line_pointer + 1);
14168
14169   /* Do we have .section Name<,"flags">?  */
14170   if (c != ',' || (c == ',' && next_c == '"'))
14171     {
14172       /* just after name is now '\0'.  */
14173       *input_line_pointer = c;
14174       input_line_pointer = section_name;
14175       obj_elf_section (ignore);
14176       return;
14177     }
14178   input_line_pointer++;
14179
14180   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14181   if (c == ',')
14182     section_type = get_absolute_expression ();
14183   else
14184     section_type = 0;
14185   if (*input_line_pointer++ == ',')
14186     section_flag = get_absolute_expression ();
14187   else
14188     section_flag = 0;
14189   if (*input_line_pointer++ == ',')
14190     section_entry_size = get_absolute_expression ();
14191   else
14192     section_entry_size = 0;
14193   if (*input_line_pointer++ == ',')
14194     section_alignment = get_absolute_expression ();
14195   else
14196     section_alignment = 0;
14197   /* FIXME: really ignore?  */
14198   (void) section_alignment;
14199
14200   section_name = xstrdup (section_name);
14201
14202   /* When using the generic form of .section (as implemented by obj-elf.c),
14203      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14204      traditionally had to fall back on the more common @progbits instead.
14205
14206      There's nothing really harmful in this, since bfd will correct
14207      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14208      means that, for backwards compatibility, the special_section entries
14209      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14210
14211      Even so, we shouldn't force users of the MIPS .section syntax to
14212      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14213      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14214      generic type-checking code.  */
14215   if (section_type == SHT_MIPS_DWARF)
14216     section_type = SHT_PROGBITS;
14217
14218   obj_elf_change_section (section_name, section_type, section_flag,
14219                           section_entry_size, 0, 0, 0);
14220
14221   if (now_seg->name != section_name)
14222     free (section_name);
14223 }
14224
14225 void
14226 mips_enable_auto_align (void)
14227 {
14228   auto_align = 1;
14229 }
14230
14231 static void
14232 s_cons (int log_size)
14233 {
14234   segment_info_type *si = seg_info (now_seg);
14235   struct insn_label_list *l = si->label_list;
14236
14237   mips_emit_delays ();
14238   if (log_size > 0 && auto_align)
14239     mips_align (log_size, 0, l);
14240   cons (1 << log_size);
14241   mips_clear_insn_labels ();
14242 }
14243
14244 static void
14245 s_float_cons (int type)
14246 {
14247   segment_info_type *si = seg_info (now_seg);
14248   struct insn_label_list *l = si->label_list;
14249
14250   mips_emit_delays ();
14251
14252   if (auto_align)
14253     {
14254       if (type == 'd')
14255         mips_align (3, 0, l);
14256       else
14257         mips_align (2, 0, l);
14258     }
14259
14260   float_cons (type);
14261   mips_clear_insn_labels ();
14262 }
14263
14264 /* Handle .globl.  We need to override it because on Irix 5 you are
14265    permitted to say
14266        .globl foo .text
14267    where foo is an undefined symbol, to mean that foo should be
14268    considered to be the address of a function.  */
14269
14270 static void
14271 s_mips_globl (int x ATTRIBUTE_UNUSED)
14272 {
14273   char *name;
14274   int c;
14275   symbolS *symbolP;
14276   flagword flag;
14277
14278   do
14279     {
14280       name = input_line_pointer;
14281       c = get_symbol_end ();
14282       symbolP = symbol_find_or_make (name);
14283       S_SET_EXTERNAL (symbolP);
14284
14285       *input_line_pointer = c;
14286       SKIP_WHITESPACE ();
14287
14288       /* On Irix 5, every global symbol that is not explicitly labelled as
14289          being a function is apparently labelled as being an object.  */
14290       flag = BSF_OBJECT;
14291
14292       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14293           && (*input_line_pointer != ','))
14294         {
14295           char *secname;
14296           asection *sec;
14297
14298           secname = input_line_pointer;
14299           c = get_symbol_end ();
14300           sec = bfd_get_section_by_name (stdoutput, secname);
14301           if (sec == NULL)
14302             as_bad (_("%s: no such section"), secname);
14303           *input_line_pointer = c;
14304
14305           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14306             flag = BSF_FUNCTION;
14307         }
14308
14309       symbol_get_bfdsym (symbolP)->flags |= flag;
14310
14311       c = *input_line_pointer;
14312       if (c == ',')
14313         {
14314           input_line_pointer++;
14315           SKIP_WHITESPACE ();
14316           if (is_end_of_line[(unsigned char) *input_line_pointer])
14317             c = '\n';
14318         }
14319     }
14320   while (c == ',');
14321
14322   demand_empty_rest_of_line ();
14323 }
14324
14325 static void
14326 s_option (int x ATTRIBUTE_UNUSED)
14327 {
14328   char *opt;
14329   char c;
14330
14331   opt = input_line_pointer;
14332   c = get_symbol_end ();
14333
14334   if (*opt == 'O')
14335     {
14336       /* FIXME: What does this mean?  */
14337     }
14338   else if (strncmp (opt, "pic", 3) == 0)
14339     {
14340       int i;
14341
14342       i = atoi (opt + 3);
14343       if (i == 0)
14344         mips_pic = NO_PIC;
14345       else if (i == 2)
14346         {
14347           mips_pic = SVR4_PIC;
14348           mips_abicalls = TRUE;
14349         }
14350       else
14351         as_bad (_(".option pic%d not supported"), i);
14352
14353       if (mips_pic == SVR4_PIC)
14354         {
14355           if (g_switch_seen && g_switch_value != 0)
14356             as_warn (_("-G may not be used with SVR4 PIC code"));
14357           g_switch_value = 0;
14358           bfd_set_gp_size (stdoutput, 0);
14359         }
14360     }
14361   else
14362     as_warn (_("Unrecognized option \"%s\""), opt);
14363
14364   *input_line_pointer = c;
14365   demand_empty_rest_of_line ();
14366 }
14367
14368 /* This structure is used to hold a stack of .set values.  */
14369
14370 struct mips_option_stack
14371 {
14372   struct mips_option_stack *next;
14373   struct mips_set_options options;
14374 };
14375
14376 static struct mips_option_stack *mips_opts_stack;
14377
14378 /* Handle the .set pseudo-op.  */
14379
14380 static void
14381 s_mipsset (int x ATTRIBUTE_UNUSED)
14382 {
14383   char *name = input_line_pointer, ch;
14384   const struct mips_ase *ase;
14385
14386   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14387     ++input_line_pointer;
14388   ch = *input_line_pointer;
14389   *input_line_pointer = '\0';
14390
14391   if (strcmp (name, "reorder") == 0)
14392     {
14393       if (mips_opts.noreorder)
14394         end_noreorder ();
14395     }
14396   else if (strcmp (name, "noreorder") == 0)
14397     {
14398       if (!mips_opts.noreorder)
14399         start_noreorder ();
14400     }
14401   else if (strncmp (name, "at=", 3) == 0)
14402     {
14403       char *s = name + 3;
14404
14405       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14406         as_bad (_("Unrecognized register name `%s'"), s);
14407     }
14408   else if (strcmp (name, "at") == 0)
14409     {
14410       mips_opts.at = ATREG;
14411     }
14412   else if (strcmp (name, "noat") == 0)
14413     {
14414       mips_opts.at = ZERO;
14415     }
14416   else if (strcmp (name, "macro") == 0)
14417     {
14418       mips_opts.warn_about_macros = 0;
14419     }
14420   else if (strcmp (name, "nomacro") == 0)
14421     {
14422       if (mips_opts.noreorder == 0)
14423         as_bad (_("`noreorder' must be set before `nomacro'"));
14424       mips_opts.warn_about_macros = 1;
14425     }
14426   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14427     {
14428       mips_opts.nomove = 0;
14429     }
14430   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14431     {
14432       mips_opts.nomove = 1;
14433     }
14434   else if (strcmp (name, "bopt") == 0)
14435     {
14436       mips_opts.nobopt = 0;
14437     }
14438   else if (strcmp (name, "nobopt") == 0)
14439     {
14440       mips_opts.nobopt = 1;
14441     }
14442   else if (strcmp (name, "gp=default") == 0)
14443     mips_opts.gp32 = file_mips_gp32;
14444   else if (strcmp (name, "gp=32") == 0)
14445     mips_opts.gp32 = 1;
14446   else if (strcmp (name, "gp=64") == 0)
14447     {
14448       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14449         as_warn (_("%s isa does not support 64-bit registers"),
14450                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14451       mips_opts.gp32 = 0;
14452     }
14453   else if (strcmp (name, "fp=default") == 0)
14454     mips_opts.fp32 = file_mips_fp32;
14455   else if (strcmp (name, "fp=32") == 0)
14456     mips_opts.fp32 = 1;
14457   else if (strcmp (name, "fp=64") == 0)
14458     {
14459       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14460         as_warn (_("%s isa does not support 64-bit floating point registers"),
14461                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14462       mips_opts.fp32 = 0;
14463     }
14464   else if (strcmp (name, "softfloat") == 0)
14465     mips_opts.soft_float = 1;
14466   else if (strcmp (name, "hardfloat") == 0)
14467     mips_opts.soft_float = 0;
14468   else if (strcmp (name, "singlefloat") == 0)
14469     mips_opts.single_float = 1;
14470   else if (strcmp (name, "doublefloat") == 0)
14471     mips_opts.single_float = 0;
14472   else if (strcmp (name, "mips16") == 0
14473            || strcmp (name, "MIPS-16") == 0)
14474     {
14475       if (mips_opts.micromips == 1)
14476         as_fatal (_("`mips16' cannot be used with `micromips'"));
14477       mips_opts.mips16 = 1;
14478     }
14479   else if (strcmp (name, "nomips16") == 0
14480            || strcmp (name, "noMIPS-16") == 0)
14481     mips_opts.mips16 = 0;
14482   else if (strcmp (name, "micromips") == 0)
14483     {
14484       if (mips_opts.mips16 == 1)
14485         as_fatal (_("`micromips' cannot be used with `mips16'"));
14486       mips_opts.micromips = 1;
14487     }
14488   else if (strcmp (name, "nomicromips") == 0)
14489     mips_opts.micromips = 0;
14490   else if (name[0] == 'n'
14491            && name[1] == 'o'
14492            && (ase = mips_lookup_ase (name + 2)))
14493     mips_set_ase (ase, FALSE);
14494   else if ((ase = mips_lookup_ase (name)))
14495     mips_set_ase (ase, TRUE);
14496   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
14497     {
14498       int reset = 0;
14499
14500       /* Permit the user to change the ISA and architecture on the fly.
14501          Needless to say, misuse can cause serious problems.  */
14502       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
14503         {
14504           reset = 1;
14505           mips_opts.isa = file_mips_isa;
14506           mips_opts.arch = file_mips_arch;
14507         }
14508       else if (strncmp (name, "arch=", 5) == 0)
14509         {
14510           const struct mips_cpu_info *p;
14511
14512           p = mips_parse_cpu("internal use", name + 5);
14513           if (!p)
14514             as_bad (_("unknown architecture %s"), name + 5);
14515           else
14516             {
14517               mips_opts.arch = p->cpu;
14518               mips_opts.isa = p->isa;
14519             }
14520         }
14521       else if (strncmp (name, "mips", 4) == 0)
14522         {
14523           const struct mips_cpu_info *p;
14524
14525           p = mips_parse_cpu("internal use", name);
14526           if (!p)
14527             as_bad (_("unknown ISA level %s"), name + 4);
14528           else
14529             {
14530               mips_opts.arch = p->cpu;
14531               mips_opts.isa = p->isa;
14532             }
14533         }
14534       else
14535         as_bad (_("unknown ISA or architecture %s"), name);
14536
14537       switch (mips_opts.isa)
14538         {
14539         case  0:
14540           break;
14541         case ISA_MIPS1:
14542         case ISA_MIPS2:
14543         case ISA_MIPS32:
14544         case ISA_MIPS32R2:
14545           mips_opts.gp32 = 1;
14546           mips_opts.fp32 = 1;
14547           break;
14548         case ISA_MIPS3:
14549         case ISA_MIPS4:
14550         case ISA_MIPS5:
14551         case ISA_MIPS64:
14552         case ISA_MIPS64R2:
14553           mips_opts.gp32 = 0;
14554           if (mips_opts.arch == CPU_R5900)
14555             {
14556                 mips_opts.fp32 = 1;
14557             }
14558           else
14559             {
14560           mips_opts.fp32 = 0;
14561             }
14562           break;
14563         default:
14564           as_bad (_("unknown ISA level %s"), name + 4);
14565           break;
14566         }
14567       if (reset)
14568         {
14569           mips_opts.gp32 = file_mips_gp32;
14570           mips_opts.fp32 = file_mips_fp32;
14571         }
14572     }
14573   else if (strcmp (name, "autoextend") == 0)
14574     mips_opts.noautoextend = 0;
14575   else if (strcmp (name, "noautoextend") == 0)
14576     mips_opts.noautoextend = 1;
14577   else if (strcmp (name, "insn32") == 0)
14578     mips_opts.insn32 = TRUE;
14579   else if (strcmp (name, "noinsn32") == 0)
14580     mips_opts.insn32 = FALSE;
14581   else if (strcmp (name, "push") == 0)
14582     {
14583       struct mips_option_stack *s;
14584
14585       s = (struct mips_option_stack *) xmalloc (sizeof *s);
14586       s->next = mips_opts_stack;
14587       s->options = mips_opts;
14588       mips_opts_stack = s;
14589     }
14590   else if (strcmp (name, "pop") == 0)
14591     {
14592       struct mips_option_stack *s;
14593
14594       s = mips_opts_stack;
14595       if (s == NULL)
14596         as_bad (_(".set pop with no .set push"));
14597       else
14598         {
14599           /* If we're changing the reorder mode we need to handle
14600              delay slots correctly.  */
14601           if (s->options.noreorder && ! mips_opts.noreorder)
14602             start_noreorder ();
14603           else if (! s->options.noreorder && mips_opts.noreorder)
14604             end_noreorder ();
14605
14606           mips_opts = s->options;
14607           mips_opts_stack = s->next;
14608           free (s);
14609         }
14610     }
14611   else if (strcmp (name, "sym32") == 0)
14612     mips_opts.sym32 = TRUE;
14613   else if (strcmp (name, "nosym32") == 0)
14614     mips_opts.sym32 = FALSE;
14615   else if (strchr (name, ','))
14616     {
14617       /* Generic ".set" directive; use the generic handler.  */
14618       *input_line_pointer = ch;
14619       input_line_pointer = name;
14620       s_set (0);
14621       return;
14622     }
14623   else
14624     {
14625       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
14626     }
14627   mips_check_isa_supports_ases ();
14628   *input_line_pointer = ch;
14629   demand_empty_rest_of_line ();
14630 }
14631
14632 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
14633    .option pic2.  It means to generate SVR4 PIC calls.  */
14634
14635 static void
14636 s_abicalls (int ignore ATTRIBUTE_UNUSED)
14637 {
14638   mips_pic = SVR4_PIC;
14639   mips_abicalls = TRUE;
14640
14641   if (g_switch_seen && g_switch_value != 0)
14642     as_warn (_("-G may not be used with SVR4 PIC code"));
14643   g_switch_value = 0;
14644
14645   bfd_set_gp_size (stdoutput, 0);
14646   demand_empty_rest_of_line ();
14647 }
14648
14649 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
14650    PIC code.  It sets the $gp register for the function based on the
14651    function address, which is in the register named in the argument.
14652    This uses a relocation against _gp_disp, which is handled specially
14653    by the linker.  The result is:
14654         lui     $gp,%hi(_gp_disp)
14655         addiu   $gp,$gp,%lo(_gp_disp)
14656         addu    $gp,$gp,.cpload argument
14657    The .cpload argument is normally $25 == $t9.
14658
14659    The -mno-shared option changes this to:
14660         lui     $gp,%hi(__gnu_local_gp)
14661         addiu   $gp,$gp,%lo(__gnu_local_gp)
14662    and the argument is ignored.  This saves an instruction, but the
14663    resulting code is not position independent; it uses an absolute
14664    address for __gnu_local_gp.  Thus code assembled with -mno-shared
14665    can go into an ordinary executable, but not into a shared library.  */
14666
14667 static void
14668 s_cpload (int ignore ATTRIBUTE_UNUSED)
14669 {
14670   expressionS ex;
14671   int reg;
14672   int in_shared;
14673
14674   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14675      .cpload is ignored.  */
14676   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14677     {
14678       s_ignore (0);
14679       return;
14680     }
14681
14682   if (mips_opts.mips16)
14683     {
14684       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
14685       ignore_rest_of_line ();
14686       return;
14687     }
14688
14689   /* .cpload should be in a .set noreorder section.  */
14690   if (mips_opts.noreorder == 0)
14691     as_warn (_(".cpload not in noreorder section"));
14692
14693   reg = tc_get_register (0);
14694
14695   /* If we need to produce a 64-bit address, we are better off using
14696      the default instruction sequence.  */
14697   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
14698
14699   ex.X_op = O_symbol;
14700   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
14701                                          "__gnu_local_gp");
14702   ex.X_op_symbol = NULL;
14703   ex.X_add_number = 0;
14704
14705   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14706   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14707
14708   mips_mark_labels ();
14709   mips_assembling_insn = TRUE;
14710
14711   macro_start ();
14712   macro_build_lui (&ex, mips_gp_register);
14713   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14714                mips_gp_register, BFD_RELOC_LO16);
14715   if (in_shared)
14716     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
14717                  mips_gp_register, reg);
14718   macro_end ();
14719
14720   mips_assembling_insn = FALSE;
14721   demand_empty_rest_of_line ();
14722 }
14723
14724 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
14725      .cpsetup $reg1, offset|$reg2, label
14726
14727    If offset is given, this results in:
14728      sd         $gp, offset($sp)
14729      lui        $gp, %hi(%neg(%gp_rel(label)))
14730      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14731      daddu      $gp, $gp, $reg1
14732
14733    If $reg2 is given, this results in:
14734      daddu      $reg2, $gp, $0
14735      lui        $gp, %hi(%neg(%gp_rel(label)))
14736      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14737      daddu      $gp, $gp, $reg1
14738    $reg1 is normally $25 == $t9.
14739
14740    The -mno-shared option replaces the last three instructions with
14741         lui     $gp,%hi(_gp)
14742         addiu   $gp,$gp,%lo(_gp)  */
14743
14744 static void
14745 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
14746 {
14747   expressionS ex_off;
14748   expressionS ex_sym;
14749   int reg1;
14750
14751   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
14752      We also need NewABI support.  */
14753   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14754     {
14755       s_ignore (0);
14756       return;
14757     }
14758
14759   if (mips_opts.mips16)
14760     {
14761       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
14762       ignore_rest_of_line ();
14763       return;
14764     }
14765
14766   reg1 = tc_get_register (0);
14767   SKIP_WHITESPACE ();
14768   if (*input_line_pointer != ',')
14769     {
14770       as_bad (_("missing argument separator ',' for .cpsetup"));
14771       return;
14772     }
14773   else
14774     ++input_line_pointer;
14775   SKIP_WHITESPACE ();
14776   if (*input_line_pointer == '$')
14777     {
14778       mips_cpreturn_register = tc_get_register (0);
14779       mips_cpreturn_offset = -1;
14780     }
14781   else
14782     {
14783       mips_cpreturn_offset = get_absolute_expression ();
14784       mips_cpreturn_register = -1;
14785     }
14786   SKIP_WHITESPACE ();
14787   if (*input_line_pointer != ',')
14788     {
14789       as_bad (_("missing argument separator ',' for .cpsetup"));
14790       return;
14791     }
14792   else
14793     ++input_line_pointer;
14794   SKIP_WHITESPACE ();
14795   expression (&ex_sym);
14796
14797   mips_mark_labels ();
14798   mips_assembling_insn = TRUE;
14799
14800   macro_start ();
14801   if (mips_cpreturn_register == -1)
14802     {
14803       ex_off.X_op = O_constant;
14804       ex_off.X_add_symbol = NULL;
14805       ex_off.X_op_symbol = NULL;
14806       ex_off.X_add_number = mips_cpreturn_offset;
14807
14808       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
14809                    BFD_RELOC_LO16, SP);
14810     }
14811   else
14812     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
14813                  mips_gp_register, 0);
14814
14815   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
14816     {
14817       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
14818                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
14819                    BFD_RELOC_HI16_S);
14820
14821       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
14822                    mips_gp_register, -1, BFD_RELOC_GPREL16,
14823                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
14824
14825       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
14826                    mips_gp_register, reg1);
14827     }
14828   else
14829     {
14830       expressionS ex;
14831
14832       ex.X_op = O_symbol;
14833       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
14834       ex.X_op_symbol = NULL;
14835       ex.X_add_number = 0;
14836
14837       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14838       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14839
14840       macro_build_lui (&ex, mips_gp_register);
14841       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14842                    mips_gp_register, BFD_RELOC_LO16);
14843     }
14844
14845   macro_end ();
14846
14847   mips_assembling_insn = FALSE;
14848   demand_empty_rest_of_line ();
14849 }
14850
14851 static void
14852 s_cplocal (int ignore ATTRIBUTE_UNUSED)
14853 {
14854   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
14855      .cplocal is ignored.  */
14856   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14857     {
14858       s_ignore (0);
14859       return;
14860     }
14861
14862   if (mips_opts.mips16)
14863     {
14864       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
14865       ignore_rest_of_line ();
14866       return;
14867     }
14868
14869   mips_gp_register = tc_get_register (0);
14870   demand_empty_rest_of_line ();
14871 }
14872
14873 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
14874    offset from $sp.  The offset is remembered, and after making a PIC
14875    call $gp is restored from that location.  */
14876
14877 static void
14878 s_cprestore (int ignore ATTRIBUTE_UNUSED)
14879 {
14880   expressionS ex;
14881
14882   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14883      .cprestore is ignored.  */
14884   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14885     {
14886       s_ignore (0);
14887       return;
14888     }
14889
14890   if (mips_opts.mips16)
14891     {
14892       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
14893       ignore_rest_of_line ();
14894       return;
14895     }
14896
14897   mips_cprestore_offset = get_absolute_expression ();
14898   mips_cprestore_valid = 1;
14899
14900   ex.X_op = O_constant;
14901   ex.X_add_symbol = NULL;
14902   ex.X_op_symbol = NULL;
14903   ex.X_add_number = mips_cprestore_offset;
14904
14905   mips_mark_labels ();
14906   mips_assembling_insn = TRUE;
14907
14908   macro_start ();
14909   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
14910                                 SP, HAVE_64BIT_ADDRESSES);
14911   macro_end ();
14912
14913   mips_assembling_insn = FALSE;
14914   demand_empty_rest_of_line ();
14915 }
14916
14917 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
14918    was given in the preceding .cpsetup, it results in:
14919      ld         $gp, offset($sp)
14920
14921    If a register $reg2 was given there, it results in:
14922      daddu      $gp, $reg2, $0  */
14923
14924 static void
14925 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
14926 {
14927   expressionS ex;
14928
14929   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
14930      We also need NewABI support.  */
14931   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14932     {
14933       s_ignore (0);
14934       return;
14935     }
14936
14937   if (mips_opts.mips16)
14938     {
14939       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
14940       ignore_rest_of_line ();
14941       return;
14942     }
14943
14944   mips_mark_labels ();
14945   mips_assembling_insn = TRUE;
14946
14947   macro_start ();
14948   if (mips_cpreturn_register == -1)
14949     {
14950       ex.X_op = O_constant;
14951       ex.X_add_symbol = NULL;
14952       ex.X_op_symbol = NULL;
14953       ex.X_add_number = mips_cpreturn_offset;
14954
14955       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
14956     }
14957   else
14958     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
14959                  mips_cpreturn_register, 0);
14960   macro_end ();
14961
14962   mips_assembling_insn = FALSE;
14963   demand_empty_rest_of_line ();
14964 }
14965
14966 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
14967    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
14968    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
14969    debug information or MIPS16 TLS.  */
14970
14971 static void
14972 s_tls_rel_directive (const size_t bytes, const char *dirstr,
14973                      bfd_reloc_code_real_type rtype)
14974 {
14975   expressionS ex;
14976   char *p;
14977
14978   expression (&ex);
14979
14980   if (ex.X_op != O_symbol)
14981     {
14982       as_bad (_("Unsupported use of %s"), dirstr);
14983       ignore_rest_of_line ();
14984     }
14985
14986   p = frag_more (bytes);
14987   md_number_to_chars (p, 0, bytes);
14988   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
14989   demand_empty_rest_of_line ();
14990   mips_clear_insn_labels ();
14991 }
14992
14993 /* Handle .dtprelword.  */
14994
14995 static void
14996 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
14997 {
14998   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
14999 }
15000
15001 /* Handle .dtpreldword.  */
15002
15003 static void
15004 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15005 {
15006   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15007 }
15008
15009 /* Handle .tprelword.  */
15010
15011 static void
15012 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15013 {
15014   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15015 }
15016
15017 /* Handle .tpreldword.  */
15018
15019 static void
15020 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15021 {
15022   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15023 }
15024
15025 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15026    code.  It sets the offset to use in gp_rel relocations.  */
15027
15028 static void
15029 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15030 {
15031   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15032      We also need NewABI support.  */
15033   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15034     {
15035       s_ignore (0);
15036       return;
15037     }
15038
15039   mips_gprel_offset = get_absolute_expression ();
15040
15041   demand_empty_rest_of_line ();
15042 }
15043
15044 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15045    code.  It generates a 32 bit GP relative reloc.  */
15046
15047 static void
15048 s_gpword (int ignore ATTRIBUTE_UNUSED)
15049 {
15050   segment_info_type *si;
15051   struct insn_label_list *l;
15052   expressionS ex;
15053   char *p;
15054
15055   /* When not generating PIC code, this is treated as .word.  */
15056   if (mips_pic != SVR4_PIC)
15057     {
15058       s_cons (2);
15059       return;
15060     }
15061
15062   si = seg_info (now_seg);
15063   l = si->label_list;
15064   mips_emit_delays ();
15065   if (auto_align)
15066     mips_align (2, 0, l);
15067
15068   expression (&ex);
15069   mips_clear_insn_labels ();
15070
15071   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15072     {
15073       as_bad (_("Unsupported use of .gpword"));
15074       ignore_rest_of_line ();
15075     }
15076
15077   p = frag_more (4);
15078   md_number_to_chars (p, 0, 4);
15079   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15080                BFD_RELOC_GPREL32);
15081
15082   demand_empty_rest_of_line ();
15083 }
15084
15085 static void
15086 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15087 {
15088   segment_info_type *si;
15089   struct insn_label_list *l;
15090   expressionS ex;
15091   char *p;
15092
15093   /* When not generating PIC code, this is treated as .dword.  */
15094   if (mips_pic != SVR4_PIC)
15095     {
15096       s_cons (3);
15097       return;
15098     }
15099
15100   si = seg_info (now_seg);
15101   l = si->label_list;
15102   mips_emit_delays ();
15103   if (auto_align)
15104     mips_align (3, 0, l);
15105
15106   expression (&ex);
15107   mips_clear_insn_labels ();
15108
15109   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15110     {
15111       as_bad (_("Unsupported use of .gpdword"));
15112       ignore_rest_of_line ();
15113     }
15114
15115   p = frag_more (8);
15116   md_number_to_chars (p, 0, 8);
15117   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15118                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15119
15120   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15121   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15122            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15123
15124   demand_empty_rest_of_line ();
15125 }
15126
15127 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15128    tables.  It generates a R_MIPS_EH reloc.  */
15129
15130 static void
15131 s_ehword (int ignore ATTRIBUTE_UNUSED)
15132 {
15133   expressionS ex;
15134   char *p;
15135
15136   mips_emit_delays ();
15137
15138   expression (&ex);
15139   mips_clear_insn_labels ();
15140
15141   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15142     {
15143       as_bad (_("Unsupported use of .ehword"));
15144       ignore_rest_of_line ();
15145     }
15146
15147   p = frag_more (4);
15148   md_number_to_chars (p, 0, 4);
15149   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15150                BFD_RELOC_MIPS_EH);
15151
15152   demand_empty_rest_of_line ();
15153 }
15154
15155 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15156    tables in SVR4 PIC code.  */
15157
15158 static void
15159 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15160 {
15161   int reg;
15162
15163   /* This is ignored when not generating SVR4 PIC code.  */
15164   if (mips_pic != SVR4_PIC)
15165     {
15166       s_ignore (0);
15167       return;
15168     }
15169
15170   mips_mark_labels ();
15171   mips_assembling_insn = TRUE;
15172
15173   /* Add $gp to the register named as an argument.  */
15174   macro_start ();
15175   reg = tc_get_register (0);
15176   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15177   macro_end ();
15178
15179   mips_assembling_insn = FALSE;
15180   demand_empty_rest_of_line ();
15181 }
15182
15183 /* Handle the .insn pseudo-op.  This marks instruction labels in
15184    mips16/micromips mode.  This permits the linker to handle them specially,
15185    such as generating jalx instructions when needed.  We also make
15186    them odd for the duration of the assembly, in order to generate the
15187    right sort of code.  We will make them even in the adjust_symtab
15188    routine, while leaving them marked.  This is convenient for the
15189    debugger and the disassembler.  The linker knows to make them odd
15190    again.  */
15191
15192 static void
15193 s_insn (int ignore ATTRIBUTE_UNUSED)
15194 {
15195   mips_mark_labels ();
15196
15197   demand_empty_rest_of_line ();
15198 }
15199
15200 /* Handle the .nan pseudo-op.  */
15201
15202 static void
15203 s_nan (int ignore ATTRIBUTE_UNUSED)
15204 {
15205   static const char str_legacy[] = "legacy";
15206   static const char str_2008[] = "2008";
15207   size_t i;
15208
15209   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15210
15211   if (i == sizeof (str_2008) - 1
15212       && memcmp (input_line_pointer, str_2008, i) == 0)
15213     mips_flag_nan2008 = TRUE;
15214   else if (i == sizeof (str_legacy) - 1
15215            && memcmp (input_line_pointer, str_legacy, i) == 0)
15216     mips_flag_nan2008 = FALSE;
15217   else
15218     as_bad (_("Bad .nan directive"));
15219
15220   input_line_pointer += i;
15221   demand_empty_rest_of_line ();
15222 }
15223
15224 /* Handle a .stab[snd] directive.  Ideally these directives would be
15225    implemented in a transparent way, so that removing them would not
15226    have any effect on the generated instructions.  However, s_stab
15227    internally changes the section, so in practice we need to decide
15228    now whether the preceding label marks compressed code.  We do not
15229    support changing the compression mode of a label after a .stab*
15230    directive, such as in:
15231
15232    foo:
15233         .stabs ...
15234         .set mips16
15235
15236    so the current mode wins.  */
15237
15238 static void
15239 s_mips_stab (int type)
15240 {
15241   mips_mark_labels ();
15242   s_stab (type);
15243 }
15244
15245 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15246
15247 static void
15248 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15249 {
15250   char *name;
15251   int c;
15252   symbolS *symbolP;
15253   expressionS exp;
15254
15255   name = input_line_pointer;
15256   c = get_symbol_end ();
15257   symbolP = symbol_find_or_make (name);
15258   S_SET_WEAK (symbolP);
15259   *input_line_pointer = c;
15260
15261   SKIP_WHITESPACE ();
15262
15263   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15264     {
15265       if (S_IS_DEFINED (symbolP))
15266         {
15267           as_bad (_("ignoring attempt to redefine symbol %s"),
15268                   S_GET_NAME (symbolP));
15269           ignore_rest_of_line ();
15270           return;
15271         }
15272
15273       if (*input_line_pointer == ',')
15274         {
15275           ++input_line_pointer;
15276           SKIP_WHITESPACE ();
15277         }
15278
15279       expression (&exp);
15280       if (exp.X_op != O_symbol)
15281         {
15282           as_bad (_("bad .weakext directive"));
15283           ignore_rest_of_line ();
15284           return;
15285         }
15286       symbol_set_value_expression (symbolP, &exp);
15287     }
15288
15289   demand_empty_rest_of_line ();
15290 }
15291
15292 /* Parse a register string into a number.  Called from the ECOFF code
15293    to parse .frame.  The argument is non-zero if this is the frame
15294    register, so that we can record it in mips_frame_reg.  */
15295
15296 int
15297 tc_get_register (int frame)
15298 {
15299   unsigned int reg;
15300
15301   SKIP_WHITESPACE ();
15302   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15303     reg = 0;
15304   if (frame)
15305     {
15306       mips_frame_reg = reg != 0 ? reg : SP;
15307       mips_frame_reg_valid = 1;
15308       mips_cprestore_valid = 0;
15309     }
15310   return reg;
15311 }
15312
15313 valueT
15314 md_section_align (asection *seg, valueT addr)
15315 {
15316   int align = bfd_get_section_alignment (stdoutput, seg);
15317
15318   /* We don't need to align ELF sections to the full alignment.
15319      However, Irix 5 may prefer that we align them at least to a 16
15320      byte boundary.  We don't bother to align the sections if we
15321      are targeted for an embedded system.  */
15322   if (strncmp (TARGET_OS, "elf", 3) == 0)
15323     return addr;
15324   if (align > 4)
15325     align = 4;
15326
15327   return ((addr + (1 << align) - 1) & (-1 << align));
15328 }
15329
15330 /* Utility routine, called from above as well.  If called while the
15331    input file is still being read, it's only an approximation.  (For
15332    example, a symbol may later become defined which appeared to be
15333    undefined earlier.)  */
15334
15335 static int
15336 nopic_need_relax (symbolS *sym, int before_relaxing)
15337 {
15338   if (sym == 0)
15339     return 0;
15340
15341   if (g_switch_value > 0)
15342     {
15343       const char *symname;
15344       int change;
15345
15346       /* Find out whether this symbol can be referenced off the $gp
15347          register.  It can be if it is smaller than the -G size or if
15348          it is in the .sdata or .sbss section.  Certain symbols can
15349          not be referenced off the $gp, although it appears as though
15350          they can.  */
15351       symname = S_GET_NAME (sym);
15352       if (symname != (const char *) NULL
15353           && (strcmp (symname, "eprol") == 0
15354               || strcmp (symname, "etext") == 0
15355               || strcmp (symname, "_gp") == 0
15356               || strcmp (symname, "edata") == 0
15357               || strcmp (symname, "_fbss") == 0
15358               || strcmp (symname, "_fdata") == 0
15359               || strcmp (symname, "_ftext") == 0
15360               || strcmp (symname, "end") == 0
15361               || strcmp (symname, "_gp_disp") == 0))
15362         change = 1;
15363       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15364                && (0
15365 #ifndef NO_ECOFF_DEBUGGING
15366                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15367                        && (symbol_get_obj (sym)->ecoff_extern_size
15368                            <= g_switch_value))
15369 #endif
15370                    /* We must defer this decision until after the whole
15371                       file has been read, since there might be a .extern
15372                       after the first use of this symbol.  */
15373                    || (before_relaxing
15374 #ifndef NO_ECOFF_DEBUGGING
15375                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15376 #endif
15377                        && S_GET_VALUE (sym) == 0)
15378                    || (S_GET_VALUE (sym) != 0
15379                        && S_GET_VALUE (sym) <= g_switch_value)))
15380         change = 0;
15381       else
15382         {
15383           const char *segname;
15384
15385           segname = segment_name (S_GET_SEGMENT (sym));
15386           gas_assert (strcmp (segname, ".lit8") != 0
15387                   && strcmp (segname, ".lit4") != 0);
15388           change = (strcmp (segname, ".sdata") != 0
15389                     && strcmp (segname, ".sbss") != 0
15390                     && strncmp (segname, ".sdata.", 7) != 0
15391                     && strncmp (segname, ".sbss.", 6) != 0
15392                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15393                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15394         }
15395       return change;
15396     }
15397   else
15398     /* We are not optimizing for the $gp register.  */
15399     return 1;
15400 }
15401
15402
15403 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15404
15405 static bfd_boolean
15406 pic_need_relax (symbolS *sym, asection *segtype)
15407 {
15408   asection *symsec;
15409
15410   /* Handle the case of a symbol equated to another symbol.  */
15411   while (symbol_equated_reloc_p (sym))
15412     {
15413       symbolS *n;
15414
15415       /* It's possible to get a loop here in a badly written program.  */
15416       n = symbol_get_value_expression (sym)->X_add_symbol;
15417       if (n == sym)
15418         break;
15419       sym = n;
15420     }
15421
15422   if (symbol_section_p (sym))
15423     return TRUE;
15424
15425   symsec = S_GET_SEGMENT (sym);
15426
15427   /* This must duplicate the test in adjust_reloc_syms.  */
15428   return (!bfd_is_und_section (symsec)
15429           && !bfd_is_abs_section (symsec)
15430           && !bfd_is_com_section (symsec)
15431           && !s_is_linkonce (sym, segtype)
15432           /* A global or weak symbol is treated as external.  */
15433           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15434 }
15435
15436
15437 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15438    extended opcode.  SEC is the section the frag is in.  */
15439
15440 static int
15441 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15442 {
15443   int type;
15444   const struct mips16_immed_operand *op;
15445   offsetT val;
15446   int mintiny, maxtiny;
15447   segT symsec;
15448   fragS *sym_frag;
15449
15450   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15451     return 0;
15452   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15453     return 1;
15454
15455   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15456   op = mips16_immed_operands;
15457   while (op->type != type)
15458     {
15459       ++op;
15460       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
15461     }
15462
15463   if (op->unsp)
15464     {
15465       if (type == '<' || type == '>' || type == '[' || type == ']')
15466         {
15467           mintiny = 1;
15468           maxtiny = 1 << op->nbits;
15469         }
15470       else
15471         {
15472           mintiny = 0;
15473           maxtiny = (1 << op->nbits) - 1;
15474         }
15475     }
15476   else
15477     {
15478       mintiny = - (1 << (op->nbits - 1));
15479       maxtiny = (1 << (op->nbits - 1)) - 1;
15480     }
15481
15482   sym_frag = symbol_get_frag (fragp->fr_symbol);
15483   val = S_GET_VALUE (fragp->fr_symbol);
15484   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15485
15486   if (op->pcrel)
15487     {
15488       addressT addr;
15489
15490       /* We won't have the section when we are called from
15491          mips_relax_frag.  However, we will always have been called
15492          from md_estimate_size_before_relax first.  If this is a
15493          branch to a different section, we mark it as such.  If SEC is
15494          NULL, and the frag is not marked, then it must be a branch to
15495          the same section.  */
15496       if (sec == NULL)
15497         {
15498           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15499             return 1;
15500         }
15501       else
15502         {
15503           /* Must have been called from md_estimate_size_before_relax.  */
15504           if (symsec != sec)
15505             {
15506               fragp->fr_subtype =
15507                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15508
15509               /* FIXME: We should support this, and let the linker
15510                  catch branches and loads that are out of range.  */
15511               as_bad_where (fragp->fr_file, fragp->fr_line,
15512                             _("unsupported PC relative reference to different section"));
15513
15514               return 1;
15515             }
15516           if (fragp != sym_frag && sym_frag->fr_address == 0)
15517             /* Assume non-extended on the first relaxation pass.
15518                The address we have calculated will be bogus if this is
15519                a forward branch to another frag, as the forward frag
15520                will have fr_address == 0.  */
15521             return 0;
15522         }
15523
15524       /* In this case, we know for sure that the symbol fragment is in
15525          the same section.  If the relax_marker of the symbol fragment
15526          differs from the relax_marker of this fragment, we have not
15527          yet adjusted the symbol fragment fr_address.  We want to add
15528          in STRETCH in order to get a better estimate of the address.
15529          This particularly matters because of the shift bits.  */
15530       if (stretch != 0
15531           && sym_frag->relax_marker != fragp->relax_marker)
15532         {
15533           fragS *f;
15534
15535           /* Adjust stretch for any alignment frag.  Note that if have
15536              been expanding the earlier code, the symbol may be
15537              defined in what appears to be an earlier frag.  FIXME:
15538              This doesn't handle the fr_subtype field, which specifies
15539              a maximum number of bytes to skip when doing an
15540              alignment.  */
15541           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
15542             {
15543               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
15544                 {
15545                   if (stretch < 0)
15546                     stretch = - ((- stretch)
15547                                  & ~ ((1 << (int) f->fr_offset) - 1));
15548                   else
15549                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
15550                   if (stretch == 0)
15551                     break;
15552                 }
15553             }
15554           if (f != NULL)
15555             val += stretch;
15556         }
15557
15558       addr = fragp->fr_address + fragp->fr_fix;
15559
15560       /* The base address rules are complicated.  The base address of
15561          a branch is the following instruction.  The base address of a
15562          PC relative load or add is the instruction itself, but if it
15563          is in a delay slot (in which case it can not be extended) use
15564          the address of the instruction whose delay slot it is in.  */
15565       if (type == 'p' || type == 'q')
15566         {
15567           addr += 2;
15568
15569           /* If we are currently assuming that this frag should be
15570              extended, then, the current address is two bytes
15571              higher.  */
15572           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
15573             addr += 2;
15574
15575           /* Ignore the low bit in the target, since it will be set
15576              for a text label.  */
15577           if ((val & 1) != 0)
15578             --val;
15579         }
15580       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
15581         addr -= 4;
15582       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
15583         addr -= 2;
15584
15585       val -= addr & ~ ((1 << op->shift) - 1);
15586
15587       /* Branch offsets have an implicit 0 in the lowest bit.  */
15588       if (type == 'p' || type == 'q')
15589         val /= 2;
15590
15591       /* If any of the shifted bits are set, we must use an extended
15592          opcode.  If the address depends on the size of this
15593          instruction, this can lead to a loop, so we arrange to always
15594          use an extended opcode.  We only check this when we are in
15595          the main relaxation loop, when SEC is NULL.  */
15596       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
15597         {
15598           fragp->fr_subtype =
15599             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15600           return 1;
15601         }
15602
15603       /* If we are about to mark a frag as extended because the value
15604          is precisely maxtiny + 1, then there is a chance of an
15605          infinite loop as in the following code:
15606              la $4,foo
15607              .skip      1020
15608              .align     2
15609            foo:
15610          In this case when the la is extended, foo is 0x3fc bytes
15611          away, so the la can be shrunk, but then foo is 0x400 away, so
15612          the la must be extended.  To avoid this loop, we mark the
15613          frag as extended if it was small, and is about to become
15614          extended with a value of maxtiny + 1.  */
15615       if (val == ((maxtiny + 1) << op->shift)
15616           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
15617           && sec == NULL)
15618         {
15619           fragp->fr_subtype =
15620             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15621           return 1;
15622         }
15623     }
15624   else if (symsec != absolute_section && sec != NULL)
15625     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
15626
15627   if ((val & ((1 << op->shift) - 1)) != 0
15628       || val < (mintiny << op->shift)
15629       || val > (maxtiny << op->shift))
15630     return 1;
15631   else
15632     return 0;
15633 }
15634
15635 /* Compute the length of a branch sequence, and adjust the
15636    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
15637    worst-case length is computed, with UPDATE being used to indicate
15638    whether an unconditional (-1), branch-likely (+1) or regular (0)
15639    branch is to be computed.  */
15640 static int
15641 relaxed_branch_length (fragS *fragp, asection *sec, int update)
15642 {
15643   bfd_boolean toofar;
15644   int length;
15645
15646   if (fragp
15647       && S_IS_DEFINED (fragp->fr_symbol)
15648       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15649     {
15650       addressT addr;
15651       offsetT val;
15652
15653       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15654
15655       addr = fragp->fr_address + fragp->fr_fix + 4;
15656
15657       val -= addr;
15658
15659       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
15660     }
15661   else if (fragp)
15662     /* If the symbol is not defined or it's in a different segment,
15663        assume the user knows what's going on and emit a short
15664        branch.  */
15665     toofar = FALSE;
15666   else
15667     toofar = TRUE;
15668
15669   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
15670     fragp->fr_subtype
15671       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
15672                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
15673                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
15674                              RELAX_BRANCH_LINK (fragp->fr_subtype),
15675                              toofar);
15676
15677   length = 4;
15678   if (toofar)
15679     {
15680       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
15681         length += 8;
15682
15683       if (mips_pic != NO_PIC)
15684         {
15685           /* Additional space for PIC loading of target address.  */
15686           length += 8;
15687           if (mips_opts.isa == ISA_MIPS1)
15688             /* Additional space for $at-stabilizing nop.  */
15689             length += 4;
15690         }
15691
15692       /* If branch is conditional.  */
15693       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
15694         length += 8;
15695     }
15696
15697   return length;
15698 }
15699
15700 /* Compute the length of a branch sequence, and adjust the
15701    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
15702    worst-case length is computed, with UPDATE being used to indicate
15703    whether an unconditional (-1), or regular (0) branch is to be
15704    computed.  */
15705
15706 static int
15707 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
15708 {
15709   bfd_boolean toofar;
15710   int length;
15711
15712   if (fragp
15713       && S_IS_DEFINED (fragp->fr_symbol)
15714       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15715     {
15716       addressT addr;
15717       offsetT val;
15718
15719       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15720       /* Ignore the low bit in the target, since it will be set
15721          for a text label.  */
15722       if ((val & 1) != 0)
15723         --val;
15724
15725       addr = fragp->fr_address + fragp->fr_fix + 4;
15726
15727       val -= addr;
15728
15729       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
15730     }
15731   else if (fragp)
15732     /* If the symbol is not defined or it's in a different segment,
15733        assume the user knows what's going on and emit a short
15734        branch.  */
15735     toofar = FALSE;
15736   else
15737     toofar = TRUE;
15738
15739   if (fragp && update
15740       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
15741     fragp->fr_subtype = (toofar
15742                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
15743                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
15744
15745   length = 4;
15746   if (toofar)
15747     {
15748       bfd_boolean compact_known = fragp != NULL;
15749       bfd_boolean compact = FALSE;
15750       bfd_boolean uncond;
15751
15752       if (compact_known)
15753         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
15754       if (fragp)
15755         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
15756       else
15757         uncond = update < 0;
15758
15759       /* If label is out of range, we turn branch <br>:
15760
15761                 <br>    label                   # 4 bytes
15762             0:
15763
15764          into:
15765
15766                 j       label                   # 4 bytes
15767                 nop                             # 2 bytes if compact && !PIC
15768             0:
15769        */
15770       if (mips_pic == NO_PIC && (!compact_known || compact))
15771         length += 2;
15772
15773       /* If assembling PIC code, we further turn:
15774
15775                         j       label                   # 4 bytes
15776
15777          into:
15778
15779                         lw/ld   at, %got(label)(gp)     # 4 bytes
15780                         d/addiu at, %lo(label)          # 4 bytes
15781                         jr/c    at                      # 2 bytes
15782        */
15783       if (mips_pic != NO_PIC)
15784         length += 6;
15785
15786       /* If branch <br> is conditional, we prepend negated branch <brneg>:
15787
15788                         <brneg> 0f                      # 4 bytes
15789                         nop                             # 2 bytes if !compact
15790        */
15791       if (!uncond)
15792         length += (compact_known && compact) ? 4 : 6;
15793     }
15794
15795   return length;
15796 }
15797
15798 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
15799    bit accordingly.  */
15800
15801 static int
15802 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
15803 {
15804   bfd_boolean toofar;
15805
15806   if (fragp
15807       && S_IS_DEFINED (fragp->fr_symbol)
15808       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15809     {
15810       addressT addr;
15811       offsetT val;
15812       int type;
15813
15814       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15815       /* Ignore the low bit in the target, since it will be set
15816          for a text label.  */
15817       if ((val & 1) != 0)
15818         --val;
15819
15820       /* Assume this is a 2-byte branch.  */
15821       addr = fragp->fr_address + fragp->fr_fix + 2;
15822
15823       /* We try to avoid the infinite loop by not adding 2 more bytes for
15824          long branches.  */
15825
15826       val -= addr;
15827
15828       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
15829       if (type == 'D')
15830         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
15831       else if (type == 'E')
15832         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
15833       else
15834         abort ();
15835     }
15836   else
15837     /* If the symbol is not defined or it's in a different segment,
15838        we emit a normal 32-bit branch.  */
15839     toofar = TRUE;
15840
15841   if (fragp && update
15842       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
15843     fragp->fr_subtype
15844       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
15845                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
15846
15847   if (toofar)
15848     return 4;
15849
15850   return 2;
15851 }
15852
15853 /* Estimate the size of a frag before relaxing.  Unless this is the
15854    mips16, we are not really relaxing here, and the final size is
15855    encoded in the subtype information.  For the mips16, we have to
15856    decide whether we are using an extended opcode or not.  */
15857
15858 int
15859 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
15860 {
15861   int change;
15862
15863   if (RELAX_BRANCH_P (fragp->fr_subtype))
15864     {
15865
15866       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
15867
15868       return fragp->fr_var;
15869     }
15870
15871   if (RELAX_MIPS16_P (fragp->fr_subtype))
15872     /* We don't want to modify the EXTENDED bit here; it might get us
15873        into infinite loops.  We change it only in mips_relax_frag().  */
15874     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
15875
15876   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
15877     {
15878       int length = 4;
15879
15880       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
15881         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
15882       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
15883         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
15884       fragp->fr_var = length;
15885
15886       return length;
15887     }
15888
15889   if (mips_pic == NO_PIC)
15890     change = nopic_need_relax (fragp->fr_symbol, 0);
15891   else if (mips_pic == SVR4_PIC)
15892     change = pic_need_relax (fragp->fr_symbol, segtype);
15893   else if (mips_pic == VXWORKS_PIC)
15894     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
15895     change = 0;
15896   else
15897     abort ();
15898
15899   if (change)
15900     {
15901       fragp->fr_subtype |= RELAX_USE_SECOND;
15902       return -RELAX_FIRST (fragp->fr_subtype);
15903     }
15904   else
15905     return -RELAX_SECOND (fragp->fr_subtype);
15906 }
15907
15908 /* This is called to see whether a reloc against a defined symbol
15909    should be converted into a reloc against a section.  */
15910
15911 int
15912 mips_fix_adjustable (fixS *fixp)
15913 {
15914   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15915       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
15916     return 0;
15917
15918   if (fixp->fx_addsy == NULL)
15919     return 1;
15920
15921   /* If symbol SYM is in a mergeable section, relocations of the form
15922      SYM + 0 can usually be made section-relative.  The mergeable data
15923      is then identified by the section offset rather than by the symbol.
15924
15925      However, if we're generating REL LO16 relocations, the offset is split
15926      between the LO16 and parterning high part relocation.  The linker will
15927      need to recalculate the complete offset in order to correctly identify
15928      the merge data.
15929
15930      The linker has traditionally not looked for the parterning high part
15931      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
15932      placed anywhere.  Rather than break backwards compatibility by changing
15933      this, it seems better not to force the issue, and instead keep the
15934      original symbol.  This will work with either linker behavior.  */
15935   if ((lo16_reloc_p (fixp->fx_r_type)
15936        || reloc_needs_lo_p (fixp->fx_r_type))
15937       && HAVE_IN_PLACE_ADDENDS
15938       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
15939     return 0;
15940
15941   /* There is no place to store an in-place offset for JALR relocations.
15942      Likewise an in-range offset of limited PC-relative relocations may
15943      overflow the in-place relocatable field if recalculated against the
15944      start address of the symbol's containing section.  */
15945   if (HAVE_IN_PLACE_ADDENDS
15946       && (limited_pcrel_reloc_p (fixp->fx_r_type)
15947           || jalr_reloc_p (fixp->fx_r_type)))
15948     return 0;
15949
15950   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
15951      to a floating-point stub.  The same is true for non-R_MIPS16_26
15952      relocations against MIPS16 functions; in this case, the stub becomes
15953      the function's canonical address.
15954
15955      Floating-point stubs are stored in unique .mips16.call.* or
15956      .mips16.fn.* sections.  If a stub T for function F is in section S,
15957      the first relocation in section S must be against F; this is how the
15958      linker determines the target function.  All relocations that might
15959      resolve to T must also be against F.  We therefore have the following
15960      restrictions, which are given in an intentionally-redundant way:
15961
15962        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
15963           symbols.
15964
15965        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
15966           if that stub might be used.
15967
15968        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
15969           symbols.
15970
15971        4. We cannot reduce a stub's relocations against MIPS16 symbols if
15972           that stub might be used.
15973
15974      There is a further restriction:
15975
15976        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
15977           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
15978           targets with in-place addends; the relocation field cannot
15979           encode the low bit.
15980
15981      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
15982      against a MIPS16 symbol.  We deal with (5) by by not reducing any
15983      such relocations on REL targets.
15984
15985      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
15986      relocation against some symbol R, no relocation against R may be
15987      reduced.  (Note that this deals with (2) as well as (1) because
15988      relocations against global symbols will never be reduced on ELF
15989      targets.)  This approach is a little simpler than trying to detect
15990      stub sections, and gives the "all or nothing" per-symbol consistency
15991      that we have for MIPS16 symbols.  */
15992   if (fixp->fx_subsy == NULL
15993       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
15994           || *symbol_get_tc (fixp->fx_addsy)
15995           || (HAVE_IN_PLACE_ADDENDS
15996               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
15997               && jmp_reloc_p (fixp->fx_r_type))))
15998     return 0;
15999
16000   return 1;
16001 }
16002
16003 /* Translate internal representation of relocation info to BFD target
16004    format.  */
16005
16006 arelent **
16007 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16008 {
16009   static arelent *retval[4];
16010   arelent *reloc;
16011   bfd_reloc_code_real_type code;
16012
16013   memset (retval, 0, sizeof(retval));
16014   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16015   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16016   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16017   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16018
16019   if (fixp->fx_pcrel)
16020     {
16021       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16022                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16023                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16024                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16025                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16026
16027       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16028          Relocations want only the symbol offset.  */
16029       reloc->addend = fixp->fx_addnumber + reloc->address;
16030     }
16031   else
16032     reloc->addend = fixp->fx_addnumber;
16033
16034   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16035      entry to be used in the relocation's section offset.  */
16036   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16037     {
16038       reloc->address = reloc->addend;
16039       reloc->addend = 0;
16040     }
16041
16042   code = fixp->fx_r_type;
16043
16044   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16045   if (reloc->howto == NULL)
16046     {
16047       as_bad_where (fixp->fx_file, fixp->fx_line,
16048                     _("Can not represent %s relocation in this object file format"),
16049                     bfd_get_reloc_code_name (code));
16050       retval[0] = NULL;
16051     }
16052
16053   return retval;
16054 }
16055
16056 /* Relax a machine dependent frag.  This returns the amount by which
16057    the current size of the frag should change.  */
16058
16059 int
16060 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16061 {
16062   if (RELAX_BRANCH_P (fragp->fr_subtype))
16063     {
16064       offsetT old_var = fragp->fr_var;
16065
16066       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16067
16068       return fragp->fr_var - old_var;
16069     }
16070
16071   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16072     {
16073       offsetT old_var = fragp->fr_var;
16074       offsetT new_var = 4;
16075
16076       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16077         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16078       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16079         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16080       fragp->fr_var = new_var;
16081
16082       return new_var - old_var;
16083     }
16084
16085   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16086     return 0;
16087
16088   if (mips16_extended_frag (fragp, NULL, stretch))
16089     {
16090       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16091         return 0;
16092       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16093       return 2;
16094     }
16095   else
16096     {
16097       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16098         return 0;
16099       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16100       return -2;
16101     }
16102
16103   return 0;
16104 }
16105
16106 /* Convert a machine dependent frag.  */
16107
16108 void
16109 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16110 {
16111   if (RELAX_BRANCH_P (fragp->fr_subtype))
16112     {
16113       char *buf;
16114       unsigned long insn;
16115       expressionS exp;
16116       fixS *fixp;
16117
16118       buf = fragp->fr_literal + fragp->fr_fix;
16119       insn = read_insn (buf);
16120
16121       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16122         {
16123           /* We generate a fixup instead of applying it right now
16124              because, if there are linker relaxations, we're going to
16125              need the relocations.  */
16126           exp.X_op = O_symbol;
16127           exp.X_add_symbol = fragp->fr_symbol;
16128           exp.X_add_number = fragp->fr_offset;
16129
16130           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16131                               BFD_RELOC_16_PCREL_S2);
16132           fixp->fx_file = fragp->fr_file;
16133           fixp->fx_line = fragp->fr_line;
16134
16135           buf = write_insn (buf, insn);
16136         }
16137       else
16138         {
16139           int i;
16140
16141           as_warn_where (fragp->fr_file, fragp->fr_line,
16142                          _("Relaxed out-of-range branch into a jump"));
16143
16144           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16145             goto uncond;
16146
16147           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16148             {
16149               /* Reverse the branch.  */
16150               switch ((insn >> 28) & 0xf)
16151                 {
16152                 case 4:
16153                   /* bc[0-3][tf]l? instructions can have the condition
16154                      reversed by tweaking a single TF bit, and their
16155                      opcodes all have 0x4???????.  */
16156                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16157                   insn ^= 0x00010000;
16158                   break;
16159
16160                 case 0:
16161                   /* bltz       0x04000000      bgez    0x04010000
16162                      bltzal     0x04100000      bgezal  0x04110000  */
16163                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16164                   insn ^= 0x00010000;
16165                   break;
16166
16167                 case 1:
16168                   /* beq        0x10000000      bne     0x14000000
16169                      blez       0x18000000      bgtz    0x1c000000  */
16170                   insn ^= 0x04000000;
16171                   break;
16172
16173                 default:
16174                   abort ();
16175                 }
16176             }
16177
16178           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16179             {
16180               /* Clear the and-link bit.  */
16181               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16182
16183               /* bltzal         0x04100000      bgezal  0x04110000
16184                  bltzall        0x04120000      bgezall 0x04130000  */
16185               insn &= ~0x00100000;
16186             }
16187
16188           /* Branch over the branch (if the branch was likely) or the
16189              full jump (not likely case).  Compute the offset from the
16190              current instruction to branch to.  */
16191           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16192             i = 16;
16193           else
16194             {
16195               /* How many bytes in instructions we've already emitted?  */
16196               i = buf - fragp->fr_literal - fragp->fr_fix;
16197               /* How many bytes in instructions from here to the end?  */
16198               i = fragp->fr_var - i;
16199             }
16200           /* Convert to instruction count.  */
16201           i >>= 2;
16202           /* Branch counts from the next instruction.  */
16203           i--;
16204           insn |= i;
16205           /* Branch over the jump.  */
16206           buf = write_insn (buf, insn);
16207
16208           /* nop */
16209           buf = write_insn (buf, 0);
16210
16211           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16212             {
16213               /* beql $0, $0, 2f */
16214               insn = 0x50000000;
16215               /* Compute the PC offset from the current instruction to
16216                  the end of the variable frag.  */
16217               /* How many bytes in instructions we've already emitted?  */
16218               i = buf - fragp->fr_literal - fragp->fr_fix;
16219               /* How many bytes in instructions from here to the end?  */
16220               i = fragp->fr_var - i;
16221               /* Convert to instruction count.  */
16222               i >>= 2;
16223               /* Don't decrement i, because we want to branch over the
16224                  delay slot.  */
16225               insn |= i;
16226
16227               buf = write_insn (buf, insn);
16228               buf = write_insn (buf, 0);
16229             }
16230
16231         uncond:
16232           if (mips_pic == NO_PIC)
16233             {
16234               /* j or jal.  */
16235               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16236                       ? 0x0c000000 : 0x08000000);
16237               exp.X_op = O_symbol;
16238               exp.X_add_symbol = fragp->fr_symbol;
16239               exp.X_add_number = fragp->fr_offset;
16240
16241               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16242                                   FALSE, BFD_RELOC_MIPS_JMP);
16243               fixp->fx_file = fragp->fr_file;
16244               fixp->fx_line = fragp->fr_line;
16245
16246               buf = write_insn (buf, insn);
16247             }
16248           else
16249             {
16250               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16251
16252               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16253               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16254               insn |= at << OP_SH_RT;
16255               exp.X_op = O_symbol;
16256               exp.X_add_symbol = fragp->fr_symbol;
16257               exp.X_add_number = fragp->fr_offset;
16258
16259               if (fragp->fr_offset)
16260                 {
16261                   exp.X_add_symbol = make_expr_symbol (&exp);
16262                   exp.X_add_number = 0;
16263                 }
16264
16265               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16266                                   FALSE, BFD_RELOC_MIPS_GOT16);
16267               fixp->fx_file = fragp->fr_file;
16268               fixp->fx_line = fragp->fr_line;
16269
16270               buf = write_insn (buf, insn);
16271
16272               if (mips_opts.isa == ISA_MIPS1)
16273                 /* nop */
16274                 buf = write_insn (buf, 0);
16275
16276               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16277               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16278               insn |= at << OP_SH_RS | at << OP_SH_RT;
16279
16280               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16281                                   FALSE, BFD_RELOC_LO16);
16282               fixp->fx_file = fragp->fr_file;
16283               fixp->fx_line = fragp->fr_line;
16284
16285               buf = write_insn (buf, insn);
16286
16287               /* j(al)r $at.  */
16288               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16289                 insn = 0x0000f809;
16290               else
16291                 insn = 0x00000008;
16292               insn |= at << OP_SH_RS;
16293
16294               buf = write_insn (buf, insn);
16295             }
16296         }
16297
16298       fragp->fr_fix += fragp->fr_var;
16299       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16300       return;
16301     }
16302
16303   /* Relax microMIPS branches.  */
16304   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16305     {
16306       char *buf = fragp->fr_literal + fragp->fr_fix;
16307       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16308       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16309       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16310       bfd_boolean short_ds;
16311       unsigned long insn;
16312       expressionS exp;
16313       fixS *fixp;
16314
16315       exp.X_op = O_symbol;
16316       exp.X_add_symbol = fragp->fr_symbol;
16317       exp.X_add_number = fragp->fr_offset;
16318
16319       fragp->fr_fix += fragp->fr_var;
16320
16321       /* Handle 16-bit branches that fit or are forced to fit.  */
16322       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16323         {
16324           /* We generate a fixup instead of applying it right now,
16325              because if there is linker relaxation, we're going to
16326              need the relocations.  */
16327           if (type == 'D')
16328             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16329                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16330           else if (type == 'E')
16331             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16332                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16333           else
16334             abort ();
16335
16336           fixp->fx_file = fragp->fr_file;
16337           fixp->fx_line = fragp->fr_line;
16338
16339           /* These relocations can have an addend that won't fit in
16340              2 octets.  */
16341           fixp->fx_no_overflow = 1;
16342
16343           return;
16344         }
16345
16346       /* Handle 32-bit branches that fit or are forced to fit.  */
16347       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16348           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16349         {
16350           /* We generate a fixup instead of applying it right now,
16351              because if there is linker relaxation, we're going to
16352              need the relocations.  */
16353           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16354                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16355           fixp->fx_file = fragp->fr_file;
16356           fixp->fx_line = fragp->fr_line;
16357
16358           if (type == 0)
16359             return;
16360         }
16361
16362       /* Relax 16-bit branches to 32-bit branches.  */
16363       if (type != 0)
16364         {
16365           insn = read_compressed_insn (buf, 2);
16366
16367           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16368             insn = 0x94000000;                          /* beq  */
16369           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16370             {
16371               unsigned long regno;
16372
16373               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16374               regno = micromips_to_32_reg_d_map [regno];
16375               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16376               insn |= regno << MICROMIPSOP_SH_RS;
16377             }
16378           else
16379             abort ();
16380
16381           /* Nothing else to do, just write it out.  */
16382           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16383               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16384             {
16385               buf = write_compressed_insn (buf, insn, 4);
16386               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16387               return;
16388             }
16389         }
16390       else
16391         insn = read_compressed_insn (buf, 4);
16392
16393       /* Relax 32-bit branches to a sequence of instructions.  */
16394       as_warn_where (fragp->fr_file, fragp->fr_line,
16395                      _("Relaxed out-of-range branch into a jump"));
16396
16397       /* Set the short-delay-slot bit.  */
16398       short_ds = al && (insn & 0x02000000) != 0;
16399
16400       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16401         {
16402           symbolS *l;
16403
16404           /* Reverse the branch.  */
16405           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16406               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16407             insn ^= 0x20000000;
16408           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16409                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16410                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16411                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16412                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16413                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16414                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16415                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16416                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16417                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16418             insn ^= 0x00400000;
16419           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16420                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16421                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16422                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16423             insn ^= 0x00200000;
16424           else
16425             abort ();
16426
16427           if (al)
16428             {
16429               /* Clear the and-link and short-delay-slot bits.  */
16430               gas_assert ((insn & 0xfda00000) == 0x40200000);
16431
16432               /* bltzal  0x40200000     bgezal  0x40600000  */
16433               /* bltzals 0x42200000     bgezals 0x42600000  */
16434               insn &= ~0x02200000;
16435             }
16436
16437           /* Make a label at the end for use with the branch.  */
16438           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16439           micromips_label_inc ();
16440           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16441
16442           /* Refer to it.  */
16443           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16444                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16445           fixp->fx_file = fragp->fr_file;
16446           fixp->fx_line = fragp->fr_line;
16447
16448           /* Branch over the jump.  */
16449           buf = write_compressed_insn (buf, insn, 4);
16450           if (!compact)
16451             /* nop */
16452             buf = write_compressed_insn (buf, 0x0c00, 2);
16453         }
16454
16455       if (mips_pic == NO_PIC)
16456         {
16457           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16458
16459           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16460           insn = al ? jal : 0xd4000000;
16461
16462           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16463                               BFD_RELOC_MICROMIPS_JMP);
16464           fixp->fx_file = fragp->fr_file;
16465           fixp->fx_line = fragp->fr_line;
16466
16467           buf = write_compressed_insn (buf, insn, 4);
16468           if (compact)
16469             /* nop */
16470             buf = write_compressed_insn (buf, 0x0c00, 2);
16471         }
16472       else
16473         {
16474           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16475           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16476           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16477
16478           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16479           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16480           insn |= at << MICROMIPSOP_SH_RT;
16481
16482           if (exp.X_add_number)
16483             {
16484               exp.X_add_symbol = make_expr_symbol (&exp);
16485               exp.X_add_number = 0;
16486             }
16487
16488           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16489                               BFD_RELOC_MICROMIPS_GOT16);
16490           fixp->fx_file = fragp->fr_file;
16491           fixp->fx_line = fragp->fr_line;
16492
16493           buf = write_compressed_insn (buf, insn, 4);
16494
16495           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16496           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16497           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16498
16499           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16500                               BFD_RELOC_MICROMIPS_LO16);
16501           fixp->fx_file = fragp->fr_file;
16502           fixp->fx_line = fragp->fr_line;
16503
16504           buf = write_compressed_insn (buf, insn, 4);
16505
16506           /* jr/jrc/jalr/jalrs $at  */
16507           insn = al ? jalr : jr;
16508           insn |= at << MICROMIPSOP_SH_MJ;
16509
16510           buf = write_compressed_insn (buf, insn, 2);
16511         }
16512
16513       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16514       return;
16515     }
16516
16517   if (RELAX_MIPS16_P (fragp->fr_subtype))
16518     {
16519       int type;
16520       const struct mips16_immed_operand *op;
16521       offsetT val;
16522       char *buf;
16523       unsigned int user_length, length;
16524       unsigned long insn;
16525       bfd_boolean ext;
16526
16527       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16528       op = mips16_immed_operands;
16529       while (op->type != type)
16530         ++op;
16531
16532       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
16533       val = resolve_symbol_value (fragp->fr_symbol);
16534       if (op->pcrel)
16535         {
16536           addressT addr;
16537
16538           addr = fragp->fr_address + fragp->fr_fix;
16539
16540           /* The rules for the base address of a PC relative reloc are
16541              complicated; see mips16_extended_frag.  */
16542           if (type == 'p' || type == 'q')
16543             {
16544               addr += 2;
16545               if (ext)
16546                 addr += 2;
16547               /* Ignore the low bit in the target, since it will be
16548                  set for a text label.  */
16549               if ((val & 1) != 0)
16550                 --val;
16551             }
16552           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16553             addr -= 4;
16554           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16555             addr -= 2;
16556
16557           addr &= ~ (addressT) ((1 << op->shift) - 1);
16558           val -= addr;
16559
16560           /* Make sure the section winds up with the alignment we have
16561              assumed.  */
16562           if (op->shift > 0)
16563             record_alignment (asec, op->shift);
16564         }
16565
16566       if (ext
16567           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
16568               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
16569         as_warn_where (fragp->fr_file, fragp->fr_line,
16570                        _("extended instruction in delay slot"));
16571
16572       buf = fragp->fr_literal + fragp->fr_fix;
16573
16574       insn = read_compressed_insn (buf, 2);
16575       if (ext)
16576         insn |= MIPS16_EXTEND;
16577
16578       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16579         user_length = 4;
16580       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16581         user_length = 2;
16582       else
16583         user_length = 0;
16584
16585       mips16_immed (fragp->fr_file, fragp->fr_line, type,
16586                     BFD_RELOC_UNUSED, val, user_length, &insn);
16587
16588       length = (ext ? 4 : 2);
16589       gas_assert (mips16_opcode_length (insn) == length);
16590       write_compressed_insn (buf, insn, length);
16591       fragp->fr_fix += length;
16592     }
16593   else
16594     {
16595       relax_substateT subtype = fragp->fr_subtype;
16596       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
16597       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
16598       int first, second;
16599       fixS *fixp;
16600
16601       first = RELAX_FIRST (subtype);
16602       second = RELAX_SECOND (subtype);
16603       fixp = (fixS *) fragp->fr_opcode;
16604
16605       /* If the delay slot chosen does not match the size of the instruction,
16606          then emit a warning.  */
16607       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
16608            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
16609         {
16610           relax_substateT s;
16611           const char *msg;
16612
16613           s = subtype & (RELAX_DELAY_SLOT_16BIT
16614                          | RELAX_DELAY_SLOT_SIZE_FIRST
16615                          | RELAX_DELAY_SLOT_SIZE_SECOND);
16616           msg = macro_warning (s);
16617           if (msg != NULL)
16618             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16619           subtype &= ~s;
16620         }
16621
16622       /* Possibly emit a warning if we've chosen the longer option.  */
16623       if (use_second == second_longer)
16624         {
16625           relax_substateT s;
16626           const char *msg;
16627
16628           s = (subtype
16629                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
16630           msg = macro_warning (s);
16631           if (msg != NULL)
16632             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16633           subtype &= ~s;
16634         }
16635
16636       /* Go through all the fixups for the first sequence.  Disable them
16637          (by marking them as done) if we're going to use the second
16638          sequence instead.  */
16639       while (fixp
16640              && fixp->fx_frag == fragp
16641              && fixp->fx_where < fragp->fr_fix - second)
16642         {
16643           if (subtype & RELAX_USE_SECOND)
16644             fixp->fx_done = 1;
16645           fixp = fixp->fx_next;
16646         }
16647
16648       /* Go through the fixups for the second sequence.  Disable them if
16649          we're going to use the first sequence, otherwise adjust their
16650          addresses to account for the relaxation.  */
16651       while (fixp && fixp->fx_frag == fragp)
16652         {
16653           if (subtype & RELAX_USE_SECOND)
16654             fixp->fx_where -= first;
16655           else
16656             fixp->fx_done = 1;
16657           fixp = fixp->fx_next;
16658         }
16659
16660       /* Now modify the frag contents.  */
16661       if (subtype & RELAX_USE_SECOND)
16662         {
16663           char *start;
16664
16665           start = fragp->fr_literal + fragp->fr_fix - first - second;
16666           memmove (start, start + first, second);
16667           fragp->fr_fix -= first;
16668         }
16669       else
16670         fragp->fr_fix -= second;
16671     }
16672 }
16673
16674 /* This function is called after the relocs have been generated.
16675    We've been storing mips16 text labels as odd.  Here we convert them
16676    back to even for the convenience of the debugger.  */
16677
16678 void
16679 mips_frob_file_after_relocs (void)
16680 {
16681   asymbol **syms;
16682   unsigned int count, i;
16683
16684   syms = bfd_get_outsymbols (stdoutput);
16685   count = bfd_get_symcount (stdoutput);
16686   for (i = 0; i < count; i++, syms++)
16687     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
16688         && ((*syms)->value & 1) != 0)
16689       {
16690         (*syms)->value &= ~1;
16691         /* If the symbol has an odd size, it was probably computed
16692            incorrectly, so adjust that as well.  */
16693         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
16694           ++elf_symbol (*syms)->internal_elf_sym.st_size;
16695       }
16696 }
16697
16698 /* This function is called whenever a label is defined, including fake
16699    labels instantiated off the dot special symbol.  It is used when
16700    handling branch delays; if a branch has a label, we assume we cannot
16701    move it.  This also bumps the value of the symbol by 1 in compressed
16702    code.  */
16703
16704 static void
16705 mips_record_label (symbolS *sym)
16706 {
16707   segment_info_type *si = seg_info (now_seg);
16708   struct insn_label_list *l;
16709
16710   if (free_insn_labels == NULL)
16711     l = (struct insn_label_list *) xmalloc (sizeof *l);
16712   else
16713     {
16714       l = free_insn_labels;
16715       free_insn_labels = l->next;
16716     }
16717
16718   l->label = sym;
16719   l->next = si->label_list;
16720   si->label_list = l;
16721 }
16722
16723 /* This function is called as tc_frob_label() whenever a label is defined
16724    and adds a DWARF-2 record we only want for true labels.  */
16725
16726 void
16727 mips_define_label (symbolS *sym)
16728 {
16729   mips_record_label (sym);
16730   dwarf2_emit_label (sym);
16731 }
16732
16733 /* This function is called by tc_new_dot_label whenever a new dot symbol
16734    is defined.  */
16735
16736 void
16737 mips_add_dot_label (symbolS *sym)
16738 {
16739   mips_record_label (sym);
16740   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
16741     mips_compressed_mark_label (sym);
16742 }
16743 \f
16744 /* Some special processing for a MIPS ELF file.  */
16745
16746 void
16747 mips_elf_final_processing (void)
16748 {
16749   /* Write out the register information.  */
16750   if (mips_abi != N64_ABI)
16751     {
16752       Elf32_RegInfo s;
16753
16754       s.ri_gprmask = mips_gprmask;
16755       s.ri_cprmask[0] = mips_cprmask[0];
16756       s.ri_cprmask[1] = mips_cprmask[1];
16757       s.ri_cprmask[2] = mips_cprmask[2];
16758       s.ri_cprmask[3] = mips_cprmask[3];
16759       /* The gp_value field is set by the MIPS ELF backend.  */
16760
16761       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
16762                                        ((Elf32_External_RegInfo *)
16763                                         mips_regmask_frag));
16764     }
16765   else
16766     {
16767       Elf64_Internal_RegInfo s;
16768
16769       s.ri_gprmask = mips_gprmask;
16770       s.ri_pad = 0;
16771       s.ri_cprmask[0] = mips_cprmask[0];
16772       s.ri_cprmask[1] = mips_cprmask[1];
16773       s.ri_cprmask[2] = mips_cprmask[2];
16774       s.ri_cprmask[3] = mips_cprmask[3];
16775       /* The gp_value field is set by the MIPS ELF backend.  */
16776
16777       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
16778                                        ((Elf64_External_RegInfo *)
16779                                         mips_regmask_frag));
16780     }
16781
16782   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
16783      sort of BFD interface for this.  */
16784   if (mips_any_noreorder)
16785     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
16786   if (mips_pic != NO_PIC)
16787     {
16788       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
16789       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16790     }
16791   if (mips_abicalls)
16792     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16793
16794   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
16795      defined at present; this might need to change in future.  */
16796   if (file_ase_mips16)
16797     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
16798   if (file_ase_micromips)
16799     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
16800   if (file_ase & ASE_MDMX)
16801     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
16802
16803   /* Set the MIPS ELF ABI flags.  */
16804   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
16805     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
16806   else if (mips_abi == O64_ABI)
16807     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
16808   else if (mips_abi == EABI_ABI)
16809     {
16810       if (!file_mips_gp32)
16811         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
16812       else
16813         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
16814     }
16815   else if (mips_abi == N32_ABI)
16816     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
16817
16818   /* Nothing to do for N64_ABI.  */
16819
16820   if (mips_32bitmode)
16821     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
16822
16823   if (mips_flag_nan2008)
16824     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
16825
16826 #if 0 /* XXX FIXME */
16827   /* 32 bit code with 64 bit FP registers.  */
16828   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
16829     elf_elfheader (stdoutput)->e_flags |= ???;
16830 #endif
16831 }
16832 \f
16833 typedef struct proc {
16834   symbolS *func_sym;
16835   symbolS *func_end_sym;
16836   unsigned long reg_mask;
16837   unsigned long reg_offset;
16838   unsigned long fpreg_mask;
16839   unsigned long fpreg_offset;
16840   unsigned long frame_offset;
16841   unsigned long frame_reg;
16842   unsigned long pc_reg;
16843 } procS;
16844
16845 static procS cur_proc;
16846 static procS *cur_proc_ptr;
16847 static int numprocs;
16848
16849 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
16850    as "2", and a normal nop as "0".  */
16851
16852 #define NOP_OPCODE_MIPS         0
16853 #define NOP_OPCODE_MIPS16       1
16854 #define NOP_OPCODE_MICROMIPS    2
16855
16856 char
16857 mips_nop_opcode (void)
16858 {
16859   if (seg_info (now_seg)->tc_segment_info_data.micromips)
16860     return NOP_OPCODE_MICROMIPS;
16861   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
16862     return NOP_OPCODE_MIPS16;
16863   else
16864     return NOP_OPCODE_MIPS;
16865 }
16866
16867 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
16868    32-bit microMIPS NOPs here (if applicable).  */
16869
16870 void
16871 mips_handle_align (fragS *fragp)
16872 {
16873   char nop_opcode;
16874   char *p;
16875   int bytes, size, excess;
16876   valueT opcode;
16877
16878   if (fragp->fr_type != rs_align_code)
16879     return;
16880
16881   p = fragp->fr_literal + fragp->fr_fix;
16882   nop_opcode = *p;
16883   switch (nop_opcode)
16884     {
16885     case NOP_OPCODE_MICROMIPS:
16886       opcode = micromips_nop32_insn.insn_opcode;
16887       size = 4;
16888       break;
16889     case NOP_OPCODE_MIPS16:
16890       opcode = mips16_nop_insn.insn_opcode;
16891       size = 2;
16892       break;
16893     case NOP_OPCODE_MIPS:
16894     default:
16895       opcode = nop_insn.insn_opcode;
16896       size = 4;
16897       break;
16898     }
16899
16900   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
16901   excess = bytes % size;
16902
16903   /* Handle the leading part if we're not inserting a whole number of
16904      instructions, and make it the end of the fixed part of the frag.
16905      Try to fit in a short microMIPS NOP if applicable and possible,
16906      and use zeroes otherwise.  */
16907   gas_assert (excess < 4);
16908   fragp->fr_fix += excess;
16909   switch (excess)
16910     {
16911     case 3:
16912       *p++ = '\0';
16913       /* Fall through.  */
16914     case 2:
16915       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
16916         {
16917           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
16918           break;
16919         }
16920       *p++ = '\0';
16921       /* Fall through.  */
16922     case 1:
16923       *p++ = '\0';
16924       /* Fall through.  */
16925     case 0:
16926       break;
16927     }
16928
16929   md_number_to_chars (p, opcode, size);
16930   fragp->fr_var = size;
16931 }
16932
16933 static void
16934 md_obj_begin (void)
16935 {
16936 }
16937
16938 static void
16939 md_obj_end (void)
16940 {
16941   /* Check for premature end, nesting errors, etc.  */
16942   if (cur_proc_ptr)
16943     as_warn (_("missing .end at end of assembly"));
16944 }
16945
16946 static long
16947 get_number (void)
16948 {
16949   int negative = 0;
16950   long val = 0;
16951
16952   if (*input_line_pointer == '-')
16953     {
16954       ++input_line_pointer;
16955       negative = 1;
16956     }
16957   if (!ISDIGIT (*input_line_pointer))
16958     as_bad (_("expected simple number"));
16959   if (input_line_pointer[0] == '0')
16960     {
16961       if (input_line_pointer[1] == 'x')
16962         {
16963           input_line_pointer += 2;
16964           while (ISXDIGIT (*input_line_pointer))
16965             {
16966               val <<= 4;
16967               val |= hex_value (*input_line_pointer++);
16968             }
16969           return negative ? -val : val;
16970         }
16971       else
16972         {
16973           ++input_line_pointer;
16974           while (ISDIGIT (*input_line_pointer))
16975             {
16976               val <<= 3;
16977               val |= *input_line_pointer++ - '0';
16978             }
16979           return negative ? -val : val;
16980         }
16981     }
16982   if (!ISDIGIT (*input_line_pointer))
16983     {
16984       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
16985               *input_line_pointer, *input_line_pointer);
16986       as_warn (_("invalid number"));
16987       return -1;
16988     }
16989   while (ISDIGIT (*input_line_pointer))
16990     {
16991       val *= 10;
16992       val += *input_line_pointer++ - '0';
16993     }
16994   return negative ? -val : val;
16995 }
16996
16997 /* The .file directive; just like the usual .file directive, but there
16998    is an initial number which is the ECOFF file index.  In the non-ECOFF
16999    case .file implies DWARF-2.  */
17000
17001 static void
17002 s_mips_file (int x ATTRIBUTE_UNUSED)
17003 {
17004   static int first_file_directive = 0;
17005
17006   if (ECOFF_DEBUGGING)
17007     {
17008       get_number ();
17009       s_app_file (0);
17010     }
17011   else
17012     {
17013       char *filename;
17014
17015       filename = dwarf2_directive_file (0);
17016
17017       /* Versions of GCC up to 3.1 start files with a ".file"
17018          directive even for stabs output.  Make sure that this
17019          ".file" is handled.  Note that you need a version of GCC
17020          after 3.1 in order to support DWARF-2 on MIPS.  */
17021       if (filename != NULL && ! first_file_directive)
17022         {
17023           (void) new_logical_line (filename, -1);
17024           s_app_file_string (filename, 0);
17025         }
17026       first_file_directive = 1;
17027     }
17028 }
17029
17030 /* The .loc directive, implying DWARF-2.  */
17031
17032 static void
17033 s_mips_loc (int x ATTRIBUTE_UNUSED)
17034 {
17035   if (!ECOFF_DEBUGGING)
17036     dwarf2_directive_loc (0);
17037 }
17038
17039 /* The .end directive.  */
17040
17041 static void
17042 s_mips_end (int x ATTRIBUTE_UNUSED)
17043 {
17044   symbolS *p;
17045
17046   /* Following functions need their own .frame and .cprestore directives.  */
17047   mips_frame_reg_valid = 0;
17048   mips_cprestore_valid = 0;
17049
17050   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17051     {
17052       p = get_symbol ();
17053       demand_empty_rest_of_line ();
17054     }
17055   else
17056     p = NULL;
17057
17058   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17059     as_warn (_(".end not in text section"));
17060
17061   if (!cur_proc_ptr)
17062     {
17063       as_warn (_(".end directive without a preceding .ent directive."));
17064       demand_empty_rest_of_line ();
17065       return;
17066     }
17067
17068   if (p != NULL)
17069     {
17070       gas_assert (S_GET_NAME (p));
17071       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17072         as_warn (_(".end symbol does not match .ent symbol."));
17073
17074       if (debug_type == DEBUG_STABS)
17075         stabs_generate_asm_endfunc (S_GET_NAME (p),
17076                                     S_GET_NAME (p));
17077     }
17078   else
17079     as_warn (_(".end directive missing or unknown symbol"));
17080
17081   /* Create an expression to calculate the size of the function.  */
17082   if (p && cur_proc_ptr)
17083     {
17084       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17085       expressionS *exp = xmalloc (sizeof (expressionS));
17086
17087       obj->size = exp;
17088       exp->X_op = O_subtract;
17089       exp->X_add_symbol = symbol_temp_new_now ();
17090       exp->X_op_symbol = p;
17091       exp->X_add_number = 0;
17092
17093       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17094     }
17095
17096   /* Generate a .pdr section.  */
17097   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17098     {
17099       segT saved_seg = now_seg;
17100       subsegT saved_subseg = now_subseg;
17101       expressionS exp;
17102       char *fragp;
17103
17104 #ifdef md_flush_pending_output
17105       md_flush_pending_output ();
17106 #endif
17107
17108       gas_assert (pdr_seg);
17109       subseg_set (pdr_seg, 0);
17110
17111       /* Write the symbol.  */
17112       exp.X_op = O_symbol;
17113       exp.X_add_symbol = p;
17114       exp.X_add_number = 0;
17115       emit_expr (&exp, 4);
17116
17117       fragp = frag_more (7 * 4);
17118
17119       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17120       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17121       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17122       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17123       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17124       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17125       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17126
17127       subseg_set (saved_seg, saved_subseg);
17128     }
17129
17130   cur_proc_ptr = NULL;
17131 }
17132
17133 /* The .aent and .ent directives.  */
17134
17135 static void
17136 s_mips_ent (int aent)
17137 {
17138   symbolS *symbolP;
17139
17140   symbolP = get_symbol ();
17141   if (*input_line_pointer == ',')
17142     ++input_line_pointer;
17143   SKIP_WHITESPACE ();
17144   if (ISDIGIT (*input_line_pointer)
17145       || *input_line_pointer == '-')
17146     get_number ();
17147
17148   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17149     as_warn (_(".ent or .aent not in text section."));
17150
17151   if (!aent && cur_proc_ptr)
17152     as_warn (_("missing .end"));
17153
17154   if (!aent)
17155     {
17156       /* This function needs its own .frame and .cprestore directives.  */
17157       mips_frame_reg_valid = 0;
17158       mips_cprestore_valid = 0;
17159
17160       cur_proc_ptr = &cur_proc;
17161       memset (cur_proc_ptr, '\0', sizeof (procS));
17162
17163       cur_proc_ptr->func_sym = symbolP;
17164
17165       ++numprocs;
17166
17167       if (debug_type == DEBUG_STABS)
17168         stabs_generate_asm_func (S_GET_NAME (symbolP),
17169                                  S_GET_NAME (symbolP));
17170     }
17171
17172   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17173
17174   demand_empty_rest_of_line ();
17175 }
17176
17177 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17178    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17179    s_mips_frame is used so that we can set the PDR information correctly.
17180    We can't use the ecoff routines because they make reference to the ecoff
17181    symbol table (in the mdebug section).  */
17182
17183 static void
17184 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17185 {
17186   if (ECOFF_DEBUGGING)
17187     s_ignore (ignore);
17188   else
17189     {
17190       long val;
17191
17192       if (cur_proc_ptr == (procS *) NULL)
17193         {
17194           as_warn (_(".frame outside of .ent"));
17195           demand_empty_rest_of_line ();
17196           return;
17197         }
17198
17199       cur_proc_ptr->frame_reg = tc_get_register (1);
17200
17201       SKIP_WHITESPACE ();
17202       if (*input_line_pointer++ != ','
17203           || get_absolute_expression_and_terminator (&val) != ',')
17204         {
17205           as_warn (_("Bad .frame directive"));
17206           --input_line_pointer;
17207           demand_empty_rest_of_line ();
17208           return;
17209         }
17210
17211       cur_proc_ptr->frame_offset = val;
17212       cur_proc_ptr->pc_reg = tc_get_register (0);
17213
17214       demand_empty_rest_of_line ();
17215     }
17216 }
17217
17218 /* The .fmask and .mask directives. If the mdebug section is present
17219    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17220    embedded targets, s_mips_mask is used so that we can set the PDR
17221    information correctly. We can't use the ecoff routines because they
17222    make reference to the ecoff symbol table (in the mdebug section).  */
17223
17224 static void
17225 s_mips_mask (int reg_type)
17226 {
17227   if (ECOFF_DEBUGGING)
17228     s_ignore (reg_type);
17229   else
17230     {
17231       long mask, off;
17232
17233       if (cur_proc_ptr == (procS *) NULL)
17234         {
17235           as_warn (_(".mask/.fmask outside of .ent"));
17236           demand_empty_rest_of_line ();
17237           return;
17238         }
17239
17240       if (get_absolute_expression_and_terminator (&mask) != ',')
17241         {
17242           as_warn (_("Bad .mask/.fmask directive"));
17243           --input_line_pointer;
17244           demand_empty_rest_of_line ();
17245           return;
17246         }
17247
17248       off = get_absolute_expression ();
17249
17250       if (reg_type == 'F')
17251         {
17252           cur_proc_ptr->fpreg_mask = mask;
17253           cur_proc_ptr->fpreg_offset = off;
17254         }
17255       else
17256         {
17257           cur_proc_ptr->reg_mask = mask;
17258           cur_proc_ptr->reg_offset = off;
17259         }
17260
17261       demand_empty_rest_of_line ();
17262     }
17263 }
17264
17265 /* A table describing all the processors gas knows about.  Names are
17266    matched in the order listed.
17267
17268    To ease comparison, please keep this table in the same order as
17269    gcc's mips_cpu_info_table[].  */
17270 static const struct mips_cpu_info mips_cpu_info_table[] =
17271 {
17272   /* Entries for generic ISAs */
17273   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17274   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17275   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17276   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17277   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17278   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17279   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17280   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17281   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17282
17283   /* MIPS I */
17284   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17285   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17286   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17287
17288   /* MIPS II */
17289   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17290
17291   /* MIPS III */
17292   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17293   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17294   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17295   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17296   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17297   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17298   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17299   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17300   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17301   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17302   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17303   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17304   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17305   /* ST Microelectronics Loongson 2E and 2F cores */
17306   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17307   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17308
17309   /* MIPS IV */
17310   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17311   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17312   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17313   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17314   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17315   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17316   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17317   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17318   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17319   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17320   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17321   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17322   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17323   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17324   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17325
17326   /* MIPS 32 */
17327   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17328   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17329   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17330   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17331
17332   /* MIPS 32 Release 2 */
17333   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17334   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17335   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17336   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17337   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17338   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17339   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17340   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17341   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17342                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17343   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17344                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17345   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17346   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17347   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17348   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17349   /* Deprecated forms of the above.  */
17350   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17351   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17352   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17353   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17354   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17355   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17356   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17357   /* Deprecated forms of the above.  */
17358   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17359   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17360   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17361   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17362   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17363   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17364   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17365   /* Deprecated forms of the above.  */
17366   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17367   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17368   /* 34Kn is a 34kc without DSP.  */
17369   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17370   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17371   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17372   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17373   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17374   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17375   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17376   /* Deprecated forms of the above.  */
17377   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17378   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17379   /* 1004K cores are multiprocessor versions of the 34K.  */
17380   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17381   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17382   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17383   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17384
17385   /* MIPS 64 */
17386   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17387   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17388   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17389   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17390
17391   /* Broadcom SB-1 CPU core */
17392   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17393   /* Broadcom SB-1A CPU core */
17394   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17395   
17396   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17397
17398   /* MIPS 64 Release 2 */
17399
17400   /* Cavium Networks Octeon CPU core */
17401   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17402   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17403   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17404
17405   /* RMI Xlr */
17406   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17407
17408   /* Broadcom XLP.
17409      XLP is mostly like XLR, with the prominent exception that it is
17410      MIPS64R2 rather than MIPS64.  */
17411   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17412
17413   /* End marker */
17414   { NULL, 0, 0, 0, 0 }
17415 };
17416
17417
17418 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17419    with a final "000" replaced by "k".  Ignore case.
17420
17421    Note: this function is shared between GCC and GAS.  */
17422
17423 static bfd_boolean
17424 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17425 {
17426   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17427     given++, canonical++;
17428
17429   return ((*given == 0 && *canonical == 0)
17430           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17431 }
17432
17433
17434 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17435    CPU name.  We've traditionally allowed a lot of variation here.
17436
17437    Note: this function is shared between GCC and GAS.  */
17438
17439 static bfd_boolean
17440 mips_matching_cpu_name_p (const char *canonical, const char *given)
17441 {
17442   /* First see if the name matches exactly, or with a final "000"
17443      turned into "k".  */
17444   if (mips_strict_matching_cpu_name_p (canonical, given))
17445     return TRUE;
17446
17447   /* If not, try comparing based on numerical designation alone.
17448      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17449   if (TOLOWER (*given) == 'r')
17450     given++;
17451   if (!ISDIGIT (*given))
17452     return FALSE;
17453
17454   /* Skip over some well-known prefixes in the canonical name,
17455      hoping to find a number there too.  */
17456   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17457     canonical += 2;
17458   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17459     canonical += 2;
17460   else if (TOLOWER (canonical[0]) == 'r')
17461     canonical += 1;
17462
17463   return mips_strict_matching_cpu_name_p (canonical, given);
17464 }
17465
17466
17467 /* Parse an option that takes the name of a processor as its argument.
17468    OPTION is the name of the option and CPU_STRING is the argument.
17469    Return the corresponding processor enumeration if the CPU_STRING is
17470    recognized, otherwise report an error and return null.
17471
17472    A similar function exists in GCC.  */
17473
17474 static const struct mips_cpu_info *
17475 mips_parse_cpu (const char *option, const char *cpu_string)
17476 {
17477   const struct mips_cpu_info *p;
17478
17479   /* 'from-abi' selects the most compatible architecture for the given
17480      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17481      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17482      version.  Look first at the -mgp options, if given, otherwise base
17483      the choice on MIPS_DEFAULT_64BIT.
17484
17485      Treat NO_ABI like the EABIs.  One reason to do this is that the
17486      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17487      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17488      'mips64', just as we did in the days before 'from-abi'.  */
17489   if (strcasecmp (cpu_string, "from-abi") == 0)
17490     {
17491       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17492         return mips_cpu_info_from_isa (ISA_MIPS1);
17493
17494       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17495         return mips_cpu_info_from_isa (ISA_MIPS3);
17496
17497       if (file_mips_gp32 >= 0)
17498         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17499
17500       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17501                                      ? ISA_MIPS3
17502                                      : ISA_MIPS1);
17503     }
17504
17505   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17506   if (strcasecmp (cpu_string, "default") == 0)
17507     return 0;
17508
17509   for (p = mips_cpu_info_table; p->name != 0; p++)
17510     if (mips_matching_cpu_name_p (p->name, cpu_string))
17511       return p;
17512
17513   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
17514   return 0;
17515 }
17516
17517 /* Return the canonical processor information for ISA (a member of the
17518    ISA_MIPS* enumeration).  */
17519
17520 static const struct mips_cpu_info *
17521 mips_cpu_info_from_isa (int isa)
17522 {
17523   int i;
17524
17525   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17526     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17527         && isa == mips_cpu_info_table[i].isa)
17528       return (&mips_cpu_info_table[i]);
17529
17530   return NULL;
17531 }
17532
17533 static const struct mips_cpu_info *
17534 mips_cpu_info_from_arch (int arch)
17535 {
17536   int i;
17537
17538   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17539     if (arch == mips_cpu_info_table[i].cpu)
17540       return (&mips_cpu_info_table[i]);
17541
17542   return NULL;
17543 }
17544 \f
17545 static void
17546 show (FILE *stream, const char *string, int *col_p, int *first_p)
17547 {
17548   if (*first_p)
17549     {
17550       fprintf (stream, "%24s", "");
17551       *col_p = 24;
17552     }
17553   else
17554     {
17555       fprintf (stream, ", ");
17556       *col_p += 2;
17557     }
17558
17559   if (*col_p + strlen (string) > 72)
17560     {
17561       fprintf (stream, "\n%24s", "");
17562       *col_p = 24;
17563     }
17564
17565   fprintf (stream, "%s", string);
17566   *col_p += strlen (string);
17567
17568   *first_p = 0;
17569 }
17570
17571 void
17572 md_show_usage (FILE *stream)
17573 {
17574   int column, first;
17575   size_t i;
17576
17577   fprintf (stream, _("\
17578 MIPS options:\n\
17579 -EB                     generate big endian output\n\
17580 -EL                     generate little endian output\n\
17581 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
17582 -G NUM                  allow referencing objects up to NUM bytes\n\
17583                         implicitly with the gp register [default 8]\n"));
17584   fprintf (stream, _("\
17585 -mips1                  generate MIPS ISA I instructions\n\
17586 -mips2                  generate MIPS ISA II instructions\n\
17587 -mips3                  generate MIPS ISA III instructions\n\
17588 -mips4                  generate MIPS ISA IV instructions\n\
17589 -mips5                  generate MIPS ISA V instructions\n\
17590 -mips32                 generate MIPS32 ISA instructions\n\
17591 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
17592 -mips64                 generate MIPS64 ISA instructions\n\
17593 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
17594 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
17595
17596   first = 1;
17597
17598   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17599     show (stream, mips_cpu_info_table[i].name, &column, &first);
17600   show (stream, "from-abi", &column, &first);
17601   fputc ('\n', stream);
17602
17603   fprintf (stream, _("\
17604 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
17605 -no-mCPU                don't generate code specific to CPU.\n\
17606                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
17607
17608   first = 1;
17609
17610   show (stream, "3900", &column, &first);
17611   show (stream, "4010", &column, &first);
17612   show (stream, "4100", &column, &first);
17613   show (stream, "4650", &column, &first);
17614   fputc ('\n', stream);
17615
17616   fprintf (stream, _("\
17617 -mips16                 generate mips16 instructions\n\
17618 -no-mips16              do not generate mips16 instructions\n"));
17619   fprintf (stream, _("\
17620 -mmicromips             generate microMIPS instructions\n\
17621 -mno-micromips          do not generate microMIPS instructions\n"));
17622   fprintf (stream, _("\
17623 -msmartmips             generate smartmips instructions\n\
17624 -mno-smartmips          do not generate smartmips instructions\n"));  
17625   fprintf (stream, _("\
17626 -mdsp                   generate DSP instructions\n\
17627 -mno-dsp                do not generate DSP instructions\n"));
17628   fprintf (stream, _("\
17629 -mdspr2                 generate DSP R2 instructions\n\
17630 -mno-dspr2              do not generate DSP R2 instructions\n"));
17631   fprintf (stream, _("\
17632 -mmt                    generate MT instructions\n\
17633 -mno-mt                 do not generate MT instructions\n"));
17634   fprintf (stream, _("\
17635 -mmcu                   generate MCU instructions\n\
17636 -mno-mcu                do not generate MCU instructions\n"));
17637   fprintf (stream, _("\
17638 -mvirt                  generate Virtualization instructions\n\
17639 -mno-virt               do not generate Virtualization instructions\n"));
17640   fprintf (stream, _("\
17641 -minsn32                only generate 32-bit microMIPS instructions\n\
17642 -mno-insn32             generate all microMIPS instructions\n"));
17643   fprintf (stream, _("\
17644 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
17645 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
17646 -mfix-vr4120            work around certain VR4120 errata\n\
17647 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
17648 -mfix-24k               insert a nop after ERET and DERET instructions\n\
17649 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
17650 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
17651 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
17652 -msym32                 assume all symbols have 32-bit values\n\
17653 -O0                     remove unneeded NOPs, do not swap branches\n\
17654 -O                      remove unneeded NOPs and swap branches\n\
17655 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
17656 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
17657   fprintf (stream, _("\
17658 -mhard-float            allow floating-point instructions\n\
17659 -msoft-float            do not allow floating-point instructions\n\
17660 -msingle-float          only allow 32-bit floating-point operations\n\
17661 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
17662 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
17663 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
17664 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
17665
17666   first = 1;
17667
17668   show (stream, "legacy", &column, &first);
17669   show (stream, "2008", &column, &first);
17670
17671   fputc ('\n', stream);
17672
17673   fprintf (stream, _("\
17674 -KPIC, -call_shared     generate SVR4 position independent code\n\
17675 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
17676 -mvxworks-pic           generate VxWorks position independent code\n\
17677 -non_shared             do not generate code that can operate with DSOs\n\
17678 -xgot                   assume a 32 bit GOT\n\
17679 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
17680 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
17681                         position dependent (non shared) code\n\
17682 -mabi=ABI               create ABI conformant object file for:\n"));
17683
17684   first = 1;
17685
17686   show (stream, "32", &column, &first);
17687   show (stream, "o64", &column, &first);
17688   show (stream, "n32", &column, &first);
17689   show (stream, "64", &column, &first);
17690   show (stream, "eabi", &column, &first);
17691
17692   fputc ('\n', stream);
17693
17694   fprintf (stream, _("\
17695 -32                     create o32 ABI object file (default)\n\
17696 -n32                    create n32 ABI object file\n\
17697 -64                     create 64 ABI object file\n"));
17698 }
17699
17700 #ifdef TE_IRIX
17701 enum dwarf2_format
17702 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
17703 {
17704   if (HAVE_64BIT_SYMBOLS)
17705     return dwarf2_format_64bit_irix;
17706   else
17707     return dwarf2_format_32bit;
17708 }
17709 #endif
17710
17711 int
17712 mips_dwarf2_addr_size (void)
17713 {
17714   if (HAVE_64BIT_OBJECTS)
17715     return 8;
17716   else
17717     return 4;
17718 }
17719
17720 /* Standard calling conventions leave the CFA at SP on entry.  */
17721 void
17722 mips_cfi_frame_initial_instructions (void)
17723 {
17724   cfi_add_CFA_def_cfa_register (SP);
17725 }
17726
17727 int
17728 tc_mips_regname_to_dw2regnum (char *regname)
17729 {
17730   unsigned int regnum = -1;
17731   unsigned int reg;
17732
17733   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
17734     regnum = reg;
17735
17736   return regnum;
17737 }