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 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
4611    the length of the value in bytes (4 for float, 8 for double) and
4612    USING_GPRS says whether the destination is a GPR rather than an FPR.
4613
4614    Return the constant in IMM and OFFSET as follows:
4615
4616    - If the constant should be loaded via memory, set IMM to O_absent and
4617      OFFSET to the memory address.
4618
4619    - Otherwise, if the constant should be loaded into two 32-bit registers,
4620      set IMM to the O_constant to load into the high register and OFFSET
4621      to the corresponding value for the low register.
4622
4623    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
4624
4625    These constants only appear as the last operand in an instruction,
4626    and every instruction that accepts them in any variant accepts them
4627    in all variants.  This means we don't have to worry about backing out
4628    any changes if the instruction does not match.  We just match
4629    unconditionally and report an error if the constant is invalid.  */
4630
4631 static char *
4632 parse_float_constant (char *s, expressionS *imm, expressionS *offset,
4633                       int length, bfd_boolean using_gprs)
4634 {
4635   char *save_in, *p, *err;
4636   unsigned char data[8];
4637   int atof_length;
4638   segT seg, new_seg;
4639   subsegT subseg;
4640   const char *newname;
4641
4642   /* Where the constant is placed is based on how the MIPS assembler
4643      does things:
4644
4645      length == 4 && using_gprs  -- immediate value only
4646      length == 8 && using_gprs  -- .rdata or immediate value
4647      length == 4 && !using_gprs -- .lit4 or immediate value
4648      length == 8 && !using_gprs -- .lit8 or immediate value
4649
4650      The .lit4 and .lit8 sections are only used if permitted by the
4651      -G argument.  */
4652   save_in = input_line_pointer;
4653   input_line_pointer = s;
4654   err = md_atof (length == 8 ? 'd' : 'f', (char *) data, &atof_length);
4655   s = input_line_pointer;
4656   input_line_pointer = save_in;
4657   if (err && *err)
4658     {
4659       as_bad (_("Bad floating point constant: %s"), err);
4660       memset (data, '\0', sizeof (data));
4661     }
4662   else
4663     gas_assert (atof_length == length);
4664
4665   /* Handle 32-bit constants for which an immediate value is best.  */
4666   if (length == 4
4667       && (using_gprs
4668           || g_switch_value < 4
4669           || (data[0] == 0 && data[1] == 0)
4670           || (data[2] == 0 && data[3] == 0)))
4671     {
4672       imm->X_op = O_constant;
4673       if (!target_big_endian)
4674         imm->X_add_number = bfd_getl32 (data);
4675       else
4676         imm->X_add_number = bfd_getb32 (data);
4677       offset->X_op = O_absent;
4678       return s;
4679     }
4680
4681   /* Handle 64-bit constants for which an immediate value is best.  */
4682   if (length == 8
4683       && !mips_disable_float_construction
4684       /* Constants can only be constructed in GPRs and copied
4685          to FPRs if the GPRs are at least as wide as the FPRs.
4686          Force the constant into memory if we are using 64-bit FPRs
4687          but the GPRs are only 32 bits wide.  */
4688       /* ??? No longer true with the addition of MTHC1, but this
4689          is legacy code...  */
4690       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
4691       && ((data[0] == 0 && data[1] == 0)
4692           || (data[2] == 0 && data[3] == 0))
4693       && ((data[4] == 0 && data[5] == 0)
4694           || (data[6] == 0 && data[7] == 0)))
4695     {
4696       /* The value is simple enough to load with a couple of instructions.
4697          If using 32-bit registers, set IMM to the high order 32 bits and
4698          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
4699          64 bit constant.  */
4700       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
4701         {
4702           imm->X_op = O_constant;
4703           offset->X_op = O_constant;
4704           if (!target_big_endian)
4705             {
4706               imm->X_add_number = bfd_getl32 (data + 4);
4707               offset->X_add_number = bfd_getl32 (data);
4708             }
4709           else
4710             {
4711               imm->X_add_number = bfd_getb32 (data);
4712               offset->X_add_number = bfd_getb32 (data + 4);
4713             }
4714           if (offset->X_add_number == 0)
4715             offset->X_op = O_absent;
4716         }
4717       else
4718         {
4719           imm->X_op = O_constant;
4720           if (!target_big_endian)
4721             imm->X_add_number = bfd_getl64 (data);
4722           else
4723             imm->X_add_number = bfd_getb64 (data);
4724           offset->X_op = O_absent;
4725         }
4726       return s;
4727     }
4728
4729   /* Switch to the right section.  */
4730   seg = now_seg;
4731   subseg = now_subseg;
4732   if (length == 4)
4733     {
4734       gas_assert (!using_gprs && g_switch_value >= 4);
4735       newname = ".lit4";
4736     }
4737   else
4738     {
4739       if (using_gprs || g_switch_value < 8)
4740         newname = RDATA_SECTION_NAME;
4741       else
4742         newname = ".lit8";
4743     }
4744
4745   new_seg = subseg_new (newname, (subsegT) 0);
4746   bfd_set_section_flags (stdoutput, new_seg,
4747                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
4748   frag_align (length == 4 ? 2 : 3, 0, 0);
4749   if (strncmp (TARGET_OS, "elf", 3) != 0)
4750     record_alignment (new_seg, 4);
4751   else
4752     record_alignment (new_seg, length == 4 ? 2 : 3);
4753   if (seg == now_seg)
4754     as_bad (_("Can't use floating point insn in this section"));
4755
4756   /* Set the argument to the current address in the section.  */
4757   imm->X_op = O_absent;
4758   offset->X_op = O_symbol;
4759   offset->X_add_symbol = symbol_temp_new_now ();
4760   offset->X_add_number = 0;
4761
4762   /* Put the floating point number into the section.  */
4763   p = frag_more (length);
4764   memcpy (p, data, length);
4765
4766   /* Switch back to the original section.  */
4767   subseg_set (seg, subseg);
4768   return s;
4769 }
4770
4771 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
4772    of the argument text if the match is successful, otherwise return null.  */
4773
4774 static char *
4775 match_operand (struct mips_arg_info *arg,
4776                const struct mips_operand *operand, char *s)
4777 {
4778   switch (operand->type)
4779     {
4780     case OP_INT:
4781       return match_int_operand (arg, operand, s);
4782
4783     case OP_MAPPED_INT:
4784       return match_mapped_int_operand (arg, operand, s);
4785
4786     case OP_MSB:
4787       return match_msb_operand (arg, operand, s);
4788
4789     case OP_REG:
4790       return match_reg_operand (arg, operand, s);
4791
4792     case OP_REG_PAIR:
4793       return match_reg_pair_operand (arg, operand, s);
4794
4795     case OP_PCREL:
4796       return match_pcrel_operand (s);
4797
4798     case OP_PERF_REG:
4799       return match_perf_reg_operand (arg, operand, s);
4800
4801     case OP_ADDIUSP_INT:
4802       return match_addiusp_operand (arg, operand, s);
4803
4804     case OP_CLO_CLZ_DEST:
4805       return match_clo_clz_dest_operand (arg, operand, s);
4806
4807     case OP_LWM_SWM_LIST:
4808       return match_lwm_swm_list_operand (arg, operand, s);
4809
4810     case OP_ENTRY_EXIT_LIST:
4811       return match_entry_exit_operand (arg, operand, s);
4812
4813     case OP_SAVE_RESTORE_LIST:
4814       return match_save_restore_list_operand (arg, s);
4815
4816     case OP_MDMX_IMM_REG:
4817       return match_mdmx_imm_reg_operand (arg, operand, s);
4818
4819     case OP_REPEAT_DEST_REG:
4820       return match_tied_reg_operand (arg, s, arg->dest_regno);
4821
4822     case OP_REPEAT_PREV_REG:
4823       return match_tied_reg_operand (arg, s, arg->last_regno);
4824
4825     case OP_PC:
4826       return match_pc_operand (s);
4827     }
4828   abort ();
4829 }
4830
4831 /* ARG is the state after successfully matching an instruction.
4832    Issue any queued-up warnings.  */
4833
4834 static void
4835 check_completed_insn (struct mips_arg_info *arg)
4836 {
4837   if (arg->seen_at)
4838     {
4839       if (AT == ATREG)
4840         as_warn (_("Used $at without \".set noat\""));
4841       else
4842         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
4843     }
4844 }
4845
4846 /* Classify an instruction according to the FIX_VR4120_* enumeration.
4847    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
4848    by VR4120 errata.  */
4849
4850 static unsigned int
4851 classify_vr4120_insn (const char *name)
4852 {
4853   if (strncmp (name, "macc", 4) == 0)
4854     return FIX_VR4120_MACC;
4855   if (strncmp (name, "dmacc", 5) == 0)
4856     return FIX_VR4120_DMACC;
4857   if (strncmp (name, "mult", 4) == 0)
4858     return FIX_VR4120_MULT;
4859   if (strncmp (name, "dmult", 5) == 0)
4860     return FIX_VR4120_DMULT;
4861   if (strstr (name, "div"))
4862     return FIX_VR4120_DIV;
4863   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
4864     return FIX_VR4120_MTHILO;
4865   return NUM_FIX_VR4120_CLASSES;
4866 }
4867
4868 #define INSN_ERET  0x42000018
4869 #define INSN_DERET 0x4200001f
4870
4871 /* Return the number of instructions that must separate INSN1 and INSN2,
4872    where INSN1 is the earlier instruction.  Return the worst-case value
4873    for any INSN2 if INSN2 is null.  */
4874
4875 static unsigned int
4876 insns_between (const struct mips_cl_insn *insn1,
4877                const struct mips_cl_insn *insn2)
4878 {
4879   unsigned long pinfo1, pinfo2;
4880   unsigned int mask;
4881
4882   /* This function needs to know which pinfo flags are set for INSN2
4883      and which registers INSN2 uses.  The former is stored in PINFO2 and
4884      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
4885      will have every flag set and INSN2_USES_GPR will always return true.  */
4886   pinfo1 = insn1->insn_mo->pinfo;
4887   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
4888
4889 #define INSN2_USES_GPR(REG) \
4890   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
4891
4892   /* For most targets, write-after-read dependencies on the HI and LO
4893      registers must be separated by at least two instructions.  */
4894   if (!hilo_interlocks)
4895     {
4896       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
4897         return 2;
4898       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
4899         return 2;
4900     }
4901
4902   /* If we're working around r7000 errata, there must be two instructions
4903      between an mfhi or mflo and any instruction that uses the result.  */
4904   if (mips_7000_hilo_fix
4905       && !mips_opts.micromips
4906       && MF_HILO_INSN (pinfo1)
4907       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
4908     return 2;
4909
4910   /* If we're working around 24K errata, one instruction is required
4911      if an ERET or DERET is followed by a branch instruction.  */
4912   if (mips_fix_24k && !mips_opts.micromips)
4913     {
4914       if (insn1->insn_opcode == INSN_ERET
4915           || insn1->insn_opcode == INSN_DERET)
4916         {
4917           if (insn2 == NULL
4918               || insn2->insn_opcode == INSN_ERET
4919               || insn2->insn_opcode == INSN_DERET
4920               || delayed_branch_p (insn2))
4921             return 1;
4922         }
4923     }
4924
4925   /* If working around VR4120 errata, check for combinations that need
4926      a single intervening instruction.  */
4927   if (mips_fix_vr4120 && !mips_opts.micromips)
4928     {
4929       unsigned int class1, class2;
4930
4931       class1 = classify_vr4120_insn (insn1->insn_mo->name);
4932       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
4933         {
4934           if (insn2 == NULL)
4935             return 1;
4936           class2 = classify_vr4120_insn (insn2->insn_mo->name);
4937           if (vr4120_conflicts[class1] & (1 << class2))
4938             return 1;
4939         }
4940     }
4941
4942   if (!HAVE_CODE_COMPRESSION)
4943     {
4944       /* Check for GPR or coprocessor load delays.  All such delays
4945          are on the RT register.  */
4946       /* Itbl support may require additional care here.  */
4947       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
4948           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
4949         {
4950           know (pinfo1 & INSN_WRITE_GPR_T);
4951           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
4952             return 1;
4953         }
4954
4955       /* Check for generic coprocessor hazards.
4956
4957          This case is not handled very well.  There is no special
4958          knowledge of CP0 handling, and the coprocessors other than
4959          the floating point unit are not distinguished at all.  */
4960       /* Itbl support may require additional care here. FIXME!
4961          Need to modify this to include knowledge about
4962          user specified delays!  */
4963       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
4964                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
4965         {
4966           /* Handle cases where INSN1 writes to a known general coprocessor
4967              register.  There must be a one instruction delay before INSN2
4968              if INSN2 reads that register, otherwise no delay is needed.  */
4969           mask = fpr_write_mask (insn1);
4970           if (mask != 0)
4971             {
4972               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
4973                 return 1;
4974             }
4975           else
4976             {
4977               /* Read-after-write dependencies on the control registers
4978                  require a two-instruction gap.  */
4979               if ((pinfo1 & INSN_WRITE_COND_CODE)
4980                   && (pinfo2 & INSN_READ_COND_CODE))
4981                 return 2;
4982
4983               /* We don't know exactly what INSN1 does.  If INSN2 is
4984                  also a coprocessor instruction, assume there must be
4985                  a one instruction gap.  */
4986               if (pinfo2 & INSN_COP)
4987                 return 1;
4988             }
4989         }
4990
4991       /* Check for read-after-write dependencies on the coprocessor
4992          control registers in cases where INSN1 does not need a general
4993          coprocessor delay.  This means that INSN1 is a floating point
4994          comparison instruction.  */
4995       /* Itbl support may require additional care here.  */
4996       else if (!cop_interlocks
4997                && (pinfo1 & INSN_WRITE_COND_CODE)
4998                && (pinfo2 & INSN_READ_COND_CODE))
4999         return 1;
5000     }
5001
5002 #undef INSN2_USES_GPR
5003
5004   return 0;
5005 }
5006
5007 /* Return the number of nops that would be needed to work around the
5008    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5009    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5010    that are contained within the first IGNORE instructions of HIST.  */
5011
5012 static int
5013 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5014                  const struct mips_cl_insn *insn)
5015 {
5016   int i, j;
5017   unsigned int mask;
5018
5019   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5020      are not affected by the errata.  */
5021   if (insn != 0
5022       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5023           || strcmp (insn->insn_mo->name, "mtlo") == 0
5024           || strcmp (insn->insn_mo->name, "mthi") == 0))
5025     return 0;
5026
5027   /* Search for the first MFLO or MFHI.  */
5028   for (i = 0; i < MAX_VR4130_NOPS; i++)
5029     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5030       {
5031         /* Extract the destination register.  */
5032         mask = gpr_write_mask (&hist[i]);
5033
5034         /* No nops are needed if INSN reads that register.  */
5035         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5036           return 0;
5037
5038         /* ...or if any of the intervening instructions do.  */
5039         for (j = 0; j < i; j++)
5040           if (gpr_read_mask (&hist[j]) & mask)
5041             return 0;
5042
5043         if (i >= ignore)
5044           return MAX_VR4130_NOPS - i;
5045       }
5046   return 0;
5047 }
5048
5049 #define BASE_REG_EQ(INSN1, INSN2)       \
5050   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5051       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5052
5053 /* Return the minimum alignment for this store instruction.  */
5054
5055 static int
5056 fix_24k_align_to (const struct mips_opcode *mo)
5057 {
5058   if (strcmp (mo->name, "sh") == 0)
5059     return 2;
5060
5061   if (strcmp (mo->name, "swc1") == 0
5062       || strcmp (mo->name, "swc2") == 0
5063       || strcmp (mo->name, "sw") == 0
5064       || strcmp (mo->name, "sc") == 0
5065       || strcmp (mo->name, "s.s") == 0)
5066     return 4;
5067
5068   if (strcmp (mo->name, "sdc1") == 0
5069       || strcmp (mo->name, "sdc2") == 0
5070       || strcmp (mo->name, "s.d") == 0)
5071     return 8;
5072
5073   /* sb, swl, swr */
5074   return 1;
5075 }
5076
5077 struct fix_24k_store_info
5078   {
5079     /* Immediate offset, if any, for this store instruction.  */
5080     short off;
5081     /* Alignment required by this store instruction.  */
5082     int align_to;
5083     /* True for register offsets.  */
5084     int register_offset;
5085   };
5086
5087 /* Comparison function used by qsort.  */
5088
5089 static int
5090 fix_24k_sort (const void *a, const void *b)
5091 {
5092   const struct fix_24k_store_info *pos1 = a;
5093   const struct fix_24k_store_info *pos2 = b;
5094
5095   return (pos1->off - pos2->off);
5096 }
5097
5098 /* INSN is a store instruction.  Try to record the store information
5099    in STINFO.  Return false if the information isn't known.  */
5100
5101 static bfd_boolean
5102 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5103                            const struct mips_cl_insn *insn)
5104 {
5105   /* The instruction must have a known offset.  */
5106   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5107     return FALSE;
5108
5109   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5110   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5111   return TRUE;
5112 }
5113
5114 /* Return the number of nops that would be needed to work around the 24k
5115    "lost data on stores during refill" errata if instruction INSN
5116    immediately followed the 2 instructions described by HIST.
5117    Ignore hazards that are contained within the first IGNORE
5118    instructions of HIST.
5119
5120    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5121    for the data cache refills and store data. The following describes
5122    the scenario where the store data could be lost.
5123
5124    * A data cache miss, due to either a load or a store, causing fill
5125      data to be supplied by the memory subsystem
5126    * The first three doublewords of fill data are returned and written
5127      into the cache
5128    * A sequence of four stores occurs in consecutive cycles around the
5129      final doubleword of the fill:
5130    * Store A
5131    * Store B
5132    * Store C
5133    * Zero, One or more instructions
5134    * Store D
5135
5136    The four stores A-D must be to different doublewords of the line that
5137    is being filled. The fourth instruction in the sequence above permits
5138    the fill of the final doubleword to be transferred from the FSB into
5139    the cache. In the sequence above, the stores may be either integer
5140    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5141    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5142    different doublewords on the line. If the floating point unit is
5143    running in 1:2 mode, it is not possible to create the sequence above
5144    using only floating point store instructions.
5145
5146    In this case, the cache line being filled is incorrectly marked
5147    invalid, thereby losing the data from any store to the line that
5148    occurs between the original miss and the completion of the five
5149    cycle sequence shown above.
5150
5151    The workarounds are:
5152
5153    * Run the data cache in write-through mode.
5154    * Insert a non-store instruction between
5155      Store A and Store B or Store B and Store C.  */
5156   
5157 static int
5158 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5159               const struct mips_cl_insn *insn)
5160 {
5161   struct fix_24k_store_info pos[3];
5162   int align, i, base_offset;
5163
5164   if (ignore >= 2)
5165     return 0;
5166
5167   /* If the previous instruction wasn't a store, there's nothing to
5168      worry about.  */
5169   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5170     return 0;
5171
5172   /* If the instructions after the previous one are unknown, we have
5173      to assume the worst.  */
5174   if (!insn)
5175     return 1;
5176
5177   /* Check whether we are dealing with three consecutive stores.  */
5178   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5179       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5180     return 0;
5181
5182   /* If we don't know the relationship between the store addresses,
5183      assume the worst.  */
5184   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5185       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5186     return 1;
5187
5188   if (!fix_24k_record_store_info (&pos[0], insn)
5189       || !fix_24k_record_store_info (&pos[1], &hist[0])
5190       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5191     return 1;
5192
5193   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5194
5195   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5196      X bytes and such that the base register + X is known to be aligned
5197      to align bytes.  */
5198
5199   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5200     align = 8;
5201   else
5202     {
5203       align = pos[0].align_to;
5204       base_offset = pos[0].off;
5205       for (i = 1; i < 3; i++)
5206         if (align < pos[i].align_to)
5207           {
5208             align = pos[i].align_to;
5209             base_offset = pos[i].off;
5210           }
5211       for (i = 0; i < 3; i++)
5212         pos[i].off -= base_offset;
5213     }
5214
5215   pos[0].off &= ~align + 1;
5216   pos[1].off &= ~align + 1;
5217   pos[2].off &= ~align + 1;
5218
5219   /* If any two stores write to the same chunk, they also write to the
5220      same doubleword.  The offsets are still sorted at this point.  */
5221   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5222     return 0;
5223
5224   /* A range of at least 9 bytes is needed for the stores to be in
5225      non-overlapping doublewords.  */
5226   if (pos[2].off - pos[0].off <= 8)
5227     return 0;
5228
5229   if (pos[2].off - pos[1].off >= 24
5230       || pos[1].off - pos[0].off >= 24
5231       || pos[2].off - pos[0].off >= 32)
5232     return 0;
5233
5234   return 1;
5235 }
5236
5237 /* Return the number of nops that would be needed if instruction INSN
5238    immediately followed the MAX_NOPS instructions given by HIST,
5239    where HIST[0] is the most recent instruction.  Ignore hazards
5240    between INSN and the first IGNORE instructions in HIST.
5241
5242    If INSN is null, return the worse-case number of nops for any
5243    instruction.  */
5244
5245 static int
5246 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5247                const struct mips_cl_insn *insn)
5248 {
5249   int i, nops, tmp_nops;
5250
5251   nops = 0;
5252   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5253     {
5254       tmp_nops = insns_between (hist + i, insn) - i;
5255       if (tmp_nops > nops)
5256         nops = tmp_nops;
5257     }
5258
5259   if (mips_fix_vr4130 && !mips_opts.micromips)
5260     {
5261       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5262       if (tmp_nops > nops)
5263         nops = tmp_nops;
5264     }
5265
5266   if (mips_fix_24k && !mips_opts.micromips)
5267     {
5268       tmp_nops = nops_for_24k (ignore, hist, insn);
5269       if (tmp_nops > nops)
5270         nops = tmp_nops;
5271     }
5272
5273   return nops;
5274 }
5275
5276 /* The variable arguments provide NUM_INSNS extra instructions that
5277    might be added to HIST.  Return the largest number of nops that
5278    would be needed after the extended sequence, ignoring hazards
5279    in the first IGNORE instructions.  */
5280
5281 static int
5282 nops_for_sequence (int num_insns, int ignore,
5283                    const struct mips_cl_insn *hist, ...)
5284 {
5285   va_list args;
5286   struct mips_cl_insn buffer[MAX_NOPS];
5287   struct mips_cl_insn *cursor;
5288   int nops;
5289
5290   va_start (args, hist);
5291   cursor = buffer + num_insns;
5292   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5293   while (cursor > buffer)
5294     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5295
5296   nops = nops_for_insn (ignore, buffer, NULL);
5297   va_end (args);
5298   return nops;
5299 }
5300
5301 /* Like nops_for_insn, but if INSN is a branch, take into account the
5302    worst-case delay for the branch target.  */
5303
5304 static int
5305 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5306                          const struct mips_cl_insn *insn)
5307 {
5308   int nops, tmp_nops;
5309
5310   nops = nops_for_insn (ignore, hist, insn);
5311   if (delayed_branch_p (insn))
5312     {
5313       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5314                                     hist, insn, get_delay_slot_nop (insn));
5315       if (tmp_nops > nops)
5316         nops = tmp_nops;
5317     }
5318   else if (compact_branch_p (insn))
5319     {
5320       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5321       if (tmp_nops > nops)
5322         nops = tmp_nops;
5323     }
5324   return nops;
5325 }
5326
5327 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5328
5329 static void
5330 fix_loongson2f_nop (struct mips_cl_insn * ip)
5331 {
5332   gas_assert (!HAVE_CODE_COMPRESSION);
5333   if (strcmp (ip->insn_mo->name, "nop") == 0)
5334     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5335 }
5336
5337 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5338                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5339
5340 static void
5341 fix_loongson2f_jump (struct mips_cl_insn * ip)
5342 {
5343   gas_assert (!HAVE_CODE_COMPRESSION);
5344   if (strcmp (ip->insn_mo->name, "j") == 0
5345       || strcmp (ip->insn_mo->name, "jr") == 0
5346       || strcmp (ip->insn_mo->name, "jalr") == 0)
5347     {
5348       int sreg;
5349       expressionS ep;
5350
5351       if (! mips_opts.at)
5352         return;
5353
5354       sreg = EXTRACT_OPERAND (0, RS, *ip);
5355       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5356         return;
5357
5358       ep.X_op = O_constant;
5359       ep.X_add_number = 0xcfff0000;
5360       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5361       ep.X_add_number = 0xffff;
5362       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5363       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5364     }
5365 }
5366
5367 static void
5368 fix_loongson2f (struct mips_cl_insn * ip)
5369 {
5370   if (mips_fix_loongson2f_nop)
5371     fix_loongson2f_nop (ip);
5372
5373   if (mips_fix_loongson2f_jump)
5374     fix_loongson2f_jump (ip);
5375 }
5376
5377 /* IP is a branch that has a delay slot, and we need to fill it
5378    automatically.   Return true if we can do that by swapping IP
5379    with the previous instruction.
5380    ADDRESS_EXPR is an operand of the instruction to be used with
5381    RELOC_TYPE.  */
5382
5383 static bfd_boolean
5384 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5385   bfd_reloc_code_real_type *reloc_type)
5386 {
5387   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5388   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
5389
5390   /* -O2 and above is required for this optimization.  */
5391   if (mips_optimize < 2)
5392     return FALSE;
5393
5394   /* If we have seen .set volatile or .set nomove, don't optimize.  */
5395   if (mips_opts.nomove)
5396     return FALSE;
5397
5398   /* We can't swap if the previous instruction's position is fixed.  */
5399   if (history[0].fixed_p)
5400     return FALSE;
5401
5402   /* If the previous previous insn was in a .set noreorder, we can't
5403      swap.  Actually, the MIPS assembler will swap in this situation.
5404      However, gcc configured -with-gnu-as will generate code like
5405
5406         .set    noreorder
5407         lw      $4,XXX
5408         .set    reorder
5409         INSN
5410         bne     $4,$0,foo
5411
5412      in which we can not swap the bne and INSN.  If gcc is not configured
5413      -with-gnu-as, it does not output the .set pseudo-ops.  */
5414   if (history[1].noreorder_p)
5415     return FALSE;
5416
5417   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
5418      This means that the previous instruction was a 4-byte one anyhow.  */
5419   if (mips_opts.mips16 && history[0].fixp[0])
5420     return FALSE;
5421
5422   /* If the branch is itself the target of a branch, we can not swap.
5423      We cheat on this; all we check for is whether there is a label on
5424      this instruction.  If there are any branches to anything other than
5425      a label, users must use .set noreorder.  */
5426   if (seg_info (now_seg)->label_list)
5427     return FALSE;
5428
5429   /* If the previous instruction is in a variant frag other than this
5430      branch's one, we cannot do the swap.  This does not apply to
5431      MIPS16 code, which uses variant frags for different purposes.  */
5432   if (!mips_opts.mips16
5433       && history[0].frag
5434       && history[0].frag->fr_type == rs_machine_dependent)
5435     return FALSE;
5436
5437   /* We do not swap with instructions that cannot architecturally
5438      be placed in a branch delay slot, such as SYNC or ERET.  We
5439      also refrain from swapping with a trap instruction, since it
5440      complicates trap handlers to have the trap instruction be in
5441      a delay slot.  */
5442   prev_pinfo = history[0].insn_mo->pinfo;
5443   if (prev_pinfo & INSN_NO_DELAY_SLOT)
5444     return FALSE;
5445
5446   /* Check for conflicts between the branch and the instructions
5447      before the candidate delay slot.  */
5448   if (nops_for_insn (0, history + 1, ip) > 0)
5449     return FALSE;
5450
5451   /* Check for conflicts between the swapped sequence and the
5452      target of the branch.  */
5453   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
5454     return FALSE;
5455
5456   /* If the branch reads a register that the previous
5457      instruction sets, we can not swap.  */
5458   gpr_read = gpr_read_mask (ip);
5459   prev_gpr_write = gpr_write_mask (&history[0]);
5460   if (gpr_read & prev_gpr_write)
5461     return FALSE;
5462
5463   /* If the branch writes a register that the previous
5464      instruction sets, we can not swap.  */
5465   gpr_write = gpr_write_mask (ip);
5466   if (gpr_write & prev_gpr_write)
5467     return FALSE;
5468
5469   /* If the branch writes a register that the previous
5470      instruction reads, we can not swap.  */
5471   prev_gpr_read = gpr_read_mask (&history[0]);
5472   if (gpr_write & prev_gpr_read)
5473     return FALSE;
5474
5475   /* If one instruction sets a condition code and the
5476      other one uses a condition code, we can not swap.  */
5477   pinfo = ip->insn_mo->pinfo;
5478   if ((pinfo & INSN_READ_COND_CODE)
5479       && (prev_pinfo & INSN_WRITE_COND_CODE))
5480     return FALSE;
5481   if ((pinfo & INSN_WRITE_COND_CODE)
5482       && (prev_pinfo & INSN_READ_COND_CODE))
5483     return FALSE;
5484
5485   /* If the previous instruction uses the PC, we can not swap.  */
5486   prev_pinfo2 = history[0].insn_mo->pinfo2;
5487   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
5488     return FALSE;
5489   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
5490     return FALSE;
5491
5492   /* If the previous instruction has an incorrect size for a fixed
5493      branch delay slot in microMIPS mode, we cannot swap.  */
5494   pinfo2 = ip->insn_mo->pinfo2;
5495   if (mips_opts.micromips
5496       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
5497       && insn_length (history) != 2)
5498     return FALSE;
5499   if (mips_opts.micromips
5500       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
5501       && insn_length (history) != 4)
5502     return FALSE;
5503
5504   /* On R5900 short loops need to be fixed by inserting a nop in
5505      the branch delay slots.
5506      A short loop can be terminated too early.  */
5507   if (mips_opts.arch == CPU_R5900
5508       /* Check if instruction has a parameter, ignore "j $31". */
5509       && (address_expr != NULL)
5510       /* Parameter must be 16 bit. */
5511       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
5512       /* Branch to same segment. */
5513       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
5514       /* Branch to same code fragment. */
5515       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
5516       /* Can only calculate branch offset if value is known. */
5517       && symbol_constant_p(address_expr->X_add_symbol)
5518       /* Check if branch is really conditional. */
5519       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
5520         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
5521         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
5522     {
5523       int distance;
5524       /* Check if loop is shorter than 6 instructions including
5525          branch and delay slot.  */
5526       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
5527       if (distance <= 20)
5528         {
5529           int i;
5530           int rv;
5531
5532           rv = FALSE;
5533           /* When the loop includes branches or jumps,
5534              it is not a short loop. */
5535           for (i = 0; i < (distance / 4); i++)
5536             {
5537               if ((history[i].cleared_p)
5538                   || delayed_branch_p(&history[i]))
5539                 {
5540                   rv = TRUE;
5541                   break;
5542                 }
5543             }
5544           if (rv == FALSE)
5545             {
5546               /* Insert nop after branch to fix short loop. */
5547               return FALSE;
5548             }
5549         }
5550     }
5551
5552   return TRUE;
5553 }
5554
5555 /* Decide how we should add IP to the instruction stream.
5556    ADDRESS_EXPR is an operand of the instruction to be used with
5557    RELOC_TYPE.  */
5558
5559 static enum append_method
5560 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
5561   bfd_reloc_code_real_type *reloc_type)
5562 {
5563   unsigned long pinfo;
5564
5565   /* The relaxed version of a macro sequence must be inherently
5566      hazard-free.  */
5567   if (mips_relax.sequence == 2)
5568     return APPEND_ADD;
5569
5570   /* We must not dabble with instructions in a ".set norerorder" block.  */
5571   if (mips_opts.noreorder)
5572     return APPEND_ADD;
5573
5574   /* Otherwise, it's our responsibility to fill branch delay slots.  */
5575   if (delayed_branch_p (ip))
5576     {
5577       if (!branch_likely_p (ip)
5578           && can_swap_branch_p (ip, address_expr, reloc_type))
5579         return APPEND_SWAP;
5580
5581       pinfo = ip->insn_mo->pinfo;
5582       if (mips_opts.mips16
5583           && ISA_SUPPORTS_MIPS16E
5584           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
5585         return APPEND_ADD_COMPACT;
5586
5587       return APPEND_ADD_WITH_NOP;
5588     }
5589
5590   return APPEND_ADD;
5591 }
5592
5593 /* IP is a MIPS16 instruction whose opcode we have just changed.
5594    Point IP->insn_mo to the new opcode's definition.  */
5595
5596 static void
5597 find_altered_mips16_opcode (struct mips_cl_insn *ip)
5598 {
5599   const struct mips_opcode *mo, *end;
5600
5601   end = &mips16_opcodes[bfd_mips16_num_opcodes];
5602   for (mo = ip->insn_mo; mo < end; mo++)
5603     if ((ip->insn_opcode & mo->mask) == mo->match)
5604       {
5605         ip->insn_mo = mo;
5606         return;
5607       }
5608   abort ();
5609 }
5610
5611 /* For microMIPS macros, we need to generate a local number label
5612    as the target of branches.  */
5613 #define MICROMIPS_LABEL_CHAR            '\037'
5614 static unsigned long micromips_target_label;
5615 static char micromips_target_name[32];
5616
5617 static char *
5618 micromips_label_name (void)
5619 {
5620   char *p = micromips_target_name;
5621   char symbol_name_temporary[24];
5622   unsigned long l;
5623   int i;
5624
5625   if (*p)
5626     return p;
5627
5628   i = 0;
5629   l = micromips_target_label;
5630 #ifdef LOCAL_LABEL_PREFIX
5631   *p++ = LOCAL_LABEL_PREFIX;
5632 #endif
5633   *p++ = 'L';
5634   *p++ = MICROMIPS_LABEL_CHAR;
5635   do
5636     {
5637       symbol_name_temporary[i++] = l % 10 + '0';
5638       l /= 10;
5639     }
5640   while (l != 0);
5641   while (i > 0)
5642     *p++ = symbol_name_temporary[--i];
5643   *p = '\0';
5644
5645   return micromips_target_name;
5646 }
5647
5648 static void
5649 micromips_label_expr (expressionS *label_expr)
5650 {
5651   label_expr->X_op = O_symbol;
5652   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
5653   label_expr->X_add_number = 0;
5654 }
5655
5656 static void
5657 micromips_label_inc (void)
5658 {
5659   micromips_target_label++;
5660   *micromips_target_name = '\0';
5661 }
5662
5663 static void
5664 micromips_add_label (void)
5665 {
5666   symbolS *s;
5667
5668   s = colon (micromips_label_name ());
5669   micromips_label_inc ();
5670   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
5671 }
5672
5673 /* If assembling microMIPS code, then return the microMIPS reloc
5674    corresponding to the requested one if any.  Otherwise return
5675    the reloc unchanged.  */
5676
5677 static bfd_reloc_code_real_type
5678 micromips_map_reloc (bfd_reloc_code_real_type reloc)
5679 {
5680   static const bfd_reloc_code_real_type relocs[][2] =
5681     {
5682       /* Keep sorted incrementally by the left-hand key.  */
5683       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
5684       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
5685       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
5686       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
5687       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
5688       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
5689       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
5690       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
5691       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
5692       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
5693       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
5694       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
5695       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
5696       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
5697       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
5698       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
5699       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
5700       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
5701       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
5702       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
5703       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
5704       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
5705       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
5706       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
5707       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
5708       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
5709       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
5710     };
5711   bfd_reloc_code_real_type r;
5712   size_t i;
5713
5714   if (!mips_opts.micromips)
5715     return reloc;
5716   for (i = 0; i < ARRAY_SIZE (relocs); i++)
5717     {
5718       r = relocs[i][0];
5719       if (r > reloc)
5720         return reloc;
5721       if (r == reloc)
5722         return relocs[i][1];
5723     }
5724   return reloc;
5725 }
5726
5727 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
5728    Return true on success, storing the resolved value in RESULT.  */
5729
5730 static bfd_boolean
5731 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
5732                  offsetT *result)
5733 {
5734   switch (reloc)
5735     {
5736     case BFD_RELOC_MIPS_HIGHEST:
5737     case BFD_RELOC_MICROMIPS_HIGHEST:
5738       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
5739       return TRUE;
5740
5741     case BFD_RELOC_MIPS_HIGHER:
5742     case BFD_RELOC_MICROMIPS_HIGHER:
5743       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
5744       return TRUE;
5745
5746     case BFD_RELOC_HI16_S:
5747     case BFD_RELOC_MICROMIPS_HI16_S:
5748     case BFD_RELOC_MIPS16_HI16_S:
5749       *result = ((operand + 0x8000) >> 16) & 0xffff;
5750       return TRUE;
5751
5752     case BFD_RELOC_HI16:
5753     case BFD_RELOC_MICROMIPS_HI16:
5754     case BFD_RELOC_MIPS16_HI16:
5755       *result = (operand >> 16) & 0xffff;
5756       return TRUE;
5757
5758     case BFD_RELOC_LO16:
5759     case BFD_RELOC_MICROMIPS_LO16:
5760     case BFD_RELOC_MIPS16_LO16:
5761       *result = operand & 0xffff;
5762       return TRUE;
5763
5764     case BFD_RELOC_UNUSED:
5765       *result = operand;
5766       return TRUE;
5767
5768     default:
5769       return FALSE;
5770     }
5771 }
5772
5773 /* Output an instruction.  IP is the instruction information.
5774    ADDRESS_EXPR is an operand of the instruction to be used with
5775    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
5776    a macro expansion.  */
5777
5778 static void
5779 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
5780              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
5781 {
5782   unsigned long prev_pinfo2, pinfo;
5783   bfd_boolean relaxed_branch = FALSE;
5784   enum append_method method;
5785   bfd_boolean relax32;
5786   int branch_disp;
5787
5788   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
5789     fix_loongson2f (ip);
5790
5791   file_ase_mips16 |= mips_opts.mips16;
5792   file_ase_micromips |= mips_opts.micromips;
5793
5794   prev_pinfo2 = history[0].insn_mo->pinfo2;
5795   pinfo = ip->insn_mo->pinfo;
5796
5797   if (mips_opts.micromips
5798       && !expansionp
5799       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
5800            && micromips_insn_length (ip->insn_mo) != 2)
5801           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
5802               && micromips_insn_length (ip->insn_mo) != 4)))
5803     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
5804              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
5805
5806   if (address_expr == NULL)
5807     ip->complete_p = 1;
5808   else if (reloc_type[0] <= BFD_RELOC_UNUSED
5809            && reloc_type[1] == BFD_RELOC_UNUSED
5810            && reloc_type[2] == BFD_RELOC_UNUSED
5811            && address_expr->X_op == O_constant)
5812     {
5813       switch (*reloc_type)
5814         {
5815         case BFD_RELOC_MIPS_JMP:
5816           {
5817             int shift;
5818
5819             shift = mips_opts.micromips ? 1 : 2;
5820             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5821               as_bad (_("jump to misaligned address (0x%lx)"),
5822                       (unsigned long) address_expr->X_add_number);
5823             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5824                                 & 0x3ffffff);
5825             ip->complete_p = 1;
5826           }
5827           break;
5828
5829         case BFD_RELOC_MIPS16_JMP:
5830           if ((address_expr->X_add_number & 3) != 0)
5831             as_bad (_("jump to misaligned address (0x%lx)"),
5832                     (unsigned long) address_expr->X_add_number);
5833           ip->insn_opcode |=
5834             (((address_expr->X_add_number & 0x7c0000) << 3)
5835                | ((address_expr->X_add_number & 0xf800000) >> 7)
5836                | ((address_expr->X_add_number & 0x3fffc) >> 2));
5837           ip->complete_p = 1;
5838           break;
5839
5840         case BFD_RELOC_16_PCREL_S2:
5841           {
5842             int shift;
5843
5844             shift = mips_opts.micromips ? 1 : 2;
5845             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5846               as_bad (_("branch to misaligned address (0x%lx)"),
5847                       (unsigned long) address_expr->X_add_number);
5848             if (!mips_relax_branch)
5849               {
5850                 if ((address_expr->X_add_number + (1 << (shift + 15)))
5851                     & ~((1 << (shift + 16)) - 1))
5852                   as_bad (_("branch address range overflow (0x%lx)"),
5853                           (unsigned long) address_expr->X_add_number);
5854                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5855                                     & 0xffff);
5856               }
5857           }
5858           break;
5859
5860         default:
5861           {
5862             offsetT value;
5863
5864             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
5865                                  &value))
5866               {
5867                 ip->insn_opcode |= value & 0xffff;
5868                 ip->complete_p = 1;
5869               }
5870           }
5871           break;
5872         }
5873     }
5874
5875   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
5876     {
5877       /* There are a lot of optimizations we could do that we don't.
5878          In particular, we do not, in general, reorder instructions.
5879          If you use gcc with optimization, it will reorder
5880          instructions and generally do much more optimization then we
5881          do here; repeating all that work in the assembler would only
5882          benefit hand written assembly code, and does not seem worth
5883          it.  */
5884       int nops = (mips_optimize == 0
5885                   ? nops_for_insn (0, history, NULL)
5886                   : nops_for_insn_or_target (0, history, ip));
5887       if (nops > 0)
5888         {
5889           fragS *old_frag;
5890           unsigned long old_frag_offset;
5891           int i;
5892
5893           old_frag = frag_now;
5894           old_frag_offset = frag_now_fix ();
5895
5896           for (i = 0; i < nops; i++)
5897             add_fixed_insn (NOP_INSN);
5898           insert_into_history (0, nops, NOP_INSN);
5899
5900           if (listing)
5901             {
5902               listing_prev_line ();
5903               /* We may be at the start of a variant frag.  In case we
5904                  are, make sure there is enough space for the frag
5905                  after the frags created by listing_prev_line.  The
5906                  argument to frag_grow here must be at least as large
5907                  as the argument to all other calls to frag_grow in
5908                  this file.  We don't have to worry about being in the
5909                  middle of a variant frag, because the variants insert
5910                  all needed nop instructions themselves.  */
5911               frag_grow (40);
5912             }
5913
5914           mips_move_text_labels ();
5915
5916 #ifndef NO_ECOFF_DEBUGGING
5917           if (ECOFF_DEBUGGING)
5918             ecoff_fix_loc (old_frag, old_frag_offset);
5919 #endif
5920         }
5921     }
5922   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
5923     {
5924       int nops;
5925
5926       /* Work out how many nops in prev_nop_frag are needed by IP,
5927          ignoring hazards generated by the first prev_nop_frag_since
5928          instructions.  */
5929       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
5930       gas_assert (nops <= prev_nop_frag_holds);
5931
5932       /* Enforce NOPS as a minimum.  */
5933       if (nops > prev_nop_frag_required)
5934         prev_nop_frag_required = nops;
5935
5936       if (prev_nop_frag_holds == prev_nop_frag_required)
5937         {
5938           /* Settle for the current number of nops.  Update the history
5939              accordingly (for the benefit of any future .set reorder code).  */
5940           prev_nop_frag = NULL;
5941           insert_into_history (prev_nop_frag_since,
5942                                prev_nop_frag_holds, NOP_INSN);
5943         }
5944       else
5945         {
5946           /* Allow this instruction to replace one of the nops that was
5947              tentatively added to prev_nop_frag.  */
5948           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
5949           prev_nop_frag_holds--;
5950           prev_nop_frag_since++;
5951         }
5952     }
5953
5954   method = get_append_method (ip, address_expr, reloc_type);
5955   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
5956
5957   dwarf2_emit_insn (0);
5958   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
5959      so "move" the instruction address accordingly.
5960
5961      Also, it doesn't seem appropriate for the assembler to reorder .loc
5962      entries.  If this instruction is a branch that we are going to swap
5963      with the previous instruction, the two instructions should be
5964      treated as a unit, and the debug information for both instructions
5965      should refer to the start of the branch sequence.  Using the
5966      current position is certainly wrong when swapping a 32-bit branch
5967      and a 16-bit delay slot, since the current position would then be
5968      in the middle of a branch.  */
5969   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
5970
5971   relax32 = (mips_relax_branch
5972              /* Don't try branch relaxation within .set nomacro, or within
5973                 .set noat if we use $at for PIC computations.  If it turns
5974                 out that the branch was out-of-range, we'll get an error.  */
5975              && !mips_opts.warn_about_macros
5976              && (mips_opts.at || mips_pic == NO_PIC)
5977              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
5978                 as they have no complementing branches.  */
5979              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
5980
5981   if (!HAVE_CODE_COMPRESSION
5982       && address_expr
5983       && relax32
5984       && *reloc_type == BFD_RELOC_16_PCREL_S2
5985       && delayed_branch_p (ip))
5986     {
5987       relaxed_branch = TRUE;
5988       add_relaxed_insn (ip, (relaxed_branch_length
5989                              (NULL, NULL,
5990                               uncond_branch_p (ip) ? -1
5991                               : branch_likely_p (ip) ? 1
5992                               : 0)), 4,
5993                         RELAX_BRANCH_ENCODE
5994                         (AT,
5995                          uncond_branch_p (ip),
5996                          branch_likely_p (ip),
5997                          pinfo & INSN_WRITE_GPR_31,
5998                          0),
5999                         address_expr->X_add_symbol,
6000                         address_expr->X_add_number);
6001       *reloc_type = BFD_RELOC_UNUSED;
6002     }
6003   else if (mips_opts.micromips
6004            && address_expr
6005            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6006                || *reloc_type > BFD_RELOC_UNUSED)
6007            && (delayed_branch_p (ip) || compact_branch_p (ip))
6008            /* Don't try branch relaxation when users specify
6009               16-bit/32-bit instructions.  */
6010            && !forced_insn_length)
6011     {
6012       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6013       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6014       int uncond = uncond_branch_p (ip) ? -1 : 0;
6015       int compact = compact_branch_p (ip);
6016       int al = pinfo & INSN_WRITE_GPR_31;
6017       int length32;
6018
6019       gas_assert (address_expr != NULL);
6020       gas_assert (!mips_relax.sequence);
6021
6022       relaxed_branch = TRUE;
6023       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6024       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6025                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6026                                                 relax32, 0, 0),
6027                         address_expr->X_add_symbol,
6028                         address_expr->X_add_number);
6029       *reloc_type = BFD_RELOC_UNUSED;
6030     }
6031   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6032     {
6033       /* We need to set up a variant frag.  */
6034       gas_assert (address_expr != NULL);
6035       add_relaxed_insn (ip, 4, 0,
6036                         RELAX_MIPS16_ENCODE
6037                         (*reloc_type - BFD_RELOC_UNUSED,
6038                          forced_insn_length == 2, forced_insn_length == 4,
6039                          delayed_branch_p (&history[0]),
6040                          history[0].mips16_absolute_jump_p),
6041                         make_expr_symbol (address_expr), 0);
6042     }
6043   else if (mips_opts.mips16 && insn_length (ip) == 2)
6044     {
6045       if (!delayed_branch_p (ip))
6046         /* Make sure there is enough room to swap this instruction with
6047            a following jump instruction.  */
6048         frag_grow (6);
6049       add_fixed_insn (ip);
6050     }
6051   else
6052     {
6053       if (mips_opts.mips16
6054           && mips_opts.noreorder
6055           && delayed_branch_p (&history[0]))
6056         as_warn (_("extended instruction in delay slot"));
6057
6058       if (mips_relax.sequence)
6059         {
6060           /* If we've reached the end of this frag, turn it into a variant
6061              frag and record the information for the instructions we've
6062              written so far.  */
6063           if (frag_room () < 4)
6064             relax_close_frag ();
6065           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6066         }
6067
6068       if (mips_relax.sequence != 2)
6069         {
6070           if (mips_macro_warning.first_insn_sizes[0] == 0)
6071             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6072           mips_macro_warning.sizes[0] += insn_length (ip);
6073           mips_macro_warning.insns[0]++;
6074         }
6075       if (mips_relax.sequence != 1)
6076         {
6077           if (mips_macro_warning.first_insn_sizes[1] == 0)
6078             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6079           mips_macro_warning.sizes[1] += insn_length (ip);
6080           mips_macro_warning.insns[1]++;
6081         }
6082
6083       if (mips_opts.mips16)
6084         {
6085           ip->fixed_p = 1;
6086           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6087         }
6088       add_fixed_insn (ip);
6089     }
6090
6091   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6092     {
6093       bfd_reloc_code_real_type final_type[3];
6094       reloc_howto_type *howto0;
6095       reloc_howto_type *howto;
6096       int i;
6097
6098       /* Perform any necessary conversion to microMIPS relocations
6099          and find out how many relocations there actually are.  */
6100       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6101         final_type[i] = micromips_map_reloc (reloc_type[i]);
6102
6103       /* In a compound relocation, it is the final (outermost)
6104          operator that determines the relocated field.  */
6105       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6106       if (!howto)
6107         abort ();
6108
6109       if (i > 1)
6110         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6111       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6112                                  bfd_get_reloc_size (howto),
6113                                  address_expr,
6114                                  howto0 && howto0->pc_relative,
6115                                  final_type[0]);
6116
6117       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6118       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6119         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6120
6121       /* These relocations can have an addend that won't fit in
6122          4 octets for 64bit assembly.  */
6123       if (HAVE_64BIT_GPRS
6124           && ! howto->partial_inplace
6125           && (reloc_type[0] == BFD_RELOC_16
6126               || reloc_type[0] == BFD_RELOC_32
6127               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6128               || reloc_type[0] == BFD_RELOC_GPREL16
6129               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6130               || reloc_type[0] == BFD_RELOC_GPREL32
6131               || reloc_type[0] == BFD_RELOC_64
6132               || reloc_type[0] == BFD_RELOC_CTOR
6133               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6134               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6135               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6136               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6137               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6138               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6139               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6140               || hi16_reloc_p (reloc_type[0])
6141               || lo16_reloc_p (reloc_type[0])))
6142         ip->fixp[0]->fx_no_overflow = 1;
6143
6144       /* These relocations can have an addend that won't fit in 2 octets.  */
6145       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6146           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6147         ip->fixp[0]->fx_no_overflow = 1;
6148
6149       if (mips_relax.sequence)
6150         {
6151           if (mips_relax.first_fixup == 0)
6152             mips_relax.first_fixup = ip->fixp[0];
6153         }
6154       else if (reloc_needs_lo_p (*reloc_type))
6155         {
6156           struct mips_hi_fixup *hi_fixup;
6157
6158           /* Reuse the last entry if it already has a matching %lo.  */
6159           hi_fixup = mips_hi_fixup_list;
6160           if (hi_fixup == 0
6161               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6162             {
6163               hi_fixup = ((struct mips_hi_fixup *)
6164                           xmalloc (sizeof (struct mips_hi_fixup)));
6165               hi_fixup->next = mips_hi_fixup_list;
6166               mips_hi_fixup_list = hi_fixup;
6167             }
6168           hi_fixup->fixp = ip->fixp[0];
6169           hi_fixup->seg = now_seg;
6170         }
6171
6172       /* Add fixups for the second and third relocations, if given.
6173          Note that the ABI allows the second relocation to be
6174          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6175          moment we only use RSS_UNDEF, but we could add support
6176          for the others if it ever becomes necessary.  */
6177       for (i = 1; i < 3; i++)
6178         if (reloc_type[i] != BFD_RELOC_UNUSED)
6179           {
6180             ip->fixp[i] = fix_new (ip->frag, ip->where,
6181                                    ip->fixp[0]->fx_size, NULL, 0,
6182                                    FALSE, final_type[i]);
6183
6184             /* Use fx_tcbit to mark compound relocs.  */
6185             ip->fixp[0]->fx_tcbit = 1;
6186             ip->fixp[i]->fx_tcbit = 1;
6187           }
6188     }
6189   install_insn (ip);
6190
6191   /* Update the register mask information.  */
6192   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6193   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6194
6195   switch (method)
6196     {
6197     case APPEND_ADD:
6198       insert_into_history (0, 1, ip);
6199       break;
6200
6201     case APPEND_ADD_WITH_NOP:
6202       {
6203         struct mips_cl_insn *nop;
6204
6205         insert_into_history (0, 1, ip);
6206         nop = get_delay_slot_nop (ip);
6207         add_fixed_insn (nop);
6208         insert_into_history (0, 1, nop);
6209         if (mips_relax.sequence)
6210           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6211       }
6212       break;
6213
6214     case APPEND_ADD_COMPACT:
6215       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6216       gas_assert (mips_opts.mips16);
6217       ip->insn_opcode |= 0x0080;
6218       find_altered_mips16_opcode (ip);
6219       install_insn (ip);
6220       insert_into_history (0, 1, ip);
6221       break;
6222
6223     case APPEND_SWAP:
6224       {
6225         struct mips_cl_insn delay = history[0];
6226         if (mips_opts.mips16)
6227           {
6228             know (delay.frag == ip->frag);
6229             move_insn (ip, delay.frag, delay.where);
6230             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6231           }
6232         else if (relaxed_branch || delay.frag != ip->frag)
6233           {
6234             /* Add the delay slot instruction to the end of the
6235                current frag and shrink the fixed part of the
6236                original frag.  If the branch occupies the tail of
6237                the latter, move it backwards to cover the gap.  */
6238             delay.frag->fr_fix -= branch_disp;
6239             if (delay.frag == ip->frag)
6240               move_insn (ip, ip->frag, ip->where - branch_disp);
6241             add_fixed_insn (&delay);
6242           }
6243         else
6244           {
6245             move_insn (&delay, ip->frag,
6246                        ip->where - branch_disp + insn_length (ip));
6247             move_insn (ip, history[0].frag, history[0].where);
6248           }
6249         history[0] = *ip;
6250         delay.fixed_p = 1;
6251         insert_into_history (0, 1, &delay);
6252       }
6253       break;
6254     }
6255
6256   /* If we have just completed an unconditional branch, clear the history.  */
6257   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6258       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6259     {
6260       unsigned int i;
6261
6262       mips_no_prev_insn ();
6263
6264       for (i = 0; i < ARRAY_SIZE (history); i++)
6265         history[i].cleared_p = 1;
6266     }
6267
6268   /* We need to emit a label at the end of branch-likely macros.  */
6269   if (emit_branch_likely_macro)
6270     {
6271       emit_branch_likely_macro = FALSE;
6272       micromips_add_label ();
6273     }
6274
6275   /* We just output an insn, so the next one doesn't have a label.  */
6276   mips_clear_insn_labels ();
6277 }
6278
6279 /* Forget that there was any previous instruction or label.
6280    When BRANCH is true, the branch history is also flushed.  */
6281
6282 static void
6283 mips_no_prev_insn (void)
6284 {
6285   prev_nop_frag = NULL;
6286   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6287   mips_clear_insn_labels ();
6288 }
6289
6290 /* This function must be called before we emit something other than
6291    instructions.  It is like mips_no_prev_insn except that it inserts
6292    any NOPS that might be needed by previous instructions.  */
6293
6294 void
6295 mips_emit_delays (void)
6296 {
6297   if (! mips_opts.noreorder)
6298     {
6299       int nops = nops_for_insn (0, history, NULL);
6300       if (nops > 0)
6301         {
6302           while (nops-- > 0)
6303             add_fixed_insn (NOP_INSN);
6304           mips_move_text_labels ();
6305         }
6306     }
6307   mips_no_prev_insn ();
6308 }
6309
6310 /* Start a (possibly nested) noreorder block.  */
6311
6312 static void
6313 start_noreorder (void)
6314 {
6315   if (mips_opts.noreorder == 0)
6316     {
6317       unsigned int i;
6318       int nops;
6319
6320       /* None of the instructions before the .set noreorder can be moved.  */
6321       for (i = 0; i < ARRAY_SIZE (history); i++)
6322         history[i].fixed_p = 1;
6323
6324       /* Insert any nops that might be needed between the .set noreorder
6325          block and the previous instructions.  We will later remove any
6326          nops that turn out not to be needed.  */
6327       nops = nops_for_insn (0, history, NULL);
6328       if (nops > 0)
6329         {
6330           if (mips_optimize != 0)
6331             {
6332               /* Record the frag which holds the nop instructions, so
6333                  that we can remove them if we don't need them.  */
6334               frag_grow (nops * NOP_INSN_SIZE);
6335               prev_nop_frag = frag_now;
6336               prev_nop_frag_holds = nops;
6337               prev_nop_frag_required = 0;
6338               prev_nop_frag_since = 0;
6339             }
6340
6341           for (; nops > 0; --nops)
6342             add_fixed_insn (NOP_INSN);
6343
6344           /* Move on to a new frag, so that it is safe to simply
6345              decrease the size of prev_nop_frag.  */
6346           frag_wane (frag_now);
6347           frag_new (0);
6348           mips_move_text_labels ();
6349         }
6350       mips_mark_labels ();
6351       mips_clear_insn_labels ();
6352     }
6353   mips_opts.noreorder++;
6354   mips_any_noreorder = 1;
6355 }
6356
6357 /* End a nested noreorder block.  */
6358
6359 static void
6360 end_noreorder (void)
6361 {
6362   mips_opts.noreorder--;
6363   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6364     {
6365       /* Commit to inserting prev_nop_frag_required nops and go back to
6366          handling nop insertion the .set reorder way.  */
6367       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6368                                 * NOP_INSN_SIZE);
6369       insert_into_history (prev_nop_frag_since,
6370                            prev_nop_frag_required, NOP_INSN);
6371       prev_nop_frag = NULL;
6372     }
6373 }
6374
6375 /* Set up global variables for the start of a new macro.  */
6376
6377 static void
6378 macro_start (void)
6379 {
6380   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
6381   memset (&mips_macro_warning.first_insn_sizes, 0,
6382           sizeof (mips_macro_warning.first_insn_sizes));
6383   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
6384   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
6385                                      && delayed_branch_p (&history[0]));
6386   switch (history[0].insn_mo->pinfo2
6387           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
6388     {
6389     case INSN2_BRANCH_DELAY_32BIT:
6390       mips_macro_warning.delay_slot_length = 4;
6391       break;
6392     case INSN2_BRANCH_DELAY_16BIT:
6393       mips_macro_warning.delay_slot_length = 2;
6394       break;
6395     default:
6396       mips_macro_warning.delay_slot_length = 0;
6397       break;
6398     }
6399   mips_macro_warning.first_frag = NULL;
6400 }
6401
6402 /* Given that a macro is longer than one instruction or of the wrong size,
6403    return the appropriate warning for it.  Return null if no warning is
6404    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
6405    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
6406    and RELAX_NOMACRO.  */
6407
6408 static const char *
6409 macro_warning (relax_substateT subtype)
6410 {
6411   if (subtype & RELAX_DELAY_SLOT)
6412     return _("Macro instruction expanded into multiple instructions"
6413              " in a branch delay slot");
6414   else if (subtype & RELAX_NOMACRO)
6415     return _("Macro instruction expanded into multiple instructions");
6416   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
6417                       | RELAX_DELAY_SLOT_SIZE_SECOND))
6418     return ((subtype & RELAX_DELAY_SLOT_16BIT)
6419             ? _("Macro instruction expanded into a wrong size instruction"
6420                 " in a 16-bit branch delay slot")
6421             : _("Macro instruction expanded into a wrong size instruction"
6422                 " in a 32-bit branch delay slot"));
6423   else
6424     return 0;
6425 }
6426
6427 /* Finish up a macro.  Emit warnings as appropriate.  */
6428
6429 static void
6430 macro_end (void)
6431 {
6432   /* Relaxation warning flags.  */
6433   relax_substateT subtype = 0;
6434
6435   /* Check delay slot size requirements.  */
6436   if (mips_macro_warning.delay_slot_length == 2)
6437     subtype |= RELAX_DELAY_SLOT_16BIT;
6438   if (mips_macro_warning.delay_slot_length != 0)
6439     {
6440       if (mips_macro_warning.delay_slot_length
6441           != mips_macro_warning.first_insn_sizes[0])
6442         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
6443       if (mips_macro_warning.delay_slot_length
6444           != mips_macro_warning.first_insn_sizes[1])
6445         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
6446     }
6447
6448   /* Check instruction count requirements.  */
6449   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
6450     {
6451       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
6452         subtype |= RELAX_SECOND_LONGER;
6453       if (mips_opts.warn_about_macros)
6454         subtype |= RELAX_NOMACRO;
6455       if (mips_macro_warning.delay_slot_p)
6456         subtype |= RELAX_DELAY_SLOT;
6457     }
6458
6459   /* If both alternatives fail to fill a delay slot correctly,
6460      emit the warning now.  */
6461   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
6462       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
6463     {
6464       relax_substateT s;
6465       const char *msg;
6466
6467       s = subtype & (RELAX_DELAY_SLOT_16BIT
6468                      | RELAX_DELAY_SLOT_SIZE_FIRST
6469                      | RELAX_DELAY_SLOT_SIZE_SECOND);
6470       msg = macro_warning (s);
6471       if (msg != NULL)
6472         as_warn ("%s", msg);
6473       subtype &= ~s;
6474     }
6475
6476   /* If both implementations are longer than 1 instruction, then emit the
6477      warning now.  */
6478   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
6479     {
6480       relax_substateT s;
6481       const char *msg;
6482
6483       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
6484       msg = macro_warning (s);
6485       if (msg != NULL)
6486         as_warn ("%s", msg);
6487       subtype &= ~s;
6488     }
6489
6490   /* If any flags still set, then one implementation might need a warning
6491      and the other either will need one of a different kind or none at all.
6492      Pass any remaining flags over to relaxation.  */
6493   if (mips_macro_warning.first_frag != NULL)
6494     mips_macro_warning.first_frag->fr_subtype |= subtype;
6495 }
6496
6497 /* Instruction operand formats used in macros that vary between
6498    standard MIPS and microMIPS code.  */
6499
6500 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
6501 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
6502 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
6503 static const char * const lui_fmt[2] = { "t,u", "s,u" };
6504 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
6505 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
6506 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
6507 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
6508
6509 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
6510 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
6511 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
6512 #define LUI_FMT (lui_fmt[mips_opts.micromips])
6513 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
6514 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
6515 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
6516 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
6517
6518 /* Read a macro's relocation codes from *ARGS and store them in *R.
6519    The first argument in *ARGS will be either the code for a single
6520    relocation or -1 followed by the three codes that make up a
6521    composite relocation.  */
6522
6523 static void
6524 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
6525 {
6526   int i, next;
6527
6528   next = va_arg (*args, int);
6529   if (next >= 0)
6530     r[0] = (bfd_reloc_code_real_type) next;
6531   else
6532     {
6533       for (i = 0; i < 3; i++)
6534         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
6535       /* This function is only used for 16-bit relocation fields.
6536          To make the macro code simpler, treat an unrelocated value
6537          in the same way as BFD_RELOC_LO16.  */
6538       if (r[0] == BFD_RELOC_UNUSED)
6539         r[0] = BFD_RELOC_LO16;
6540     }
6541 }
6542
6543 /* Build an instruction created by a macro expansion.  This is passed
6544    a pointer to the count of instructions created so far, an
6545    expression, the name of the instruction to build, an operand format
6546    string, and corresponding arguments.  */
6547
6548 static void
6549 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
6550 {
6551   const struct mips_opcode *mo = NULL;
6552   bfd_reloc_code_real_type r[3];
6553   const struct mips_opcode *amo;
6554   const struct mips_operand *operand;
6555   struct hash_control *hash;
6556   struct mips_cl_insn insn;
6557   va_list args;
6558   unsigned int uval;
6559
6560   va_start (args, fmt);
6561
6562   if (mips_opts.mips16)
6563     {
6564       mips16_macro_build (ep, name, fmt, &args);
6565       va_end (args);
6566       return;
6567     }
6568
6569   r[0] = BFD_RELOC_UNUSED;
6570   r[1] = BFD_RELOC_UNUSED;
6571   r[2] = BFD_RELOC_UNUSED;
6572   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
6573   amo = (struct mips_opcode *) hash_find (hash, name);
6574   gas_assert (amo);
6575   gas_assert (strcmp (name, amo->name) == 0);
6576
6577   do
6578     {
6579       /* Search until we get a match for NAME.  It is assumed here that
6580          macros will never generate MDMX, MIPS-3D, or MT instructions.
6581          We try to match an instruction that fulfils the branch delay
6582          slot instruction length requirement (if any) of the previous
6583          instruction.  While doing this we record the first instruction
6584          seen that matches all the other conditions and use it anyway
6585          if the requirement cannot be met; we will issue an appropriate
6586          warning later on.  */
6587       if (strcmp (fmt, amo->args) == 0
6588           && amo->pinfo != INSN_MACRO
6589           && is_opcode_valid (amo)
6590           && is_size_valid (amo))
6591         {
6592           if (is_delay_slot_valid (amo))
6593             {
6594               mo = amo;
6595               break;
6596             }
6597           else if (!mo)
6598             mo = amo;
6599         }
6600
6601       ++amo;
6602       gas_assert (amo->name);
6603     }
6604   while (strcmp (name, amo->name) == 0);
6605
6606   gas_assert (mo);
6607   create_insn (&insn, mo);
6608   for (; *fmt; ++fmt)
6609     {
6610       switch (*fmt)
6611         {
6612         case ',':
6613         case '(':
6614         case ')':
6615         case 'z':
6616           break;
6617
6618         case 'i':
6619         case 'j':
6620           macro_read_relocs (&args, r);
6621           gas_assert (*r == BFD_RELOC_GPREL16
6622                       || *r == BFD_RELOC_MIPS_HIGHER
6623                       || *r == BFD_RELOC_HI16_S
6624                       || *r == BFD_RELOC_LO16
6625                       || *r == BFD_RELOC_MIPS_GOT_OFST);
6626           break;
6627
6628         case 'o':
6629           macro_read_relocs (&args, r);
6630           break;
6631
6632         case 'u':
6633           macro_read_relocs (&args, r);
6634           gas_assert (ep != NULL
6635                       && (ep->X_op == O_constant
6636                           || (ep->X_op == O_symbol
6637                               && (*r == BFD_RELOC_MIPS_HIGHEST
6638                                   || *r == BFD_RELOC_HI16_S
6639                                   || *r == BFD_RELOC_HI16
6640                                   || *r == BFD_RELOC_GPREL16
6641                                   || *r == BFD_RELOC_MIPS_GOT_HI16
6642                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
6643           break;
6644
6645         case 'p':
6646           gas_assert (ep != NULL);
6647
6648           /*
6649            * This allows macro() to pass an immediate expression for
6650            * creating short branches without creating a symbol.
6651            *
6652            * We don't allow branch relaxation for these branches, as
6653            * they should only appear in ".set nomacro" anyway.
6654            */
6655           if (ep->X_op == O_constant)
6656             {
6657               /* For microMIPS we always use relocations for branches.
6658                  So we should not resolve immediate values.  */
6659               gas_assert (!mips_opts.micromips);
6660
6661               if ((ep->X_add_number & 3) != 0)
6662                 as_bad (_("branch to misaligned address (0x%lx)"),
6663                         (unsigned long) ep->X_add_number);
6664               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
6665                 as_bad (_("branch address range overflow (0x%lx)"),
6666                         (unsigned long) ep->X_add_number);
6667               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
6668               ep = NULL;
6669             }
6670           else
6671             *r = BFD_RELOC_16_PCREL_S2;
6672           break;
6673
6674         case 'a':
6675           gas_assert (ep != NULL);
6676           *r = BFD_RELOC_MIPS_JMP;
6677           break;
6678
6679         default:
6680           operand = (mips_opts.micromips
6681                      ? decode_micromips_operand (fmt)
6682                      : decode_mips_operand (fmt));
6683           if (!operand)
6684             abort ();
6685
6686           uval = va_arg (args, int);
6687           if (operand->type == OP_CLO_CLZ_DEST)
6688             uval |= (uval << 5);
6689           insn_insert_operand (&insn, operand, uval);
6690
6691           if (*fmt == '+' || *fmt == 'm')
6692             ++fmt;
6693           break;
6694         }
6695     }
6696   va_end (args);
6697   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6698
6699   append_insn (&insn, ep, r, TRUE);
6700 }
6701
6702 static void
6703 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
6704                     va_list *args)
6705 {
6706   struct mips_opcode *mo;
6707   struct mips_cl_insn insn;
6708   const struct mips_operand *operand;
6709   bfd_reloc_code_real_type r[3]
6710     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
6711
6712   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
6713   gas_assert (mo);
6714   gas_assert (strcmp (name, mo->name) == 0);
6715
6716   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
6717     {
6718       ++mo;
6719       gas_assert (mo->name);
6720       gas_assert (strcmp (name, mo->name) == 0);
6721     }
6722
6723   create_insn (&insn, mo);
6724   for (; *fmt; ++fmt)
6725     {
6726       int c;
6727
6728       c = *fmt;
6729       switch (c)
6730         {
6731         case ',':
6732         case '(':
6733         case ')':
6734           break;
6735
6736         case '0':
6737         case 'S':
6738         case 'P':
6739         case 'R':
6740           break;
6741
6742         case '<':
6743         case '>':
6744         case '4':
6745         case '5':
6746         case 'H':
6747         case 'W':
6748         case 'D':
6749         case 'j':
6750         case '8':
6751         case 'V':
6752         case 'C':
6753         case 'U':
6754         case 'k':
6755         case 'K':
6756         case 'p':
6757         case 'q':
6758           {
6759             offsetT value;
6760
6761             gas_assert (ep != NULL);
6762
6763             if (ep->X_op != O_constant)
6764               *r = (int) BFD_RELOC_UNUSED + c;
6765             else if (calculate_reloc (*r, ep->X_add_number, &value))
6766               {
6767                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
6768                 ep = NULL;
6769                 *r = BFD_RELOC_UNUSED;
6770               }
6771           }
6772           break;
6773
6774         default:
6775           operand = decode_mips16_operand (c, FALSE);
6776           if (!operand)
6777             abort ();
6778
6779           insn_insert_operand (&insn, operand, va_arg (args, int));
6780           break;
6781         }
6782     }
6783
6784   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6785
6786   append_insn (&insn, ep, r, TRUE);
6787 }
6788
6789 /*
6790  * Sign-extend 32-bit mode constants that have bit 31 set and all
6791  * higher bits unset.
6792  */
6793 static void
6794 normalize_constant_expr (expressionS *ex)
6795 {
6796   if (ex->X_op == O_constant
6797       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6798     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6799                         - 0x80000000);
6800 }
6801
6802 /*
6803  * Sign-extend 32-bit mode address offsets that have bit 31 set and
6804  * all higher bits unset.
6805  */
6806 static void
6807 normalize_address_expr (expressionS *ex)
6808 {
6809   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
6810         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
6811       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6812     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6813                         - 0x80000000);
6814 }
6815
6816 /*
6817  * Generate a "jalr" instruction with a relocation hint to the called
6818  * function.  This occurs in NewABI PIC code.
6819  */
6820 static void
6821 macro_build_jalr (expressionS *ep, int cprestore)
6822 {
6823   static const bfd_reloc_code_real_type jalr_relocs[2]
6824     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
6825   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
6826   const char *jalr;
6827   char *f = NULL;
6828
6829   if (MIPS_JALR_HINT_P (ep))
6830     {
6831       frag_grow (8);
6832       f = frag_more (0);
6833     }
6834   if (mips_opts.micromips)
6835     {
6836       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
6837               ? "jalr" : "jalrs");
6838       if (MIPS_JALR_HINT_P (ep)
6839           || mips_opts.insn32
6840           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6841         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
6842       else
6843         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
6844     }
6845   else
6846     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
6847   if (MIPS_JALR_HINT_P (ep))
6848     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
6849 }
6850
6851 /*
6852  * Generate a "lui" instruction.
6853  */
6854 static void
6855 macro_build_lui (expressionS *ep, int regnum)
6856 {
6857   gas_assert (! mips_opts.mips16);
6858
6859   if (ep->X_op != O_constant)
6860     {
6861       gas_assert (ep->X_op == O_symbol);
6862       /* _gp_disp is a special case, used from s_cpload.
6863          __gnu_local_gp is used if mips_no_shared.  */
6864       gas_assert (mips_pic == NO_PIC
6865               || (! HAVE_NEWABI
6866                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
6867               || (! mips_in_shared
6868                   && strcmp (S_GET_NAME (ep->X_add_symbol),
6869                              "__gnu_local_gp") == 0));
6870     }
6871
6872   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
6873 }
6874
6875 /* Generate a sequence of instructions to do a load or store from a constant
6876    offset off of a base register (breg) into/from a target register (treg),
6877    using AT if necessary.  */
6878 static void
6879 macro_build_ldst_constoffset (expressionS *ep, const char *op,
6880                               int treg, int breg, int dbl)
6881 {
6882   gas_assert (ep->X_op == O_constant);
6883
6884   /* Sign-extending 32-bit constants makes their handling easier.  */
6885   if (!dbl)
6886     normalize_constant_expr (ep);
6887
6888   /* Right now, this routine can only handle signed 32-bit constants.  */
6889   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
6890     as_warn (_("operand overflow"));
6891
6892   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
6893     {
6894       /* Signed 16-bit offset will fit in the op.  Easy!  */
6895       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6896     }
6897   else
6898     {
6899       /* 32-bit offset, need multiple instructions and AT, like:
6900            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
6901            addu     $tempreg,$tempreg,$breg
6902            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
6903          to handle the complete offset.  */
6904       macro_build_lui (ep, AT);
6905       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
6906       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
6907
6908       if (!mips_opts.at)
6909         as_bad (_("Macro used $at after \".set noat\""));
6910     }
6911 }
6912
6913 /*                      set_at()
6914  * Generates code to set the $at register to true (one)
6915  * if reg is less than the immediate expression.
6916  */
6917 static void
6918 set_at (int reg, int unsignedp)
6919 {
6920   if (imm_expr.X_op == O_constant
6921       && imm_expr.X_add_number >= -0x8000
6922       && imm_expr.X_add_number < 0x8000)
6923     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
6924                  AT, reg, BFD_RELOC_LO16);
6925   else
6926     {
6927       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6928       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
6929     }
6930 }
6931
6932 /* Count the leading zeroes by performing a binary chop. This is a
6933    bulky bit of source, but performance is a LOT better for the
6934    majority of values than a simple loop to count the bits:
6935        for (lcnt = 0; (lcnt < 32); lcnt++)
6936          if ((v) & (1 << (31 - lcnt)))
6937            break;
6938   However it is not code size friendly, and the gain will drop a bit
6939   on certain cached systems.
6940 */
6941 #define COUNT_TOP_ZEROES(v)             \
6942   (((v) & ~0xffff) == 0                 \
6943    ? ((v) & ~0xff) == 0                 \
6944      ? ((v) & ~0xf) == 0                \
6945        ? ((v) & ~0x3) == 0              \
6946          ? ((v) & ~0x1) == 0            \
6947            ? !(v)                       \
6948              ? 32                       \
6949              : 31                       \
6950            : 30                         \
6951          : ((v) & ~0x7) == 0            \
6952            ? 29                         \
6953            : 28                         \
6954        : ((v) & ~0x3f) == 0             \
6955          ? ((v) & ~0x1f) == 0           \
6956            ? 27                         \
6957            : 26                         \
6958          : ((v) & ~0x7f) == 0           \
6959            ? 25                         \
6960            : 24                         \
6961      : ((v) & ~0xfff) == 0              \
6962        ? ((v) & ~0x3ff) == 0            \
6963          ? ((v) & ~0x1ff) == 0          \
6964            ? 23                         \
6965            : 22                         \
6966          : ((v) & ~0x7ff) == 0          \
6967            ? 21                         \
6968            : 20                         \
6969        : ((v) & ~0x3fff) == 0           \
6970          ? ((v) & ~0x1fff) == 0         \
6971            ? 19                         \
6972            : 18                         \
6973          : ((v) & ~0x7fff) == 0         \
6974            ? 17                         \
6975            : 16                         \
6976    : ((v) & ~0xffffff) == 0             \
6977      ? ((v) & ~0xfffff) == 0            \
6978        ? ((v) & ~0x3ffff) == 0          \
6979          ? ((v) & ~0x1ffff) == 0        \
6980            ? 15                         \
6981            : 14                         \
6982          : ((v) & ~0x7ffff) == 0        \
6983            ? 13                         \
6984            : 12                         \
6985        : ((v) & ~0x3fffff) == 0         \
6986          ? ((v) & ~0x1fffff) == 0       \
6987            ? 11                         \
6988            : 10                         \
6989          : ((v) & ~0x7fffff) == 0       \
6990            ? 9                          \
6991            : 8                          \
6992      : ((v) & ~0xfffffff) == 0          \
6993        ? ((v) & ~0x3ffffff) == 0        \
6994          ? ((v) & ~0x1ffffff) == 0      \
6995            ? 7                          \
6996            : 6                          \
6997          : ((v) & ~0x7ffffff) == 0      \
6998            ? 5                          \
6999            : 4                          \
7000        : ((v) & ~0x3fffffff) == 0       \
7001          ? ((v) & ~0x1fffffff) == 0     \
7002            ? 3                          \
7003            : 2                          \
7004          : ((v) & ~0x7fffffff) == 0     \
7005            ? 1                          \
7006            : 0)
7007
7008 /*                      load_register()
7009  *  This routine generates the least number of instructions necessary to load
7010  *  an absolute expression value into a register.
7011  */
7012 static void
7013 load_register (int reg, expressionS *ep, int dbl)
7014 {
7015   int freg;
7016   expressionS hi32, lo32;
7017
7018   if (ep->X_op != O_big)
7019     {
7020       gas_assert (ep->X_op == O_constant);
7021
7022       /* Sign-extending 32-bit constants makes their handling easier.  */
7023       if (!dbl)
7024         normalize_constant_expr (ep);
7025
7026       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
7027         {
7028           /* We can handle 16 bit signed values with an addiu to
7029              $zero.  No need to ever use daddiu here, since $zero and
7030              the result are always correct in 32 bit mode.  */
7031           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7032           return;
7033         }
7034       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
7035         {
7036           /* We can handle 16 bit unsigned values with an ori to
7037              $zero.  */
7038           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
7039           return;
7040         }
7041       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
7042         {
7043           /* 32 bit values require an lui.  */
7044           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7045           if ((ep->X_add_number & 0xffff) != 0)
7046             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
7047           return;
7048         }
7049     }
7050
7051   /* The value is larger than 32 bits.  */
7052
7053   if (!dbl || HAVE_32BIT_GPRS)
7054     {
7055       char value[32];
7056
7057       sprintf_vma (value, ep->X_add_number);
7058       as_bad (_("Number (0x%s) larger than 32 bits"), value);
7059       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7060       return;
7061     }
7062
7063   if (ep->X_op != O_big)
7064     {
7065       hi32 = *ep;
7066       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
7067       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
7068       hi32.X_add_number &= 0xffffffff;
7069       lo32 = *ep;
7070       lo32.X_add_number &= 0xffffffff;
7071     }
7072   else
7073     {
7074       gas_assert (ep->X_add_number > 2);
7075       if (ep->X_add_number == 3)
7076         generic_bignum[3] = 0;
7077       else if (ep->X_add_number > 4)
7078         as_bad (_("Number larger than 64 bits"));
7079       lo32.X_op = O_constant;
7080       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
7081       hi32.X_op = O_constant;
7082       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
7083     }
7084
7085   if (hi32.X_add_number == 0)
7086     freg = 0;
7087   else
7088     {
7089       int shift, bit;
7090       unsigned long hi, lo;
7091
7092       if (hi32.X_add_number == (offsetT) 0xffffffff)
7093         {
7094           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
7095             {
7096               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7097               return;
7098             }
7099           if (lo32.X_add_number & 0x80000000)
7100             {
7101               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7102               if (lo32.X_add_number & 0xffff)
7103                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
7104               return;
7105             }
7106         }
7107
7108       /* Check for 16bit shifted constant.  We know that hi32 is
7109          non-zero, so start the mask on the first bit of the hi32
7110          value.  */
7111       shift = 17;
7112       do
7113         {
7114           unsigned long himask, lomask;
7115
7116           if (shift < 32)
7117             {
7118               himask = 0xffff >> (32 - shift);
7119               lomask = (0xffff << shift) & 0xffffffff;
7120             }
7121           else
7122             {
7123               himask = 0xffff << (shift - 32);
7124               lomask = 0;
7125             }
7126           if ((hi32.X_add_number & ~(offsetT) himask) == 0
7127               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
7128             {
7129               expressionS tmp;
7130
7131               tmp.X_op = O_constant;
7132               if (shift < 32)
7133                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
7134                                     | (lo32.X_add_number >> shift));
7135               else
7136                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
7137               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
7138               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7139                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7140               return;
7141             }
7142           ++shift;
7143         }
7144       while (shift <= (64 - 16));
7145
7146       /* Find the bit number of the lowest one bit, and store the
7147          shifted value in hi/lo.  */
7148       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
7149       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
7150       if (lo != 0)
7151         {
7152           bit = 0;
7153           while ((lo & 1) == 0)
7154             {
7155               lo >>= 1;
7156               ++bit;
7157             }
7158           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
7159           hi >>= bit;
7160         }
7161       else
7162         {
7163           bit = 32;
7164           while ((hi & 1) == 0)
7165             {
7166               hi >>= 1;
7167               ++bit;
7168             }
7169           lo = hi;
7170           hi = 0;
7171         }
7172
7173       /* Optimize if the shifted value is a (power of 2) - 1.  */
7174       if ((hi == 0 && ((lo + 1) & lo) == 0)
7175           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
7176         {
7177           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
7178           if (shift != 0)
7179             {
7180               expressionS tmp;
7181
7182               /* This instruction will set the register to be all
7183                  ones.  */
7184               tmp.X_op = O_constant;
7185               tmp.X_add_number = (offsetT) -1;
7186               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7187               if (bit != 0)
7188                 {
7189                   bit += shift;
7190                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7191                                reg, reg, (bit >= 32) ? bit - 32 : bit);
7192                 }
7193               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
7194                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7195               return;
7196             }
7197         }
7198
7199       /* Sign extend hi32 before calling load_register, because we can
7200          generally get better code when we load a sign extended value.  */
7201       if ((hi32.X_add_number & 0x80000000) != 0)
7202         hi32.X_add_number |= ~(offsetT) 0xffffffff;
7203       load_register (reg, &hi32, 0);
7204       freg = reg;
7205     }
7206   if ((lo32.X_add_number & 0xffff0000) == 0)
7207     {
7208       if (freg != 0)
7209         {
7210           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
7211           freg = reg;
7212         }
7213     }
7214   else
7215     {
7216       expressionS mid16;
7217
7218       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
7219         {
7220           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7221           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
7222           return;
7223         }
7224
7225       if (freg != 0)
7226         {
7227           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
7228           freg = reg;
7229         }
7230       mid16 = lo32;
7231       mid16.X_add_number >>= 16;
7232       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7233       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7234       freg = reg;
7235     }
7236   if ((lo32.X_add_number & 0xffff) != 0)
7237     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7238 }
7239
7240 static inline void
7241 load_delay_nop (void)
7242 {
7243   if (!gpr_interlocks)
7244     macro_build (NULL, "nop", "");
7245 }
7246
7247 /* Load an address into a register.  */
7248
7249 static void
7250 load_address (int reg, expressionS *ep, int *used_at)
7251 {
7252   if (ep->X_op != O_constant
7253       && ep->X_op != O_symbol)
7254     {
7255       as_bad (_("expression too complex"));
7256       ep->X_op = O_constant;
7257     }
7258
7259   if (ep->X_op == O_constant)
7260     {
7261       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
7262       return;
7263     }
7264
7265   if (mips_pic == NO_PIC)
7266     {
7267       /* If this is a reference to a GP relative symbol, we want
7268            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
7269          Otherwise we want
7270            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
7271            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7272          If we have an addend, we always use the latter form.
7273
7274          With 64bit address space and a usable $at we want
7275            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7276            lui          $at,<sym>               (BFD_RELOC_HI16_S)
7277            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7278            daddiu       $at,<sym>               (BFD_RELOC_LO16)
7279            dsll32       $reg,0
7280            daddu        $reg,$reg,$at
7281
7282          If $at is already in use, we use a path which is suboptimal
7283          on superscalar processors.
7284            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7285            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7286            dsll         $reg,16
7287            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
7288            dsll         $reg,16
7289            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
7290
7291          For GP relative symbols in 64bit address space we can use
7292          the same sequence as in 32bit address space.  */
7293       if (HAVE_64BIT_SYMBOLS)
7294         {
7295           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7296               && !nopic_need_relax (ep->X_add_symbol, 1))
7297             {
7298               relax_start (ep->X_add_symbol);
7299               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7300                            mips_gp_register, BFD_RELOC_GPREL16);
7301               relax_switch ();
7302             }
7303
7304           if (*used_at == 0 && mips_opts.at)
7305             {
7306               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7307               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
7308               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7309                            BFD_RELOC_MIPS_HIGHER);
7310               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
7311               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
7312               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
7313               *used_at = 1;
7314             }
7315           else
7316             {
7317               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7318               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7319                            BFD_RELOC_MIPS_HIGHER);
7320               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7321               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
7322               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7323               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
7324             }
7325
7326           if (mips_relax.sequence)
7327             relax_end ();
7328         }
7329       else
7330         {
7331           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7332               && !nopic_need_relax (ep->X_add_symbol, 1))
7333             {
7334               relax_start (ep->X_add_symbol);
7335               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7336                            mips_gp_register, BFD_RELOC_GPREL16);
7337               relax_switch ();
7338             }
7339           macro_build_lui (ep, reg);
7340           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
7341                        reg, reg, BFD_RELOC_LO16);
7342           if (mips_relax.sequence)
7343             relax_end ();
7344         }
7345     }
7346   else if (!mips_big_got)
7347     {
7348       expressionS ex;
7349
7350       /* If this is a reference to an external symbol, we want
7351            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7352          Otherwise we want
7353            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7354            nop
7355            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7356          If there is a constant, it must be added in after.
7357
7358          If we have NewABI, we want
7359            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7360          unless we're referencing a global symbol with a non-zero
7361          offset, in which case cst must be added separately.  */
7362       if (HAVE_NEWABI)
7363         {
7364           if (ep->X_add_number)
7365             {
7366               ex.X_add_number = ep->X_add_number;
7367               ep->X_add_number = 0;
7368               relax_start (ep->X_add_symbol);
7369               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7370                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7371               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7372                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7373               ex.X_op = O_constant;
7374               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7375                            reg, reg, BFD_RELOC_LO16);
7376               ep->X_add_number = ex.X_add_number;
7377               relax_switch ();
7378             }
7379           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7380                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7381           if (mips_relax.sequence)
7382             relax_end ();
7383         }
7384       else
7385         {
7386           ex.X_add_number = ep->X_add_number;
7387           ep->X_add_number = 0;
7388           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7389                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7390           load_delay_nop ();
7391           relax_start (ep->X_add_symbol);
7392           relax_switch ();
7393           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7394                        BFD_RELOC_LO16);
7395           relax_end ();
7396
7397           if (ex.X_add_number != 0)
7398             {
7399               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7400                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7401               ex.X_op = O_constant;
7402               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7403                            reg, reg, BFD_RELOC_LO16);
7404             }
7405         }
7406     }
7407   else if (mips_big_got)
7408     {
7409       expressionS ex;
7410
7411       /* This is the large GOT case.  If this is a reference to an
7412          external symbol, we want
7413            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
7414            addu         $reg,$reg,$gp
7415            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
7416
7417          Otherwise, for a reference to a local symbol in old ABI, we want
7418            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7419            nop
7420            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7421          If there is a constant, it must be added in after.
7422
7423          In the NewABI, for local symbols, with or without offsets, we want:
7424            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7425            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7426       */
7427       if (HAVE_NEWABI)
7428         {
7429           ex.X_add_number = ep->X_add_number;
7430           ep->X_add_number = 0;
7431           relax_start (ep->X_add_symbol);
7432           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7433           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7434                        reg, reg, mips_gp_register);
7435           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7436                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7437           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7438             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7439           else if (ex.X_add_number)
7440             {
7441               ex.X_op = O_constant;
7442               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7443                            BFD_RELOC_LO16);
7444             }
7445
7446           ep->X_add_number = ex.X_add_number;
7447           relax_switch ();
7448           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7449                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7450           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7451                        BFD_RELOC_MIPS_GOT_OFST);
7452           relax_end ();
7453         }
7454       else
7455         {
7456           ex.X_add_number = ep->X_add_number;
7457           ep->X_add_number = 0;
7458           relax_start (ep->X_add_symbol);
7459           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7460           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7461                        reg, reg, mips_gp_register);
7462           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7463                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7464           relax_switch ();
7465           if (reg_needs_delay (mips_gp_register))
7466             {
7467               /* We need a nop before loading from $gp.  This special
7468                  check is required because the lui which starts the main
7469                  instruction stream does not refer to $gp, and so will not
7470                  insert the nop which may be required.  */
7471               macro_build (NULL, "nop", "");
7472             }
7473           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7474                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7475           load_delay_nop ();
7476           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7477                        BFD_RELOC_LO16);
7478           relax_end ();
7479
7480           if (ex.X_add_number != 0)
7481             {
7482               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7483                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7484               ex.X_op = O_constant;
7485               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7486                            BFD_RELOC_LO16);
7487             }
7488         }
7489     }
7490   else
7491     abort ();
7492
7493   if (!mips_opts.at && *used_at == 1)
7494     as_bad (_("Macro used $at after \".set noat\""));
7495 }
7496
7497 /* Move the contents of register SOURCE into register DEST.  */
7498
7499 static void
7500 move_register (int dest, int source)
7501 {
7502   /* Prefer to use a 16-bit microMIPS instruction unless the previous
7503      instruction specifically requires a 32-bit one.  */
7504   if (mips_opts.micromips
7505       && !mips_opts.insn32
7506       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7507     macro_build (NULL, "move", "mp,mj", dest, source);
7508   else
7509     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
7510                  dest, source, 0);
7511 }
7512
7513 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
7514    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
7515    The two alternatives are:
7516
7517    Global symbol                Local sybmol
7518    -------------                ------------
7519    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
7520    ...                          ...
7521    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
7522
7523    load_got_offset emits the first instruction and add_got_offset
7524    emits the second for a 16-bit offset or add_got_offset_hilo emits
7525    a sequence to add a 32-bit offset using a scratch register.  */
7526
7527 static void
7528 load_got_offset (int dest, expressionS *local)
7529 {
7530   expressionS global;
7531
7532   global = *local;
7533   global.X_add_number = 0;
7534
7535   relax_start (local->X_add_symbol);
7536   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7537                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7538   relax_switch ();
7539   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7540                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7541   relax_end ();
7542 }
7543
7544 static void
7545 add_got_offset (int dest, expressionS *local)
7546 {
7547   expressionS global;
7548
7549   global.X_op = O_constant;
7550   global.X_op_symbol = NULL;
7551   global.X_add_symbol = NULL;
7552   global.X_add_number = local->X_add_number;
7553
7554   relax_start (local->X_add_symbol);
7555   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
7556                dest, dest, BFD_RELOC_LO16);
7557   relax_switch ();
7558   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
7559   relax_end ();
7560 }
7561
7562 static void
7563 add_got_offset_hilo (int dest, expressionS *local, int tmp)
7564 {
7565   expressionS global;
7566   int hold_mips_optimize;
7567
7568   global.X_op = O_constant;
7569   global.X_op_symbol = NULL;
7570   global.X_add_symbol = NULL;
7571   global.X_add_number = local->X_add_number;
7572
7573   relax_start (local->X_add_symbol);
7574   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
7575   relax_switch ();
7576   /* Set mips_optimize around the lui instruction to avoid
7577      inserting an unnecessary nop after the lw.  */
7578   hold_mips_optimize = mips_optimize;
7579   mips_optimize = 2;
7580   macro_build_lui (&global, tmp);
7581   mips_optimize = hold_mips_optimize;
7582   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
7583   relax_end ();
7584
7585   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
7586 }
7587
7588 /* Emit a sequence of instructions to emulate a branch likely operation.
7589    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
7590    is its complementing branch with the original condition negated.
7591    CALL is set if the original branch specified the link operation.
7592    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
7593
7594    Code like this is produced in the noreorder mode:
7595
7596         BRNEG   <args>, 1f
7597          nop
7598         b       <sym>
7599          delay slot (executed only if branch taken)
7600     1:
7601
7602    or, if CALL is set:
7603
7604         BRNEG   <args>, 1f
7605          nop
7606         bal     <sym>
7607          delay slot (executed only if branch taken)
7608     1:
7609
7610    In the reorder mode the delay slot would be filled with a nop anyway,
7611    so code produced is simply:
7612
7613         BR      <args>, <sym>
7614          nop
7615
7616    This function is used when producing code for the microMIPS ASE that
7617    does not implement branch likely instructions in hardware.  */
7618
7619 static void
7620 macro_build_branch_likely (const char *br, const char *brneg,
7621                            int call, expressionS *ep, const char *fmt,
7622                            unsigned int sreg, unsigned int treg)
7623 {
7624   int noreorder = mips_opts.noreorder;
7625   expressionS expr1;
7626
7627   gas_assert (mips_opts.micromips);
7628   start_noreorder ();
7629   if (noreorder)
7630     {
7631       micromips_label_expr (&expr1);
7632       macro_build (&expr1, brneg, fmt, sreg, treg);
7633       macro_build (NULL, "nop", "");
7634       macro_build (ep, call ? "bal" : "b", "p");
7635
7636       /* Set to true so that append_insn adds a label.  */
7637       emit_branch_likely_macro = TRUE;
7638     }
7639   else
7640     {
7641       macro_build (ep, br, fmt, sreg, treg);
7642       macro_build (NULL, "nop", "");
7643     }
7644   end_noreorder ();
7645 }
7646
7647 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
7648    the condition code tested.  EP specifies the branch target.  */
7649
7650 static void
7651 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
7652 {
7653   const int call = 0;
7654   const char *brneg;
7655   const char *br;
7656
7657   switch (type)
7658     {
7659     case M_BC1FL:
7660       br = "bc1f";
7661       brneg = "bc1t";
7662       break;
7663     case M_BC1TL:
7664       br = "bc1t";
7665       brneg = "bc1f";
7666       break;
7667     case M_BC2FL:
7668       br = "bc2f";
7669       brneg = "bc2t";
7670       break;
7671     case M_BC2TL:
7672       br = "bc2t";
7673       brneg = "bc2f";
7674       break;
7675     default:
7676       abort ();
7677     }
7678   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
7679 }
7680
7681 /* Emit a two-argument branch macro specified by TYPE, using SREG as
7682    the register tested.  EP specifies the branch target.  */
7683
7684 static void
7685 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
7686 {
7687   const char *brneg = NULL;
7688   const char *br;
7689   int call = 0;
7690
7691   switch (type)
7692     {
7693     case M_BGEZ:
7694       br = "bgez";
7695       break;
7696     case M_BGEZL:
7697       br = mips_opts.micromips ? "bgez" : "bgezl";
7698       brneg = "bltz";
7699       break;
7700     case M_BGEZALL:
7701       gas_assert (mips_opts.micromips);
7702       br = mips_opts.insn32 ? "bgezal" : "bgezals";
7703       brneg = "bltz";
7704       call = 1;
7705       break;
7706     case M_BGTZ:
7707       br = "bgtz";
7708       break;
7709     case M_BGTZL:
7710       br = mips_opts.micromips ? "bgtz" : "bgtzl";
7711       brneg = "blez";
7712       break;
7713     case M_BLEZ:
7714       br = "blez";
7715       break;
7716     case M_BLEZL:
7717       br = mips_opts.micromips ? "blez" : "blezl";
7718       brneg = "bgtz";
7719       break;
7720     case M_BLTZ:
7721       br = "bltz";
7722       break;
7723     case M_BLTZL:
7724       br = mips_opts.micromips ? "bltz" : "bltzl";
7725       brneg = "bgez";
7726       break;
7727     case M_BLTZALL:
7728       gas_assert (mips_opts.micromips);
7729       br = mips_opts.insn32 ? "bltzal" : "bltzals";
7730       brneg = "bgez";
7731       call = 1;
7732       break;
7733     default:
7734       abort ();
7735     }
7736   if (mips_opts.micromips && brneg)
7737     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
7738   else
7739     macro_build (ep, br, "s,p", sreg);
7740 }
7741
7742 /* Emit a three-argument branch macro specified by TYPE, using SREG and
7743    TREG as the registers tested.  EP specifies the branch target.  */
7744
7745 static void
7746 macro_build_branch_rsrt (int type, expressionS *ep,
7747                          unsigned int sreg, unsigned int treg)
7748 {
7749   const char *brneg = NULL;
7750   const int call = 0;
7751   const char *br;
7752
7753   switch (type)
7754     {
7755     case M_BEQ:
7756     case M_BEQ_I:
7757       br = "beq";
7758       break;
7759     case M_BEQL:
7760     case M_BEQL_I:
7761       br = mips_opts.micromips ? "beq" : "beql";
7762       brneg = "bne";
7763       break;
7764     case M_BNE:
7765     case M_BNE_I:
7766       br = "bne";
7767       break;
7768     case M_BNEL:
7769     case M_BNEL_I:
7770       br = mips_opts.micromips ? "bne" : "bnel";
7771       brneg = "beq";
7772       break;
7773     default:
7774       abort ();
7775     }
7776   if (mips_opts.micromips && brneg)
7777     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
7778   else
7779     macro_build (ep, br, "s,t,p", sreg, treg);
7780 }
7781
7782 /* Return the high part that should be loaded in order to make the low
7783    part of VALUE accessible using an offset of OFFBITS bits.  */
7784
7785 static offsetT
7786 offset_high_part (offsetT value, unsigned int offbits)
7787 {
7788   offsetT bias;
7789   addressT low_mask;
7790
7791   if (offbits == 0)
7792     return value;
7793   bias = 1 << (offbits - 1);
7794   low_mask = bias * 2 - 1;
7795   return (value + bias) & ~low_mask;
7796 }
7797
7798 /* Return true if the value stored in offset_expr and offset_reloc
7799    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
7800    amount that the caller wants to add without inducing overflow
7801    and ALIGN is the known alignment of the value in bytes.  */
7802
7803 static bfd_boolean
7804 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
7805 {
7806   if (offbits == 16)
7807     {
7808       /* Accept any relocation operator if overflow isn't a concern.  */
7809       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
7810         return TRUE;
7811
7812       /* These relocations are guaranteed not to overflow in correct links.  */
7813       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
7814           || gprel16_reloc_p (*offset_reloc))
7815         return TRUE;
7816     }
7817   if (offset_expr.X_op == O_constant
7818       && offset_high_part (offset_expr.X_add_number, offbits) == 0
7819       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
7820     return TRUE;
7821   return FALSE;
7822 }
7823
7824 /*
7825  *                      Build macros
7826  *   This routine implements the seemingly endless macro or synthesized
7827  * instructions and addressing modes in the mips assembly language. Many
7828  * of these macros are simple and are similar to each other. These could
7829  * probably be handled by some kind of table or grammar approach instead of
7830  * this verbose method. Others are not simple macros but are more like
7831  * optimizing code generation.
7832  *   One interesting optimization is when several store macros appear
7833  * consecutively that would load AT with the upper half of the same address.
7834  * The ensuing load upper instructions are ommited. This implies some kind
7835  * of global optimization. We currently only optimize within a single macro.
7836  *   For many of the load and store macros if the address is specified as a
7837  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
7838  * first load register 'at' with zero and use it as the base register. The
7839  * mips assembler simply uses register $zero. Just one tiny optimization
7840  * we're missing.
7841  */
7842 static void
7843 macro (struct mips_cl_insn *ip, char *str)
7844 {
7845   unsigned int treg, sreg, dreg, breg;
7846   unsigned int tempreg;
7847   int mask;
7848   int used_at = 0;
7849   expressionS label_expr;
7850   expressionS expr1;
7851   expressionS *ep;
7852   const char *s;
7853   const char *s2;
7854   const char *fmt;
7855   int likely = 0;
7856   int coproc = 0;
7857   int offbits = 16;
7858   int call = 0;
7859   int jals = 0;
7860   int dbl = 0;
7861   int imm = 0;
7862   int ust = 0;
7863   int lp = 0;
7864   bfd_boolean large_offset;
7865   int off;
7866   int hold_mips_optimize;
7867   unsigned int align;
7868
7869   gas_assert (! mips_opts.mips16);
7870
7871   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
7872   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
7873   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
7874   mask = ip->insn_mo->mask;
7875
7876   label_expr.X_op = O_constant;
7877   label_expr.X_op_symbol = NULL;
7878   label_expr.X_add_symbol = NULL;
7879   label_expr.X_add_number = 0;
7880
7881   expr1.X_op = O_constant;
7882   expr1.X_op_symbol = NULL;
7883   expr1.X_add_symbol = NULL;
7884   expr1.X_add_number = 1;
7885   align = 1;
7886
7887   switch (mask)
7888     {
7889     case M_DABS:
7890       dbl = 1;
7891     case M_ABS:
7892       /*    bgez    $a0,1f
7893             move    v0,$a0
7894             sub     v0,$zero,$a0
7895          1:
7896        */
7897
7898       start_noreorder ();
7899
7900       if (mips_opts.micromips)
7901         micromips_label_expr (&label_expr);
7902       else
7903         label_expr.X_add_number = 8;
7904       macro_build (&label_expr, "bgez", "s,p", sreg);
7905       if (dreg == sreg)
7906         macro_build (NULL, "nop", "");
7907       else
7908         move_register (dreg, sreg);
7909       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
7910       if (mips_opts.micromips)
7911         micromips_add_label ();
7912
7913       end_noreorder ();
7914       break;
7915
7916     case M_ADD_I:
7917       s = "addi";
7918       s2 = "add";
7919       goto do_addi;
7920     case M_ADDU_I:
7921       s = "addiu";
7922       s2 = "addu";
7923       goto do_addi;
7924     case M_DADD_I:
7925       dbl = 1;
7926       s = "daddi";
7927       s2 = "dadd";
7928       if (!mips_opts.micromips)
7929         goto do_addi;
7930       if (imm_expr.X_op == O_constant
7931           && imm_expr.X_add_number >= -0x200
7932           && imm_expr.X_add_number < 0x200)
7933         {
7934           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
7935           break;
7936         }
7937       goto do_addi_i;
7938     case M_DADDU_I:
7939       dbl = 1;
7940       s = "daddiu";
7941       s2 = "daddu";
7942     do_addi:
7943       if (imm_expr.X_op == O_constant
7944           && imm_expr.X_add_number >= -0x8000
7945           && imm_expr.X_add_number < 0x8000)
7946         {
7947           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
7948           break;
7949         }
7950     do_addi_i:
7951       used_at = 1;
7952       load_register (AT, &imm_expr, dbl);
7953       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7954       break;
7955
7956     case M_AND_I:
7957       s = "andi";
7958       s2 = "and";
7959       goto do_bit;
7960     case M_OR_I:
7961       s = "ori";
7962       s2 = "or";
7963       goto do_bit;
7964     case M_NOR_I:
7965       s = "";
7966       s2 = "nor";
7967       goto do_bit;
7968     case M_XOR_I:
7969       s = "xori";
7970       s2 = "xor";
7971     do_bit:
7972       if (imm_expr.X_op == O_constant
7973           && imm_expr.X_add_number >= 0
7974           && imm_expr.X_add_number < 0x10000)
7975         {
7976           if (mask != M_NOR_I)
7977             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
7978           else
7979             {
7980               macro_build (&imm_expr, "ori", "t,r,i",
7981                            treg, sreg, BFD_RELOC_LO16);
7982               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
7983             }
7984           break;
7985         }
7986
7987       used_at = 1;
7988       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7989       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7990       break;
7991
7992     case M_BALIGN:
7993       switch (imm_expr.X_add_number)
7994         {
7995         case 0:
7996           macro_build (NULL, "nop", "");
7997           break;
7998         case 2:
7999           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
8000           break;
8001         case 1:
8002         case 3:
8003           macro_build (NULL, "balign", "t,s,2", treg, sreg,
8004                        (int) imm_expr.X_add_number);
8005           break;
8006         default:
8007           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
8008                   (unsigned long) imm_expr.X_add_number);
8009           break;
8010         }
8011       break;
8012
8013     case M_BC1FL:
8014     case M_BC1TL:
8015     case M_BC2FL:
8016     case M_BC2TL:
8017       gas_assert (mips_opts.micromips);
8018       macro_build_branch_ccl (mask, &offset_expr,
8019                               EXTRACT_OPERAND (1, BCC, *ip));
8020       break;
8021
8022     case M_BEQ_I:
8023     case M_BEQL_I:
8024     case M_BNE_I:
8025     case M_BNEL_I:
8026       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8027         treg = 0;
8028       else
8029         {
8030           treg = AT;
8031           used_at = 1;
8032           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
8033         }
8034       /* Fall through.  */
8035     case M_BEQL:
8036     case M_BNEL:
8037       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
8038       break;
8039
8040     case M_BGEL:
8041       likely = 1;
8042     case M_BGE:
8043       if (treg == 0)
8044         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
8045       else if (sreg == 0)
8046         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
8047       else
8048         {
8049           used_at = 1;
8050           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
8051           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8052                                    &offset_expr, AT, ZERO);
8053         }
8054       break;
8055
8056     case M_BGEZL:
8057     case M_BGEZALL:
8058     case M_BGTZL:
8059     case M_BLEZL:
8060     case M_BLTZL:
8061     case M_BLTZALL:
8062       macro_build_branch_rs (mask, &offset_expr, sreg);
8063       break;
8064
8065     case M_BGTL_I:
8066       likely = 1;
8067     case M_BGT_I:
8068       /* Check for > max integer.  */
8069       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8070         {
8071         do_false:
8072           /* Result is always false.  */
8073           if (! likely)
8074             macro_build (NULL, "nop", "");
8075           else
8076             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
8077           break;
8078         }
8079       if (imm_expr.X_op != O_constant)
8080         as_bad (_("Unsupported large constant"));
8081       ++imm_expr.X_add_number;
8082       /* FALLTHROUGH */
8083     case M_BGE_I:
8084     case M_BGEL_I:
8085       if (mask == M_BGEL_I)
8086         likely = 1;
8087       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8088         {
8089           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
8090                                  &offset_expr, sreg);
8091           break;
8092         }
8093       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8094         {
8095           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
8096                                  &offset_expr, sreg);
8097           break;
8098         }
8099       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
8100         {
8101         do_true:
8102           /* result is always true */
8103           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
8104           macro_build (&offset_expr, "b", "p");
8105           break;
8106         }
8107       used_at = 1;
8108       set_at (sreg, 0);
8109       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8110                                &offset_expr, AT, ZERO);
8111       break;
8112
8113     case M_BGEUL:
8114       likely = 1;
8115     case M_BGEU:
8116       if (treg == 0)
8117         goto do_true;
8118       else if (sreg == 0)
8119         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8120                                  &offset_expr, ZERO, treg);
8121       else
8122         {
8123           used_at = 1;
8124           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
8125           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8126                                    &offset_expr, AT, ZERO);
8127         }
8128       break;
8129
8130     case M_BGTUL_I:
8131       likely = 1;
8132     case M_BGTU_I:
8133       if (sreg == 0
8134           || (HAVE_32BIT_GPRS
8135               && imm_expr.X_op == O_constant
8136               && imm_expr.X_add_number == -1))
8137         goto do_false;
8138       if (imm_expr.X_op != O_constant)
8139         as_bad (_("Unsupported large constant"));
8140       ++imm_expr.X_add_number;
8141       /* FALLTHROUGH */
8142     case M_BGEU_I:
8143     case M_BGEUL_I:
8144       if (mask == M_BGEUL_I)
8145         likely = 1;
8146       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8147         goto do_true;
8148       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8149         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8150                                  &offset_expr, sreg, ZERO);
8151       else
8152         {
8153           used_at = 1;
8154           set_at (sreg, 1);
8155           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8156                                    &offset_expr, AT, ZERO);
8157         }
8158       break;
8159
8160     case M_BGTL:
8161       likely = 1;
8162     case M_BGT:
8163       if (treg == 0)
8164         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
8165       else if (sreg == 0)
8166         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
8167       else
8168         {
8169           used_at = 1;
8170           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8171           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8172                                    &offset_expr, AT, ZERO);
8173         }
8174       break;
8175
8176     case M_BGTUL:
8177       likely = 1;
8178     case M_BGTU:
8179       if (treg == 0)
8180         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8181                                  &offset_expr, sreg, ZERO);
8182       else if (sreg == 0)
8183         goto do_false;
8184       else
8185         {
8186           used_at = 1;
8187           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8188           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8189                                    &offset_expr, AT, ZERO);
8190         }
8191       break;
8192
8193     case M_BLEL:
8194       likely = 1;
8195     case M_BLE:
8196       if (treg == 0)
8197         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8198       else if (sreg == 0)
8199         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
8200       else
8201         {
8202           used_at = 1;
8203           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
8204           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8205                                    &offset_expr, AT, ZERO);
8206         }
8207       break;
8208
8209     case M_BLEL_I:
8210       likely = 1;
8211     case M_BLE_I:
8212       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8213         goto do_true;
8214       if (imm_expr.X_op != O_constant)
8215         as_bad (_("Unsupported large constant"));
8216       ++imm_expr.X_add_number;
8217       /* FALLTHROUGH */
8218     case M_BLT_I:
8219     case M_BLTL_I:
8220       if (mask == M_BLTL_I)
8221         likely = 1;
8222       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8223         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8224       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8225         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
8226       else
8227         {
8228           used_at = 1;
8229           set_at (sreg, 0);
8230           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8231                                    &offset_expr, AT, ZERO);
8232         }
8233       break;
8234
8235     case M_BLEUL:
8236       likely = 1;
8237     case M_BLEU:
8238       if (treg == 0)
8239         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8240                                  &offset_expr, sreg, ZERO);
8241       else if (sreg == 0)
8242         goto do_true;
8243       else
8244         {
8245           used_at = 1;
8246           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
8247           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8248                                    &offset_expr, AT, ZERO);
8249         }
8250       break;
8251
8252     case M_BLEUL_I:
8253       likely = 1;
8254     case M_BLEU_I:
8255       if (sreg == 0
8256           || (HAVE_32BIT_GPRS
8257               && imm_expr.X_op == O_constant
8258               && imm_expr.X_add_number == -1))
8259         goto do_true;
8260       if (imm_expr.X_op != O_constant)
8261         as_bad (_("Unsupported large constant"));
8262       ++imm_expr.X_add_number;
8263       /* FALLTHROUGH */
8264     case M_BLTU_I:
8265     case M_BLTUL_I:
8266       if (mask == M_BLTUL_I)
8267         likely = 1;
8268       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8269         goto do_false;
8270       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8271         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8272                                  &offset_expr, sreg, ZERO);
8273       else
8274         {
8275           used_at = 1;
8276           set_at (sreg, 1);
8277           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8278                                    &offset_expr, AT, ZERO);
8279         }
8280       break;
8281
8282     case M_BLTL:
8283       likely = 1;
8284     case M_BLT:
8285       if (treg == 0)
8286         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8287       else if (sreg == 0)
8288         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
8289       else
8290         {
8291           used_at = 1;
8292           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
8293           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8294                                    &offset_expr, AT, ZERO);
8295         }
8296       break;
8297
8298     case M_BLTUL:
8299       likely = 1;
8300     case M_BLTU:
8301       if (treg == 0)
8302         goto do_false;
8303       else if (sreg == 0)
8304         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8305                                  &offset_expr, ZERO, treg);
8306       else
8307         {
8308           used_at = 1;
8309           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
8310           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8311                                    &offset_expr, AT, ZERO);
8312         }
8313       break;
8314
8315     case M_DEXT:
8316       {
8317         /* Use unsigned arithmetic.  */
8318         addressT pos;
8319         addressT size;
8320
8321         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8322           {
8323             as_bad (_("Unsupported large constant"));
8324             pos = size = 1;
8325           }
8326         else
8327           {
8328             pos = imm_expr.X_add_number;
8329             size = imm2_expr.X_add_number;
8330           }
8331
8332         if (pos > 63)
8333           {
8334             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8335             pos = 1;
8336           }
8337         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8338           {
8339             report_bad_field (pos, size);
8340             size = 1;
8341           }
8342
8343         if (size <= 32 && pos < 32)
8344           {
8345             s = "dext";
8346             fmt = "t,r,+A,+C";
8347           }
8348         else if (size <= 32)
8349           {
8350             s = "dextu";
8351             fmt = "t,r,+E,+H";
8352           }
8353         else
8354           {
8355             s = "dextm";
8356             fmt = "t,r,+A,+G";
8357           }
8358         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8359                      (int) (size - 1));
8360       }
8361       break;
8362
8363     case M_DINS:
8364       {
8365         /* Use unsigned arithmetic.  */
8366         addressT pos;
8367         addressT size;
8368
8369         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8370           {
8371             as_bad (_("Unsupported large constant"));
8372             pos = size = 1;
8373           }
8374         else
8375           {
8376             pos = imm_expr.X_add_number;
8377             size = imm2_expr.X_add_number;
8378           }
8379
8380         if (pos > 63)
8381           {
8382             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8383             pos = 1;
8384           }
8385         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8386           {
8387             report_bad_field (pos, size);
8388             size = 1;
8389           }
8390
8391         if (pos < 32 && (pos + size - 1) < 32)
8392           {
8393             s = "dins";
8394             fmt = "t,r,+A,+B";
8395           }
8396         else if (pos >= 32)
8397           {
8398             s = "dinsu";
8399             fmt = "t,r,+E,+F";
8400           }
8401         else
8402           {
8403             s = "dinsm";
8404             fmt = "t,r,+A,+F";
8405           }
8406         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8407                      (int) (pos + size - 1));
8408       }
8409       break;
8410
8411     case M_DDIV_3:
8412       dbl = 1;
8413     case M_DIV_3:
8414       s = "mflo";
8415       goto do_div3;
8416     case M_DREM_3:
8417       dbl = 1;
8418     case M_REM_3:
8419       s = "mfhi";
8420     do_div3:
8421       if (treg == 0)
8422         {
8423           as_warn (_("Divide by zero."));
8424           if (mips_trap)
8425             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8426           else
8427             macro_build (NULL, "break", BRK_FMT, 7);
8428           break;
8429         }
8430
8431       start_noreorder ();
8432       if (mips_trap)
8433         {
8434           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8435           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8436         }
8437       else
8438         {
8439           if (mips_opts.micromips)
8440             micromips_label_expr (&label_expr);
8441           else
8442             label_expr.X_add_number = 8;
8443           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8444           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8445           macro_build (NULL, "break", BRK_FMT, 7);
8446           if (mips_opts.micromips)
8447             micromips_add_label ();
8448         }
8449       expr1.X_add_number = -1;
8450       used_at = 1;
8451       load_register (AT, &expr1, dbl);
8452       if (mips_opts.micromips)
8453         micromips_label_expr (&label_expr);
8454       else
8455         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
8456       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
8457       if (dbl)
8458         {
8459           expr1.X_add_number = 1;
8460           load_register (AT, &expr1, dbl);
8461           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
8462         }
8463       else
8464         {
8465           expr1.X_add_number = 0x80000000;
8466           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
8467         }
8468       if (mips_trap)
8469         {
8470           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
8471           /* We want to close the noreorder block as soon as possible, so
8472              that later insns are available for delay slot filling.  */
8473           end_noreorder ();
8474         }
8475       else
8476         {
8477           if (mips_opts.micromips)
8478             micromips_label_expr (&label_expr);
8479           else
8480             label_expr.X_add_number = 8;
8481           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
8482           macro_build (NULL, "nop", "");
8483
8484           /* We want to close the noreorder block as soon as possible, so
8485              that later insns are available for delay slot filling.  */
8486           end_noreorder ();
8487
8488           macro_build (NULL, "break", BRK_FMT, 6);
8489         }
8490       if (mips_opts.micromips)
8491         micromips_add_label ();
8492       macro_build (NULL, s, MFHL_FMT, dreg);
8493       break;
8494
8495     case M_DIV_3I:
8496       s = "div";
8497       s2 = "mflo";
8498       goto do_divi;
8499     case M_DIVU_3I:
8500       s = "divu";
8501       s2 = "mflo";
8502       goto do_divi;
8503     case M_REM_3I:
8504       s = "div";
8505       s2 = "mfhi";
8506       goto do_divi;
8507     case M_REMU_3I:
8508       s = "divu";
8509       s2 = "mfhi";
8510       goto do_divi;
8511     case M_DDIV_3I:
8512       dbl = 1;
8513       s = "ddiv";
8514       s2 = "mflo";
8515       goto do_divi;
8516     case M_DDIVU_3I:
8517       dbl = 1;
8518       s = "ddivu";
8519       s2 = "mflo";
8520       goto do_divi;
8521     case M_DREM_3I:
8522       dbl = 1;
8523       s = "ddiv";
8524       s2 = "mfhi";
8525       goto do_divi;
8526     case M_DREMU_3I:
8527       dbl = 1;
8528       s = "ddivu";
8529       s2 = "mfhi";
8530     do_divi:
8531       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8532         {
8533           as_warn (_("Divide by zero."));
8534           if (mips_trap)
8535             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8536           else
8537             macro_build (NULL, "break", BRK_FMT, 7);
8538           break;
8539         }
8540       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8541         {
8542           if (strcmp (s2, "mflo") == 0)
8543             move_register (dreg, sreg);
8544           else
8545             move_register (dreg, ZERO);
8546           break;
8547         }
8548       if (imm_expr.X_op == O_constant
8549           && imm_expr.X_add_number == -1
8550           && s[strlen (s) - 1] != 'u')
8551         {
8552           if (strcmp (s2, "mflo") == 0)
8553             {
8554               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
8555             }
8556           else
8557             move_register (dreg, ZERO);
8558           break;
8559         }
8560
8561       used_at = 1;
8562       load_register (AT, &imm_expr, dbl);
8563       macro_build (NULL, s, "z,s,t", sreg, AT);
8564       macro_build (NULL, s2, MFHL_FMT, dreg);
8565       break;
8566
8567     case M_DIVU_3:
8568       s = "divu";
8569       s2 = "mflo";
8570       goto do_divu3;
8571     case M_REMU_3:
8572       s = "divu";
8573       s2 = "mfhi";
8574       goto do_divu3;
8575     case M_DDIVU_3:
8576       s = "ddivu";
8577       s2 = "mflo";
8578       goto do_divu3;
8579     case M_DREMU_3:
8580       s = "ddivu";
8581       s2 = "mfhi";
8582     do_divu3:
8583       start_noreorder ();
8584       if (mips_trap)
8585         {
8586           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8587           macro_build (NULL, s, "z,s,t", sreg, treg);
8588           /* We want to close the noreorder block as soon as possible, so
8589              that later insns are available for delay slot filling.  */
8590           end_noreorder ();
8591         }
8592       else
8593         {
8594           if (mips_opts.micromips)
8595             micromips_label_expr (&label_expr);
8596           else
8597             label_expr.X_add_number = 8;
8598           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8599           macro_build (NULL, s, "z,s,t", sreg, treg);
8600
8601           /* We want to close the noreorder block as soon as possible, so
8602              that later insns are available for delay slot filling.  */
8603           end_noreorder ();
8604           macro_build (NULL, "break", BRK_FMT, 7);
8605           if (mips_opts.micromips)
8606             micromips_add_label ();
8607         }
8608       macro_build (NULL, s2, MFHL_FMT, dreg);
8609       break;
8610
8611     case M_DLCA_AB:
8612       dbl = 1;
8613     case M_LCA_AB:
8614       call = 1;
8615       goto do_la;
8616     case M_DLA_AB:
8617       dbl = 1;
8618     case M_LA_AB:
8619     do_la:
8620       /* Load the address of a symbol into a register.  If breg is not
8621          zero, we then add a base register to it.  */
8622
8623       if (dbl && HAVE_32BIT_GPRS)
8624         as_warn (_("dla used to load 32-bit register"));
8625
8626       if (!dbl && HAVE_64BIT_OBJECTS)
8627         as_warn (_("la used to load 64-bit address"));
8628
8629       if (small_offset_p (0, align, 16))
8630         {
8631           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
8632                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8633           break;
8634         }
8635
8636       if (mips_opts.at && (treg == breg))
8637         {
8638           tempreg = AT;
8639           used_at = 1;
8640         }
8641       else
8642         {
8643           tempreg = treg;
8644         }
8645
8646       if (offset_expr.X_op != O_symbol
8647           && offset_expr.X_op != O_constant)
8648         {
8649           as_bad (_("Expression too complex"));
8650           offset_expr.X_op = O_constant;
8651         }
8652
8653       if (offset_expr.X_op == O_constant)
8654         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
8655       else if (mips_pic == NO_PIC)
8656         {
8657           /* If this is a reference to a GP relative symbol, we want
8658                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
8659              Otherwise we want
8660                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8661                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8662              If we have a constant, we need two instructions anyhow,
8663              so we may as well always use the latter form.
8664
8665              With 64bit address space and a usable $at we want
8666                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8667                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8668                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8669                daddiu   $at,<sym>               (BFD_RELOC_LO16)
8670                dsll32   $tempreg,0
8671                daddu    $tempreg,$tempreg,$at
8672
8673              If $at is already in use, we use a path which is suboptimal
8674              on superscalar processors.
8675                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8676                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8677                dsll     $tempreg,16
8678                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8679                dsll     $tempreg,16
8680                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
8681
8682              For GP relative symbols in 64bit address space we can use
8683              the same sequence as in 32bit address space.  */
8684           if (HAVE_64BIT_SYMBOLS)
8685             {
8686               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8687                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8688                 {
8689                   relax_start (offset_expr.X_add_symbol);
8690                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8691                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8692                   relax_switch ();
8693                 }
8694
8695               if (used_at == 0 && mips_opts.at)
8696                 {
8697                   macro_build (&offset_expr, "lui", LUI_FMT,
8698                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8699                   macro_build (&offset_expr, "lui", LUI_FMT,
8700                                AT, BFD_RELOC_HI16_S);
8701                   macro_build (&offset_expr, "daddiu", "t,r,j",
8702                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8703                   macro_build (&offset_expr, "daddiu", "t,r,j",
8704                                AT, AT, BFD_RELOC_LO16);
8705                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8706                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8707                   used_at = 1;
8708                 }
8709               else
8710                 {
8711                   macro_build (&offset_expr, "lui", LUI_FMT,
8712                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8713                   macro_build (&offset_expr, "daddiu", "t,r,j",
8714                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8715                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8716                   macro_build (&offset_expr, "daddiu", "t,r,j",
8717                                tempreg, tempreg, BFD_RELOC_HI16_S);
8718                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8719                   macro_build (&offset_expr, "daddiu", "t,r,j",
8720                                tempreg, tempreg, BFD_RELOC_LO16);
8721                 }
8722
8723               if (mips_relax.sequence)
8724                 relax_end ();
8725             }
8726           else
8727             {
8728               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8729                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8730                 {
8731                   relax_start (offset_expr.X_add_symbol);
8732                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8733                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8734                   relax_switch ();
8735                 }
8736               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8737                 as_bad (_("Offset too large"));
8738               macro_build_lui (&offset_expr, tempreg);
8739               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8740                            tempreg, tempreg, BFD_RELOC_LO16);
8741               if (mips_relax.sequence)
8742                 relax_end ();
8743             }
8744         }
8745       else if (!mips_big_got && !HAVE_NEWABI)
8746         {
8747           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8748
8749           /* If this is a reference to an external symbol, and there
8750              is no constant, we want
8751                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8752              or for lca or if tempreg is PIC_CALL_REG
8753                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8754              For a local symbol, we want
8755                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8756                nop
8757                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8758
8759              If we have a small constant, and this is a reference to
8760              an external symbol, we want
8761                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8762                nop
8763                addiu    $tempreg,$tempreg,<constant>
8764              For a local symbol, we want the same instruction
8765              sequence, but we output a BFD_RELOC_LO16 reloc on the
8766              addiu instruction.
8767
8768              If we have a large constant, and this is a reference to
8769              an external symbol, we want
8770                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8771                lui      $at,<hiconstant>
8772                addiu    $at,$at,<loconstant>
8773                addu     $tempreg,$tempreg,$at
8774              For a local symbol, we want the same instruction
8775              sequence, but we output a BFD_RELOC_LO16 reloc on the
8776              addiu instruction.
8777            */
8778
8779           if (offset_expr.X_add_number == 0)
8780             {
8781               if (mips_pic == SVR4_PIC
8782                   && breg == 0
8783                   && (call || tempreg == PIC_CALL_REG))
8784                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
8785
8786               relax_start (offset_expr.X_add_symbol);
8787               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8788                            lw_reloc_type, mips_gp_register);
8789               if (breg != 0)
8790                 {
8791                   /* We're going to put in an addu instruction using
8792                      tempreg, so we may as well insert the nop right
8793                      now.  */
8794                   load_delay_nop ();
8795                 }
8796               relax_switch ();
8797               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8798                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
8799               load_delay_nop ();
8800               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8801                            tempreg, tempreg, BFD_RELOC_LO16);
8802               relax_end ();
8803               /* FIXME: If breg == 0, and the next instruction uses
8804                  $tempreg, then if this variant case is used an extra
8805                  nop will be generated.  */
8806             }
8807           else if (offset_expr.X_add_number >= -0x8000
8808                    && offset_expr.X_add_number < 0x8000)
8809             {
8810               load_got_offset (tempreg, &offset_expr);
8811               load_delay_nop ();
8812               add_got_offset (tempreg, &offset_expr);
8813             }
8814           else
8815             {
8816               expr1.X_add_number = offset_expr.X_add_number;
8817               offset_expr.X_add_number =
8818                 SEXT_16BIT (offset_expr.X_add_number);
8819               load_got_offset (tempreg, &offset_expr);
8820               offset_expr.X_add_number = expr1.X_add_number;
8821               /* If we are going to add in a base register, and the
8822                  target register and the base register are the same,
8823                  then we are using AT as a temporary register.  Since
8824                  we want to load the constant into AT, we add our
8825                  current AT (from the global offset table) and the
8826                  register into the register now, and pretend we were
8827                  not using a base register.  */
8828               if (breg == treg)
8829                 {
8830                   load_delay_nop ();
8831                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8832                                treg, AT, breg);
8833                   breg = 0;
8834                   tempreg = treg;
8835                 }
8836               add_got_offset_hilo (tempreg, &offset_expr, AT);
8837               used_at = 1;
8838             }
8839         }
8840       else if (!mips_big_got && HAVE_NEWABI)
8841         {
8842           int add_breg_early = 0;
8843
8844           /* If this is a reference to an external, and there is no
8845              constant, or local symbol (*), with or without a
8846              constant, we want
8847                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8848              or for lca or if tempreg is PIC_CALL_REG
8849                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8850
8851              If we have a small constant, and this is a reference to
8852              an external symbol, we want
8853                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8854                addiu    $tempreg,$tempreg,<constant>
8855
8856              If we have a large constant, and this is a reference to
8857              an external symbol, we want
8858                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8859                lui      $at,<hiconstant>
8860                addiu    $at,$at,<loconstant>
8861                addu     $tempreg,$tempreg,$at
8862
8863              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
8864              local symbols, even though it introduces an additional
8865              instruction.  */
8866
8867           if (offset_expr.X_add_number)
8868             {
8869               expr1.X_add_number = offset_expr.X_add_number;
8870               offset_expr.X_add_number = 0;
8871
8872               relax_start (offset_expr.X_add_symbol);
8873               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8874                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8875
8876               if (expr1.X_add_number >= -0x8000
8877                   && expr1.X_add_number < 0x8000)
8878                 {
8879                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8880                                tempreg, tempreg, BFD_RELOC_LO16);
8881                 }
8882               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8883                 {
8884                   /* If we are going to add in a base register, and the
8885                      target register and the base register are the same,
8886                      then we are using AT as a temporary register.  Since
8887                      we want to load the constant into AT, we add our
8888                      current AT (from the global offset table) and the
8889                      register into the register now, and pretend we were
8890                      not using a base register.  */
8891                   if (breg != treg)
8892                     dreg = tempreg;
8893                   else
8894                     {
8895                       gas_assert (tempreg == AT);
8896                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8897                                    treg, AT, breg);
8898                       dreg = treg;
8899                       add_breg_early = 1;
8900                     }
8901
8902                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8903                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8904                                dreg, dreg, AT);
8905
8906                   used_at = 1;
8907                 }
8908               else
8909                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8910
8911               relax_switch ();
8912               offset_expr.X_add_number = expr1.X_add_number;
8913
8914               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8915                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8916               if (add_breg_early)
8917                 {
8918                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8919                                treg, tempreg, breg);
8920                   breg = 0;
8921                   tempreg = treg;
8922                 }
8923               relax_end ();
8924             }
8925           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
8926             {
8927               relax_start (offset_expr.X_add_symbol);
8928               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8929                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
8930               relax_switch ();
8931               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8932                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8933               relax_end ();
8934             }
8935           else
8936             {
8937               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8938                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8939             }
8940         }
8941       else if (mips_big_got && !HAVE_NEWABI)
8942         {
8943           int gpdelay;
8944           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8945           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8946           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8947
8948           /* This is the large GOT case.  If this is a reference to an
8949              external symbol, and there is no constant, we want
8950                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8951                addu     $tempreg,$tempreg,$gp
8952                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8953              or for lca or if tempreg is PIC_CALL_REG
8954                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8955                addu     $tempreg,$tempreg,$gp
8956                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8957              For a local symbol, we want
8958                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8959                nop
8960                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8961
8962              If we have a small constant, and this is a reference to
8963              an external symbol, we want
8964                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8965                addu     $tempreg,$tempreg,$gp
8966                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8967                nop
8968                addiu    $tempreg,$tempreg,<constant>
8969              For a local symbol, we want
8970                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8971                nop
8972                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
8973
8974              If we have a large constant, and this is a reference to
8975              an external symbol, we want
8976                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8977                addu     $tempreg,$tempreg,$gp
8978                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8979                lui      $at,<hiconstant>
8980                addiu    $at,$at,<loconstant>
8981                addu     $tempreg,$tempreg,$at
8982              For a local symbol, we want
8983                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8984                lui      $at,<hiconstant>
8985                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
8986                addu     $tempreg,$tempreg,$at
8987           */
8988
8989           expr1.X_add_number = offset_expr.X_add_number;
8990           offset_expr.X_add_number = 0;
8991           relax_start (offset_expr.X_add_symbol);
8992           gpdelay = reg_needs_delay (mips_gp_register);
8993           if (expr1.X_add_number == 0 && breg == 0
8994               && (call || tempreg == PIC_CALL_REG))
8995             {
8996               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8997               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8998             }
8999           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
9000           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9001                        tempreg, tempreg, mips_gp_register);
9002           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9003                        tempreg, lw_reloc_type, tempreg);
9004           if (expr1.X_add_number == 0)
9005             {
9006               if (breg != 0)
9007                 {
9008                   /* We're going to put in an addu instruction using
9009                      tempreg, so we may as well insert the nop right
9010                      now.  */
9011                   load_delay_nop ();
9012                 }
9013             }
9014           else if (expr1.X_add_number >= -0x8000
9015                    && expr1.X_add_number < 0x8000)
9016             {
9017               load_delay_nop ();
9018               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9019                            tempreg, tempreg, BFD_RELOC_LO16);
9020             }
9021           else
9022             {
9023               /* If we are going to add in a base register, and the
9024                  target register and the base register are the same,
9025                  then we are using AT as a temporary register.  Since
9026                  we want to load the constant into AT, we add our
9027                  current AT (from the global offset table) and the
9028                  register into the register now, and pretend we were
9029                  not using a base register.  */
9030               if (breg != treg)
9031                 dreg = tempreg;
9032               else
9033                 {
9034                   gas_assert (tempreg == AT);
9035                   load_delay_nop ();
9036                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9037                                treg, AT, breg);
9038                   dreg = treg;
9039                 }
9040
9041               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9042               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9043
9044               used_at = 1;
9045             }
9046           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
9047           relax_switch ();
9048
9049           if (gpdelay)
9050             {
9051               /* This is needed because this instruction uses $gp, but
9052                  the first instruction on the main stream does not.  */
9053               macro_build (NULL, "nop", "");
9054             }
9055
9056           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9057                        local_reloc_type, mips_gp_register);
9058           if (expr1.X_add_number >= -0x8000
9059               && expr1.X_add_number < 0x8000)
9060             {
9061               load_delay_nop ();
9062               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9063                            tempreg, tempreg, BFD_RELOC_LO16);
9064               /* FIXME: If add_number is 0, and there was no base
9065                  register, the external symbol case ended with a load,
9066                  so if the symbol turns out to not be external, and
9067                  the next instruction uses tempreg, an unnecessary nop
9068                  will be inserted.  */
9069             }
9070           else
9071             {
9072               if (breg == treg)
9073                 {
9074                   /* We must add in the base register now, as in the
9075                      external symbol case.  */
9076                   gas_assert (tempreg == AT);
9077                   load_delay_nop ();
9078                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9079                                treg, AT, breg);
9080                   tempreg = treg;
9081                   /* We set breg to 0 because we have arranged to add
9082                      it in in both cases.  */
9083                   breg = 0;
9084                 }
9085
9086               macro_build_lui (&expr1, AT);
9087               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9088                            AT, AT, BFD_RELOC_LO16);
9089               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9090                            tempreg, tempreg, AT);
9091               used_at = 1;
9092             }
9093           relax_end ();
9094         }
9095       else if (mips_big_got && HAVE_NEWABI)
9096         {
9097           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
9098           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
9099           int add_breg_early = 0;
9100
9101           /* This is the large GOT case.  If this is a reference to an
9102              external symbol, and there is no constant, we want
9103                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9104                add      $tempreg,$tempreg,$gp
9105                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9106              or for lca or if tempreg is PIC_CALL_REG
9107                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
9108                add      $tempreg,$tempreg,$gp
9109                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
9110
9111              If we have a small constant, and this is a reference to
9112              an external symbol, we want
9113                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9114                add      $tempreg,$tempreg,$gp
9115                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9116                addi     $tempreg,$tempreg,<constant>
9117
9118              If we have a large constant, and this is a reference to
9119              an external symbol, we want
9120                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9121                addu     $tempreg,$tempreg,$gp
9122                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9123                lui      $at,<hiconstant>
9124                addi     $at,$at,<loconstant>
9125                add      $tempreg,$tempreg,$at
9126
9127              If we have NewABI, and we know it's a local symbol, we want
9128                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9129                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9130              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
9131
9132           relax_start (offset_expr.X_add_symbol);
9133
9134           expr1.X_add_number = offset_expr.X_add_number;
9135           offset_expr.X_add_number = 0;
9136
9137           if (expr1.X_add_number == 0 && breg == 0
9138               && (call || tempreg == PIC_CALL_REG))
9139             {
9140               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
9141               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
9142             }
9143           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
9144           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9145                        tempreg, tempreg, mips_gp_register);
9146           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9147                        tempreg, lw_reloc_type, tempreg);
9148
9149           if (expr1.X_add_number == 0)
9150             ;
9151           else if (expr1.X_add_number >= -0x8000
9152                    && expr1.X_add_number < 0x8000)
9153             {
9154               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9155                            tempreg, tempreg, BFD_RELOC_LO16);
9156             }
9157           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9158             {
9159               /* If we are going to add in a base register, and the
9160                  target register and the base register are the same,
9161                  then we are using AT as a temporary register.  Since
9162                  we want to load the constant into AT, we add our
9163                  current AT (from the global offset table) and the
9164                  register into the register now, and pretend we were
9165                  not using a base register.  */
9166               if (breg != treg)
9167                 dreg = tempreg;
9168               else
9169                 {
9170                   gas_assert (tempreg == AT);
9171                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9172                                treg, AT, breg);
9173                   dreg = treg;
9174                   add_breg_early = 1;
9175                 }
9176
9177               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9178               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9179
9180               used_at = 1;
9181             }
9182           else
9183             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9184
9185           relax_switch ();
9186           offset_expr.X_add_number = expr1.X_add_number;
9187           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9188                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9189           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9190                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
9191           if (add_breg_early)
9192             {
9193               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9194                            treg, tempreg, breg);
9195               breg = 0;
9196               tempreg = treg;
9197             }
9198           relax_end ();
9199         }
9200       else
9201         abort ();
9202
9203       if (breg != 0)
9204         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
9205       break;
9206
9207     case M_MSGSND:
9208       gas_assert (!mips_opts.micromips);
9209       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
9210       break;
9211
9212     case M_MSGLD:
9213       gas_assert (!mips_opts.micromips);
9214       macro_build (NULL, "c2", "C", 0x02);
9215       break;
9216
9217     case M_MSGLD_T:
9218       gas_assert (!mips_opts.micromips);
9219       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
9220       break;
9221
9222     case M_MSGWAIT:
9223       gas_assert (!mips_opts.micromips);
9224       macro_build (NULL, "c2", "C", 3);
9225       break;
9226
9227     case M_MSGWAIT_T:
9228       gas_assert (!mips_opts.micromips);
9229       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
9230       break;
9231
9232     case M_J_A:
9233       /* The j instruction may not be used in PIC code, since it
9234          requires an absolute address.  We convert it to a b
9235          instruction.  */
9236       if (mips_pic == NO_PIC)
9237         macro_build (&offset_expr, "j", "a");
9238       else
9239         macro_build (&offset_expr, "b", "p");
9240       break;
9241
9242       /* The jal instructions must be handled as macros because when
9243          generating PIC code they expand to multi-instruction
9244          sequences.  Normally they are simple instructions.  */
9245     case M_JALS_1:
9246       dreg = RA;
9247       /* Fall through.  */
9248     case M_JALS_2:
9249       gas_assert (mips_opts.micromips);
9250       if (mips_opts.insn32)
9251         {
9252           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9253           break;
9254         }
9255       jals = 1;
9256       goto jal;
9257     case M_JAL_1:
9258       dreg = RA;
9259       /* Fall through.  */
9260     case M_JAL_2:
9261     jal:
9262       if (mips_pic == NO_PIC)
9263         {
9264           s = jals ? "jalrs" : "jalr";
9265           if (mips_opts.micromips
9266               && !mips_opts.insn32
9267               && dreg == RA
9268               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9269             macro_build (NULL, s, "mj", sreg);
9270           else
9271             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9272         }
9273       else
9274         {
9275           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
9276                            && mips_cprestore_offset >= 0);
9277
9278           if (sreg != PIC_CALL_REG)
9279             as_warn (_("MIPS PIC call to register other than $25"));
9280
9281           s = ((mips_opts.micromips
9282                 && !mips_opts.insn32
9283                 && (!mips_opts.noreorder || cprestore))
9284                ? "jalrs" : "jalr");
9285           if (mips_opts.micromips
9286               && !mips_opts.insn32
9287               && dreg == RA
9288               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9289             macro_build (NULL, s, "mj", sreg);
9290           else
9291             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9292           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
9293             {
9294               if (mips_cprestore_offset < 0)
9295                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9296               else
9297                 {
9298                   if (!mips_frame_reg_valid)
9299                     {
9300                       as_warn (_("No .frame pseudo-op used in PIC code"));
9301                       /* Quiet this warning.  */
9302                       mips_frame_reg_valid = 1;
9303                     }
9304                   if (!mips_cprestore_valid)
9305                     {
9306                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9307                       /* Quiet this warning.  */
9308                       mips_cprestore_valid = 1;
9309                     }
9310                   if (mips_opts.noreorder)
9311                     macro_build (NULL, "nop", "");
9312                   expr1.X_add_number = mips_cprestore_offset;
9313                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9314                                                 mips_gp_register,
9315                                                 mips_frame_reg,
9316                                                 HAVE_64BIT_ADDRESSES);
9317                 }
9318             }
9319         }
9320
9321       break;
9322
9323     case M_JALS_A:
9324       gas_assert (mips_opts.micromips);
9325       if (mips_opts.insn32)
9326         {
9327           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9328           break;
9329         }
9330       jals = 1;
9331       /* Fall through.  */
9332     case M_JAL_A:
9333       if (mips_pic == NO_PIC)
9334         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
9335       else if (mips_pic == SVR4_PIC)
9336         {
9337           /* If this is a reference to an external symbol, and we are
9338              using a small GOT, we want
9339                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
9340                nop
9341                jalr     $ra,$25
9342                nop
9343                lw       $gp,cprestore($sp)
9344              The cprestore value is set using the .cprestore
9345              pseudo-op.  If we are using a big GOT, we want
9346                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
9347                addu     $25,$25,$gp
9348                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
9349                nop
9350                jalr     $ra,$25
9351                nop
9352                lw       $gp,cprestore($sp)
9353              If the symbol is not external, we want
9354                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9355                nop
9356                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
9357                jalr     $ra,$25
9358                nop
9359                lw $gp,cprestore($sp)
9360
9361              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
9362              sequences above, minus nops, unless the symbol is local,
9363              which enables us to use GOT_PAGE/GOT_OFST (big got) or
9364              GOT_DISP.  */
9365           if (HAVE_NEWABI)
9366             {
9367               if (!mips_big_got)
9368                 {
9369                   relax_start (offset_expr.X_add_symbol);
9370                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9371                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9372                                mips_gp_register);
9373                   relax_switch ();
9374                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9375                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
9376                                mips_gp_register);
9377                   relax_end ();
9378                 }
9379               else
9380                 {
9381                   relax_start (offset_expr.X_add_symbol);
9382                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9383                                BFD_RELOC_MIPS_CALL_HI16);
9384                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9385                                PIC_CALL_REG, mips_gp_register);
9386                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9387                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9388                                PIC_CALL_REG);
9389                   relax_switch ();
9390                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9391                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
9392                                mips_gp_register);
9393                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9394                                PIC_CALL_REG, PIC_CALL_REG,
9395                                BFD_RELOC_MIPS_GOT_OFST);
9396                   relax_end ();
9397                 }
9398
9399               macro_build_jalr (&offset_expr, 0);
9400             }
9401           else
9402             {
9403               relax_start (offset_expr.X_add_symbol);
9404               if (!mips_big_got)
9405                 {
9406                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9407                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9408                                mips_gp_register);
9409                   load_delay_nop ();
9410                   relax_switch ();
9411                 }
9412               else
9413                 {
9414                   int gpdelay;
9415
9416                   gpdelay = reg_needs_delay (mips_gp_register);
9417                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9418                                BFD_RELOC_MIPS_CALL_HI16);
9419                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9420                                PIC_CALL_REG, mips_gp_register);
9421                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9422                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9423                                PIC_CALL_REG);
9424                   load_delay_nop ();
9425                   relax_switch ();
9426                   if (gpdelay)
9427                     macro_build (NULL, "nop", "");
9428                 }
9429               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9430                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
9431                            mips_gp_register);
9432               load_delay_nop ();
9433               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9434                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
9435               relax_end ();
9436               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
9437
9438               if (mips_cprestore_offset < 0)
9439                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9440               else
9441                 {
9442                   if (!mips_frame_reg_valid)
9443                     {
9444                       as_warn (_("No .frame pseudo-op used in PIC code"));
9445                       /* Quiet this warning.  */
9446                       mips_frame_reg_valid = 1;
9447                     }
9448                   if (!mips_cprestore_valid)
9449                     {
9450                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9451                       /* Quiet this warning.  */
9452                       mips_cprestore_valid = 1;
9453                     }
9454                   if (mips_opts.noreorder)
9455                     macro_build (NULL, "nop", "");
9456                   expr1.X_add_number = mips_cprestore_offset;
9457                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9458                                                 mips_gp_register,
9459                                                 mips_frame_reg,
9460                                                 HAVE_64BIT_ADDRESSES);
9461                 }
9462             }
9463         }
9464       else if (mips_pic == VXWORKS_PIC)
9465         as_bad (_("Non-PIC jump used in PIC library"));
9466       else
9467         abort ();
9468
9469       break;
9470
9471     case M_LBUE_AB:
9472       s = "lbue";
9473       fmt = "t,+j(b)";
9474       offbits = 9;
9475       goto ld_st;
9476     case M_LHUE_AB:
9477       s = "lhue";
9478       fmt = "t,+j(b)";
9479       offbits = 9;
9480       goto ld_st;
9481     case M_LBE_AB:
9482       s = "lbe";
9483       fmt = "t,+j(b)";
9484       offbits = 9;
9485       goto ld_st;
9486     case M_LHE_AB:
9487       s = "lhe";
9488       fmt = "t,+j(b)";
9489       offbits = 9;
9490       goto ld_st;
9491     case M_LLE_AB:
9492       s = "lle";
9493       fmt = "t,+j(b)";
9494       offbits = 9;
9495       goto ld_st;
9496     case M_LWE_AB:
9497       s = "lwe";
9498       fmt = "t,+j(b)";
9499       offbits = 9;
9500       goto ld_st;
9501     case M_LWLE_AB:
9502       s = "lwle";
9503       fmt = "t,+j(b)";
9504       offbits = 9;
9505       goto ld_st;
9506     case M_LWRE_AB:
9507       s = "lwre";
9508       fmt = "t,+j(b)";
9509       offbits = 9;
9510       goto ld_st;
9511     case M_SBE_AB:
9512       s = "sbe";
9513       fmt = "t,+j(b)";
9514       offbits = 9;
9515       goto ld_st;
9516     case M_SCE_AB:
9517       s = "sce";
9518       fmt = "t,+j(b)";
9519       offbits = 9;
9520       goto ld_st;
9521     case M_SHE_AB:
9522       s = "she";
9523       fmt = "t,+j(b)";
9524       offbits = 9;
9525       goto ld_st;
9526     case M_SWE_AB:
9527       s = "swe";
9528       fmt = "t,+j(b)";
9529       offbits = 9;
9530       goto ld_st;
9531     case M_SWLE_AB:
9532       s = "swle";
9533       fmt = "t,+j(b)";
9534       offbits = 9;
9535       goto ld_st;
9536     case M_SWRE_AB:
9537       s = "swre";
9538       fmt = "t,+j(b)";
9539       offbits = 9;
9540       goto ld_st;
9541     case M_ACLR_AB:
9542       s = "aclr";
9543       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9544       fmt = "\\,~(b)";
9545       offbits = 12;
9546       goto ld_st;
9547     case M_ASET_AB:
9548       s = "aset";
9549       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9550       fmt = "\\,~(b)";
9551       offbits = 12;
9552       goto ld_st;
9553     case M_LB_AB:
9554       s = "lb";
9555       fmt = "t,o(b)";
9556       goto ld;
9557     case M_LBU_AB:
9558       s = "lbu";
9559       fmt = "t,o(b)";
9560       goto ld;
9561     case M_LH_AB:
9562       s = "lh";
9563       fmt = "t,o(b)";
9564       goto ld;
9565     case M_LHU_AB:
9566       s = "lhu";
9567       fmt = "t,o(b)";
9568       goto ld;
9569     case M_LW_AB:
9570       s = "lw";
9571       fmt = "t,o(b)";
9572       goto ld;
9573     case M_LWC0_AB:
9574       gas_assert (!mips_opts.micromips);
9575       s = "lwc0";
9576       fmt = "E,o(b)";
9577       /* Itbl support may require additional care here.  */
9578       coproc = 1;
9579       goto ld_st;
9580     case M_LWC1_AB:
9581       s = "lwc1";
9582       fmt = "T,o(b)";
9583       /* Itbl support may require additional care here.  */
9584       coproc = 1;
9585       goto ld_st;
9586     case M_LWC2_AB:
9587       s = "lwc2";
9588       fmt = COP12_FMT;
9589       offbits = (mips_opts.micromips ? 12 : 16);
9590       /* Itbl support may require additional care here.  */
9591       coproc = 1;
9592       goto ld_st;
9593     case M_LWC3_AB:
9594       gas_assert (!mips_opts.micromips);
9595       s = "lwc3";
9596       fmt = "E,o(b)";
9597       /* Itbl support may require additional care here.  */
9598       coproc = 1;
9599       goto ld_st;
9600     case M_LWL_AB:
9601       s = "lwl";
9602       fmt = MEM12_FMT;
9603       offbits = (mips_opts.micromips ? 12 : 16);
9604       goto ld_st;
9605     case M_LWR_AB:
9606       s = "lwr";
9607       fmt = MEM12_FMT;
9608       offbits = (mips_opts.micromips ? 12 : 16);
9609       goto ld_st;
9610     case M_LDC1_AB:
9611       s = "ldc1";
9612       fmt = "T,o(b)";
9613       /* Itbl support may require additional care here.  */
9614       coproc = 1;
9615       goto ld_st;
9616     case M_LDC2_AB:
9617       s = "ldc2";
9618       fmt = COP12_FMT;
9619       offbits = (mips_opts.micromips ? 12 : 16);
9620       /* Itbl support may require additional care here.  */
9621       coproc = 1;
9622       goto ld_st;
9623     case M_LQC2_AB:
9624       s = "lqc2";
9625       fmt = "E,o(b)";
9626       /* Itbl support may require additional care here.  */
9627       coproc = 1;
9628       goto ld_st;
9629     case M_LDC3_AB:
9630       s = "ldc3";
9631       fmt = "E,o(b)";
9632       /* Itbl support may require additional care here.  */
9633       coproc = 1;
9634       goto ld_st;
9635     case M_LDL_AB:
9636       s = "ldl";
9637       fmt = MEM12_FMT;
9638       offbits = (mips_opts.micromips ? 12 : 16);
9639       goto ld_st;
9640     case M_LDR_AB:
9641       s = "ldr";
9642       fmt = MEM12_FMT;
9643       offbits = (mips_opts.micromips ? 12 : 16);
9644       goto ld_st;
9645     case M_LL_AB:
9646       s = "ll";
9647       fmt = MEM12_FMT;
9648       offbits = (mips_opts.micromips ? 12 : 16);
9649       goto ld;
9650     case M_LLD_AB:
9651       s = "lld";
9652       fmt = MEM12_FMT;
9653       offbits = (mips_opts.micromips ? 12 : 16);
9654       goto ld;
9655     case M_LWU_AB:
9656       s = "lwu";
9657       fmt = MEM12_FMT;
9658       offbits = (mips_opts.micromips ? 12 : 16);
9659       goto ld;
9660     case M_LWP_AB:
9661       gas_assert (mips_opts.micromips);
9662       s = "lwp";
9663       fmt = "t,~(b)";
9664       offbits = 12;
9665       lp = 1;
9666       goto ld;
9667     case M_LDP_AB:
9668       gas_assert (mips_opts.micromips);
9669       s = "ldp";
9670       fmt = "t,~(b)";
9671       offbits = 12;
9672       lp = 1;
9673       goto ld;
9674     case M_LWM_AB:
9675       gas_assert (mips_opts.micromips);
9676       s = "lwm";
9677       fmt = "n,~(b)";
9678       offbits = 12;
9679       goto ld_st;
9680     case M_LDM_AB:
9681       gas_assert (mips_opts.micromips);
9682       s = "ldm";
9683       fmt = "n,~(b)";
9684       offbits = 12;
9685       goto ld_st;
9686
9687     ld:
9688       /* We don't want to use $0 as tempreg.  */
9689       if (breg == treg + lp || treg + lp == ZERO)
9690         goto ld_st;
9691       else
9692         tempreg = treg + lp;
9693       goto ld_noat;
9694
9695     case M_SB_AB:
9696       s = "sb";
9697       fmt = "t,o(b)";
9698       goto ld_st;
9699     case M_SH_AB:
9700       s = "sh";
9701       fmt = "t,o(b)";
9702       goto ld_st;
9703     case M_SW_AB:
9704       s = "sw";
9705       fmt = "t,o(b)";
9706       goto ld_st;
9707     case M_SWC0_AB:
9708       gas_assert (!mips_opts.micromips);
9709       s = "swc0";
9710       fmt = "E,o(b)";
9711       /* Itbl support may require additional care here.  */
9712       coproc = 1;
9713       goto ld_st;
9714     case M_SWC1_AB:
9715       s = "swc1";
9716       fmt = "T,o(b)";
9717       /* Itbl support may require additional care here.  */
9718       coproc = 1;
9719       goto ld_st;
9720     case M_SWC2_AB:
9721       s = "swc2";
9722       fmt = COP12_FMT;
9723       offbits = (mips_opts.micromips ? 12 : 16);
9724       /* Itbl support may require additional care here.  */
9725       coproc = 1;
9726       goto ld_st;
9727     case M_SWC3_AB:
9728       gas_assert (!mips_opts.micromips);
9729       s = "swc3";
9730       fmt = "E,o(b)";
9731       /* Itbl support may require additional care here.  */
9732       coproc = 1;
9733       goto ld_st;
9734     case M_SWL_AB:
9735       s = "swl";
9736       fmt = MEM12_FMT;
9737       offbits = (mips_opts.micromips ? 12 : 16);
9738       goto ld_st;
9739     case M_SWR_AB:
9740       s = "swr";
9741       fmt = MEM12_FMT;
9742       offbits = (mips_opts.micromips ? 12 : 16);
9743       goto ld_st;
9744     case M_SC_AB:
9745       s = "sc";
9746       fmt = MEM12_FMT;
9747       offbits = (mips_opts.micromips ? 12 : 16);
9748       goto ld_st;
9749     case M_SCD_AB:
9750       s = "scd";
9751       fmt = MEM12_FMT;
9752       offbits = (mips_opts.micromips ? 12 : 16);
9753       goto ld_st;
9754     case M_CACHE_AB:
9755       s = "cache";
9756       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
9757       offbits = (mips_opts.micromips ? 12 : 16);
9758       goto ld_st;
9759     case M_CACHEE_AB:
9760       s = "cachee";
9761       fmt = "k,+j(b)";
9762       offbits = 9;
9763       goto ld_st;
9764     case M_PREF_AB:
9765       s = "pref";
9766       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
9767       offbits = (mips_opts.micromips ? 12 : 16);
9768       goto ld_st;
9769     case M_PREFE_AB:
9770       s = "prefe";
9771       fmt = "k,+j(b)";
9772       offbits = 9;
9773       goto ld_st;
9774     case M_SDC1_AB:
9775       s = "sdc1";
9776       fmt = "T,o(b)";
9777       coproc = 1;
9778       /* Itbl support may require additional care here.  */
9779       goto ld_st;
9780     case M_SDC2_AB:
9781       s = "sdc2";
9782       fmt = COP12_FMT;
9783       offbits = (mips_opts.micromips ? 12 : 16);
9784       /* Itbl support may require additional care here.  */
9785       coproc = 1;
9786       goto ld_st;
9787     case M_SQC2_AB:
9788       s = "sqc2";
9789       fmt = "E,o(b)";
9790       /* Itbl support may require additional care here.  */
9791       coproc = 1;
9792       goto ld_st;
9793     case M_SDC3_AB:
9794       gas_assert (!mips_opts.micromips);
9795       s = "sdc3";
9796       fmt = "E,o(b)";
9797       /* Itbl support may require additional care here.  */
9798       coproc = 1;
9799       goto ld_st;
9800     case M_SDL_AB:
9801       s = "sdl";
9802       fmt = MEM12_FMT;
9803       offbits = (mips_opts.micromips ? 12 : 16);
9804       goto ld_st;
9805     case M_SDR_AB:
9806       s = "sdr";
9807       fmt = MEM12_FMT;
9808       offbits = (mips_opts.micromips ? 12 : 16);
9809       goto ld_st;
9810     case M_SWP_AB:
9811       gas_assert (mips_opts.micromips);
9812       s = "swp";
9813       fmt = "t,~(b)";
9814       offbits = 12;
9815       goto ld_st;
9816     case M_SDP_AB:
9817       gas_assert (mips_opts.micromips);
9818       s = "sdp";
9819       fmt = "t,~(b)";
9820       offbits = 12;
9821       goto ld_st;
9822     case M_SWM_AB:
9823       gas_assert (mips_opts.micromips);
9824       s = "swm";
9825       fmt = "n,~(b)";
9826       offbits = 12;
9827       goto ld_st;
9828     case M_SDM_AB:
9829       gas_assert (mips_opts.micromips);
9830       s = "sdm";
9831       fmt = "n,~(b)";
9832       offbits = 12;
9833
9834     ld_st:
9835       tempreg = AT;
9836     ld_noat:
9837       if (small_offset_p (0, align, 16))
9838         {
9839           /* The first case exists for M_LD_AB and M_SD_AB, which are
9840              macros for o32 but which should act like normal instructions
9841              otherwise.  */
9842           if (offbits == 16)
9843             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
9844                          offset_reloc[1], offset_reloc[2], breg);
9845           else if (small_offset_p (0, align, offbits))
9846             {
9847               if (offbits == 0)
9848                 macro_build (NULL, s, fmt, treg, breg);
9849               else
9850                 macro_build (NULL, s, fmt, treg,
9851                              (int) offset_expr.X_add_number, breg);
9852             }
9853           else
9854             {
9855               if (tempreg == AT)
9856                 used_at = 1;
9857               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9858                            tempreg, breg, -1, offset_reloc[0],
9859                            offset_reloc[1], offset_reloc[2]);
9860               if (offbits == 0)
9861                 macro_build (NULL, s, fmt, treg, tempreg);
9862               else
9863                 macro_build (NULL, s, fmt, treg, 0, tempreg);
9864             }
9865           break;
9866         }
9867
9868       if (tempreg == AT)
9869         used_at = 1;
9870
9871       if (offset_expr.X_op != O_constant
9872           && offset_expr.X_op != O_symbol)
9873         {
9874           as_bad (_("Expression too complex"));
9875           offset_expr.X_op = O_constant;
9876         }
9877
9878       if (HAVE_32BIT_ADDRESSES
9879           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9880         {
9881           char value [32];
9882
9883           sprintf_vma (value, offset_expr.X_add_number);
9884           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9885         }
9886
9887       /* A constant expression in PIC code can be handled just as it
9888          is in non PIC code.  */
9889       if (offset_expr.X_op == O_constant)
9890         {
9891           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
9892                                                  offbits == 0 ? 16 : offbits);
9893           offset_expr.X_add_number -= expr1.X_add_number;
9894
9895           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
9896           if (breg != 0)
9897             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9898                          tempreg, tempreg, breg);
9899           if (offbits == 0)
9900             {
9901               if (offset_expr.X_add_number != 0)
9902                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
9903                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
9904               macro_build (NULL, s, fmt, treg, tempreg);
9905             }
9906           else if (offbits == 16)
9907             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9908           else
9909             macro_build (NULL, s, fmt, treg,
9910                          (int) offset_expr.X_add_number, tempreg);
9911         }
9912       else if (offbits != 16)
9913         {
9914           /* The offset field is too narrow to be used for a low-part
9915              relocation, so load the whole address into the auxillary
9916              register.  */
9917           load_address (tempreg, &offset_expr, &used_at);
9918           if (breg != 0)
9919             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9920                          tempreg, tempreg, breg);
9921           if (offbits == 0)
9922             macro_build (NULL, s, fmt, treg, tempreg);
9923           else
9924             macro_build (NULL, s, fmt, treg, 0, tempreg);
9925         }
9926       else if (mips_pic == NO_PIC)
9927         {
9928           /* If this is a reference to a GP relative symbol, and there
9929              is no base register, we want
9930                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9931              Otherwise, if there is no base register, we want
9932                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9933                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9934              If we have a constant, we need two instructions anyhow,
9935              so we always use the latter form.
9936
9937              If we have a base register, and this is a reference to a
9938              GP relative symbol, we want
9939                addu     $tempreg,$breg,$gp
9940                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9941              Otherwise we want
9942                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9943                addu     $tempreg,$tempreg,$breg
9944                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9945              With a constant we always use the latter case.
9946
9947              With 64bit address space and no base register and $at usable,
9948              we want
9949                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9950                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9951                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9952                dsll32   $tempreg,0
9953                daddu    $tempreg,$at
9954                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9955              If we have a base register, we want
9956                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9957                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9958                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9959                daddu    $at,$breg
9960                dsll32   $tempreg,0
9961                daddu    $tempreg,$at
9962                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9963
9964              Without $at we can't generate the optimal path for superscalar
9965              processors here since this would require two temporary registers.
9966                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9967                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9968                dsll     $tempreg,16
9969                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9970                dsll     $tempreg,16
9971                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9972              If we have a base register, we want
9973                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9974                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9975                dsll     $tempreg,16
9976                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9977                dsll     $tempreg,16
9978                daddu    $tempreg,$tempreg,$breg
9979                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9980
9981              For GP relative symbols in 64bit address space we can use
9982              the same sequence as in 32bit address space.  */
9983           if (HAVE_64BIT_SYMBOLS)
9984             {
9985               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9986                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9987                 {
9988                   relax_start (offset_expr.X_add_symbol);
9989                   if (breg == 0)
9990                     {
9991                       macro_build (&offset_expr, s, fmt, treg,
9992                                    BFD_RELOC_GPREL16, mips_gp_register);
9993                     }
9994                   else
9995                     {
9996                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9997                                    tempreg, breg, mips_gp_register);
9998                       macro_build (&offset_expr, s, fmt, treg,
9999                                    BFD_RELOC_GPREL16, tempreg);
10000                     }
10001                   relax_switch ();
10002                 }
10003
10004               if (used_at == 0 && mips_opts.at)
10005                 {
10006                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10007                                BFD_RELOC_MIPS_HIGHEST);
10008                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
10009                                BFD_RELOC_HI16_S);
10010                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10011                                tempreg, BFD_RELOC_MIPS_HIGHER);
10012                   if (breg != 0)
10013                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
10014                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10015                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10016                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
10017                                tempreg);
10018                   used_at = 1;
10019                 }
10020               else
10021                 {
10022                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10023                                BFD_RELOC_MIPS_HIGHEST);
10024                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10025                                tempreg, BFD_RELOC_MIPS_HIGHER);
10026                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10027                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10028                                tempreg, BFD_RELOC_HI16_S);
10029                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10030                   if (breg != 0)
10031                     macro_build (NULL, "daddu", "d,v,t",
10032                                  tempreg, tempreg, breg);
10033                   macro_build (&offset_expr, s, fmt, treg,
10034                                BFD_RELOC_LO16, tempreg);
10035                 }
10036
10037               if (mips_relax.sequence)
10038                 relax_end ();
10039               break;
10040             }
10041
10042           if (breg == 0)
10043             {
10044               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10045                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10046                 {
10047                   relax_start (offset_expr.X_add_symbol);
10048                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
10049                                mips_gp_register);
10050                   relax_switch ();
10051                 }
10052               macro_build_lui (&offset_expr, tempreg);
10053               macro_build (&offset_expr, s, fmt, treg,
10054                            BFD_RELOC_LO16, tempreg);
10055               if (mips_relax.sequence)
10056                 relax_end ();
10057             }
10058           else
10059             {
10060               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10061                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10062                 {
10063                   relax_start (offset_expr.X_add_symbol);
10064                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10065                                tempreg, breg, mips_gp_register);
10066                   macro_build (&offset_expr, s, fmt, treg,
10067                                BFD_RELOC_GPREL16, tempreg);
10068                   relax_switch ();
10069                 }
10070               macro_build_lui (&offset_expr, tempreg);
10071               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10072                            tempreg, tempreg, breg);
10073               macro_build (&offset_expr, s, fmt, treg,
10074                            BFD_RELOC_LO16, tempreg);
10075               if (mips_relax.sequence)
10076                 relax_end ();
10077             }
10078         }
10079       else if (!mips_big_got)
10080         {
10081           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10082
10083           /* If this is a reference to an external symbol, we want
10084                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10085                nop
10086                <op>     $treg,0($tempreg)
10087              Otherwise we want
10088                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10089                nop
10090                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10091                <op>     $treg,0($tempreg)
10092
10093              For NewABI, we want
10094                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10095                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
10096
10097              If there is a base register, we add it to $tempreg before
10098              the <op>.  If there is a constant, we stick it in the
10099              <op> instruction.  We don't handle constants larger than
10100              16 bits, because we have no way to load the upper 16 bits
10101              (actually, we could handle them for the subset of cases
10102              in which we are not using $at).  */
10103           gas_assert (offset_expr.X_op == O_symbol);
10104           if (HAVE_NEWABI)
10105             {
10106               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10107                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10108               if (breg != 0)
10109                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10110                              tempreg, tempreg, breg);
10111               macro_build (&offset_expr, s, fmt, treg,
10112                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
10113               break;
10114             }
10115           expr1.X_add_number = offset_expr.X_add_number;
10116           offset_expr.X_add_number = 0;
10117           if (expr1.X_add_number < -0x8000
10118               || expr1.X_add_number >= 0x8000)
10119             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10120           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10121                        lw_reloc_type, mips_gp_register);
10122           load_delay_nop ();
10123           relax_start (offset_expr.X_add_symbol);
10124           relax_switch ();
10125           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10126                        tempreg, BFD_RELOC_LO16);
10127           relax_end ();
10128           if (breg != 0)
10129             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10130                          tempreg, tempreg, breg);
10131           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10132         }
10133       else if (mips_big_got && !HAVE_NEWABI)
10134         {
10135           int gpdelay;
10136
10137           /* If this is a reference to an external symbol, we want
10138                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10139                addu     $tempreg,$tempreg,$gp
10140                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10141                <op>     $treg,0($tempreg)
10142              Otherwise we want
10143                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10144                nop
10145                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10146                <op>     $treg,0($tempreg)
10147              If there is a base register, we add it to $tempreg before
10148              the <op>.  If there is a constant, we stick it in the
10149              <op> instruction.  We don't handle constants larger than
10150              16 bits, because we have no way to load the upper 16 bits
10151              (actually, we could handle them for the subset of cases
10152              in which we are not using $at).  */
10153           gas_assert (offset_expr.X_op == O_symbol);
10154           expr1.X_add_number = offset_expr.X_add_number;
10155           offset_expr.X_add_number = 0;
10156           if (expr1.X_add_number < -0x8000
10157               || expr1.X_add_number >= 0x8000)
10158             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10159           gpdelay = reg_needs_delay (mips_gp_register);
10160           relax_start (offset_expr.X_add_symbol);
10161           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10162                        BFD_RELOC_MIPS_GOT_HI16);
10163           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10164                        mips_gp_register);
10165           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10166                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10167           relax_switch ();
10168           if (gpdelay)
10169             macro_build (NULL, "nop", "");
10170           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10171                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10172           load_delay_nop ();
10173           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10174                        tempreg, BFD_RELOC_LO16);
10175           relax_end ();
10176
10177           if (breg != 0)
10178             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10179                          tempreg, tempreg, breg);
10180           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10181         }
10182       else if (mips_big_got && HAVE_NEWABI)
10183         {
10184           /* If this is a reference to an external symbol, we want
10185                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10186                add      $tempreg,$tempreg,$gp
10187                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10188                <op>     $treg,<ofst>($tempreg)
10189              Otherwise, for local symbols, we want:
10190                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10191                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
10192           gas_assert (offset_expr.X_op == O_symbol);
10193           expr1.X_add_number = offset_expr.X_add_number;
10194           offset_expr.X_add_number = 0;
10195           if (expr1.X_add_number < -0x8000
10196               || expr1.X_add_number >= 0x8000)
10197             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10198           relax_start (offset_expr.X_add_symbol);
10199           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10200                        BFD_RELOC_MIPS_GOT_HI16);
10201           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10202                        mips_gp_register);
10203           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10204                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10205           if (breg != 0)
10206             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10207                          tempreg, tempreg, breg);
10208           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
10209
10210           relax_switch ();
10211           offset_expr.X_add_number = expr1.X_add_number;
10212           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10213                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10214           if (breg != 0)
10215             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10216                          tempreg, tempreg, breg);
10217           macro_build (&offset_expr, s, fmt, treg,
10218                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
10219           relax_end ();
10220         }
10221       else
10222         abort ();
10223
10224       break;
10225
10226     case M_JRADDIUSP:
10227       gas_assert (mips_opts.micromips);
10228       gas_assert (mips_opts.insn32);
10229       start_noreorder ();
10230       macro_build (NULL, "jr", "s", RA);
10231       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
10232       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
10233       end_noreorder ();
10234       break;
10235
10236     case M_JRC:
10237       gas_assert (mips_opts.micromips);
10238       gas_assert (mips_opts.insn32);
10239       macro_build (NULL, "jr", "s", sreg);
10240       if (mips_opts.noreorder)
10241         macro_build (NULL, "nop", "");
10242       break;
10243
10244     case M_LI:
10245     case M_LI_S:
10246       load_register (treg, &imm_expr, 0);
10247       break;
10248
10249     case M_DLI:
10250       load_register (treg, &imm_expr, 1);
10251       break;
10252
10253     case M_LI_SS:
10254       if (imm_expr.X_op == O_constant)
10255         {
10256           used_at = 1;
10257           load_register (AT, &imm_expr, 0);
10258           macro_build (NULL, "mtc1", "t,G", AT, treg);
10259           break;
10260         }
10261       else
10262         {
10263           gas_assert (offset_expr.X_op == O_symbol
10264                       && strcmp (segment_name (S_GET_SEGMENT
10265                                                (offset_expr.X_add_symbol)),
10266                                  ".lit4") == 0
10267                       && offset_expr.X_add_number == 0);
10268           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
10269                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
10270           break;
10271         }
10272
10273     case M_LI_D:
10274       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
10275          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
10276          order 32 bits of the value and the low order 32 bits are either
10277          zero or in OFFSET_EXPR.  */
10278       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10279         {
10280           if (HAVE_64BIT_GPRS)
10281             load_register (treg, &imm_expr, 1);
10282           else
10283             {
10284               int hreg, lreg;
10285
10286               if (target_big_endian)
10287                 {
10288                   hreg = treg;
10289                   lreg = treg + 1;
10290                 }
10291               else
10292                 {
10293                   hreg = treg + 1;
10294                   lreg = treg;
10295                 }
10296
10297               if (hreg <= 31)
10298                 load_register (hreg, &imm_expr, 0);
10299               if (lreg <= 31)
10300                 {
10301                   if (offset_expr.X_op == O_absent)
10302                     move_register (lreg, 0);
10303                   else
10304                     {
10305                       gas_assert (offset_expr.X_op == O_constant);
10306                       load_register (lreg, &offset_expr, 0);
10307                     }
10308                 }
10309             }
10310           break;
10311         }
10312
10313       /* We know that sym is in the .rdata section.  First we get the
10314          upper 16 bits of the address.  */
10315       if (mips_pic == NO_PIC)
10316         {
10317           macro_build_lui (&offset_expr, AT);
10318           used_at = 1;
10319         }
10320       else
10321         {
10322           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10323                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10324           used_at = 1;
10325         }
10326
10327       /* Now we load the register(s).  */
10328       if (HAVE_64BIT_GPRS)
10329         {
10330           used_at = 1;
10331           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10332         }
10333       else
10334         {
10335           used_at = 1;
10336           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10337           if (treg != RA)
10338             {
10339               /* FIXME: How in the world do we deal with the possible
10340                  overflow here?  */
10341               offset_expr.X_add_number += 4;
10342               macro_build (&offset_expr, "lw", "t,o(b)",
10343                            treg + 1, BFD_RELOC_LO16, AT);
10344             }
10345         }
10346       break;
10347
10348     case M_LI_DD:
10349       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
10350          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
10351          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
10352          the value and the low order 32 bits are either zero or in
10353          OFFSET_EXPR.  */
10354       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10355         {
10356           used_at = 1;
10357           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
10358           if (HAVE_64BIT_FPRS)
10359             {
10360               gas_assert (HAVE_64BIT_GPRS);
10361               macro_build (NULL, "dmtc1", "t,S", AT, treg);
10362             }
10363           else
10364             {
10365               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
10366               if (offset_expr.X_op == O_absent)
10367                 macro_build (NULL, "mtc1", "t,G", 0, treg);
10368               else
10369                 {
10370                   gas_assert (offset_expr.X_op == O_constant);
10371                   load_register (AT, &offset_expr, 0);
10372                   macro_build (NULL, "mtc1", "t,G", AT, treg);
10373                 }
10374             }
10375           break;
10376         }
10377
10378       gas_assert (offset_expr.X_op == O_symbol
10379                   && offset_expr.X_add_number == 0);
10380       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
10381       if (strcmp (s, ".lit8") == 0)
10382         {
10383           breg = mips_gp_register;
10384           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
10385           offset_reloc[1] = BFD_RELOC_UNUSED;
10386           offset_reloc[2] = BFD_RELOC_UNUSED;
10387         }
10388       else
10389         {
10390           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
10391           used_at = 1;
10392           if (mips_pic != NO_PIC)
10393             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10394                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
10395           else
10396             {
10397               /* FIXME: This won't work for a 64 bit address.  */
10398               macro_build_lui (&offset_expr, AT);
10399             }
10400
10401           breg = AT;
10402           offset_reloc[0] = BFD_RELOC_LO16;
10403           offset_reloc[1] = BFD_RELOC_UNUSED;
10404           offset_reloc[2] = BFD_RELOC_UNUSED;
10405         }
10406       align = 8;
10407       /* Fall through */
10408
10409     case M_L_DAB:
10410       /*
10411        * The MIPS assembler seems to check for X_add_number not
10412        * being double aligned and generating:
10413        *        lui     at,%hi(foo+1)
10414        *        addu    at,at,v1
10415        *        addiu   at,at,%lo(foo+1)
10416        *        lwc1    f2,0(at)
10417        *        lwc1    f3,4(at)
10418        * But, the resulting address is the same after relocation so why
10419        * generate the extra instruction?
10420        */
10421       /* Itbl support may require additional care here.  */
10422       coproc = 1;
10423       fmt = "T,o(b)";
10424       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10425         {
10426           s = "ldc1";
10427           goto ld_st;
10428         }
10429       s = "lwc1";
10430       goto ldd_std;
10431
10432     case M_S_DAB:
10433       gas_assert (!mips_opts.micromips);
10434       /* Itbl support may require additional care here.  */
10435       coproc = 1;
10436       fmt = "T,o(b)";
10437       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10438         {
10439           s = "sdc1";
10440           goto ld_st;
10441         }
10442       s = "swc1";
10443       goto ldd_std;
10444
10445     case M_LQ_AB:
10446       fmt = "t,o(b)";
10447       s = "lq";
10448       goto ld;
10449
10450     case M_SQ_AB:
10451       fmt = "t,o(b)";
10452       s = "sq";
10453       goto ld_st;
10454
10455     case M_LD_AB:
10456       fmt = "t,o(b)";
10457       if (HAVE_64BIT_GPRS)
10458         {
10459           s = "ld";
10460           goto ld;
10461         }
10462       s = "lw";
10463       goto ldd_std;
10464
10465     case M_SD_AB:
10466       fmt = "t,o(b)";
10467       if (HAVE_64BIT_GPRS)
10468         {
10469           s = "sd";
10470           goto ld_st;
10471         }
10472       s = "sw";
10473
10474     ldd_std:
10475       /* Even on a big endian machine $fn comes before $fn+1.  We have
10476          to adjust when loading from memory.  We set coproc if we must
10477          load $fn+1 first.  */
10478       /* Itbl support may require additional care here.  */
10479       if (!target_big_endian)
10480         coproc = 0;
10481
10482       if (small_offset_p (0, align, 16))
10483         {
10484           ep = &offset_expr;
10485           if (!small_offset_p (4, align, 16))
10486             {
10487               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
10488                            -1, offset_reloc[0], offset_reloc[1],
10489                            offset_reloc[2]);
10490               expr1.X_add_number = 0;
10491               ep = &expr1;
10492               breg = AT;
10493               used_at = 1;
10494               offset_reloc[0] = BFD_RELOC_LO16;
10495               offset_reloc[1] = BFD_RELOC_UNUSED;
10496               offset_reloc[2] = BFD_RELOC_UNUSED;
10497             }
10498           if (strcmp (s, "lw") == 0 && treg == breg)
10499             {
10500               ep->X_add_number += 4;
10501               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
10502                            offset_reloc[1], offset_reloc[2], breg);
10503               ep->X_add_number -= 4;
10504               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
10505                            offset_reloc[1], offset_reloc[2], breg);
10506             }
10507           else
10508             {
10509               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
10510                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10511                            breg);
10512               ep->X_add_number += 4;
10513               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
10514                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10515                            breg);
10516             }
10517           break;
10518         }
10519
10520       if (offset_expr.X_op != O_symbol
10521           && offset_expr.X_op != O_constant)
10522         {
10523           as_bad (_("Expression too complex"));
10524           offset_expr.X_op = O_constant;
10525         }
10526
10527       if (HAVE_32BIT_ADDRESSES
10528           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10529         {
10530           char value [32];
10531
10532           sprintf_vma (value, offset_expr.X_add_number);
10533           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10534         }
10535
10536       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
10537         {
10538           /* If this is a reference to a GP relative symbol, we want
10539                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
10540                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
10541              If we have a base register, we use this
10542                addu     $at,$breg,$gp
10543                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
10544                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
10545              If this is not a GP relative symbol, we want
10546                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10547                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10548                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10549              If there is a base register, we add it to $at after the
10550              lui instruction.  If there is a constant, we always use
10551              the last case.  */
10552           if (offset_expr.X_op == O_symbol
10553               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10554               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10555             {
10556               relax_start (offset_expr.X_add_symbol);
10557               if (breg == 0)
10558                 {
10559                   tempreg = mips_gp_register;
10560                 }
10561               else
10562                 {
10563                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10564                                AT, breg, mips_gp_register);
10565                   tempreg = AT;
10566                   used_at = 1;
10567                 }
10568
10569               /* Itbl support may require additional care here.  */
10570               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10571                            BFD_RELOC_GPREL16, tempreg);
10572               offset_expr.X_add_number += 4;
10573
10574               /* Set mips_optimize to 2 to avoid inserting an
10575                  undesired nop.  */
10576               hold_mips_optimize = mips_optimize;
10577               mips_optimize = 2;
10578               /* Itbl support may require additional care here.  */
10579               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10580                            BFD_RELOC_GPREL16, tempreg);
10581               mips_optimize = hold_mips_optimize;
10582
10583               relax_switch ();
10584
10585               offset_expr.X_add_number -= 4;
10586             }
10587           used_at = 1;
10588           if (offset_high_part (offset_expr.X_add_number, 16)
10589               != offset_high_part (offset_expr.X_add_number + 4, 16))
10590             {
10591               load_address (AT, &offset_expr, &used_at);
10592               offset_expr.X_op = O_constant;
10593               offset_expr.X_add_number = 0;
10594             }
10595           else
10596             macro_build_lui (&offset_expr, AT);
10597           if (breg != 0)
10598             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10599           /* Itbl support may require additional care here.  */
10600           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10601                        BFD_RELOC_LO16, AT);
10602           /* FIXME: How do we handle overflow here?  */
10603           offset_expr.X_add_number += 4;
10604           /* Itbl support may require additional care here.  */
10605           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10606                        BFD_RELOC_LO16, AT);
10607           if (mips_relax.sequence)
10608             relax_end ();
10609         }
10610       else if (!mips_big_got)
10611         {
10612           /* If this is a reference to an external symbol, we want
10613                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10614                nop
10615                <op>     $treg,0($at)
10616                <op>     $treg+1,4($at)
10617              Otherwise we want
10618                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10619                nop
10620                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10621                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10622              If there is a base register we add it to $at before the
10623              lwc1 instructions.  If there is a constant we include it
10624              in the lwc1 instructions.  */
10625           used_at = 1;
10626           expr1.X_add_number = offset_expr.X_add_number;
10627           if (expr1.X_add_number < -0x8000
10628               || expr1.X_add_number >= 0x8000 - 4)
10629             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10630           load_got_offset (AT, &offset_expr);
10631           load_delay_nop ();
10632           if (breg != 0)
10633             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10634
10635           /* Set mips_optimize to 2 to avoid inserting an undesired
10636              nop.  */
10637           hold_mips_optimize = mips_optimize;
10638           mips_optimize = 2;
10639
10640           /* Itbl support may require additional care here.  */
10641           relax_start (offset_expr.X_add_symbol);
10642           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10643                        BFD_RELOC_LO16, AT);
10644           expr1.X_add_number += 4;
10645           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10646                        BFD_RELOC_LO16, AT);
10647           relax_switch ();
10648           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10649                        BFD_RELOC_LO16, AT);
10650           offset_expr.X_add_number += 4;
10651           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10652                        BFD_RELOC_LO16, AT);
10653           relax_end ();
10654
10655           mips_optimize = hold_mips_optimize;
10656         }
10657       else if (mips_big_got)
10658         {
10659           int gpdelay;
10660
10661           /* If this is a reference to an external symbol, we want
10662                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
10663                addu     $at,$at,$gp
10664                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
10665                nop
10666                <op>     $treg,0($at)
10667                <op>     $treg+1,4($at)
10668              Otherwise we want
10669                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10670                nop
10671                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10672                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10673              If there is a base register we add it to $at before the
10674              lwc1 instructions.  If there is a constant we include it
10675              in the lwc1 instructions.  */
10676           used_at = 1;
10677           expr1.X_add_number = offset_expr.X_add_number;
10678           offset_expr.X_add_number = 0;
10679           if (expr1.X_add_number < -0x8000
10680               || expr1.X_add_number >= 0x8000 - 4)
10681             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10682           gpdelay = reg_needs_delay (mips_gp_register);
10683           relax_start (offset_expr.X_add_symbol);
10684           macro_build (&offset_expr, "lui", LUI_FMT,
10685                        AT, BFD_RELOC_MIPS_GOT_HI16);
10686           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10687                        AT, AT, mips_gp_register);
10688           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10689                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
10690           load_delay_nop ();
10691           if (breg != 0)
10692             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10693           /* Itbl support may require additional care here.  */
10694           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10695                        BFD_RELOC_LO16, AT);
10696           expr1.X_add_number += 4;
10697
10698           /* Set mips_optimize to 2 to avoid inserting an undesired
10699              nop.  */
10700           hold_mips_optimize = mips_optimize;
10701           mips_optimize = 2;
10702           /* Itbl support may require additional care here.  */
10703           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10704                        BFD_RELOC_LO16, AT);
10705           mips_optimize = hold_mips_optimize;
10706           expr1.X_add_number -= 4;
10707
10708           relax_switch ();
10709           offset_expr.X_add_number = expr1.X_add_number;
10710           if (gpdelay)
10711             macro_build (NULL, "nop", "");
10712           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10713                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10714           load_delay_nop ();
10715           if (breg != 0)
10716             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10717           /* Itbl support may require additional care here.  */
10718           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10719                        BFD_RELOC_LO16, AT);
10720           offset_expr.X_add_number += 4;
10721
10722           /* Set mips_optimize to 2 to avoid inserting an undesired
10723              nop.  */
10724           hold_mips_optimize = mips_optimize;
10725           mips_optimize = 2;
10726           /* Itbl support may require additional care here.  */
10727           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10728                        BFD_RELOC_LO16, AT);
10729           mips_optimize = hold_mips_optimize;
10730           relax_end ();
10731         }
10732       else
10733         abort ();
10734
10735       break;
10736         
10737     case M_SAA_AB:
10738       s = "saa";
10739       offbits = 0;
10740       fmt = "t,(b)";
10741       goto ld_st;
10742     case M_SAAD_AB:
10743       s = "saad";
10744       offbits = 0;
10745       fmt = "t,(b)";
10746       goto ld_st;
10747
10748    /* New code added to support COPZ instructions.
10749       This code builds table entries out of the macros in mip_opcodes.
10750       R4000 uses interlocks to handle coproc delays.
10751       Other chips (like the R3000) require nops to be inserted for delays.
10752
10753       FIXME: Currently, we require that the user handle delays.
10754       In order to fill delay slots for non-interlocked chips,
10755       we must have a way to specify delays based on the coprocessor.
10756       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
10757       What are the side-effects of the cop instruction?
10758       What cache support might we have and what are its effects?
10759       Both coprocessor & memory require delays. how long???
10760       What registers are read/set/modified?
10761
10762       If an itbl is provided to interpret cop instructions,
10763       this knowledge can be encoded in the itbl spec.  */
10764
10765     case M_COP0:
10766       s = "c0";
10767       goto copz;
10768     case M_COP1:
10769       s = "c1";
10770       goto copz;
10771     case M_COP2:
10772       s = "c2";
10773       goto copz;
10774     case M_COP3:
10775       s = "c3";
10776     copz:
10777       gas_assert (!mips_opts.micromips);
10778       /* For now we just do C (same as Cz).  The parameter will be
10779          stored in insn_opcode by mips_ip.  */
10780       macro_build (NULL, s, "C", (int) ip->insn_opcode);
10781       break;
10782
10783     case M_MOVE:
10784       move_register (dreg, sreg);
10785       break;
10786
10787     case M_MOVEP:
10788       gas_assert (mips_opts.micromips);
10789       gas_assert (mips_opts.insn32);
10790       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
10791       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
10792       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
10793       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
10794       move_register (dreg, sreg);
10795       move_register (breg, treg);
10796       break;
10797
10798     case M_DMUL:
10799       dbl = 1;
10800     case M_MUL:
10801       if (mips_opts.arch == CPU_R5900)
10802         {
10803           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
10804         }
10805       else
10806         {
10807       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
10808       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10809         }
10810       break;
10811
10812     case M_DMUL_I:
10813       dbl = 1;
10814     case M_MUL_I:
10815       /* The MIPS assembler some times generates shifts and adds.  I'm
10816          not trying to be that fancy. GCC should do this for us
10817          anyway.  */
10818       used_at = 1;
10819       load_register (AT, &imm_expr, dbl);
10820       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
10821       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10822       break;
10823
10824     case M_DMULO_I:
10825       dbl = 1;
10826     case M_MULO_I:
10827       imm = 1;
10828       goto do_mulo;
10829
10830     case M_DMULO:
10831       dbl = 1;
10832     case M_MULO:
10833     do_mulo:
10834       start_noreorder ();
10835       used_at = 1;
10836       if (imm)
10837         load_register (AT, &imm_expr, dbl);
10838       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
10839       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10840       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
10841       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10842       if (mips_trap)
10843         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
10844       else
10845         {
10846           if (mips_opts.micromips)
10847             micromips_label_expr (&label_expr);
10848           else
10849             label_expr.X_add_number = 8;
10850           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
10851           macro_build (NULL, "nop", "");
10852           macro_build (NULL, "break", BRK_FMT, 6);
10853           if (mips_opts.micromips)
10854             micromips_add_label ();
10855         }
10856       end_noreorder ();
10857       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10858       break;
10859
10860     case M_DMULOU_I:
10861       dbl = 1;
10862     case M_MULOU_I:
10863       imm = 1;
10864       goto do_mulou;
10865
10866     case M_DMULOU:
10867       dbl = 1;
10868     case M_MULOU:
10869     do_mulou:
10870       start_noreorder ();
10871       used_at = 1;
10872       if (imm)
10873         load_register (AT, &imm_expr, dbl);
10874       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
10875                    sreg, imm ? AT : treg);
10876       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10877       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10878       if (mips_trap)
10879         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
10880       else
10881         {
10882           if (mips_opts.micromips)
10883             micromips_label_expr (&label_expr);
10884           else
10885             label_expr.X_add_number = 8;
10886           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
10887           macro_build (NULL, "nop", "");
10888           macro_build (NULL, "break", BRK_FMT, 6);
10889           if (mips_opts.micromips)
10890             micromips_add_label ();
10891         }
10892       end_noreorder ();
10893       break;
10894
10895     case M_DROL:
10896       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10897         {
10898           if (dreg == sreg)
10899             {
10900               tempreg = AT;
10901               used_at = 1;
10902             }
10903           else
10904             {
10905               tempreg = dreg;
10906             }
10907           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
10908           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
10909           break;
10910         }
10911       used_at = 1;
10912       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10913       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
10914       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
10915       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10916       break;
10917
10918     case M_ROL:
10919       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10920         {
10921           if (dreg == sreg)
10922             {
10923               tempreg = AT;
10924               used_at = 1;
10925             }
10926           else
10927             {
10928               tempreg = dreg;
10929             }
10930           macro_build (NULL, "negu", "d,w", tempreg, treg);
10931           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
10932           break;
10933         }
10934       used_at = 1;
10935       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10936       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
10937       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
10938       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10939       break;
10940
10941     case M_DROL_I:
10942       {
10943         unsigned int rot;
10944         char *l;
10945         char *rr;
10946
10947         if (imm_expr.X_op != O_constant)
10948           as_bad (_("Improper rotate count"));
10949         rot = imm_expr.X_add_number & 0x3f;
10950         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10951           {
10952             rot = (64 - rot) & 0x3f;
10953             if (rot >= 32)
10954               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10955             else
10956               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10957             break;
10958           }
10959         if (rot == 0)
10960           {
10961             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10962             break;
10963           }
10964         l = (rot < 0x20) ? "dsll" : "dsll32";
10965         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10966         rot &= 0x1f;
10967         used_at = 1;
10968         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10969         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10970         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10971       }
10972       break;
10973
10974     case M_ROL_I:
10975       {
10976         unsigned int rot;
10977
10978         if (imm_expr.X_op != O_constant)
10979           as_bad (_("Improper rotate count"));
10980         rot = imm_expr.X_add_number & 0x1f;
10981         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10982           {
10983             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10984             break;
10985           }
10986         if (rot == 0)
10987           {
10988             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10989             break;
10990           }
10991         used_at = 1;
10992         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10993         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10994         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10995       }
10996       break;
10997
10998     case M_DROR:
10999       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11000         {
11001           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
11002           break;
11003         }
11004       used_at = 1;
11005       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
11006       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
11007       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
11008       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
11009       break;
11010
11011     case M_ROR:
11012       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11013         {
11014           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
11015           break;
11016         }
11017       used_at = 1;
11018       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
11019       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
11020       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
11021       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
11022       break;
11023
11024     case M_DROR_I:
11025       {
11026         unsigned int rot;
11027         char *l;
11028         char *rr;
11029
11030         if (imm_expr.X_op != O_constant)
11031           as_bad (_("Improper rotate count"));
11032         rot = imm_expr.X_add_number & 0x3f;
11033         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11034           {
11035             if (rot >= 32)
11036               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
11037             else
11038               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
11039             break;
11040           }
11041         if (rot == 0)
11042           {
11043             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
11044             break;
11045           }
11046         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
11047         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
11048         rot &= 0x1f;
11049         used_at = 1;
11050         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
11051         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
11052         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
11053       }
11054       break;
11055
11056     case M_ROR_I:
11057       {
11058         unsigned int rot;
11059
11060         if (imm_expr.X_op != O_constant)
11061           as_bad (_("Improper rotate count"));
11062         rot = imm_expr.X_add_number & 0x1f;
11063         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11064           {
11065             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
11066             break;
11067           }
11068         if (rot == 0)
11069           {
11070             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
11071             break;
11072           }
11073         used_at = 1;
11074         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
11075         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
11076         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
11077       }
11078       break;
11079
11080     case M_SEQ:
11081       if (sreg == 0)
11082         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
11083       else if (treg == 0)
11084         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11085       else
11086         {
11087           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
11088           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
11089         }
11090       break;
11091
11092     case M_SEQ_I:
11093       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11094         {
11095           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11096           break;
11097         }
11098       if (sreg == 0)
11099         {
11100           as_warn (_("Instruction %s: result is always false"),
11101                    ip->insn_mo->name);
11102           move_register (dreg, 0);
11103           break;
11104         }
11105       if (CPU_HAS_SEQ (mips_opts.arch)
11106           && -512 <= imm_expr.X_add_number
11107           && imm_expr.X_add_number < 512)
11108         {
11109           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
11110                        (int) imm_expr.X_add_number);
11111           break;
11112         }
11113       if (imm_expr.X_op == O_constant
11114           && imm_expr.X_add_number >= 0
11115           && imm_expr.X_add_number < 0x10000)
11116         {
11117           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
11118         }
11119       else if (imm_expr.X_op == O_constant
11120                && imm_expr.X_add_number > -0x8000
11121                && imm_expr.X_add_number < 0)
11122         {
11123           imm_expr.X_add_number = -imm_expr.X_add_number;
11124           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11125                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11126         }
11127       else if (CPU_HAS_SEQ (mips_opts.arch))
11128         {
11129           used_at = 1;
11130           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11131           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
11132           break;
11133         }
11134       else
11135         {
11136           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11137           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11138           used_at = 1;
11139         }
11140       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
11141       break;
11142
11143     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
11144       s = "slt";
11145       goto sge;
11146     case M_SGEU:
11147       s = "sltu";
11148     sge:
11149       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
11150       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11151       break;
11152
11153     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
11154     case M_SGEU_I:
11155       if (imm_expr.X_op == O_constant
11156           && imm_expr.X_add_number >= -0x8000
11157           && imm_expr.X_add_number < 0x8000)
11158         {
11159           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
11160                        dreg, sreg, BFD_RELOC_LO16);
11161         }
11162       else
11163         {
11164           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11165           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
11166                        dreg, sreg, AT);
11167           used_at = 1;
11168         }
11169       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11170       break;
11171
11172     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
11173       s = "slt";
11174       goto sgt;
11175     case M_SGTU:
11176       s = "sltu";
11177     sgt:
11178       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11179       break;
11180
11181     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
11182       s = "slt";
11183       goto sgti;
11184     case M_SGTU_I:
11185       s = "sltu";
11186     sgti:
11187       used_at = 1;
11188       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11189       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11190       break;
11191
11192     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
11193       s = "slt";
11194       goto sle;
11195     case M_SLEU:
11196       s = "sltu";
11197     sle:
11198       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
11199       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11200       break;
11201
11202     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
11203       s = "slt";
11204       goto slei;
11205     case M_SLEU_I:
11206       s = "sltu";
11207     slei:
11208       used_at = 1;
11209       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11210       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
11211       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
11212       break;
11213
11214     case M_SLT_I:
11215       if (imm_expr.X_op == O_constant
11216           && imm_expr.X_add_number >= -0x8000
11217           && imm_expr.X_add_number < 0x8000)
11218         {
11219           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11220           break;
11221         }
11222       used_at = 1;
11223       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11224       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
11225       break;
11226
11227     case M_SLTU_I:
11228       if (imm_expr.X_op == O_constant
11229           && imm_expr.X_add_number >= -0x8000
11230           && imm_expr.X_add_number < 0x8000)
11231         {
11232           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
11233                        BFD_RELOC_LO16);
11234           break;
11235         }
11236       used_at = 1;
11237       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11238       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
11239       break;
11240
11241     case M_SNE:
11242       if (sreg == 0)
11243         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
11244       else if (treg == 0)
11245         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11246       else
11247         {
11248           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
11249           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11250         }
11251       break;
11252
11253     case M_SNE_I:
11254       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11255         {
11256           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
11257           break;
11258         }
11259       if (sreg == 0)
11260         {
11261           as_warn (_("Instruction %s: result is always true"),
11262                    ip->insn_mo->name);
11263           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
11264                        dreg, 0, BFD_RELOC_LO16);
11265           break;
11266         }
11267       if (CPU_HAS_SEQ (mips_opts.arch)
11268           && -512 <= imm_expr.X_add_number
11269           && imm_expr.X_add_number < 512)
11270         {
11271           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
11272                        (int) imm_expr.X_add_number);
11273           break;
11274         }
11275       if (imm_expr.X_op == O_constant
11276           && imm_expr.X_add_number >= 0
11277           && imm_expr.X_add_number < 0x10000)
11278         {
11279           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
11280         }
11281       else if (imm_expr.X_op == O_constant
11282                && imm_expr.X_add_number > -0x8000
11283                && imm_expr.X_add_number < 0)
11284         {
11285           imm_expr.X_add_number = -imm_expr.X_add_number;
11286           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11287                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11288         }
11289       else if (CPU_HAS_SEQ (mips_opts.arch))
11290         {
11291           used_at = 1;
11292           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11293           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
11294           break;
11295         }
11296       else
11297         {
11298           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11299           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11300           used_at = 1;
11301         }
11302       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11303       break;
11304
11305     case M_SUB_I:
11306       s = "addi";
11307       s2 = "sub";
11308       goto do_subi;
11309     case M_SUBU_I:
11310       s = "addiu";
11311       s2 = "subu";
11312       goto do_subi;
11313     case M_DSUB_I:
11314       dbl = 1;
11315       s = "daddi";
11316       s2 = "dsub";
11317       if (!mips_opts.micromips)
11318         goto do_subi;
11319       if (imm_expr.X_op == O_constant
11320           && imm_expr.X_add_number > -0x200
11321           && imm_expr.X_add_number <= 0x200)
11322         {
11323           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
11324           break;
11325         }
11326       goto do_subi_i;
11327     case M_DSUBU_I:
11328       dbl = 1;
11329       s = "daddiu";
11330       s2 = "dsubu";
11331     do_subi:
11332       if (imm_expr.X_op == O_constant
11333           && imm_expr.X_add_number > -0x8000
11334           && imm_expr.X_add_number <= 0x8000)
11335         {
11336           imm_expr.X_add_number = -imm_expr.X_add_number;
11337           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11338           break;
11339         }
11340     do_subi_i:
11341       used_at = 1;
11342       load_register (AT, &imm_expr, dbl);
11343       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
11344       break;
11345
11346     case M_TEQ_I:
11347       s = "teq";
11348       goto trap;
11349     case M_TGE_I:
11350       s = "tge";
11351       goto trap;
11352     case M_TGEU_I:
11353       s = "tgeu";
11354       goto trap;
11355     case M_TLT_I:
11356       s = "tlt";
11357       goto trap;
11358     case M_TLTU_I:
11359       s = "tltu";
11360       goto trap;
11361     case M_TNE_I:
11362       s = "tne";
11363     trap:
11364       used_at = 1;
11365       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11366       macro_build (NULL, s, "s,t", sreg, AT);
11367       break;
11368
11369     case M_TRUNCWS:
11370     case M_TRUNCWD:
11371       gas_assert (!mips_opts.micromips);
11372       gas_assert (mips_opts.isa == ISA_MIPS1);
11373       used_at = 1;
11374       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
11375       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
11376
11377       /*
11378        * Is the double cfc1 instruction a bug in the mips assembler;
11379        * or is there a reason for it?
11380        */
11381       start_noreorder ();
11382       macro_build (NULL, "cfc1", "t,G", treg, RA);
11383       macro_build (NULL, "cfc1", "t,G", treg, RA);
11384       macro_build (NULL, "nop", "");
11385       expr1.X_add_number = 3;
11386       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
11387       expr1.X_add_number = 2;
11388       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
11389       macro_build (NULL, "ctc1", "t,G", AT, RA);
11390       macro_build (NULL, "nop", "");
11391       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
11392                    dreg, sreg);
11393       macro_build (NULL, "ctc1", "t,G", treg, RA);
11394       macro_build (NULL, "nop", "");
11395       end_noreorder ();
11396       break;
11397
11398     case M_ULH_AB:
11399       s = "lb";
11400       s2 = "lbu";
11401       off = 1;
11402       goto uld_st;
11403     case M_ULHU_AB:
11404       s = "lbu";
11405       s2 = "lbu";
11406       off = 1;
11407       goto uld_st;
11408     case M_ULW_AB:
11409       s = "lwl";
11410       s2 = "lwr";
11411       offbits = (mips_opts.micromips ? 12 : 16);
11412       off = 3;
11413       goto uld_st;
11414     case M_ULD_AB:
11415       s = "ldl";
11416       s2 = "ldr";
11417       offbits = (mips_opts.micromips ? 12 : 16);
11418       off = 7;
11419       goto uld_st;
11420     case M_USH_AB:
11421       s = "sb";
11422       s2 = "sb";
11423       off = 1;
11424       ust = 1;
11425       goto uld_st;
11426     case M_USW_AB:
11427       s = "swl";
11428       s2 = "swr";
11429       offbits = (mips_opts.micromips ? 12 : 16);
11430       off = 3;
11431       ust = 1;
11432       goto uld_st;
11433     case M_USD_AB:
11434       s = "sdl";
11435       s2 = "sdr";
11436       offbits = (mips_opts.micromips ? 12 : 16);
11437       off = 7;
11438       ust = 1;
11439
11440     uld_st:
11441       large_offset = !small_offset_p (off, align, offbits);
11442       ep = &offset_expr;
11443       expr1.X_add_number = 0;
11444       if (large_offset)
11445         {
11446           used_at = 1;
11447           tempreg = AT;
11448           if (small_offset_p (0, align, 16))
11449             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
11450                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11451           else
11452             {
11453               load_address (tempreg, ep, &used_at);
11454               if (breg != 0)
11455                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11456                              tempreg, tempreg, breg);
11457             }
11458           offset_reloc[0] = BFD_RELOC_LO16;
11459           offset_reloc[1] = BFD_RELOC_UNUSED;
11460           offset_reloc[2] = BFD_RELOC_UNUSED;
11461           breg = tempreg;
11462           tempreg = treg;
11463           ep = &expr1;
11464         }
11465       else if (!ust && treg == breg)
11466         {
11467           used_at = 1;
11468           tempreg = AT;
11469         }
11470       else
11471         tempreg = treg;
11472
11473       if (off == 1)
11474         goto ulh_sh;
11475
11476       if (!target_big_endian)
11477         ep->X_add_number += off;
11478       if (offbits == 12)
11479         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
11480       else
11481         macro_build (ep, s, "t,o(b)", tempreg, -1,
11482                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11483
11484       if (!target_big_endian)
11485         ep->X_add_number -= off;
11486       else
11487         ep->X_add_number += off;
11488       if (offbits == 12)
11489         macro_build (NULL, s2, "t,~(b)",
11490                      tempreg, (int) ep->X_add_number, breg);
11491       else
11492         macro_build (ep, s2, "t,o(b)", tempreg, -1,
11493                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11494
11495       /* If necessary, move the result in tempreg to the final destination.  */
11496       if (!ust && treg != tempreg)
11497         {
11498           /* Protect second load's delay slot.  */
11499           load_delay_nop ();
11500           move_register (treg, tempreg);
11501         }
11502       break;
11503
11504     ulh_sh:
11505       used_at = 1;
11506       if (target_big_endian == ust)
11507         ep->X_add_number += off;
11508       tempreg = ust || large_offset ? treg : AT;
11509       macro_build (ep, s, "t,o(b)", tempreg, -1,
11510                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11511
11512       /* For halfword transfers we need a temporary register to shuffle
11513          bytes.  Unfortunately for M_USH_A we have none available before
11514          the next store as AT holds the base address.  We deal with this
11515          case by clobbering TREG and then restoring it as with ULH.  */
11516       tempreg = ust == large_offset ? treg : AT;
11517       if (ust)
11518         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
11519
11520       if (target_big_endian == ust)
11521         ep->X_add_number -= off;
11522       else
11523         ep->X_add_number += off;
11524       macro_build (ep, s2, "t,o(b)", tempreg, -1,
11525                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11526
11527       /* For M_USH_A re-retrieve the LSB.  */
11528       if (ust && large_offset)
11529         {
11530           if (target_big_endian)
11531             ep->X_add_number += off;
11532           else
11533             ep->X_add_number -= off;
11534           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
11535                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
11536         }
11537       /* For ULH and M_USH_A OR the LSB in.  */
11538       if (!ust || large_offset)
11539         {
11540           tempreg = !large_offset ? AT : treg;
11541           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
11542           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
11543         }
11544       break;
11545
11546     default:
11547       /* FIXME: Check if this is one of the itbl macros, since they
11548          are added dynamically.  */
11549       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
11550       break;
11551     }
11552   if (!mips_opts.at && used_at)
11553     as_bad (_("Macro used $at after \".set noat\""));
11554 }
11555
11556 /* Implement macros in mips16 mode.  */
11557
11558 static void
11559 mips16_macro (struct mips_cl_insn *ip)
11560 {
11561   int mask;
11562   int xreg, yreg, zreg, tmp;
11563   expressionS expr1;
11564   int dbl;
11565   const char *s, *s2, *s3;
11566
11567   mask = ip->insn_mo->mask;
11568
11569   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
11570   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
11571   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
11572
11573   expr1.X_op = O_constant;
11574   expr1.X_op_symbol = NULL;
11575   expr1.X_add_symbol = NULL;
11576   expr1.X_add_number = 1;
11577
11578   dbl = 0;
11579
11580   switch (mask)
11581     {
11582     default:
11583       abort ();
11584
11585     case M_DDIV_3:
11586       dbl = 1;
11587     case M_DIV_3:
11588       s = "mflo";
11589       goto do_div3;
11590     case M_DREM_3:
11591       dbl = 1;
11592     case M_REM_3:
11593       s = "mfhi";
11594     do_div3:
11595       start_noreorder ();
11596       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
11597       expr1.X_add_number = 2;
11598       macro_build (&expr1, "bnez", "x,p", yreg);
11599       macro_build (NULL, "break", "6", 7);
11600
11601       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
11602          since that causes an overflow.  We should do that as well,
11603          but I don't see how to do the comparisons without a temporary
11604          register.  */
11605       end_noreorder ();
11606       macro_build (NULL, s, "x", zreg);
11607       break;
11608
11609     case M_DIVU_3:
11610       s = "divu";
11611       s2 = "mflo";
11612       goto do_divu3;
11613     case M_REMU_3:
11614       s = "divu";
11615       s2 = "mfhi";
11616       goto do_divu3;
11617     case M_DDIVU_3:
11618       s = "ddivu";
11619       s2 = "mflo";
11620       goto do_divu3;
11621     case M_DREMU_3:
11622       s = "ddivu";
11623       s2 = "mfhi";
11624     do_divu3:
11625       start_noreorder ();
11626       macro_build (NULL, s, "0,x,y", xreg, yreg);
11627       expr1.X_add_number = 2;
11628       macro_build (&expr1, "bnez", "x,p", yreg);
11629       macro_build (NULL, "break", "6", 7);
11630       end_noreorder ();
11631       macro_build (NULL, s2, "x", zreg);
11632       break;
11633
11634     case M_DMUL:
11635       dbl = 1;
11636     case M_MUL:
11637       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
11638       macro_build (NULL, "mflo", "x", zreg);
11639       break;
11640
11641     case M_DSUBU_I:
11642       dbl = 1;
11643       goto do_subu;
11644     case M_SUBU_I:
11645     do_subu:
11646       if (imm_expr.X_op != O_constant)
11647         as_bad (_("Unsupported large constant"));
11648       imm_expr.X_add_number = -imm_expr.X_add_number;
11649       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
11650       break;
11651
11652     case M_SUBU_I_2:
11653       if (imm_expr.X_op != O_constant)
11654         as_bad (_("Unsupported large constant"));
11655       imm_expr.X_add_number = -imm_expr.X_add_number;
11656       macro_build (&imm_expr, "addiu", "x,k", xreg);
11657       break;
11658
11659     case M_DSUBU_I_2:
11660       if (imm_expr.X_op != O_constant)
11661         as_bad (_("Unsupported large constant"));
11662       imm_expr.X_add_number = -imm_expr.X_add_number;
11663       macro_build (&imm_expr, "daddiu", "y,j", yreg);
11664       break;
11665
11666     case M_BEQ:
11667       s = "cmp";
11668       s2 = "bteqz";
11669       goto do_branch;
11670     case M_BNE:
11671       s = "cmp";
11672       s2 = "btnez";
11673       goto do_branch;
11674     case M_BLT:
11675       s = "slt";
11676       s2 = "btnez";
11677       goto do_branch;
11678     case M_BLTU:
11679       s = "sltu";
11680       s2 = "btnez";
11681       goto do_branch;
11682     case M_BLE:
11683       s = "slt";
11684       s2 = "bteqz";
11685       goto do_reverse_branch;
11686     case M_BLEU:
11687       s = "sltu";
11688       s2 = "bteqz";
11689       goto do_reverse_branch;
11690     case M_BGE:
11691       s = "slt";
11692       s2 = "bteqz";
11693       goto do_branch;
11694     case M_BGEU:
11695       s = "sltu";
11696       s2 = "bteqz";
11697       goto do_branch;
11698     case M_BGT:
11699       s = "slt";
11700       s2 = "btnez";
11701       goto do_reverse_branch;
11702     case M_BGTU:
11703       s = "sltu";
11704       s2 = "btnez";
11705
11706     do_reverse_branch:
11707       tmp = xreg;
11708       xreg = yreg;
11709       yreg = tmp;
11710
11711     do_branch:
11712       macro_build (NULL, s, "x,y", xreg, yreg);
11713       macro_build (&offset_expr, s2, "p");
11714       break;
11715
11716     case M_BEQ_I:
11717       s = "cmpi";
11718       s2 = "bteqz";
11719       s3 = "x,U";
11720       goto do_branch_i;
11721     case M_BNE_I:
11722       s = "cmpi";
11723       s2 = "btnez";
11724       s3 = "x,U";
11725       goto do_branch_i;
11726     case M_BLT_I:
11727       s = "slti";
11728       s2 = "btnez";
11729       s3 = "x,8";
11730       goto do_branch_i;
11731     case M_BLTU_I:
11732       s = "sltiu";
11733       s2 = "btnez";
11734       s3 = "x,8";
11735       goto do_branch_i;
11736     case M_BLE_I:
11737       s = "slti";
11738       s2 = "btnez";
11739       s3 = "x,8";
11740       goto do_addone_branch_i;
11741     case M_BLEU_I:
11742       s = "sltiu";
11743       s2 = "btnez";
11744       s3 = "x,8";
11745       goto do_addone_branch_i;
11746     case M_BGE_I:
11747       s = "slti";
11748       s2 = "bteqz";
11749       s3 = "x,8";
11750       goto do_branch_i;
11751     case M_BGEU_I:
11752       s = "sltiu";
11753       s2 = "bteqz";
11754       s3 = "x,8";
11755       goto do_branch_i;
11756     case M_BGT_I:
11757       s = "slti";
11758       s2 = "bteqz";
11759       s3 = "x,8";
11760       goto do_addone_branch_i;
11761     case M_BGTU_I:
11762       s = "sltiu";
11763       s2 = "bteqz";
11764       s3 = "x,8";
11765
11766     do_addone_branch_i:
11767       if (imm_expr.X_op != O_constant)
11768         as_bad (_("Unsupported large constant"));
11769       ++imm_expr.X_add_number;
11770
11771     do_branch_i:
11772       macro_build (&imm_expr, s, s3, xreg);
11773       macro_build (&offset_expr, s2, "p");
11774       break;
11775
11776     case M_ABS:
11777       expr1.X_add_number = 0;
11778       macro_build (&expr1, "slti", "x,8", yreg);
11779       if (xreg != yreg)
11780         move_register (xreg, yreg);
11781       expr1.X_add_number = 2;
11782       macro_build (&expr1, "bteqz", "p");
11783       macro_build (NULL, "neg", "x,w", xreg, xreg);
11784     }
11785 }
11786
11787 /* Assemble an instruction into its binary format.  If the instruction
11788    is a macro, set imm_expr, imm2_expr and offset_expr to the values
11789    associated with "I", "+I" and "A" operands respectively.  Otherwise
11790    store the value of the relocatable field (if any) in offset_expr.
11791    In both cases set offset_reloc to the relocation operators applied
11792    to offset_expr.  */
11793
11794 static void
11795 mips_ip (char *str, struct mips_cl_insn *ip)
11796 {
11797   bfd_boolean wrong_delay_slot_insns = FALSE;
11798   bfd_boolean need_delay_slot_ok = TRUE;
11799   struct mips_opcode *firstinsn = NULL;
11800   const struct mips_opcode *past;
11801   struct hash_control *hash;
11802   char *s;
11803   const char *args;
11804   char c = 0;
11805   struct mips_opcode *insn;
11806   char *argsStart;
11807   long opend;
11808   char *name;
11809   char *dot;
11810   long end;
11811   const struct mips_operand *operand;
11812   struct mips_arg_info arg;
11813
11814   insn_error = NULL;
11815
11816   if (mips_opts.micromips)
11817     {
11818       hash = micromips_op_hash;
11819       past = &micromips_opcodes[bfd_micromips_num_opcodes];
11820     }
11821   else
11822     {
11823       hash = op_hash;
11824       past = &mips_opcodes[NUMOPCODES];
11825     }
11826   forced_insn_length = 0;
11827   insn = NULL;
11828
11829   /* We first try to match an instruction up to a space or to the end.  */
11830   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
11831     continue;
11832
11833   /* Make a copy of the instruction so that we can fiddle with it.  */
11834   name = alloca (end + 1);
11835   memcpy (name, str, end);
11836   name[end] = '\0';
11837
11838   for (;;)
11839     {
11840       insn = (struct mips_opcode *) hash_find (hash, name);
11841
11842       if (insn != NULL || !mips_opts.micromips)
11843         break;
11844       if (forced_insn_length)
11845         break;
11846
11847       /* See if there's an instruction size override suffix,
11848          either `16' or `32', at the end of the mnemonic proper,
11849          that defines the operation, i.e. before the first `.'
11850          character if any.  Strip it and retry.  */
11851       dot = strchr (name, '.');
11852       opend = dot != NULL ? dot - name : end;
11853       if (opend < 3)
11854         break;
11855       if (name[opend - 2] == '1' && name[opend - 1] == '6')
11856         forced_insn_length = 2;
11857       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11858         forced_insn_length = 4;
11859       else
11860         break;
11861       memcpy (name + opend - 2, name + opend, end - opend + 1);
11862     }
11863   if (insn == NULL)
11864     {
11865       insn_error = _("Unrecognized opcode");
11866       return;
11867     }
11868
11869   /* For microMIPS instructions placed in a fixed-length branch delay slot
11870      we make up to two passes over the relevant fragment of the opcode
11871      table.  First we try instructions that meet the delay slot's length
11872      requirement.  If none matched, then we retry with the remaining ones
11873      and if one matches, then we use it and then issue an appropriate
11874      warning later on.  */
11875   argsStart = s = str + end;
11876   for (;;)
11877     {
11878       bfd_boolean delay_slot_ok;
11879       bfd_boolean size_ok;
11880       bfd_boolean ok;
11881       bfd_boolean more_alts;
11882
11883       gas_assert (strcmp (insn->name, name) == 0);
11884
11885       ok = is_opcode_valid (insn);
11886       size_ok = is_size_valid (insn);
11887       delay_slot_ok = is_delay_slot_valid (insn);
11888       if (!delay_slot_ok && !wrong_delay_slot_insns)
11889         {
11890           firstinsn = insn;
11891           wrong_delay_slot_insns = TRUE;
11892         }
11893       more_alts = (insn + 1 < past
11894                    && strcmp (insn[0].name, insn[1].name) == 0);
11895       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11896         {
11897           static char buf[256];
11898
11899           if (more_alts)
11900             {
11901               ++insn;
11902               continue;
11903             }
11904           if (wrong_delay_slot_insns && need_delay_slot_ok)
11905             {
11906               gas_assert (firstinsn);
11907               need_delay_slot_ok = FALSE;
11908               past = insn + 1;
11909               insn = firstinsn;
11910               continue;
11911             }
11912
11913           if (insn_error)
11914             return;
11915
11916           if (!ok)
11917             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11918                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11919                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11920           else if (mips_opts.insn32)
11921             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
11922           else
11923             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11924                      8 * forced_insn_length);
11925           insn_error = buf;
11926
11927           return;
11928         }
11929
11930       imm_expr.X_op = O_absent;
11931       imm2_expr.X_op = O_absent;
11932       offset_expr.X_op = O_absent;
11933       offset_reloc[0] = BFD_RELOC_UNUSED;
11934       offset_reloc[1] = BFD_RELOC_UNUSED;
11935       offset_reloc[2] = BFD_RELOC_UNUSED;
11936
11937       create_insn (ip, insn);
11938       insn_error = NULL;
11939       memset (&arg, 0, sizeof (arg));
11940       arg.insn = ip;
11941       arg.argnum = 1;
11942       arg.last_regno = ILLEGAL_REG;
11943       arg.dest_regno = ILLEGAL_REG;
11944       arg.soft_match = (more_alts
11945                         || (wrong_delay_slot_insns && need_delay_slot_ok));
11946       for (args = insn->args;; ++args)
11947         {
11948           SKIP_SPACE_TABS (s);
11949           if (*s == 0)
11950             {
11951               /* Handle unary instructions in which only one operand is given.
11952                  The source is then the same as the destination.  */
11953               if (arg.opnum == 1 && *args == ',')
11954                 switch (args[1])
11955                   {
11956                   case 'r':
11957                   case 'v':
11958                   case 'w':
11959                   case 'W':
11960                   case 'V':
11961                     arg.argnum = 1;
11962                     s = argsStart;
11963                     continue;
11964                   }
11965
11966               /* Treat elided base registers as $0.  */
11967               if (strcmp (args, "(b)") == 0)
11968                 args += 3;
11969
11970               /* Fail the match if there were too few operands.  */
11971               if (*args)
11972                 break;
11973
11974               /* Successful match.  */
11975               if (arg.dest_regno == arg.last_regno
11976                   && strncmp (ip->insn_mo->name, "jalr", 4) == 0)
11977                 {
11978                   if (arg.opnum == 2)
11979                     as_bad (_("Source and destination must be different"));
11980                   else if (arg.last_regno == 31)
11981                     as_bad (_("A destination register must be supplied"));
11982                 }
11983               check_completed_insn (&arg);
11984               return;
11985             }
11986
11987           /* Fail the match if the line has too many operands.   */
11988           if (*args == 0)
11989             break;
11990
11991           /* Handle characters that need to match exactly.  */
11992           if (*args == '(' || *args == ')' || *args == ',')
11993             {
11994               if (*s != *args)
11995                 break;
11996               if (*s == ',')
11997                 arg.argnum += 1;
11998               ++s;
11999               continue;
12000             }
12001
12002           /* Handle special macro operands.  Work out the properties of
12003              other operands.  */
12004           arg.opnum += 1;
12005           arg.optional_reg = FALSE;
12006           arg.lax_max = FALSE;
12007           switch (*args)
12008             {
12009             case '+':
12010               switch (args[1])
12011                 {
12012                 case '1':
12013                 case '2':
12014                 case '3':
12015                 case '4':
12016                 case 'B':
12017                 case 'C':
12018                 case 'F':
12019                 case 'G':
12020                 case 'H':
12021                 case 'J':
12022                 case 'Q':
12023                 case 'S':
12024                 case 's':
12025                   /* If these integer forms come last, there is no other
12026                      form of the instruction that could match.  Prefer to
12027                      give detailed error messages where possible.  */
12028                   if (args[2] == 0)
12029                     arg.soft_match = FALSE;
12030                   break;
12031
12032                 case 'I':
12033                   /* "+I" is like "I", except that imm2_expr is used.  */
12034                   my_getExpression (&imm2_expr, s);
12035                   if (imm2_expr.X_op != O_big
12036                       && imm2_expr.X_op != O_constant)
12037                   insn_error = _("absolute expression required");
12038                   if (HAVE_32BIT_GPRS)
12039                     normalize_constant_expr (&imm2_expr);
12040                   s = expr_end;
12041                   ++args;
12042                   continue;
12043
12044                 case 'i':
12045                   *offset_reloc = BFD_RELOC_MIPS_JMP;
12046                   break;
12047                 }
12048               break;
12049
12050             case '\'':
12051             case ':':
12052             case '@':
12053             case '^':
12054             case '$':
12055             case '\\':
12056             case '%':
12057             case '|':
12058             case '0':
12059             case '1':
12060             case '2':
12061             case '3':
12062             case '4':
12063             case '5':
12064             case '6':
12065             case '8':
12066             case 'B':
12067             case 'C':
12068             case 'J':
12069             case 'O':
12070             case 'P':
12071             case 'Q':
12072             case 'c':
12073             case 'h':
12074             case 'q':
12075               /* If these integer forms come last, there is no other
12076                  form of the instruction that could match.  Prefer to
12077                  give detailed error messages where possible.  */
12078               if (args[1] == 0)
12079                 arg.soft_match = FALSE;
12080               break;
12081
12082             case 'r':
12083             case 'v':
12084             case 'w':
12085             case 'W':
12086             case 'V':
12087               /* We have already matched a comma by this point, so the register
12088                  is only optional if there is another operand to come.  */
12089               gas_assert (arg.opnum == 2);
12090               arg.optional_reg = (args[1] == ',');
12091               break;
12092
12093             case 'I':
12094               my_getExpression (&imm_expr, s);
12095               if (imm_expr.X_op != O_big
12096                   && imm_expr.X_op != O_constant)
12097                 insn_error = _("absolute expression required");
12098               if (HAVE_32BIT_GPRS)
12099                 normalize_constant_expr (&imm_expr);
12100               s = expr_end;
12101               continue;
12102
12103             case 'A':
12104               my_getSmallExpression (&offset_expr, offset_reloc, s);
12105               if (offset_expr.X_op == O_register)
12106                 {
12107                   /* Assume that the offset has been elided and that what
12108                      we saw was a base register.  The match will fail later
12109                      if that assumption turns out to be wrong.  */
12110                   offset_expr.X_op = O_constant;
12111                   offset_expr.X_add_number = 0;
12112                 }
12113               else
12114                 {
12115                   normalize_address_expr (&offset_expr);
12116                   s = expr_end;
12117                 }
12118               continue;
12119
12120             case 'F':
12121               s = parse_float_constant (s, &imm_expr, &offset_expr, 8, TRUE);
12122               continue;
12123
12124             case 'L':
12125               s = parse_float_constant (s, &imm_expr, &offset_expr, 8, FALSE);
12126               continue;
12127
12128             case 'f':
12129               s = parse_float_constant (s, &imm_expr, &offset_expr, 4, TRUE);
12130               continue;
12131
12132             case 'l':
12133               s = parse_float_constant (s, &imm_expr, &offset_expr, 4, FALSE);
12134               continue;
12135
12136               /* ??? This is the traditional behavior, but is flaky if
12137                  there are alternative versions of the same instruction
12138                  for different subarchitectures.  The next alternative
12139                  might not be suitable.  */
12140             case 'j':
12141               /* For compatibility with older assemblers, we accept
12142                  0x8000-0xffff as signed 16-bit numbers when only
12143                  signed numbers are allowed.  */
12144               arg.lax_max = !more_alts;
12145             case 'i':
12146               /* Only accept non-constant operands if this is the
12147                  final alternative.  Later alternatives might include
12148                  a macro implementation.  */
12149               arg.allow_nonconst = !more_alts;
12150               break;
12151
12152             case 'u':
12153               /* There are no macro implementations for out-of-range values.  */
12154               arg.allow_nonconst = TRUE;
12155               break;
12156
12157             case 'o':
12158               /* There should always be a macro implementation.  */
12159               arg.allow_nonconst = FALSE;
12160               break;
12161
12162             case 'p':
12163               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12164               break;
12165
12166             case 'a':
12167               *offset_reloc = BFD_RELOC_MIPS_JMP;
12168               break;
12169
12170             case 'm':
12171               gas_assert (mips_opts.micromips);
12172               c = args[1];
12173               switch (c)
12174                 {
12175                 case 't':
12176                 case 'c':
12177                 case 'e':
12178                   /* We have already matched a comma by this point,
12179                      so the register is only optional if there is another
12180                      operand to come.  */
12181                   gas_assert (arg.opnum == 2);
12182                   arg.optional_reg = (args[2] == ',');
12183                   break;
12184
12185                 case 'D':
12186                 case 'E':
12187                   if (!forced_insn_length)
12188                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12189                   else if (c == 'D')
12190                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12191                   else
12192                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12193                   break;
12194                 }
12195               break;
12196             }
12197
12198           operand = (mips_opts.micromips
12199                      ? decode_micromips_operand (args)
12200                      : decode_mips_operand (args));
12201           if (!operand)
12202             abort ();
12203
12204           s = match_operand (&arg, operand, s);
12205           if (!s && arg.optional_reg)
12206             {
12207               /* Assume that the register has been elided and is the
12208                  same as the first operand.  */
12209               arg.optional_reg = FALSE;
12210               arg.argnum = 1;
12211               s = argsStart;
12212               SKIP_SPACE_TABS (s);
12213               s = match_operand (&arg, operand, s);
12214             }
12215           if (!s)
12216             break;
12217
12218           /* Skip prefixes.  */
12219           if (*args == '+' || *args == 'm')
12220             args++;
12221
12222           continue;
12223         }
12224       /* Args don't match.  */
12225       s = argsStart;
12226       insn_error = _("Illegal operands");
12227       if (more_alts)
12228         {
12229           ++insn;
12230           continue;
12231         }
12232       if (wrong_delay_slot_insns && need_delay_slot_ok)
12233         {
12234           gas_assert (firstinsn);
12235           need_delay_slot_ok = FALSE;
12236           past = insn + 1;
12237           insn = firstinsn;
12238           continue;
12239         }
12240       return;
12241     }
12242 }
12243
12244 /* As for mips_ip, but used when assembling MIPS16 code.
12245    Also set forced_insn_length to the resulting instruction size in
12246    bytes if the user explicitly requested a small or extended instruction.  */
12247
12248 static void
12249 mips16_ip (char *str, struct mips_cl_insn *ip)
12250 {
12251   char *s;
12252   const char *args;
12253   struct mips_opcode *insn;
12254   char *argsstart;
12255   size_t i;
12256   const struct mips_operand *operand;
12257   const struct mips_operand *ext_operand;
12258   struct mips_arg_info arg;
12259
12260   insn_error = NULL;
12261
12262   forced_insn_length = 0;
12263
12264   for (s = str; ISLOWER (*s); ++s)
12265     ;
12266   switch (*s)
12267     {
12268     case '\0':
12269       break;
12270
12271     case ' ':
12272       *s++ = '\0';
12273       break;
12274
12275     case '.':
12276       if (s[1] == 't' && s[2] == ' ')
12277         {
12278           *s = '\0';
12279           forced_insn_length = 2;
12280           s += 3;
12281           break;
12282         }
12283       else if (s[1] == 'e' && s[2] == ' ')
12284         {
12285           *s = '\0';
12286           forced_insn_length = 4;
12287           s += 3;
12288           break;
12289         }
12290       /* Fall through.  */
12291     default:
12292       insn_error = _("unknown opcode");
12293       return;
12294     }
12295
12296   if (mips_opts.noautoextend && !forced_insn_length)
12297     forced_insn_length = 2;
12298
12299   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
12300     {
12301       insn_error = _("unrecognized opcode");
12302       return;
12303     }
12304
12305   argsstart = s;
12306   for (;;)
12307     {
12308       bfd_boolean ok;
12309       bfd_boolean more_alts;
12310       char relax_char;
12311
12312       gas_assert (strcmp (insn->name, str) == 0);
12313
12314       ok = is_opcode_valid_16 (insn);
12315       more_alts = (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
12316                    && strcmp (insn[0].name, insn[1].name) == 0);
12317       if (! ok)
12318         {
12319           if (more_alts)
12320             {
12321               ++insn;
12322               continue;
12323             }
12324           else
12325             {
12326               if (!insn_error)
12327                 {
12328                   static char buf[100];
12329                   sprintf (buf,
12330                            _("Opcode not supported on this processor: %s (%s)"),
12331                            mips_cpu_info_from_arch (mips_opts.arch)->name,
12332                            mips_cpu_info_from_isa (mips_opts.isa)->name);
12333                   insn_error = buf;
12334                 }
12335               return;
12336             }
12337         }
12338
12339       create_insn (ip, insn);
12340       imm_expr.X_op = O_absent;
12341       imm2_expr.X_op = O_absent;
12342       offset_expr.X_op = O_absent;
12343       offset_reloc[0] = BFD_RELOC_UNUSED;
12344       offset_reloc[1] = BFD_RELOC_UNUSED;
12345       offset_reloc[2] = BFD_RELOC_UNUSED;
12346       relax_char = 0;
12347
12348       memset (&arg, 0, sizeof (arg));
12349       arg.insn = ip;
12350       arg.argnum = 1;
12351       arg.last_regno = ILLEGAL_REG;
12352       arg.dest_regno = ILLEGAL_REG;
12353       arg.soft_match = more_alts;
12354       relax_char = 0;
12355       for (args = insn->args; 1; ++args)
12356         {
12357           int c;
12358
12359           SKIP_SPACE_TABS (s);
12360           if (*s == 0)
12361             {
12362               offsetT value;
12363
12364               /* Handle unary instructions in which only one operand is given.
12365                  The source is then the same as the destination.  */
12366               if (arg.opnum == 1 && *args == ',')
12367                 switch (args[1])
12368                   {
12369                   case 'v':
12370                   case 'w':
12371                     arg.argnum = 1;
12372                     s = argsstart;
12373                     continue;
12374                   }
12375
12376               /* Fail the match if there were too few operands.  */
12377               if (*args)
12378                 break;
12379
12380               /* Successful match.  Stuff the immediate value in now, if
12381                  we can.  */
12382               if (insn->pinfo == INSN_MACRO)
12383                 {
12384                   gas_assert (relax_char == 0);
12385                   gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
12386                 }
12387               else if (relax_char
12388                        && offset_expr.X_op == O_constant
12389                        && calculate_reloc (*offset_reloc,
12390                                            offset_expr.X_add_number,
12391                                            &value))
12392                 {
12393                   mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
12394                                 forced_insn_length, &ip->insn_opcode);
12395                   offset_expr.X_op = O_absent;
12396                   *offset_reloc = BFD_RELOC_UNUSED;
12397                 }
12398               else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
12399                 {
12400                   if (forced_insn_length == 2)
12401                     as_bad (_("invalid unextended operand value"));
12402                   forced_insn_length = 4;
12403                   ip->insn_opcode |= MIPS16_EXTEND;
12404                 }
12405               else if (relax_char)
12406                 *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
12407
12408               check_completed_insn (&arg);
12409               return;
12410             }
12411
12412           /* Fail the match if the line has too many operands.   */
12413           if (*args == 0)
12414             break;
12415
12416           /* Handle characters that need to match exactly.  */
12417           if (*args == '(' || *args == ')' || *args == ',')
12418             {
12419               if (*s != *args)
12420                 break;
12421               if (*s == ',')
12422                 arg.argnum += 1;
12423               ++s;
12424               continue;
12425             }
12426
12427           arg.opnum += 1;
12428           arg.optional_reg = FALSE;
12429           c = *args;
12430           switch (c)
12431             {
12432             case 'v':
12433             case 'w':
12434               arg.optional_reg = (args[1] == ',');
12435               break;
12436
12437             case 'p':
12438             case 'q':
12439             case 'A':
12440             case 'B':
12441             case 'E':
12442               relax_char = c;
12443               break;
12444
12445             case 'I':
12446               my_getExpression (&imm_expr, s);
12447               if (imm_expr.X_op != O_big
12448                   && imm_expr.X_op != O_constant)
12449                 insn_error = _("absolute expression required");
12450               if (HAVE_32BIT_GPRS)
12451                 normalize_constant_expr (&imm_expr);
12452               s = expr_end;
12453               continue;
12454
12455             case 'a':
12456             case 'i':
12457               *offset_reloc = BFD_RELOC_MIPS16_JMP;
12458               ip->insn_opcode <<= 16;
12459               break;
12460             }
12461
12462           operand = decode_mips16_operand (c, FALSE);
12463           if (!operand)
12464             abort ();
12465
12466           /* '6' is a special case.  It is used for BREAK and SDBBP,
12467              whose operands are only meaningful to the software that decodes
12468              them.  This means that there is no architectural reason why
12469              they cannot be prefixed by EXTEND, but in practice,
12470              exception handlers will only look at the instruction
12471              itself.  We therefore allow '6' to be extended when
12472              disassembling but not when assembling.  */
12473           if (operand->type != OP_PCREL && c != '6')
12474             {
12475               ext_operand = decode_mips16_operand (c, TRUE);
12476               if (operand != ext_operand)
12477                 {
12478                   /* Parse the expression, allowing relocation operators.  */
12479                   i = my_getSmallExpression (&offset_expr, offset_reloc, s);
12480                   s = expr_end;
12481
12482                   if (offset_expr.X_op == O_register)
12483                     {
12484                       /* Handle elided offsets, which are equivalent to 0.  */
12485                       if (*s == '(')
12486                         {
12487                           offset_expr.X_op = O_constant;
12488                           offset_expr.X_add_number = 0;
12489                           relax_char = c;
12490                           continue;
12491                         }
12492                       /* Fail the match.  */
12493                       break;
12494                     }
12495                   /* '8' is used for SLTI(U) and has traditionally not
12496                      been allowed to take relocation operators.  */
12497                   if (i > 0 && (ext_operand->size != 16 || c == '8'))
12498                     break;
12499                   relax_char = c;
12500                   continue;
12501                 }
12502             }
12503
12504           s = match_operand (&arg, operand, s);
12505           if (!s && arg.optional_reg)
12506             {
12507               /* Assume that the register has been elided and is the
12508                  same as the first operand.  */
12509               arg.optional_reg = FALSE;
12510               arg.argnum = 1;
12511               s = argsstart;
12512               SKIP_SPACE_TABS (s);
12513               s = match_operand (&arg, operand, s);
12514             }
12515           if (!s)
12516             break;
12517           continue;
12518         }
12519
12520       /* Args don't match.  */
12521       if (more_alts)
12522         {
12523           ++insn;
12524           s = argsstart;
12525           continue;
12526         }
12527
12528       insn_error = _("illegal operands");
12529
12530       return;
12531     }
12532 }
12533
12534 /* This structure holds information we know about a mips16 immediate
12535    argument type.  */
12536
12537 struct mips16_immed_operand
12538 {
12539   /* The type code used in the argument string in the opcode table.  */
12540   int type;
12541   /* The number of bits in the short form of the opcode.  */
12542   int nbits;
12543   /* The number of bits in the extended form of the opcode.  */
12544   int extbits;
12545   /* The amount by which the short form is shifted when it is used;
12546      for example, the sw instruction has a shift count of 2.  */
12547   int shift;
12548   /* The amount by which the short form is shifted when it is stored
12549      into the instruction code.  */
12550   int op_shift;
12551   /* Non-zero if the short form is unsigned.  */
12552   int unsp;
12553   /* Non-zero if the extended form is unsigned.  */
12554   int extu;
12555   /* Non-zero if the value is PC relative.  */
12556   int pcrel;
12557 };
12558
12559 /* The mips16 immediate operand types.  */
12560
12561 static const struct mips16_immed_operand mips16_immed_operands[] =
12562 {
12563   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12564   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12565   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
12566   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
12567   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
12568   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
12569   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
12570   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
12571   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
12572   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
12573   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
12574   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
12575   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
12576   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
12577   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
12578   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
12579   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12580   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
12581   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
12582   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
12583   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
12584 };
12585
12586 #define MIPS16_NUM_IMMED \
12587   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
12588
12589 /* Marshal immediate value VAL for an extended MIPS16 instruction.
12590    NBITS is the number of significant bits in VAL.  */
12591
12592 static unsigned long
12593 mips16_immed_extend (offsetT val, unsigned int nbits)
12594 {
12595   int extval;
12596   if (nbits == 16)
12597     {
12598       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
12599       val &= 0x1f;
12600     }
12601   else if (nbits == 15)
12602     {
12603       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
12604       val &= 0xf;
12605     }
12606   else
12607     {
12608       extval = ((val & 0x1f) << 6) | (val & 0x20);
12609       val = 0;
12610     }
12611   return (extval << 16) | val;
12612 }
12613
12614 /* Install immediate value VAL into MIPS16 instruction *INSN,
12615    extending it if necessary.  The instruction in *INSN may
12616    already be extended.
12617
12618    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
12619    if none.  In the former case, VAL is a 16-bit number with no
12620    defined signedness.
12621
12622    TYPE is the type of the immediate field.  USER_INSN_LENGTH
12623    is the length that the user requested, or 0 if none.  */
12624
12625 static void
12626 mips16_immed (char *file, unsigned int line, int type,
12627               bfd_reloc_code_real_type reloc, offsetT val,
12628               unsigned int user_insn_length, unsigned long *insn)
12629 {
12630   const struct mips16_immed_operand *op;
12631   int mintiny, maxtiny;
12632
12633   op = mips16_immed_operands;
12634   while (op->type != type)
12635     {
12636       ++op;
12637       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
12638     }
12639
12640   if (op->unsp)
12641     {
12642       if (type == '<' || type == '>' || type == '[' || type == ']')
12643         {
12644           mintiny = 1;
12645           maxtiny = 1 << op->nbits;
12646         }
12647       else
12648         {
12649           mintiny = 0;
12650           maxtiny = (1 << op->nbits) - 1;
12651         }
12652       if (reloc != BFD_RELOC_UNUSED)
12653         val &= 0xffff;
12654     }
12655   else
12656     {
12657       mintiny = - (1 << (op->nbits - 1));
12658       maxtiny = (1 << (op->nbits - 1)) - 1;
12659       if (reloc != BFD_RELOC_UNUSED)
12660         val = SEXT_16BIT (val);
12661     }
12662
12663   /* Branch offsets have an implicit 0 in the lowest bit.  */
12664   if (type == 'p' || type == 'q')
12665     val /= 2;
12666
12667   if ((val & ((1 << op->shift) - 1)) != 0
12668       || val < (mintiny << op->shift)
12669       || val > (maxtiny << op->shift))
12670     {
12671       /* We need an extended instruction.  */
12672       if (user_insn_length == 2)
12673         as_bad_where (file, line, _("invalid unextended operand value"));
12674       else
12675         *insn |= MIPS16_EXTEND;
12676     }
12677   else if (user_insn_length == 4)
12678     {
12679       /* The operand doesn't force an unextended instruction to be extended.
12680          Warn if the user wanted an extended instruction anyway.  */
12681       *insn |= MIPS16_EXTEND;
12682       as_warn_where (file, line,
12683                      _("extended operand requested but not required"));
12684     }
12685
12686   if (mips16_opcode_length (*insn) == 2)
12687     {
12688       int insnval;
12689
12690       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
12691       insnval <<= op->op_shift;
12692       *insn |= insnval;
12693     }
12694   else
12695     {
12696       long minext, maxext;
12697
12698       if (reloc == BFD_RELOC_UNUSED)
12699         {
12700           if (op->extu)
12701             {
12702               minext = 0;
12703               maxext = (1 << op->extbits) - 1;
12704             }
12705           else
12706             {
12707               minext = - (1 << (op->extbits - 1));
12708               maxext = (1 << (op->extbits - 1)) - 1;
12709             }
12710           if (val < minext || val > maxext)
12711             as_bad_where (file, line,
12712                           _("operand value out of range for instruction"));
12713         }
12714
12715       *insn |= mips16_immed_extend (val, op->extbits);
12716     }
12717 }
12718 \f
12719 struct percent_op_match
12720 {
12721   const char *str;
12722   bfd_reloc_code_real_type reloc;
12723 };
12724
12725 static const struct percent_op_match mips_percent_op[] =
12726 {
12727   {"%lo", BFD_RELOC_LO16},
12728   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
12729   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
12730   {"%call16", BFD_RELOC_MIPS_CALL16},
12731   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
12732   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
12733   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
12734   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
12735   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
12736   {"%got", BFD_RELOC_MIPS_GOT16},
12737   {"%gp_rel", BFD_RELOC_GPREL16},
12738   {"%half", BFD_RELOC_16},
12739   {"%highest", BFD_RELOC_MIPS_HIGHEST},
12740   {"%higher", BFD_RELOC_MIPS_HIGHER},
12741   {"%neg", BFD_RELOC_MIPS_SUB},
12742   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
12743   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
12744   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
12745   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
12746   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
12747   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
12748   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
12749   {"%hi", BFD_RELOC_HI16_S}
12750 };
12751
12752 static const struct percent_op_match mips16_percent_op[] =
12753 {
12754   {"%lo", BFD_RELOC_MIPS16_LO16},
12755   {"%gprel", BFD_RELOC_MIPS16_GPREL},
12756   {"%got", BFD_RELOC_MIPS16_GOT16},
12757   {"%call16", BFD_RELOC_MIPS16_CALL16},
12758   {"%hi", BFD_RELOC_MIPS16_HI16_S},
12759   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
12760   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
12761   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
12762   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
12763   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
12764   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
12765   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
12766 };
12767
12768
12769 /* Return true if *STR points to a relocation operator.  When returning true,
12770    move *STR over the operator and store its relocation code in *RELOC.
12771    Leave both *STR and *RELOC alone when returning false.  */
12772
12773 static bfd_boolean
12774 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
12775 {
12776   const struct percent_op_match *percent_op;
12777   size_t limit, i;
12778
12779   if (mips_opts.mips16)
12780     {
12781       percent_op = mips16_percent_op;
12782       limit = ARRAY_SIZE (mips16_percent_op);
12783     }
12784   else
12785     {
12786       percent_op = mips_percent_op;
12787       limit = ARRAY_SIZE (mips_percent_op);
12788     }
12789
12790   for (i = 0; i < limit; i++)
12791     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
12792       {
12793         int len = strlen (percent_op[i].str);
12794
12795         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
12796           continue;
12797
12798         *str += strlen (percent_op[i].str);
12799         *reloc = percent_op[i].reloc;
12800
12801         /* Check whether the output BFD supports this relocation.
12802            If not, issue an error and fall back on something safe.  */
12803         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
12804           {
12805             as_bad (_("relocation %s isn't supported by the current ABI"),
12806                     percent_op[i].str);
12807             *reloc = BFD_RELOC_UNUSED;
12808           }
12809         return TRUE;
12810       }
12811   return FALSE;
12812 }
12813
12814
12815 /* Parse string STR as a 16-bit relocatable operand.  Store the
12816    expression in *EP and the relocations in the array starting
12817    at RELOC.  Return the number of relocation operators used.
12818
12819    On exit, EXPR_END points to the first character after the expression.  */
12820
12821 static size_t
12822 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
12823                        char *str)
12824 {
12825   bfd_reloc_code_real_type reversed_reloc[3];
12826   size_t reloc_index, i;
12827   int crux_depth, str_depth;
12828   char *crux;
12829
12830   /* Search for the start of the main expression, recoding relocations
12831      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
12832      of the main expression and with CRUX_DEPTH containing the number
12833      of open brackets at that point.  */
12834   reloc_index = -1;
12835   str_depth = 0;
12836   do
12837     {
12838       reloc_index++;
12839       crux = str;
12840       crux_depth = str_depth;
12841
12842       /* Skip over whitespace and brackets, keeping count of the number
12843          of brackets.  */
12844       while (*str == ' ' || *str == '\t' || *str == '(')
12845         if (*str++ == '(')
12846           str_depth++;
12847     }
12848   while (*str == '%'
12849          && reloc_index < (HAVE_NEWABI ? 3 : 1)
12850          && parse_relocation (&str, &reversed_reloc[reloc_index]));
12851
12852   my_getExpression (ep, crux);
12853   str = expr_end;
12854
12855   /* Match every open bracket.  */
12856   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
12857     if (*str++ == ')')
12858       crux_depth--;
12859
12860   if (crux_depth > 0)
12861     as_bad (_("unclosed '('"));
12862
12863   expr_end = str;
12864
12865   if (reloc_index != 0)
12866     {
12867       prev_reloc_op_frag = frag_now;
12868       for (i = 0; i < reloc_index; i++)
12869         reloc[i] = reversed_reloc[reloc_index - 1 - i];
12870     }
12871
12872   return reloc_index;
12873 }
12874
12875 static void
12876 my_getExpression (expressionS *ep, char *str)
12877 {
12878   char *save_in;
12879
12880   save_in = input_line_pointer;
12881   input_line_pointer = str;
12882   expression (ep);
12883   expr_end = input_line_pointer;
12884   input_line_pointer = save_in;
12885 }
12886
12887 char *
12888 md_atof (int type, char *litP, int *sizeP)
12889 {
12890   return ieee_md_atof (type, litP, sizeP, target_big_endian);
12891 }
12892
12893 void
12894 md_number_to_chars (char *buf, valueT val, int n)
12895 {
12896   if (target_big_endian)
12897     number_to_chars_bigendian (buf, val, n);
12898   else
12899     number_to_chars_littleendian (buf, val, n);
12900 }
12901 \f
12902 static int support_64bit_objects(void)
12903 {
12904   const char **list, **l;
12905   int yes;
12906
12907   list = bfd_target_list ();
12908   for (l = list; *l != NULL; l++)
12909     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
12910         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
12911       break;
12912   yes = (*l != NULL);
12913   free (list);
12914   return yes;
12915 }
12916
12917 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
12918    NEW_VALUE.  Warn if another value was already specified.  Note:
12919    we have to defer parsing the -march and -mtune arguments in order
12920    to handle 'from-abi' correctly, since the ABI might be specified
12921    in a later argument.  */
12922
12923 static void
12924 mips_set_option_string (const char **string_ptr, const char *new_value)
12925 {
12926   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
12927     as_warn (_("A different %s was already specified, is now %s"),
12928              string_ptr == &mips_arch_string ? "-march" : "-mtune",
12929              new_value);
12930
12931   *string_ptr = new_value;
12932 }
12933
12934 int
12935 md_parse_option (int c, char *arg)
12936 {
12937   unsigned int i;
12938
12939   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
12940     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
12941       {
12942         file_ase_explicit |= mips_set_ase (&mips_ases[i],
12943                                            c == mips_ases[i].option_on);
12944         return 1;
12945       }
12946
12947   switch (c)
12948     {
12949     case OPTION_CONSTRUCT_FLOATS:
12950       mips_disable_float_construction = 0;
12951       break;
12952
12953     case OPTION_NO_CONSTRUCT_FLOATS:
12954       mips_disable_float_construction = 1;
12955       break;
12956
12957     case OPTION_TRAP:
12958       mips_trap = 1;
12959       break;
12960
12961     case OPTION_BREAK:
12962       mips_trap = 0;
12963       break;
12964
12965     case OPTION_EB:
12966       target_big_endian = 1;
12967       break;
12968
12969     case OPTION_EL:
12970       target_big_endian = 0;
12971       break;
12972
12973     case 'O':
12974       if (arg == NULL)
12975         mips_optimize = 1;
12976       else if (arg[0] == '0')
12977         mips_optimize = 0;
12978       else if (arg[0] == '1')
12979         mips_optimize = 1;
12980       else
12981         mips_optimize = 2;
12982       break;
12983
12984     case 'g':
12985       if (arg == NULL)
12986         mips_debug = 2;
12987       else
12988         mips_debug = atoi (arg);
12989       break;
12990
12991     case OPTION_MIPS1:
12992       file_mips_isa = ISA_MIPS1;
12993       break;
12994
12995     case OPTION_MIPS2:
12996       file_mips_isa = ISA_MIPS2;
12997       break;
12998
12999     case OPTION_MIPS3:
13000       file_mips_isa = ISA_MIPS3;
13001       break;
13002
13003     case OPTION_MIPS4:
13004       file_mips_isa = ISA_MIPS4;
13005       break;
13006
13007     case OPTION_MIPS5:
13008       file_mips_isa = ISA_MIPS5;
13009       break;
13010
13011     case OPTION_MIPS32:
13012       file_mips_isa = ISA_MIPS32;
13013       break;
13014
13015     case OPTION_MIPS32R2:
13016       file_mips_isa = ISA_MIPS32R2;
13017       break;
13018
13019     case OPTION_MIPS64R2:
13020       file_mips_isa = ISA_MIPS64R2;
13021       break;
13022
13023     case OPTION_MIPS64:
13024       file_mips_isa = ISA_MIPS64;
13025       break;
13026
13027     case OPTION_MTUNE:
13028       mips_set_option_string (&mips_tune_string, arg);
13029       break;
13030
13031     case OPTION_MARCH:
13032       mips_set_option_string (&mips_arch_string, arg);
13033       break;
13034
13035     case OPTION_M4650:
13036       mips_set_option_string (&mips_arch_string, "4650");
13037       mips_set_option_string (&mips_tune_string, "4650");
13038       break;
13039
13040     case OPTION_NO_M4650:
13041       break;
13042
13043     case OPTION_M4010:
13044       mips_set_option_string (&mips_arch_string, "4010");
13045       mips_set_option_string (&mips_tune_string, "4010");
13046       break;
13047
13048     case OPTION_NO_M4010:
13049       break;
13050
13051     case OPTION_M4100:
13052       mips_set_option_string (&mips_arch_string, "4100");
13053       mips_set_option_string (&mips_tune_string, "4100");
13054       break;
13055
13056     case OPTION_NO_M4100:
13057       break;
13058
13059     case OPTION_M3900:
13060       mips_set_option_string (&mips_arch_string, "3900");
13061       mips_set_option_string (&mips_tune_string, "3900");
13062       break;
13063
13064     case OPTION_NO_M3900:
13065       break;
13066
13067     case OPTION_MICROMIPS:
13068       if (mips_opts.mips16 == 1)
13069         {
13070           as_bad (_("-mmicromips cannot be used with -mips16"));
13071           return 0;
13072         }
13073       mips_opts.micromips = 1;
13074       mips_no_prev_insn ();
13075       break;
13076
13077     case OPTION_NO_MICROMIPS:
13078       mips_opts.micromips = 0;
13079       mips_no_prev_insn ();
13080       break;
13081
13082     case OPTION_MIPS16:
13083       if (mips_opts.micromips == 1)
13084         {
13085           as_bad (_("-mips16 cannot be used with -micromips"));
13086           return 0;
13087         }
13088       mips_opts.mips16 = 1;
13089       mips_no_prev_insn ();
13090       break;
13091
13092     case OPTION_NO_MIPS16:
13093       mips_opts.mips16 = 0;
13094       mips_no_prev_insn ();
13095       break;
13096
13097     case OPTION_FIX_24K:
13098       mips_fix_24k = 1;
13099       break;
13100
13101     case OPTION_NO_FIX_24K:
13102       mips_fix_24k = 0;
13103       break;
13104
13105     case OPTION_FIX_LOONGSON2F_JUMP:
13106       mips_fix_loongson2f_jump = TRUE;
13107       break;
13108
13109     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13110       mips_fix_loongson2f_jump = FALSE;
13111       break;
13112
13113     case OPTION_FIX_LOONGSON2F_NOP:
13114       mips_fix_loongson2f_nop = TRUE;
13115       break;
13116
13117     case OPTION_NO_FIX_LOONGSON2F_NOP:
13118       mips_fix_loongson2f_nop = FALSE;
13119       break;
13120
13121     case OPTION_FIX_VR4120:
13122       mips_fix_vr4120 = 1;
13123       break;
13124
13125     case OPTION_NO_FIX_VR4120:
13126       mips_fix_vr4120 = 0;
13127       break;
13128
13129     case OPTION_FIX_VR4130:
13130       mips_fix_vr4130 = 1;
13131       break;
13132
13133     case OPTION_NO_FIX_VR4130:
13134       mips_fix_vr4130 = 0;
13135       break;
13136
13137     case OPTION_FIX_CN63XXP1:
13138       mips_fix_cn63xxp1 = TRUE;
13139       break;
13140
13141     case OPTION_NO_FIX_CN63XXP1:
13142       mips_fix_cn63xxp1 = FALSE;
13143       break;
13144
13145     case OPTION_RELAX_BRANCH:
13146       mips_relax_branch = 1;
13147       break;
13148
13149     case OPTION_NO_RELAX_BRANCH:
13150       mips_relax_branch = 0;
13151       break;
13152
13153     case OPTION_INSN32:
13154       mips_opts.insn32 = TRUE;
13155       break;
13156
13157     case OPTION_NO_INSN32:
13158       mips_opts.insn32 = FALSE;
13159       break;
13160
13161     case OPTION_MSHARED:
13162       mips_in_shared = TRUE;
13163       break;
13164
13165     case OPTION_MNO_SHARED:
13166       mips_in_shared = FALSE;
13167       break;
13168
13169     case OPTION_MSYM32:
13170       mips_opts.sym32 = TRUE;
13171       break;
13172
13173     case OPTION_MNO_SYM32:
13174       mips_opts.sym32 = FALSE;
13175       break;
13176
13177       /* When generating ELF code, we permit -KPIC and -call_shared to
13178          select SVR4_PIC, and -non_shared to select no PIC.  This is
13179          intended to be compatible with Irix 5.  */
13180     case OPTION_CALL_SHARED:
13181       mips_pic = SVR4_PIC;
13182       mips_abicalls = TRUE;
13183       break;
13184
13185     case OPTION_CALL_NONPIC:
13186       mips_pic = NO_PIC;
13187       mips_abicalls = TRUE;
13188       break;
13189
13190     case OPTION_NON_SHARED:
13191       mips_pic = NO_PIC;
13192       mips_abicalls = FALSE;
13193       break;
13194
13195       /* The -xgot option tells the assembler to use 32 bit offsets
13196          when accessing the got in SVR4_PIC mode.  It is for Irix
13197          compatibility.  */
13198     case OPTION_XGOT:
13199       mips_big_got = 1;
13200       break;
13201
13202     case 'G':
13203       g_switch_value = atoi (arg);
13204       g_switch_seen = 1;
13205       break;
13206
13207       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13208          and -mabi=64.  */
13209     case OPTION_32:
13210       mips_abi = O32_ABI;
13211       break;
13212
13213     case OPTION_N32:
13214       mips_abi = N32_ABI;
13215       break;
13216
13217     case OPTION_64:
13218       mips_abi = N64_ABI;
13219       if (!support_64bit_objects())
13220         as_fatal (_("No compiled in support for 64 bit object file format"));
13221       break;
13222
13223     case OPTION_GP32:
13224       file_mips_gp32 = 1;
13225       break;
13226
13227     case OPTION_GP64:
13228       file_mips_gp32 = 0;
13229       break;
13230
13231     case OPTION_FP32:
13232       file_mips_fp32 = 1;
13233       break;
13234
13235     case OPTION_FP64:
13236       file_mips_fp32 = 0;
13237       break;
13238
13239     case OPTION_SINGLE_FLOAT:
13240       file_mips_single_float = 1;
13241       break;
13242
13243     case OPTION_DOUBLE_FLOAT:
13244       file_mips_single_float = 0;
13245       break;
13246
13247     case OPTION_SOFT_FLOAT:
13248       file_mips_soft_float = 1;
13249       break;
13250
13251     case OPTION_HARD_FLOAT:
13252       file_mips_soft_float = 0;
13253       break;
13254
13255     case OPTION_MABI:
13256       if (strcmp (arg, "32") == 0)
13257         mips_abi = O32_ABI;
13258       else if (strcmp (arg, "o64") == 0)
13259         mips_abi = O64_ABI;
13260       else if (strcmp (arg, "n32") == 0)
13261         mips_abi = N32_ABI;
13262       else if (strcmp (arg, "64") == 0)
13263         {
13264           mips_abi = N64_ABI;
13265           if (! support_64bit_objects())
13266             as_fatal (_("No compiled in support for 64 bit object file "
13267                         "format"));
13268         }
13269       else if (strcmp (arg, "eabi") == 0)
13270         mips_abi = EABI_ABI;
13271       else
13272         {
13273           as_fatal (_("invalid abi -mabi=%s"), arg);
13274           return 0;
13275         }
13276       break;
13277
13278     case OPTION_M7000_HILO_FIX:
13279       mips_7000_hilo_fix = TRUE;
13280       break;
13281
13282     case OPTION_MNO_7000_HILO_FIX:
13283       mips_7000_hilo_fix = FALSE;
13284       break;
13285
13286     case OPTION_MDEBUG:
13287       mips_flag_mdebug = TRUE;
13288       break;
13289
13290     case OPTION_NO_MDEBUG:
13291       mips_flag_mdebug = FALSE;
13292       break;
13293
13294     case OPTION_PDR:
13295       mips_flag_pdr = TRUE;
13296       break;
13297
13298     case OPTION_NO_PDR:
13299       mips_flag_pdr = FALSE;
13300       break;
13301
13302     case OPTION_MVXWORKS_PIC:
13303       mips_pic = VXWORKS_PIC;
13304       break;
13305
13306     case OPTION_NAN:
13307       if (strcmp (arg, "2008") == 0)
13308         mips_flag_nan2008 = TRUE;
13309       else if (strcmp (arg, "legacy") == 0)
13310         mips_flag_nan2008 = FALSE;
13311       else
13312         {
13313           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13314           return 0;
13315         }
13316       break;
13317
13318     default:
13319       return 0;
13320     }
13321
13322     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13323
13324   return 1;
13325 }
13326 \f
13327 /* Set up globals to generate code for the ISA or processor
13328    described by INFO.  */
13329
13330 static void
13331 mips_set_architecture (const struct mips_cpu_info *info)
13332 {
13333   if (info != 0)
13334     {
13335       file_mips_arch = info->cpu;
13336       mips_opts.arch = info->cpu;
13337       mips_opts.isa = info->isa;
13338     }
13339 }
13340
13341
13342 /* Likewise for tuning.  */
13343
13344 static void
13345 mips_set_tune (const struct mips_cpu_info *info)
13346 {
13347   if (info != 0)
13348     mips_tune = info->cpu;
13349 }
13350
13351
13352 void
13353 mips_after_parse_args (void)
13354 {
13355   const struct mips_cpu_info *arch_info = 0;
13356   const struct mips_cpu_info *tune_info = 0;
13357
13358   /* GP relative stuff not working for PE */
13359   if (strncmp (TARGET_OS, "pe", 2) == 0)
13360     {
13361       if (g_switch_seen && g_switch_value != 0)
13362         as_bad (_("-G not supported in this configuration."));
13363       g_switch_value = 0;
13364     }
13365
13366   if (mips_abi == NO_ABI)
13367     mips_abi = MIPS_DEFAULT_ABI;
13368
13369   /* The following code determines the architecture and register size.
13370      Similar code was added to GCC 3.3 (see override_options() in
13371      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13372      as much as possible.  */
13373
13374   if (mips_arch_string != 0)
13375     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13376
13377   if (file_mips_isa != ISA_UNKNOWN)
13378     {
13379       /* Handle -mipsN.  At this point, file_mips_isa contains the
13380          ISA level specified by -mipsN, while arch_info->isa contains
13381          the -march selection (if any).  */
13382       if (arch_info != 0)
13383         {
13384           /* -march takes precedence over -mipsN, since it is more descriptive.
13385              There's no harm in specifying both as long as the ISA levels
13386              are the same.  */
13387           if (file_mips_isa != arch_info->isa)
13388             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13389                     mips_cpu_info_from_isa (file_mips_isa)->name,
13390                     mips_cpu_info_from_isa (arch_info->isa)->name);
13391         }
13392       else
13393         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13394     }
13395
13396   if (arch_info == 0)
13397     {
13398       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13399       gas_assert (arch_info);
13400     }
13401
13402   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13403     as_bad (_("-march=%s is not compatible with the selected ABI"),
13404             arch_info->name);
13405
13406   mips_set_architecture (arch_info);
13407
13408   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13409   if (mips_tune_string != 0)
13410     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13411
13412   if (tune_info == 0)
13413     mips_set_tune (arch_info);
13414   else
13415     mips_set_tune (tune_info);
13416
13417   if (file_mips_gp32 >= 0)
13418     {
13419       /* The user specified the size of the integer registers.  Make sure
13420          it agrees with the ABI and ISA.  */
13421       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13422         as_bad (_("-mgp64 used with a 32-bit processor"));
13423       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13424         as_bad (_("-mgp32 used with a 64-bit ABI"));
13425       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13426         as_bad (_("-mgp64 used with a 32-bit ABI"));
13427     }
13428   else
13429     {
13430       /* Infer the integer register size from the ABI and processor.
13431          Restrict ourselves to 32-bit registers if that's all the
13432          processor has, or if the ABI cannot handle 64-bit registers.  */
13433       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13434                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13435     }
13436
13437   switch (file_mips_fp32)
13438     {
13439     default:
13440     case -1:
13441       /* No user specified float register size.
13442          ??? GAS treats single-float processors as though they had 64-bit
13443          float registers (although it complains when double-precision
13444          instructions are used).  As things stand, saying they have 32-bit
13445          registers would lead to spurious "register must be even" messages.
13446          So here we assume float registers are never smaller than the
13447          integer ones.  */
13448       if (file_mips_gp32 == 0)
13449         /* 64-bit integer registers implies 64-bit float registers.  */
13450         file_mips_fp32 = 0;
13451       else if ((mips_opts.ase & FP64_ASES)
13452                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13453         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13454         file_mips_fp32 = 0;
13455       else
13456         /* 32-bit float registers.  */
13457         file_mips_fp32 = 1;
13458       break;
13459
13460     /* The user specified the size of the float registers.  Check if it
13461        agrees with the ABI and ISA.  */
13462     case 0:
13463       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13464         as_bad (_("-mfp64 used with a 32-bit fpu"));
13465       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13466                && !ISA_HAS_MXHC1 (mips_opts.isa))
13467         as_warn (_("-mfp64 used with a 32-bit ABI"));
13468       break;
13469     case 1:
13470       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13471         as_warn (_("-mfp32 used with a 64-bit ABI"));
13472       break;
13473     }
13474
13475   /* End of GCC-shared inference code.  */
13476
13477   /* This flag is set when we have a 64-bit capable CPU but use only
13478      32-bit wide registers.  Note that EABI does not use it.  */
13479   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13480       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13481           || mips_abi == O32_ABI))
13482     mips_32bitmode = 1;
13483
13484   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13485     as_bad (_("trap exception not supported at ISA 1"));
13486
13487   /* If the selected architecture includes support for ASEs, enable
13488      generation of code for them.  */
13489   if (mips_opts.mips16 == -1)
13490     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13491   if (mips_opts.micromips == -1)
13492     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13493
13494   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13495      ASEs from being selected implicitly.  */
13496   if (file_mips_fp32 == 1)
13497     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13498
13499   /* If the user didn't explicitly select or deselect a particular ASE,
13500      use the default setting for the CPU.  */
13501   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13502
13503   file_mips_isa = mips_opts.isa;
13504   file_ase = mips_opts.ase;
13505   mips_opts.gp32 = file_mips_gp32;
13506   mips_opts.fp32 = file_mips_fp32;
13507   mips_opts.soft_float = file_mips_soft_float;
13508   mips_opts.single_float = file_mips_single_float;
13509
13510   mips_check_isa_supports_ases ();
13511
13512   if (mips_flag_mdebug < 0)
13513     mips_flag_mdebug = 0;
13514 }
13515 \f
13516 void
13517 mips_init_after_args (void)
13518 {
13519   /* initialize opcodes */
13520   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
13521   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
13522 }
13523
13524 long
13525 md_pcrel_from (fixS *fixP)
13526 {
13527   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
13528   switch (fixP->fx_r_type)
13529     {
13530     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13531     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13532       /* Return the address of the delay slot.  */
13533       return addr + 2;
13534
13535     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13536     case BFD_RELOC_MICROMIPS_JMP:
13537     case BFD_RELOC_16_PCREL_S2:
13538     case BFD_RELOC_MIPS_JMP:
13539       /* Return the address of the delay slot.  */
13540       return addr + 4;
13541
13542     case BFD_RELOC_32_PCREL:
13543       return addr;
13544
13545     default:
13546       /* We have no relocation type for PC relative MIPS16 instructions.  */
13547       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
13548         as_bad_where (fixP->fx_file, fixP->fx_line,
13549                       _("PC relative MIPS16 instruction references a different section"));
13550       return addr;
13551     }
13552 }
13553
13554 /* This is called before the symbol table is processed.  In order to
13555    work with gcc when using mips-tfile, we must keep all local labels.
13556    However, in other cases, we want to discard them.  If we were
13557    called with -g, but we didn't see any debugging information, it may
13558    mean that gcc is smuggling debugging information through to
13559    mips-tfile, in which case we must generate all local labels.  */
13560
13561 void
13562 mips_frob_file_before_adjust (void)
13563 {
13564 #ifndef NO_ECOFF_DEBUGGING
13565   if (ECOFF_DEBUGGING
13566       && mips_debug != 0
13567       && ! ecoff_debugging_seen)
13568     flag_keep_locals = 1;
13569 #endif
13570 }
13571
13572 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
13573    the corresponding LO16 reloc.  This is called before md_apply_fix and
13574    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
13575    relocation operators.
13576
13577    For our purposes, a %lo() expression matches a %got() or %hi()
13578    expression if:
13579
13580       (a) it refers to the same symbol; and
13581       (b) the offset applied in the %lo() expression is no lower than
13582           the offset applied in the %got() or %hi().
13583
13584    (b) allows us to cope with code like:
13585
13586         lui     $4,%hi(foo)
13587         lh      $4,%lo(foo+2)($4)
13588
13589    ...which is legal on RELA targets, and has a well-defined behaviour
13590    if the user knows that adding 2 to "foo" will not induce a carry to
13591    the high 16 bits.
13592
13593    When several %lo()s match a particular %got() or %hi(), we use the
13594    following rules to distinguish them:
13595
13596      (1) %lo()s with smaller offsets are a better match than %lo()s with
13597          higher offsets.
13598
13599      (2) %lo()s with no matching %got() or %hi() are better than those
13600          that already have a matching %got() or %hi().
13601
13602      (3) later %lo()s are better than earlier %lo()s.
13603
13604    These rules are applied in order.
13605
13606    (1) means, among other things, that %lo()s with identical offsets are
13607    chosen if they exist.
13608
13609    (2) means that we won't associate several high-part relocations with
13610    the same low-part relocation unless there's no alternative.  Having
13611    several high parts for the same low part is a GNU extension; this rule
13612    allows careful users to avoid it.
13613
13614    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
13615    with the last high-part relocation being at the front of the list.
13616    It therefore makes sense to choose the last matching low-part
13617    relocation, all other things being equal.  It's also easier
13618    to code that way.  */
13619
13620 void
13621 mips_frob_file (void)
13622 {
13623   struct mips_hi_fixup *l;
13624   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
13625
13626   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
13627     {
13628       segment_info_type *seginfo;
13629       bfd_boolean matched_lo_p;
13630       fixS **hi_pos, **lo_pos, **pos;
13631
13632       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
13633
13634       /* If a GOT16 relocation turns out to be against a global symbol,
13635          there isn't supposed to be a matching LO.  Ignore %gots against
13636          constants; we'll report an error for those later.  */
13637       if (got16_reloc_p (l->fixp->fx_r_type)
13638           && !(l->fixp->fx_addsy
13639                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
13640         continue;
13641
13642       /* Check quickly whether the next fixup happens to be a matching %lo.  */
13643       if (fixup_has_matching_lo_p (l->fixp))
13644         continue;
13645
13646       seginfo = seg_info (l->seg);
13647
13648       /* Set HI_POS to the position of this relocation in the chain.
13649          Set LO_POS to the position of the chosen low-part relocation.
13650          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
13651          relocation that matches an immediately-preceding high-part
13652          relocation.  */
13653       hi_pos = NULL;
13654       lo_pos = NULL;
13655       matched_lo_p = FALSE;
13656       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
13657
13658       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
13659         {
13660           if (*pos == l->fixp)
13661             hi_pos = pos;
13662
13663           if ((*pos)->fx_r_type == looking_for_rtype
13664               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
13665               && (*pos)->fx_offset >= l->fixp->fx_offset
13666               && (lo_pos == NULL
13667                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
13668                   || (!matched_lo_p
13669                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
13670             lo_pos = pos;
13671
13672           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
13673                           && fixup_has_matching_lo_p (*pos));
13674         }
13675
13676       /* If we found a match, remove the high-part relocation from its
13677          current position and insert it before the low-part relocation.
13678          Make the offsets match so that fixup_has_matching_lo_p()
13679          will return true.
13680
13681          We don't warn about unmatched high-part relocations since some
13682          versions of gcc have been known to emit dead "lui ...%hi(...)"
13683          instructions.  */
13684       if (lo_pos != NULL)
13685         {
13686           l->fixp->fx_offset = (*lo_pos)->fx_offset;
13687           if (l->fixp->fx_next != *lo_pos)
13688             {
13689               *hi_pos = l->fixp->fx_next;
13690               l->fixp->fx_next = *lo_pos;
13691               *lo_pos = l->fixp;
13692             }
13693         }
13694     }
13695 }
13696
13697 int
13698 mips_force_relocation (fixS *fixp)
13699 {
13700   if (generic_force_reloc (fixp))
13701     return 1;
13702
13703   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
13704      so that the linker relaxation can update targets.  */
13705   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13706       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13707       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
13708     return 1;
13709
13710   return 0;
13711 }
13712
13713 /* Read the instruction associated with RELOC from BUF.  */
13714
13715 static unsigned int
13716 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
13717 {
13718   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13719     return read_compressed_insn (buf, 4);
13720   else
13721     return read_insn (buf);
13722 }
13723
13724 /* Write instruction INSN to BUF, given that it has been relocated
13725    by RELOC.  */
13726
13727 static void
13728 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
13729                   unsigned long insn)
13730 {
13731   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
13732     write_compressed_insn (buf, insn, 4);
13733   else
13734     write_insn (buf, insn);
13735 }
13736
13737 /* Apply a fixup to the object file.  */
13738
13739 void
13740 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
13741 {
13742   char *buf;
13743   unsigned long insn;
13744   reloc_howto_type *howto;
13745
13746   /* We ignore generic BFD relocations we don't know about.  */
13747   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
13748   if (! howto)
13749     return;
13750
13751   gas_assert (fixP->fx_size == 2
13752               || fixP->fx_size == 4
13753               || fixP->fx_r_type == BFD_RELOC_16
13754               || fixP->fx_r_type == BFD_RELOC_64
13755               || fixP->fx_r_type == BFD_RELOC_CTOR
13756               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
13757               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
13758               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
13759               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
13760               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
13761
13762   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
13763
13764   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
13765               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
13766               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
13767               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
13768               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
13769
13770   /* Don't treat parts of a composite relocation as done.  There are two
13771      reasons for this:
13772
13773      (1) The second and third parts will be against 0 (RSS_UNDEF) but
13774          should nevertheless be emitted if the first part is.
13775
13776      (2) In normal usage, composite relocations are never assembly-time
13777          constants.  The easiest way of dealing with the pathological
13778          exceptions is to generate a relocation against STN_UNDEF and
13779          leave everything up to the linker.  */
13780   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
13781     fixP->fx_done = 1;
13782
13783   switch (fixP->fx_r_type)
13784     {
13785     case BFD_RELOC_MIPS_TLS_GD:
13786     case BFD_RELOC_MIPS_TLS_LDM:
13787     case BFD_RELOC_MIPS_TLS_DTPREL32:
13788     case BFD_RELOC_MIPS_TLS_DTPREL64:
13789     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
13790     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
13791     case BFD_RELOC_MIPS_TLS_GOTTPREL:
13792     case BFD_RELOC_MIPS_TLS_TPREL32:
13793     case BFD_RELOC_MIPS_TLS_TPREL64:
13794     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
13795     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
13796     case BFD_RELOC_MICROMIPS_TLS_GD:
13797     case BFD_RELOC_MICROMIPS_TLS_LDM:
13798     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
13799     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
13800     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
13801     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
13802     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
13803     case BFD_RELOC_MIPS16_TLS_GD:
13804     case BFD_RELOC_MIPS16_TLS_LDM:
13805     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
13806     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
13807     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
13808     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
13809     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
13810       if (!fixP->fx_addsy)
13811         {
13812           as_bad_where (fixP->fx_file, fixP->fx_line,
13813                         _("TLS relocation against a constant"));
13814           break;
13815         }
13816       S_SET_THREAD_LOCAL (fixP->fx_addsy);
13817       /* fall through */
13818
13819     case BFD_RELOC_MIPS_JMP:
13820     case BFD_RELOC_MIPS_SHIFT5:
13821     case BFD_RELOC_MIPS_SHIFT6:
13822     case BFD_RELOC_MIPS_GOT_DISP:
13823     case BFD_RELOC_MIPS_GOT_PAGE:
13824     case BFD_RELOC_MIPS_GOT_OFST:
13825     case BFD_RELOC_MIPS_SUB:
13826     case BFD_RELOC_MIPS_INSERT_A:
13827     case BFD_RELOC_MIPS_INSERT_B:
13828     case BFD_RELOC_MIPS_DELETE:
13829     case BFD_RELOC_MIPS_HIGHEST:
13830     case BFD_RELOC_MIPS_HIGHER:
13831     case BFD_RELOC_MIPS_SCN_DISP:
13832     case BFD_RELOC_MIPS_REL16:
13833     case BFD_RELOC_MIPS_RELGOT:
13834     case BFD_RELOC_MIPS_JALR:
13835     case BFD_RELOC_HI16:
13836     case BFD_RELOC_HI16_S:
13837     case BFD_RELOC_LO16:
13838     case BFD_RELOC_GPREL16:
13839     case BFD_RELOC_MIPS_LITERAL:
13840     case BFD_RELOC_MIPS_CALL16:
13841     case BFD_RELOC_MIPS_GOT16:
13842     case BFD_RELOC_GPREL32:
13843     case BFD_RELOC_MIPS_GOT_HI16:
13844     case BFD_RELOC_MIPS_GOT_LO16:
13845     case BFD_RELOC_MIPS_CALL_HI16:
13846     case BFD_RELOC_MIPS_CALL_LO16:
13847     case BFD_RELOC_MIPS16_GPREL:
13848     case BFD_RELOC_MIPS16_GOT16:
13849     case BFD_RELOC_MIPS16_CALL16:
13850     case BFD_RELOC_MIPS16_HI16:
13851     case BFD_RELOC_MIPS16_HI16_S:
13852     case BFD_RELOC_MIPS16_LO16:
13853     case BFD_RELOC_MIPS16_JMP:
13854     case BFD_RELOC_MICROMIPS_JMP:
13855     case BFD_RELOC_MICROMIPS_GOT_DISP:
13856     case BFD_RELOC_MICROMIPS_GOT_PAGE:
13857     case BFD_RELOC_MICROMIPS_GOT_OFST:
13858     case BFD_RELOC_MICROMIPS_SUB:
13859     case BFD_RELOC_MICROMIPS_HIGHEST:
13860     case BFD_RELOC_MICROMIPS_HIGHER:
13861     case BFD_RELOC_MICROMIPS_SCN_DISP:
13862     case BFD_RELOC_MICROMIPS_JALR:
13863     case BFD_RELOC_MICROMIPS_HI16:
13864     case BFD_RELOC_MICROMIPS_HI16_S:
13865     case BFD_RELOC_MICROMIPS_LO16:
13866     case BFD_RELOC_MICROMIPS_GPREL16:
13867     case BFD_RELOC_MICROMIPS_LITERAL:
13868     case BFD_RELOC_MICROMIPS_CALL16:
13869     case BFD_RELOC_MICROMIPS_GOT16:
13870     case BFD_RELOC_MICROMIPS_GOT_HI16:
13871     case BFD_RELOC_MICROMIPS_GOT_LO16:
13872     case BFD_RELOC_MICROMIPS_CALL_HI16:
13873     case BFD_RELOC_MICROMIPS_CALL_LO16:
13874     case BFD_RELOC_MIPS_EH:
13875       if (fixP->fx_done)
13876         {
13877           offsetT value;
13878
13879           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
13880             {
13881               insn = read_reloc_insn (buf, fixP->fx_r_type);
13882               if (mips16_reloc_p (fixP->fx_r_type))
13883                 insn |= mips16_immed_extend (value, 16);
13884               else
13885                 insn |= (value & 0xffff);
13886               write_reloc_insn (buf, fixP->fx_r_type, insn);
13887             }
13888           else
13889             as_bad_where (fixP->fx_file, fixP->fx_line,
13890                           _("Unsupported constant in relocation"));
13891         }
13892       break;
13893
13894     case BFD_RELOC_64:
13895       /* This is handled like BFD_RELOC_32, but we output a sign
13896          extended value if we are only 32 bits.  */
13897       if (fixP->fx_done)
13898         {
13899           if (8 <= sizeof (valueT))
13900             md_number_to_chars (buf, *valP, 8);
13901           else
13902             {
13903               valueT hiv;
13904
13905               if ((*valP & 0x80000000) != 0)
13906                 hiv = 0xffffffff;
13907               else
13908                 hiv = 0;
13909               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
13910               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
13911             }
13912         }
13913       break;
13914
13915     case BFD_RELOC_RVA:
13916     case BFD_RELOC_32:
13917     case BFD_RELOC_32_PCREL:
13918     case BFD_RELOC_16:
13919       /* If we are deleting this reloc entry, we must fill in the
13920          value now.  This can happen if we have a .word which is not
13921          resolved when it appears but is later defined.  */
13922       if (fixP->fx_done)
13923         md_number_to_chars (buf, *valP, fixP->fx_size);
13924       break;
13925
13926     case BFD_RELOC_16_PCREL_S2:
13927       if ((*valP & 0x3) != 0)
13928         as_bad_where (fixP->fx_file, fixP->fx_line,
13929                       _("Branch to misaligned address (%lx)"), (long) *valP);
13930
13931       /* We need to save the bits in the instruction since fixup_segment()
13932          might be deleting the relocation entry (i.e., a branch within
13933          the current segment).  */
13934       if (! fixP->fx_done)
13935         break;
13936
13937       /* Update old instruction data.  */
13938       insn = read_insn (buf);
13939
13940       if (*valP + 0x20000 <= 0x3ffff)
13941         {
13942           insn |= (*valP >> 2) & 0xffff;
13943           write_insn (buf, insn);
13944         }
13945       else if (mips_pic == NO_PIC
13946                && fixP->fx_done
13947                && fixP->fx_frag->fr_address >= text_section->vma
13948                && (fixP->fx_frag->fr_address
13949                    < text_section->vma + bfd_get_section_size (text_section))
13950                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
13951                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
13952                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
13953         {
13954           /* The branch offset is too large.  If this is an
13955              unconditional branch, and we are not generating PIC code,
13956              we can convert it to an absolute jump instruction.  */
13957           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
13958             insn = 0x0c000000;  /* jal */
13959           else
13960             insn = 0x08000000;  /* j */
13961           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
13962           fixP->fx_done = 0;
13963           fixP->fx_addsy = section_symbol (text_section);
13964           *valP += md_pcrel_from (fixP);
13965           write_insn (buf, insn);
13966         }
13967       else
13968         {
13969           /* If we got here, we have branch-relaxation disabled,
13970              and there's nothing we can do to fix this instruction
13971              without turning it into a longer sequence.  */
13972           as_bad_where (fixP->fx_file, fixP->fx_line,
13973                         _("Branch out of range"));
13974         }
13975       break;
13976
13977     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13978     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13979     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13980       /* We adjust the offset back to even.  */
13981       if ((*valP & 0x1) != 0)
13982         --(*valP);
13983
13984       if (! fixP->fx_done)
13985         break;
13986
13987       /* Should never visit here, because we keep the relocation.  */
13988       abort ();
13989       break;
13990
13991     case BFD_RELOC_VTABLE_INHERIT:
13992       fixP->fx_done = 0;
13993       if (fixP->fx_addsy
13994           && !S_IS_DEFINED (fixP->fx_addsy)
13995           && !S_IS_WEAK (fixP->fx_addsy))
13996         S_SET_WEAK (fixP->fx_addsy);
13997       break;
13998
13999     case BFD_RELOC_VTABLE_ENTRY:
14000       fixP->fx_done = 0;
14001       break;
14002
14003     default:
14004       abort ();
14005     }
14006
14007   /* Remember value for tc_gen_reloc.  */
14008   fixP->fx_addnumber = *valP;
14009 }
14010
14011 static symbolS *
14012 get_symbol (void)
14013 {
14014   int c;
14015   char *name;
14016   symbolS *p;
14017
14018   name = input_line_pointer;
14019   c = get_symbol_end ();
14020   p = (symbolS *) symbol_find_or_make (name);
14021   *input_line_pointer = c;
14022   return p;
14023 }
14024
14025 /* Align the current frag to a given power of two.  If a particular
14026    fill byte should be used, FILL points to an integer that contains
14027    that byte, otherwise FILL is null.
14028
14029    This function used to have the comment:
14030
14031       The MIPS assembler also automatically adjusts any preceding label.
14032
14033    The implementation therefore applied the adjustment to a maximum of
14034    one label.  However, other label adjustments are applied to batches
14035    of labels, and adjusting just one caused problems when new labels
14036    were added for the sake of debugging or unwind information.
14037    We therefore adjust all preceding labels (given as LABELS) instead.  */
14038
14039 static void
14040 mips_align (int to, int *fill, struct insn_label_list *labels)
14041 {
14042   mips_emit_delays ();
14043   mips_record_compressed_mode ();
14044   if (fill == NULL && subseg_text_p (now_seg))
14045     frag_align_code (to, 0);
14046   else
14047     frag_align (to, fill ? *fill : 0, 0);
14048   record_alignment (now_seg, to);
14049   mips_move_labels (labels, FALSE);
14050 }
14051
14052 /* Align to a given power of two.  .align 0 turns off the automatic
14053    alignment used by the data creating pseudo-ops.  */
14054
14055 static void
14056 s_align (int x ATTRIBUTE_UNUSED)
14057 {
14058   int temp, fill_value, *fill_ptr;
14059   long max_alignment = 28;
14060
14061   /* o Note that the assembler pulls down any immediately preceding label
14062        to the aligned address.
14063      o It's not documented but auto alignment is reinstated by
14064        a .align pseudo instruction.
14065      o Note also that after auto alignment is turned off the mips assembler
14066        issues an error on attempt to assemble an improperly aligned data item.
14067        We don't.  */
14068
14069   temp = get_absolute_expression ();
14070   if (temp > max_alignment)
14071     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14072   else if (temp < 0)
14073     {
14074       as_warn (_("Alignment negative: 0 assumed."));
14075       temp = 0;
14076     }
14077   if (*input_line_pointer == ',')
14078     {
14079       ++input_line_pointer;
14080       fill_value = get_absolute_expression ();
14081       fill_ptr = &fill_value;
14082     }
14083   else
14084     fill_ptr = 0;
14085   if (temp)
14086     {
14087       segment_info_type *si = seg_info (now_seg);
14088       struct insn_label_list *l = si->label_list;
14089       /* Auto alignment should be switched on by next section change.  */
14090       auto_align = 1;
14091       mips_align (temp, fill_ptr, l);
14092     }
14093   else
14094     {
14095       auto_align = 0;
14096     }
14097
14098   demand_empty_rest_of_line ();
14099 }
14100
14101 static void
14102 s_change_sec (int sec)
14103 {
14104   segT seg;
14105
14106   /* The ELF backend needs to know that we are changing sections, so
14107      that .previous works correctly.  We could do something like check
14108      for an obj_section_change_hook macro, but that might be confusing
14109      as it would not be appropriate to use it in the section changing
14110      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14111      This should be cleaner, somehow.  */
14112   obj_elf_section_change_hook ();
14113
14114   mips_emit_delays ();
14115
14116   switch (sec)
14117     {
14118     case 't':
14119       s_text (0);
14120       break;
14121     case 'd':
14122       s_data (0);
14123       break;
14124     case 'b':
14125       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14126       demand_empty_rest_of_line ();
14127       break;
14128
14129     case 'r':
14130       seg = subseg_new (RDATA_SECTION_NAME,
14131                         (subsegT) get_absolute_expression ());
14132       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14133                                               | SEC_READONLY | SEC_RELOC
14134                                               | SEC_DATA));
14135       if (strncmp (TARGET_OS, "elf", 3) != 0)
14136         record_alignment (seg, 4);
14137       demand_empty_rest_of_line ();
14138       break;
14139
14140     case 's':
14141       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14142       bfd_set_section_flags (stdoutput, seg,
14143                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14144       if (strncmp (TARGET_OS, "elf", 3) != 0)
14145         record_alignment (seg, 4);
14146       demand_empty_rest_of_line ();
14147       break;
14148
14149     case 'B':
14150       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14151       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14152       if (strncmp (TARGET_OS, "elf", 3) != 0)
14153         record_alignment (seg, 4);
14154       demand_empty_rest_of_line ();
14155       break;
14156     }
14157
14158   auto_align = 1;
14159 }
14160
14161 void
14162 s_change_section (int ignore ATTRIBUTE_UNUSED)
14163 {
14164   char *section_name;
14165   char c;
14166   char next_c = 0;
14167   int section_type;
14168   int section_flag;
14169   int section_entry_size;
14170   int section_alignment;
14171
14172   section_name = input_line_pointer;
14173   c = get_symbol_end ();
14174   if (c)
14175     next_c = *(input_line_pointer + 1);
14176
14177   /* Do we have .section Name<,"flags">?  */
14178   if (c != ',' || (c == ',' && next_c == '"'))
14179     {
14180       /* just after name is now '\0'.  */
14181       *input_line_pointer = c;
14182       input_line_pointer = section_name;
14183       obj_elf_section (ignore);
14184       return;
14185     }
14186   input_line_pointer++;
14187
14188   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14189   if (c == ',')
14190     section_type = get_absolute_expression ();
14191   else
14192     section_type = 0;
14193   if (*input_line_pointer++ == ',')
14194     section_flag = get_absolute_expression ();
14195   else
14196     section_flag = 0;
14197   if (*input_line_pointer++ == ',')
14198     section_entry_size = get_absolute_expression ();
14199   else
14200     section_entry_size = 0;
14201   if (*input_line_pointer++ == ',')
14202     section_alignment = get_absolute_expression ();
14203   else
14204     section_alignment = 0;
14205   /* FIXME: really ignore?  */
14206   (void) section_alignment;
14207
14208   section_name = xstrdup (section_name);
14209
14210   /* When using the generic form of .section (as implemented by obj-elf.c),
14211      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14212      traditionally had to fall back on the more common @progbits instead.
14213
14214      There's nothing really harmful in this, since bfd will correct
14215      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14216      means that, for backwards compatibility, the special_section entries
14217      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14218
14219      Even so, we shouldn't force users of the MIPS .section syntax to
14220      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14221      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14222      generic type-checking code.  */
14223   if (section_type == SHT_MIPS_DWARF)
14224     section_type = SHT_PROGBITS;
14225
14226   obj_elf_change_section (section_name, section_type, section_flag,
14227                           section_entry_size, 0, 0, 0);
14228
14229   if (now_seg->name != section_name)
14230     free (section_name);
14231 }
14232
14233 void
14234 mips_enable_auto_align (void)
14235 {
14236   auto_align = 1;
14237 }
14238
14239 static void
14240 s_cons (int log_size)
14241 {
14242   segment_info_type *si = seg_info (now_seg);
14243   struct insn_label_list *l = si->label_list;
14244
14245   mips_emit_delays ();
14246   if (log_size > 0 && auto_align)
14247     mips_align (log_size, 0, l);
14248   cons (1 << log_size);
14249   mips_clear_insn_labels ();
14250 }
14251
14252 static void
14253 s_float_cons (int type)
14254 {
14255   segment_info_type *si = seg_info (now_seg);
14256   struct insn_label_list *l = si->label_list;
14257
14258   mips_emit_delays ();
14259
14260   if (auto_align)
14261     {
14262       if (type == 'd')
14263         mips_align (3, 0, l);
14264       else
14265         mips_align (2, 0, l);
14266     }
14267
14268   float_cons (type);
14269   mips_clear_insn_labels ();
14270 }
14271
14272 /* Handle .globl.  We need to override it because on Irix 5 you are
14273    permitted to say
14274        .globl foo .text
14275    where foo is an undefined symbol, to mean that foo should be
14276    considered to be the address of a function.  */
14277
14278 static void
14279 s_mips_globl (int x ATTRIBUTE_UNUSED)
14280 {
14281   char *name;
14282   int c;
14283   symbolS *symbolP;
14284   flagword flag;
14285
14286   do
14287     {
14288       name = input_line_pointer;
14289       c = get_symbol_end ();
14290       symbolP = symbol_find_or_make (name);
14291       S_SET_EXTERNAL (symbolP);
14292
14293       *input_line_pointer = c;
14294       SKIP_WHITESPACE ();
14295
14296       /* On Irix 5, every global symbol that is not explicitly labelled as
14297          being a function is apparently labelled as being an object.  */
14298       flag = BSF_OBJECT;
14299
14300       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14301           && (*input_line_pointer != ','))
14302         {
14303           char *secname;
14304           asection *sec;
14305
14306           secname = input_line_pointer;
14307           c = get_symbol_end ();
14308           sec = bfd_get_section_by_name (stdoutput, secname);
14309           if (sec == NULL)
14310             as_bad (_("%s: no such section"), secname);
14311           *input_line_pointer = c;
14312
14313           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14314             flag = BSF_FUNCTION;
14315         }
14316
14317       symbol_get_bfdsym (symbolP)->flags |= flag;
14318
14319       c = *input_line_pointer;
14320       if (c == ',')
14321         {
14322           input_line_pointer++;
14323           SKIP_WHITESPACE ();
14324           if (is_end_of_line[(unsigned char) *input_line_pointer])
14325             c = '\n';
14326         }
14327     }
14328   while (c == ',');
14329
14330   demand_empty_rest_of_line ();
14331 }
14332
14333 static void
14334 s_option (int x ATTRIBUTE_UNUSED)
14335 {
14336   char *opt;
14337   char c;
14338
14339   opt = input_line_pointer;
14340   c = get_symbol_end ();
14341
14342   if (*opt == 'O')
14343     {
14344       /* FIXME: What does this mean?  */
14345     }
14346   else if (strncmp (opt, "pic", 3) == 0)
14347     {
14348       int i;
14349
14350       i = atoi (opt + 3);
14351       if (i == 0)
14352         mips_pic = NO_PIC;
14353       else if (i == 2)
14354         {
14355           mips_pic = SVR4_PIC;
14356           mips_abicalls = TRUE;
14357         }
14358       else
14359         as_bad (_(".option pic%d not supported"), i);
14360
14361       if (mips_pic == SVR4_PIC)
14362         {
14363           if (g_switch_seen && g_switch_value != 0)
14364             as_warn (_("-G may not be used with SVR4 PIC code"));
14365           g_switch_value = 0;
14366           bfd_set_gp_size (stdoutput, 0);
14367         }
14368     }
14369   else
14370     as_warn (_("Unrecognized option \"%s\""), opt);
14371
14372   *input_line_pointer = c;
14373   demand_empty_rest_of_line ();
14374 }
14375
14376 /* This structure is used to hold a stack of .set values.  */
14377
14378 struct mips_option_stack
14379 {
14380   struct mips_option_stack *next;
14381   struct mips_set_options options;
14382 };
14383
14384 static struct mips_option_stack *mips_opts_stack;
14385
14386 /* Handle the .set pseudo-op.  */
14387
14388 static void
14389 s_mipsset (int x ATTRIBUTE_UNUSED)
14390 {
14391   char *name = input_line_pointer, ch;
14392   const struct mips_ase *ase;
14393
14394   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14395     ++input_line_pointer;
14396   ch = *input_line_pointer;
14397   *input_line_pointer = '\0';
14398
14399   if (strcmp (name, "reorder") == 0)
14400     {
14401       if (mips_opts.noreorder)
14402         end_noreorder ();
14403     }
14404   else if (strcmp (name, "noreorder") == 0)
14405     {
14406       if (!mips_opts.noreorder)
14407         start_noreorder ();
14408     }
14409   else if (strncmp (name, "at=", 3) == 0)
14410     {
14411       char *s = name + 3;
14412
14413       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14414         as_bad (_("Unrecognized register name `%s'"), s);
14415     }
14416   else if (strcmp (name, "at") == 0)
14417     {
14418       mips_opts.at = ATREG;
14419     }
14420   else if (strcmp (name, "noat") == 0)
14421     {
14422       mips_opts.at = ZERO;
14423     }
14424   else if (strcmp (name, "macro") == 0)
14425     {
14426       mips_opts.warn_about_macros = 0;
14427     }
14428   else if (strcmp (name, "nomacro") == 0)
14429     {
14430       if (mips_opts.noreorder == 0)
14431         as_bad (_("`noreorder' must be set before `nomacro'"));
14432       mips_opts.warn_about_macros = 1;
14433     }
14434   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14435     {
14436       mips_opts.nomove = 0;
14437     }
14438   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14439     {
14440       mips_opts.nomove = 1;
14441     }
14442   else if (strcmp (name, "bopt") == 0)
14443     {
14444       mips_opts.nobopt = 0;
14445     }
14446   else if (strcmp (name, "nobopt") == 0)
14447     {
14448       mips_opts.nobopt = 1;
14449     }
14450   else if (strcmp (name, "gp=default") == 0)
14451     mips_opts.gp32 = file_mips_gp32;
14452   else if (strcmp (name, "gp=32") == 0)
14453     mips_opts.gp32 = 1;
14454   else if (strcmp (name, "gp=64") == 0)
14455     {
14456       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14457         as_warn (_("%s isa does not support 64-bit registers"),
14458                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14459       mips_opts.gp32 = 0;
14460     }
14461   else if (strcmp (name, "fp=default") == 0)
14462     mips_opts.fp32 = file_mips_fp32;
14463   else if (strcmp (name, "fp=32") == 0)
14464     mips_opts.fp32 = 1;
14465   else if (strcmp (name, "fp=64") == 0)
14466     {
14467       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14468         as_warn (_("%s isa does not support 64-bit floating point registers"),
14469                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14470       mips_opts.fp32 = 0;
14471     }
14472   else if (strcmp (name, "softfloat") == 0)
14473     mips_opts.soft_float = 1;
14474   else if (strcmp (name, "hardfloat") == 0)
14475     mips_opts.soft_float = 0;
14476   else if (strcmp (name, "singlefloat") == 0)
14477     mips_opts.single_float = 1;
14478   else if (strcmp (name, "doublefloat") == 0)
14479     mips_opts.single_float = 0;
14480   else if (strcmp (name, "mips16") == 0
14481            || strcmp (name, "MIPS-16") == 0)
14482     {
14483       if (mips_opts.micromips == 1)
14484         as_fatal (_("`mips16' cannot be used with `micromips'"));
14485       mips_opts.mips16 = 1;
14486     }
14487   else if (strcmp (name, "nomips16") == 0
14488            || strcmp (name, "noMIPS-16") == 0)
14489     mips_opts.mips16 = 0;
14490   else if (strcmp (name, "micromips") == 0)
14491     {
14492       if (mips_opts.mips16 == 1)
14493         as_fatal (_("`micromips' cannot be used with `mips16'"));
14494       mips_opts.micromips = 1;
14495     }
14496   else if (strcmp (name, "nomicromips") == 0)
14497     mips_opts.micromips = 0;
14498   else if (name[0] == 'n'
14499            && name[1] == 'o'
14500            && (ase = mips_lookup_ase (name + 2)))
14501     mips_set_ase (ase, FALSE);
14502   else if ((ase = mips_lookup_ase (name)))
14503     mips_set_ase (ase, TRUE);
14504   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
14505     {
14506       int reset = 0;
14507
14508       /* Permit the user to change the ISA and architecture on the fly.
14509          Needless to say, misuse can cause serious problems.  */
14510       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
14511         {
14512           reset = 1;
14513           mips_opts.isa = file_mips_isa;
14514           mips_opts.arch = file_mips_arch;
14515         }
14516       else if (strncmp (name, "arch=", 5) == 0)
14517         {
14518           const struct mips_cpu_info *p;
14519
14520           p = mips_parse_cpu("internal use", name + 5);
14521           if (!p)
14522             as_bad (_("unknown architecture %s"), name + 5);
14523           else
14524             {
14525               mips_opts.arch = p->cpu;
14526               mips_opts.isa = p->isa;
14527             }
14528         }
14529       else if (strncmp (name, "mips", 4) == 0)
14530         {
14531           const struct mips_cpu_info *p;
14532
14533           p = mips_parse_cpu("internal use", name);
14534           if (!p)
14535             as_bad (_("unknown ISA level %s"), name + 4);
14536           else
14537             {
14538               mips_opts.arch = p->cpu;
14539               mips_opts.isa = p->isa;
14540             }
14541         }
14542       else
14543         as_bad (_("unknown ISA or architecture %s"), name);
14544
14545       switch (mips_opts.isa)
14546         {
14547         case  0:
14548           break;
14549         case ISA_MIPS1:
14550         case ISA_MIPS2:
14551         case ISA_MIPS32:
14552         case ISA_MIPS32R2:
14553           mips_opts.gp32 = 1;
14554           mips_opts.fp32 = 1;
14555           break;
14556         case ISA_MIPS3:
14557         case ISA_MIPS4:
14558         case ISA_MIPS5:
14559         case ISA_MIPS64:
14560         case ISA_MIPS64R2:
14561           mips_opts.gp32 = 0;
14562           if (mips_opts.arch == CPU_R5900)
14563             {
14564                 mips_opts.fp32 = 1;
14565             }
14566           else
14567             {
14568           mips_opts.fp32 = 0;
14569             }
14570           break;
14571         default:
14572           as_bad (_("unknown ISA level %s"), name + 4);
14573           break;
14574         }
14575       if (reset)
14576         {
14577           mips_opts.gp32 = file_mips_gp32;
14578           mips_opts.fp32 = file_mips_fp32;
14579         }
14580     }
14581   else if (strcmp (name, "autoextend") == 0)
14582     mips_opts.noautoextend = 0;
14583   else if (strcmp (name, "noautoextend") == 0)
14584     mips_opts.noautoextend = 1;
14585   else if (strcmp (name, "insn32") == 0)
14586     mips_opts.insn32 = TRUE;
14587   else if (strcmp (name, "noinsn32") == 0)
14588     mips_opts.insn32 = FALSE;
14589   else if (strcmp (name, "push") == 0)
14590     {
14591       struct mips_option_stack *s;
14592
14593       s = (struct mips_option_stack *) xmalloc (sizeof *s);
14594       s->next = mips_opts_stack;
14595       s->options = mips_opts;
14596       mips_opts_stack = s;
14597     }
14598   else if (strcmp (name, "pop") == 0)
14599     {
14600       struct mips_option_stack *s;
14601
14602       s = mips_opts_stack;
14603       if (s == NULL)
14604         as_bad (_(".set pop with no .set push"));
14605       else
14606         {
14607           /* If we're changing the reorder mode we need to handle
14608              delay slots correctly.  */
14609           if (s->options.noreorder && ! mips_opts.noreorder)
14610             start_noreorder ();
14611           else if (! s->options.noreorder && mips_opts.noreorder)
14612             end_noreorder ();
14613
14614           mips_opts = s->options;
14615           mips_opts_stack = s->next;
14616           free (s);
14617         }
14618     }
14619   else if (strcmp (name, "sym32") == 0)
14620     mips_opts.sym32 = TRUE;
14621   else if (strcmp (name, "nosym32") == 0)
14622     mips_opts.sym32 = FALSE;
14623   else if (strchr (name, ','))
14624     {
14625       /* Generic ".set" directive; use the generic handler.  */
14626       *input_line_pointer = ch;
14627       input_line_pointer = name;
14628       s_set (0);
14629       return;
14630     }
14631   else
14632     {
14633       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
14634     }
14635   mips_check_isa_supports_ases ();
14636   *input_line_pointer = ch;
14637   demand_empty_rest_of_line ();
14638 }
14639
14640 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
14641    .option pic2.  It means to generate SVR4 PIC calls.  */
14642
14643 static void
14644 s_abicalls (int ignore ATTRIBUTE_UNUSED)
14645 {
14646   mips_pic = SVR4_PIC;
14647   mips_abicalls = TRUE;
14648
14649   if (g_switch_seen && g_switch_value != 0)
14650     as_warn (_("-G may not be used with SVR4 PIC code"));
14651   g_switch_value = 0;
14652
14653   bfd_set_gp_size (stdoutput, 0);
14654   demand_empty_rest_of_line ();
14655 }
14656
14657 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
14658    PIC code.  It sets the $gp register for the function based on the
14659    function address, which is in the register named in the argument.
14660    This uses a relocation against _gp_disp, which is handled specially
14661    by the linker.  The result is:
14662         lui     $gp,%hi(_gp_disp)
14663         addiu   $gp,$gp,%lo(_gp_disp)
14664         addu    $gp,$gp,.cpload argument
14665    The .cpload argument is normally $25 == $t9.
14666
14667    The -mno-shared option changes this to:
14668         lui     $gp,%hi(__gnu_local_gp)
14669         addiu   $gp,$gp,%lo(__gnu_local_gp)
14670    and the argument is ignored.  This saves an instruction, but the
14671    resulting code is not position independent; it uses an absolute
14672    address for __gnu_local_gp.  Thus code assembled with -mno-shared
14673    can go into an ordinary executable, but not into a shared library.  */
14674
14675 static void
14676 s_cpload (int ignore ATTRIBUTE_UNUSED)
14677 {
14678   expressionS ex;
14679   int reg;
14680   int in_shared;
14681
14682   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14683      .cpload is ignored.  */
14684   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14685     {
14686       s_ignore (0);
14687       return;
14688     }
14689
14690   if (mips_opts.mips16)
14691     {
14692       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
14693       ignore_rest_of_line ();
14694       return;
14695     }
14696
14697   /* .cpload should be in a .set noreorder section.  */
14698   if (mips_opts.noreorder == 0)
14699     as_warn (_(".cpload not in noreorder section"));
14700
14701   reg = tc_get_register (0);
14702
14703   /* If we need to produce a 64-bit address, we are better off using
14704      the default instruction sequence.  */
14705   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
14706
14707   ex.X_op = O_symbol;
14708   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
14709                                          "__gnu_local_gp");
14710   ex.X_op_symbol = NULL;
14711   ex.X_add_number = 0;
14712
14713   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14714   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14715
14716   mips_mark_labels ();
14717   mips_assembling_insn = TRUE;
14718
14719   macro_start ();
14720   macro_build_lui (&ex, mips_gp_register);
14721   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14722                mips_gp_register, BFD_RELOC_LO16);
14723   if (in_shared)
14724     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
14725                  mips_gp_register, reg);
14726   macro_end ();
14727
14728   mips_assembling_insn = FALSE;
14729   demand_empty_rest_of_line ();
14730 }
14731
14732 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
14733      .cpsetup $reg1, offset|$reg2, label
14734
14735    If offset is given, this results in:
14736      sd         $gp, offset($sp)
14737      lui        $gp, %hi(%neg(%gp_rel(label)))
14738      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14739      daddu      $gp, $gp, $reg1
14740
14741    If $reg2 is given, this results in:
14742      daddu      $reg2, $gp, $0
14743      lui        $gp, %hi(%neg(%gp_rel(label)))
14744      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
14745      daddu      $gp, $gp, $reg1
14746    $reg1 is normally $25 == $t9.
14747
14748    The -mno-shared option replaces the last three instructions with
14749         lui     $gp,%hi(_gp)
14750         addiu   $gp,$gp,%lo(_gp)  */
14751
14752 static void
14753 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
14754 {
14755   expressionS ex_off;
14756   expressionS ex_sym;
14757   int reg1;
14758
14759   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
14760      We also need NewABI support.  */
14761   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14762     {
14763       s_ignore (0);
14764       return;
14765     }
14766
14767   if (mips_opts.mips16)
14768     {
14769       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
14770       ignore_rest_of_line ();
14771       return;
14772     }
14773
14774   reg1 = tc_get_register (0);
14775   SKIP_WHITESPACE ();
14776   if (*input_line_pointer != ',')
14777     {
14778       as_bad (_("missing argument separator ',' for .cpsetup"));
14779       return;
14780     }
14781   else
14782     ++input_line_pointer;
14783   SKIP_WHITESPACE ();
14784   if (*input_line_pointer == '$')
14785     {
14786       mips_cpreturn_register = tc_get_register (0);
14787       mips_cpreturn_offset = -1;
14788     }
14789   else
14790     {
14791       mips_cpreturn_offset = get_absolute_expression ();
14792       mips_cpreturn_register = -1;
14793     }
14794   SKIP_WHITESPACE ();
14795   if (*input_line_pointer != ',')
14796     {
14797       as_bad (_("missing argument separator ',' for .cpsetup"));
14798       return;
14799     }
14800   else
14801     ++input_line_pointer;
14802   SKIP_WHITESPACE ();
14803   expression (&ex_sym);
14804
14805   mips_mark_labels ();
14806   mips_assembling_insn = TRUE;
14807
14808   macro_start ();
14809   if (mips_cpreturn_register == -1)
14810     {
14811       ex_off.X_op = O_constant;
14812       ex_off.X_add_symbol = NULL;
14813       ex_off.X_op_symbol = NULL;
14814       ex_off.X_add_number = mips_cpreturn_offset;
14815
14816       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
14817                    BFD_RELOC_LO16, SP);
14818     }
14819   else
14820     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
14821                  mips_gp_register, 0);
14822
14823   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
14824     {
14825       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
14826                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
14827                    BFD_RELOC_HI16_S);
14828
14829       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
14830                    mips_gp_register, -1, BFD_RELOC_GPREL16,
14831                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
14832
14833       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
14834                    mips_gp_register, reg1);
14835     }
14836   else
14837     {
14838       expressionS ex;
14839
14840       ex.X_op = O_symbol;
14841       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
14842       ex.X_op_symbol = NULL;
14843       ex.X_add_number = 0;
14844
14845       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
14846       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
14847
14848       macro_build_lui (&ex, mips_gp_register);
14849       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
14850                    mips_gp_register, BFD_RELOC_LO16);
14851     }
14852
14853   macro_end ();
14854
14855   mips_assembling_insn = FALSE;
14856   demand_empty_rest_of_line ();
14857 }
14858
14859 static void
14860 s_cplocal (int ignore ATTRIBUTE_UNUSED)
14861 {
14862   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
14863      .cplocal is ignored.  */
14864   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14865     {
14866       s_ignore (0);
14867       return;
14868     }
14869
14870   if (mips_opts.mips16)
14871     {
14872       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
14873       ignore_rest_of_line ();
14874       return;
14875     }
14876
14877   mips_gp_register = tc_get_register (0);
14878   demand_empty_rest_of_line ();
14879 }
14880
14881 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
14882    offset from $sp.  The offset is remembered, and after making a PIC
14883    call $gp is restored from that location.  */
14884
14885 static void
14886 s_cprestore (int ignore ATTRIBUTE_UNUSED)
14887 {
14888   expressionS ex;
14889
14890   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
14891      .cprestore is ignored.  */
14892   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
14893     {
14894       s_ignore (0);
14895       return;
14896     }
14897
14898   if (mips_opts.mips16)
14899     {
14900       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
14901       ignore_rest_of_line ();
14902       return;
14903     }
14904
14905   mips_cprestore_offset = get_absolute_expression ();
14906   mips_cprestore_valid = 1;
14907
14908   ex.X_op = O_constant;
14909   ex.X_add_symbol = NULL;
14910   ex.X_op_symbol = NULL;
14911   ex.X_add_number = mips_cprestore_offset;
14912
14913   mips_mark_labels ();
14914   mips_assembling_insn = TRUE;
14915
14916   macro_start ();
14917   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
14918                                 SP, HAVE_64BIT_ADDRESSES);
14919   macro_end ();
14920
14921   mips_assembling_insn = FALSE;
14922   demand_empty_rest_of_line ();
14923 }
14924
14925 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
14926    was given in the preceding .cpsetup, it results in:
14927      ld         $gp, offset($sp)
14928
14929    If a register $reg2 was given there, it results in:
14930      daddu      $gp, $reg2, $0  */
14931
14932 static void
14933 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
14934 {
14935   expressionS ex;
14936
14937   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
14938      We also need NewABI support.  */
14939   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
14940     {
14941       s_ignore (0);
14942       return;
14943     }
14944
14945   if (mips_opts.mips16)
14946     {
14947       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
14948       ignore_rest_of_line ();
14949       return;
14950     }
14951
14952   mips_mark_labels ();
14953   mips_assembling_insn = TRUE;
14954
14955   macro_start ();
14956   if (mips_cpreturn_register == -1)
14957     {
14958       ex.X_op = O_constant;
14959       ex.X_add_symbol = NULL;
14960       ex.X_op_symbol = NULL;
14961       ex.X_add_number = mips_cpreturn_offset;
14962
14963       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
14964     }
14965   else
14966     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
14967                  mips_cpreturn_register, 0);
14968   macro_end ();
14969
14970   mips_assembling_insn = FALSE;
14971   demand_empty_rest_of_line ();
14972 }
14973
14974 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
14975    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
14976    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
14977    debug information or MIPS16 TLS.  */
14978
14979 static void
14980 s_tls_rel_directive (const size_t bytes, const char *dirstr,
14981                      bfd_reloc_code_real_type rtype)
14982 {
14983   expressionS ex;
14984   char *p;
14985
14986   expression (&ex);
14987
14988   if (ex.X_op != O_symbol)
14989     {
14990       as_bad (_("Unsupported use of %s"), dirstr);
14991       ignore_rest_of_line ();
14992     }
14993
14994   p = frag_more (bytes);
14995   md_number_to_chars (p, 0, bytes);
14996   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
14997   demand_empty_rest_of_line ();
14998   mips_clear_insn_labels ();
14999 }
15000
15001 /* Handle .dtprelword.  */
15002
15003 static void
15004 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15005 {
15006   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15007 }
15008
15009 /* Handle .dtpreldword.  */
15010
15011 static void
15012 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15013 {
15014   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15015 }
15016
15017 /* Handle .tprelword.  */
15018
15019 static void
15020 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15021 {
15022   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15023 }
15024
15025 /* Handle .tpreldword.  */
15026
15027 static void
15028 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15029 {
15030   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15031 }
15032
15033 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15034    code.  It sets the offset to use in gp_rel relocations.  */
15035
15036 static void
15037 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15038 {
15039   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15040      We also need NewABI support.  */
15041   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15042     {
15043       s_ignore (0);
15044       return;
15045     }
15046
15047   mips_gprel_offset = get_absolute_expression ();
15048
15049   demand_empty_rest_of_line ();
15050 }
15051
15052 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15053    code.  It generates a 32 bit GP relative reloc.  */
15054
15055 static void
15056 s_gpword (int ignore ATTRIBUTE_UNUSED)
15057 {
15058   segment_info_type *si;
15059   struct insn_label_list *l;
15060   expressionS ex;
15061   char *p;
15062
15063   /* When not generating PIC code, this is treated as .word.  */
15064   if (mips_pic != SVR4_PIC)
15065     {
15066       s_cons (2);
15067       return;
15068     }
15069
15070   si = seg_info (now_seg);
15071   l = si->label_list;
15072   mips_emit_delays ();
15073   if (auto_align)
15074     mips_align (2, 0, l);
15075
15076   expression (&ex);
15077   mips_clear_insn_labels ();
15078
15079   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15080     {
15081       as_bad (_("Unsupported use of .gpword"));
15082       ignore_rest_of_line ();
15083     }
15084
15085   p = frag_more (4);
15086   md_number_to_chars (p, 0, 4);
15087   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15088                BFD_RELOC_GPREL32);
15089
15090   demand_empty_rest_of_line ();
15091 }
15092
15093 static void
15094 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15095 {
15096   segment_info_type *si;
15097   struct insn_label_list *l;
15098   expressionS ex;
15099   char *p;
15100
15101   /* When not generating PIC code, this is treated as .dword.  */
15102   if (mips_pic != SVR4_PIC)
15103     {
15104       s_cons (3);
15105       return;
15106     }
15107
15108   si = seg_info (now_seg);
15109   l = si->label_list;
15110   mips_emit_delays ();
15111   if (auto_align)
15112     mips_align (3, 0, l);
15113
15114   expression (&ex);
15115   mips_clear_insn_labels ();
15116
15117   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15118     {
15119       as_bad (_("Unsupported use of .gpdword"));
15120       ignore_rest_of_line ();
15121     }
15122
15123   p = frag_more (8);
15124   md_number_to_chars (p, 0, 8);
15125   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15126                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15127
15128   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15129   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15130            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15131
15132   demand_empty_rest_of_line ();
15133 }
15134
15135 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15136    tables.  It generates a R_MIPS_EH reloc.  */
15137
15138 static void
15139 s_ehword (int ignore ATTRIBUTE_UNUSED)
15140 {
15141   expressionS ex;
15142   char *p;
15143
15144   mips_emit_delays ();
15145
15146   expression (&ex);
15147   mips_clear_insn_labels ();
15148
15149   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15150     {
15151       as_bad (_("Unsupported use of .ehword"));
15152       ignore_rest_of_line ();
15153     }
15154
15155   p = frag_more (4);
15156   md_number_to_chars (p, 0, 4);
15157   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15158                BFD_RELOC_MIPS_EH);
15159
15160   demand_empty_rest_of_line ();
15161 }
15162
15163 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15164    tables in SVR4 PIC code.  */
15165
15166 static void
15167 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15168 {
15169   int reg;
15170
15171   /* This is ignored when not generating SVR4 PIC code.  */
15172   if (mips_pic != SVR4_PIC)
15173     {
15174       s_ignore (0);
15175       return;
15176     }
15177
15178   mips_mark_labels ();
15179   mips_assembling_insn = TRUE;
15180
15181   /* Add $gp to the register named as an argument.  */
15182   macro_start ();
15183   reg = tc_get_register (0);
15184   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15185   macro_end ();
15186
15187   mips_assembling_insn = FALSE;
15188   demand_empty_rest_of_line ();
15189 }
15190
15191 /* Handle the .insn pseudo-op.  This marks instruction labels in
15192    mips16/micromips mode.  This permits the linker to handle them specially,
15193    such as generating jalx instructions when needed.  We also make
15194    them odd for the duration of the assembly, in order to generate the
15195    right sort of code.  We will make them even in the adjust_symtab
15196    routine, while leaving them marked.  This is convenient for the
15197    debugger and the disassembler.  The linker knows to make them odd
15198    again.  */
15199
15200 static void
15201 s_insn (int ignore ATTRIBUTE_UNUSED)
15202 {
15203   mips_mark_labels ();
15204
15205   demand_empty_rest_of_line ();
15206 }
15207
15208 /* Handle the .nan pseudo-op.  */
15209
15210 static void
15211 s_nan (int ignore ATTRIBUTE_UNUSED)
15212 {
15213   static const char str_legacy[] = "legacy";
15214   static const char str_2008[] = "2008";
15215   size_t i;
15216
15217   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15218
15219   if (i == sizeof (str_2008) - 1
15220       && memcmp (input_line_pointer, str_2008, i) == 0)
15221     mips_flag_nan2008 = TRUE;
15222   else if (i == sizeof (str_legacy) - 1
15223            && memcmp (input_line_pointer, str_legacy, i) == 0)
15224     mips_flag_nan2008 = FALSE;
15225   else
15226     as_bad (_("Bad .nan directive"));
15227
15228   input_line_pointer += i;
15229   demand_empty_rest_of_line ();
15230 }
15231
15232 /* Handle a .stab[snd] directive.  Ideally these directives would be
15233    implemented in a transparent way, so that removing them would not
15234    have any effect on the generated instructions.  However, s_stab
15235    internally changes the section, so in practice we need to decide
15236    now whether the preceding label marks compressed code.  We do not
15237    support changing the compression mode of a label after a .stab*
15238    directive, such as in:
15239
15240    foo:
15241         .stabs ...
15242         .set mips16
15243
15244    so the current mode wins.  */
15245
15246 static void
15247 s_mips_stab (int type)
15248 {
15249   mips_mark_labels ();
15250   s_stab (type);
15251 }
15252
15253 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15254
15255 static void
15256 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15257 {
15258   char *name;
15259   int c;
15260   symbolS *symbolP;
15261   expressionS exp;
15262
15263   name = input_line_pointer;
15264   c = get_symbol_end ();
15265   symbolP = symbol_find_or_make (name);
15266   S_SET_WEAK (symbolP);
15267   *input_line_pointer = c;
15268
15269   SKIP_WHITESPACE ();
15270
15271   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15272     {
15273       if (S_IS_DEFINED (symbolP))
15274         {
15275           as_bad (_("ignoring attempt to redefine symbol %s"),
15276                   S_GET_NAME (symbolP));
15277           ignore_rest_of_line ();
15278           return;
15279         }
15280
15281       if (*input_line_pointer == ',')
15282         {
15283           ++input_line_pointer;
15284           SKIP_WHITESPACE ();
15285         }
15286
15287       expression (&exp);
15288       if (exp.X_op != O_symbol)
15289         {
15290           as_bad (_("bad .weakext directive"));
15291           ignore_rest_of_line ();
15292           return;
15293         }
15294       symbol_set_value_expression (symbolP, &exp);
15295     }
15296
15297   demand_empty_rest_of_line ();
15298 }
15299
15300 /* Parse a register string into a number.  Called from the ECOFF code
15301    to parse .frame.  The argument is non-zero if this is the frame
15302    register, so that we can record it in mips_frame_reg.  */
15303
15304 int
15305 tc_get_register (int frame)
15306 {
15307   unsigned int reg;
15308
15309   SKIP_WHITESPACE ();
15310   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15311     reg = 0;
15312   if (frame)
15313     {
15314       mips_frame_reg = reg != 0 ? reg : SP;
15315       mips_frame_reg_valid = 1;
15316       mips_cprestore_valid = 0;
15317     }
15318   return reg;
15319 }
15320
15321 valueT
15322 md_section_align (asection *seg, valueT addr)
15323 {
15324   int align = bfd_get_section_alignment (stdoutput, seg);
15325
15326   /* We don't need to align ELF sections to the full alignment.
15327      However, Irix 5 may prefer that we align them at least to a 16
15328      byte boundary.  We don't bother to align the sections if we
15329      are targeted for an embedded system.  */
15330   if (strncmp (TARGET_OS, "elf", 3) == 0)
15331     return addr;
15332   if (align > 4)
15333     align = 4;
15334
15335   return ((addr + (1 << align) - 1) & (-1 << align));
15336 }
15337
15338 /* Utility routine, called from above as well.  If called while the
15339    input file is still being read, it's only an approximation.  (For
15340    example, a symbol may later become defined which appeared to be
15341    undefined earlier.)  */
15342
15343 static int
15344 nopic_need_relax (symbolS *sym, int before_relaxing)
15345 {
15346   if (sym == 0)
15347     return 0;
15348
15349   if (g_switch_value > 0)
15350     {
15351       const char *symname;
15352       int change;
15353
15354       /* Find out whether this symbol can be referenced off the $gp
15355          register.  It can be if it is smaller than the -G size or if
15356          it is in the .sdata or .sbss section.  Certain symbols can
15357          not be referenced off the $gp, although it appears as though
15358          they can.  */
15359       symname = S_GET_NAME (sym);
15360       if (symname != (const char *) NULL
15361           && (strcmp (symname, "eprol") == 0
15362               || strcmp (symname, "etext") == 0
15363               || strcmp (symname, "_gp") == 0
15364               || strcmp (symname, "edata") == 0
15365               || strcmp (symname, "_fbss") == 0
15366               || strcmp (symname, "_fdata") == 0
15367               || strcmp (symname, "_ftext") == 0
15368               || strcmp (symname, "end") == 0
15369               || strcmp (symname, "_gp_disp") == 0))
15370         change = 1;
15371       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15372                && (0
15373 #ifndef NO_ECOFF_DEBUGGING
15374                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15375                        && (symbol_get_obj (sym)->ecoff_extern_size
15376                            <= g_switch_value))
15377 #endif
15378                    /* We must defer this decision until after the whole
15379                       file has been read, since there might be a .extern
15380                       after the first use of this symbol.  */
15381                    || (before_relaxing
15382 #ifndef NO_ECOFF_DEBUGGING
15383                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15384 #endif
15385                        && S_GET_VALUE (sym) == 0)
15386                    || (S_GET_VALUE (sym) != 0
15387                        && S_GET_VALUE (sym) <= g_switch_value)))
15388         change = 0;
15389       else
15390         {
15391           const char *segname;
15392
15393           segname = segment_name (S_GET_SEGMENT (sym));
15394           gas_assert (strcmp (segname, ".lit8") != 0
15395                   && strcmp (segname, ".lit4") != 0);
15396           change = (strcmp (segname, ".sdata") != 0
15397                     && strcmp (segname, ".sbss") != 0
15398                     && strncmp (segname, ".sdata.", 7) != 0
15399                     && strncmp (segname, ".sbss.", 6) != 0
15400                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15401                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15402         }
15403       return change;
15404     }
15405   else
15406     /* We are not optimizing for the $gp register.  */
15407     return 1;
15408 }
15409
15410
15411 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15412
15413 static bfd_boolean
15414 pic_need_relax (symbolS *sym, asection *segtype)
15415 {
15416   asection *symsec;
15417
15418   /* Handle the case of a symbol equated to another symbol.  */
15419   while (symbol_equated_reloc_p (sym))
15420     {
15421       symbolS *n;
15422
15423       /* It's possible to get a loop here in a badly written program.  */
15424       n = symbol_get_value_expression (sym)->X_add_symbol;
15425       if (n == sym)
15426         break;
15427       sym = n;
15428     }
15429
15430   if (symbol_section_p (sym))
15431     return TRUE;
15432
15433   symsec = S_GET_SEGMENT (sym);
15434
15435   /* This must duplicate the test in adjust_reloc_syms.  */
15436   return (!bfd_is_und_section (symsec)
15437           && !bfd_is_abs_section (symsec)
15438           && !bfd_is_com_section (symsec)
15439           && !s_is_linkonce (sym, segtype)
15440           /* A global or weak symbol is treated as external.  */
15441           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15442 }
15443
15444
15445 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15446    extended opcode.  SEC is the section the frag is in.  */
15447
15448 static int
15449 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15450 {
15451   int type;
15452   const struct mips16_immed_operand *op;
15453   offsetT val;
15454   int mintiny, maxtiny;
15455   segT symsec;
15456   fragS *sym_frag;
15457
15458   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15459     return 0;
15460   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15461     return 1;
15462
15463   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15464   op = mips16_immed_operands;
15465   while (op->type != type)
15466     {
15467       ++op;
15468       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
15469     }
15470
15471   if (op->unsp)
15472     {
15473       if (type == '<' || type == '>' || type == '[' || type == ']')
15474         {
15475           mintiny = 1;
15476           maxtiny = 1 << op->nbits;
15477         }
15478       else
15479         {
15480           mintiny = 0;
15481           maxtiny = (1 << op->nbits) - 1;
15482         }
15483     }
15484   else
15485     {
15486       mintiny = - (1 << (op->nbits - 1));
15487       maxtiny = (1 << (op->nbits - 1)) - 1;
15488     }
15489
15490   sym_frag = symbol_get_frag (fragp->fr_symbol);
15491   val = S_GET_VALUE (fragp->fr_symbol);
15492   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15493
15494   if (op->pcrel)
15495     {
15496       addressT addr;
15497
15498       /* We won't have the section when we are called from
15499          mips_relax_frag.  However, we will always have been called
15500          from md_estimate_size_before_relax first.  If this is a
15501          branch to a different section, we mark it as such.  If SEC is
15502          NULL, and the frag is not marked, then it must be a branch to
15503          the same section.  */
15504       if (sec == NULL)
15505         {
15506           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15507             return 1;
15508         }
15509       else
15510         {
15511           /* Must have been called from md_estimate_size_before_relax.  */
15512           if (symsec != sec)
15513             {
15514               fragp->fr_subtype =
15515                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15516
15517               /* FIXME: We should support this, and let the linker
15518                  catch branches and loads that are out of range.  */
15519               as_bad_where (fragp->fr_file, fragp->fr_line,
15520                             _("unsupported PC relative reference to different section"));
15521
15522               return 1;
15523             }
15524           if (fragp != sym_frag && sym_frag->fr_address == 0)
15525             /* Assume non-extended on the first relaxation pass.
15526                The address we have calculated will be bogus if this is
15527                a forward branch to another frag, as the forward frag
15528                will have fr_address == 0.  */
15529             return 0;
15530         }
15531
15532       /* In this case, we know for sure that the symbol fragment is in
15533          the same section.  If the relax_marker of the symbol fragment
15534          differs from the relax_marker of this fragment, we have not
15535          yet adjusted the symbol fragment fr_address.  We want to add
15536          in STRETCH in order to get a better estimate of the address.
15537          This particularly matters because of the shift bits.  */
15538       if (stretch != 0
15539           && sym_frag->relax_marker != fragp->relax_marker)
15540         {
15541           fragS *f;
15542
15543           /* Adjust stretch for any alignment frag.  Note that if have
15544              been expanding the earlier code, the symbol may be
15545              defined in what appears to be an earlier frag.  FIXME:
15546              This doesn't handle the fr_subtype field, which specifies
15547              a maximum number of bytes to skip when doing an
15548              alignment.  */
15549           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
15550             {
15551               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
15552                 {
15553                   if (stretch < 0)
15554                     stretch = - ((- stretch)
15555                                  & ~ ((1 << (int) f->fr_offset) - 1));
15556                   else
15557                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
15558                   if (stretch == 0)
15559                     break;
15560                 }
15561             }
15562           if (f != NULL)
15563             val += stretch;
15564         }
15565
15566       addr = fragp->fr_address + fragp->fr_fix;
15567
15568       /* The base address rules are complicated.  The base address of
15569          a branch is the following instruction.  The base address of a
15570          PC relative load or add is the instruction itself, but if it
15571          is in a delay slot (in which case it can not be extended) use
15572          the address of the instruction whose delay slot it is in.  */
15573       if (type == 'p' || type == 'q')
15574         {
15575           addr += 2;
15576
15577           /* If we are currently assuming that this frag should be
15578              extended, then, the current address is two bytes
15579              higher.  */
15580           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
15581             addr += 2;
15582
15583           /* Ignore the low bit in the target, since it will be set
15584              for a text label.  */
15585           if ((val & 1) != 0)
15586             --val;
15587         }
15588       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
15589         addr -= 4;
15590       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
15591         addr -= 2;
15592
15593       val -= addr & ~ ((1 << op->shift) - 1);
15594
15595       /* Branch offsets have an implicit 0 in the lowest bit.  */
15596       if (type == 'p' || type == 'q')
15597         val /= 2;
15598
15599       /* If any of the shifted bits are set, we must use an extended
15600          opcode.  If the address depends on the size of this
15601          instruction, this can lead to a loop, so we arrange to always
15602          use an extended opcode.  We only check this when we are in
15603          the main relaxation loop, when SEC is NULL.  */
15604       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
15605         {
15606           fragp->fr_subtype =
15607             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15608           return 1;
15609         }
15610
15611       /* If we are about to mark a frag as extended because the value
15612          is precisely maxtiny + 1, then there is a chance of an
15613          infinite loop as in the following code:
15614              la $4,foo
15615              .skip      1020
15616              .align     2
15617            foo:
15618          In this case when the la is extended, foo is 0x3fc bytes
15619          away, so the la can be shrunk, but then foo is 0x400 away, so
15620          the la must be extended.  To avoid this loop, we mark the
15621          frag as extended if it was small, and is about to become
15622          extended with a value of maxtiny + 1.  */
15623       if (val == ((maxtiny + 1) << op->shift)
15624           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
15625           && sec == NULL)
15626         {
15627           fragp->fr_subtype =
15628             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15629           return 1;
15630         }
15631     }
15632   else if (symsec != absolute_section && sec != NULL)
15633     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
15634
15635   if ((val & ((1 << op->shift) - 1)) != 0
15636       || val < (mintiny << op->shift)
15637       || val > (maxtiny << op->shift))
15638     return 1;
15639   else
15640     return 0;
15641 }
15642
15643 /* Compute the length of a branch sequence, and adjust the
15644    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
15645    worst-case length is computed, with UPDATE being used to indicate
15646    whether an unconditional (-1), branch-likely (+1) or regular (0)
15647    branch is to be computed.  */
15648 static int
15649 relaxed_branch_length (fragS *fragp, asection *sec, int update)
15650 {
15651   bfd_boolean toofar;
15652   int length;
15653
15654   if (fragp
15655       && S_IS_DEFINED (fragp->fr_symbol)
15656       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15657     {
15658       addressT addr;
15659       offsetT val;
15660
15661       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15662
15663       addr = fragp->fr_address + fragp->fr_fix + 4;
15664
15665       val -= addr;
15666
15667       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
15668     }
15669   else if (fragp)
15670     /* If the symbol is not defined or it's in a different segment,
15671        assume the user knows what's going on and emit a short
15672        branch.  */
15673     toofar = FALSE;
15674   else
15675     toofar = TRUE;
15676
15677   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
15678     fragp->fr_subtype
15679       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
15680                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
15681                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
15682                              RELAX_BRANCH_LINK (fragp->fr_subtype),
15683                              toofar);
15684
15685   length = 4;
15686   if (toofar)
15687     {
15688       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
15689         length += 8;
15690
15691       if (mips_pic != NO_PIC)
15692         {
15693           /* Additional space for PIC loading of target address.  */
15694           length += 8;
15695           if (mips_opts.isa == ISA_MIPS1)
15696             /* Additional space for $at-stabilizing nop.  */
15697             length += 4;
15698         }
15699
15700       /* If branch is conditional.  */
15701       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
15702         length += 8;
15703     }
15704
15705   return length;
15706 }
15707
15708 /* Compute the length of a branch sequence, and adjust the
15709    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
15710    worst-case length is computed, with UPDATE being used to indicate
15711    whether an unconditional (-1), or regular (0) branch is to be
15712    computed.  */
15713
15714 static int
15715 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
15716 {
15717   bfd_boolean toofar;
15718   int length;
15719
15720   if (fragp
15721       && S_IS_DEFINED (fragp->fr_symbol)
15722       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15723     {
15724       addressT addr;
15725       offsetT val;
15726
15727       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15728       /* Ignore the low bit in the target, since it will be set
15729          for a text label.  */
15730       if ((val & 1) != 0)
15731         --val;
15732
15733       addr = fragp->fr_address + fragp->fr_fix + 4;
15734
15735       val -= addr;
15736
15737       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
15738     }
15739   else if (fragp)
15740     /* If the symbol is not defined or it's in a different segment,
15741        assume the user knows what's going on and emit a short
15742        branch.  */
15743     toofar = FALSE;
15744   else
15745     toofar = TRUE;
15746
15747   if (fragp && update
15748       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
15749     fragp->fr_subtype = (toofar
15750                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
15751                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
15752
15753   length = 4;
15754   if (toofar)
15755     {
15756       bfd_boolean compact_known = fragp != NULL;
15757       bfd_boolean compact = FALSE;
15758       bfd_boolean uncond;
15759
15760       if (compact_known)
15761         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
15762       if (fragp)
15763         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
15764       else
15765         uncond = update < 0;
15766
15767       /* If label is out of range, we turn branch <br>:
15768
15769                 <br>    label                   # 4 bytes
15770             0:
15771
15772          into:
15773
15774                 j       label                   # 4 bytes
15775                 nop                             # 2 bytes if compact && !PIC
15776             0:
15777        */
15778       if (mips_pic == NO_PIC && (!compact_known || compact))
15779         length += 2;
15780
15781       /* If assembling PIC code, we further turn:
15782
15783                         j       label                   # 4 bytes
15784
15785          into:
15786
15787                         lw/ld   at, %got(label)(gp)     # 4 bytes
15788                         d/addiu at, %lo(label)          # 4 bytes
15789                         jr/c    at                      # 2 bytes
15790        */
15791       if (mips_pic != NO_PIC)
15792         length += 6;
15793
15794       /* If branch <br> is conditional, we prepend negated branch <brneg>:
15795
15796                         <brneg> 0f                      # 4 bytes
15797                         nop                             # 2 bytes if !compact
15798        */
15799       if (!uncond)
15800         length += (compact_known && compact) ? 4 : 6;
15801     }
15802
15803   return length;
15804 }
15805
15806 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
15807    bit accordingly.  */
15808
15809 static int
15810 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
15811 {
15812   bfd_boolean toofar;
15813
15814   if (fragp
15815       && S_IS_DEFINED (fragp->fr_symbol)
15816       && sec == S_GET_SEGMENT (fragp->fr_symbol))
15817     {
15818       addressT addr;
15819       offsetT val;
15820       int type;
15821
15822       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
15823       /* Ignore the low bit in the target, since it will be set
15824          for a text label.  */
15825       if ((val & 1) != 0)
15826         --val;
15827
15828       /* Assume this is a 2-byte branch.  */
15829       addr = fragp->fr_address + fragp->fr_fix + 2;
15830
15831       /* We try to avoid the infinite loop by not adding 2 more bytes for
15832          long branches.  */
15833
15834       val -= addr;
15835
15836       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
15837       if (type == 'D')
15838         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
15839       else if (type == 'E')
15840         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
15841       else
15842         abort ();
15843     }
15844   else
15845     /* If the symbol is not defined or it's in a different segment,
15846        we emit a normal 32-bit branch.  */
15847     toofar = TRUE;
15848
15849   if (fragp && update
15850       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
15851     fragp->fr_subtype
15852       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
15853                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
15854
15855   if (toofar)
15856     return 4;
15857
15858   return 2;
15859 }
15860
15861 /* Estimate the size of a frag before relaxing.  Unless this is the
15862    mips16, we are not really relaxing here, and the final size is
15863    encoded in the subtype information.  For the mips16, we have to
15864    decide whether we are using an extended opcode or not.  */
15865
15866 int
15867 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
15868 {
15869   int change;
15870
15871   if (RELAX_BRANCH_P (fragp->fr_subtype))
15872     {
15873
15874       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
15875
15876       return fragp->fr_var;
15877     }
15878
15879   if (RELAX_MIPS16_P (fragp->fr_subtype))
15880     /* We don't want to modify the EXTENDED bit here; it might get us
15881        into infinite loops.  We change it only in mips_relax_frag().  */
15882     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
15883
15884   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
15885     {
15886       int length = 4;
15887
15888       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
15889         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
15890       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
15891         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
15892       fragp->fr_var = length;
15893
15894       return length;
15895     }
15896
15897   if (mips_pic == NO_PIC)
15898     change = nopic_need_relax (fragp->fr_symbol, 0);
15899   else if (mips_pic == SVR4_PIC)
15900     change = pic_need_relax (fragp->fr_symbol, segtype);
15901   else if (mips_pic == VXWORKS_PIC)
15902     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
15903     change = 0;
15904   else
15905     abort ();
15906
15907   if (change)
15908     {
15909       fragp->fr_subtype |= RELAX_USE_SECOND;
15910       return -RELAX_FIRST (fragp->fr_subtype);
15911     }
15912   else
15913     return -RELAX_SECOND (fragp->fr_subtype);
15914 }
15915
15916 /* This is called to see whether a reloc against a defined symbol
15917    should be converted into a reloc against a section.  */
15918
15919 int
15920 mips_fix_adjustable (fixS *fixp)
15921 {
15922   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15923       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
15924     return 0;
15925
15926   if (fixp->fx_addsy == NULL)
15927     return 1;
15928
15929   /* If symbol SYM is in a mergeable section, relocations of the form
15930      SYM + 0 can usually be made section-relative.  The mergeable data
15931      is then identified by the section offset rather than by the symbol.
15932
15933      However, if we're generating REL LO16 relocations, the offset is split
15934      between the LO16 and parterning high part relocation.  The linker will
15935      need to recalculate the complete offset in order to correctly identify
15936      the merge data.
15937
15938      The linker has traditionally not looked for the parterning high part
15939      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
15940      placed anywhere.  Rather than break backwards compatibility by changing
15941      this, it seems better not to force the issue, and instead keep the
15942      original symbol.  This will work with either linker behavior.  */
15943   if ((lo16_reloc_p (fixp->fx_r_type)
15944        || reloc_needs_lo_p (fixp->fx_r_type))
15945       && HAVE_IN_PLACE_ADDENDS
15946       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
15947     return 0;
15948
15949   /* There is no place to store an in-place offset for JALR relocations.
15950      Likewise an in-range offset of limited PC-relative relocations may
15951      overflow the in-place relocatable field if recalculated against the
15952      start address of the symbol's containing section.  */
15953   if (HAVE_IN_PLACE_ADDENDS
15954       && (limited_pcrel_reloc_p (fixp->fx_r_type)
15955           || jalr_reloc_p (fixp->fx_r_type)))
15956     return 0;
15957
15958   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
15959      to a floating-point stub.  The same is true for non-R_MIPS16_26
15960      relocations against MIPS16 functions; in this case, the stub becomes
15961      the function's canonical address.
15962
15963      Floating-point stubs are stored in unique .mips16.call.* or
15964      .mips16.fn.* sections.  If a stub T for function F is in section S,
15965      the first relocation in section S must be against F; this is how the
15966      linker determines the target function.  All relocations that might
15967      resolve to T must also be against F.  We therefore have the following
15968      restrictions, which are given in an intentionally-redundant way:
15969
15970        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
15971           symbols.
15972
15973        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
15974           if that stub might be used.
15975
15976        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
15977           symbols.
15978
15979        4. We cannot reduce a stub's relocations against MIPS16 symbols if
15980           that stub might be used.
15981
15982      There is a further restriction:
15983
15984        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
15985           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
15986           targets with in-place addends; the relocation field cannot
15987           encode the low bit.
15988
15989      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
15990      against a MIPS16 symbol.  We deal with (5) by by not reducing any
15991      such relocations on REL targets.
15992
15993      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
15994      relocation against some symbol R, no relocation against R may be
15995      reduced.  (Note that this deals with (2) as well as (1) because
15996      relocations against global symbols will never be reduced on ELF
15997      targets.)  This approach is a little simpler than trying to detect
15998      stub sections, and gives the "all or nothing" per-symbol consistency
15999      that we have for MIPS16 symbols.  */
16000   if (fixp->fx_subsy == NULL
16001       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16002           || *symbol_get_tc (fixp->fx_addsy)
16003           || (HAVE_IN_PLACE_ADDENDS
16004               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16005               && jmp_reloc_p (fixp->fx_r_type))))
16006     return 0;
16007
16008   return 1;
16009 }
16010
16011 /* Translate internal representation of relocation info to BFD target
16012    format.  */
16013
16014 arelent **
16015 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16016 {
16017   static arelent *retval[4];
16018   arelent *reloc;
16019   bfd_reloc_code_real_type code;
16020
16021   memset (retval, 0, sizeof(retval));
16022   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16023   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16024   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16025   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16026
16027   if (fixp->fx_pcrel)
16028     {
16029       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16030                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16031                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16032                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16033                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16034
16035       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16036          Relocations want only the symbol offset.  */
16037       reloc->addend = fixp->fx_addnumber + reloc->address;
16038     }
16039   else
16040     reloc->addend = fixp->fx_addnumber;
16041
16042   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16043      entry to be used in the relocation's section offset.  */
16044   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16045     {
16046       reloc->address = reloc->addend;
16047       reloc->addend = 0;
16048     }
16049
16050   code = fixp->fx_r_type;
16051
16052   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16053   if (reloc->howto == NULL)
16054     {
16055       as_bad_where (fixp->fx_file, fixp->fx_line,
16056                     _("Can not represent %s relocation in this object file format"),
16057                     bfd_get_reloc_code_name (code));
16058       retval[0] = NULL;
16059     }
16060
16061   return retval;
16062 }
16063
16064 /* Relax a machine dependent frag.  This returns the amount by which
16065    the current size of the frag should change.  */
16066
16067 int
16068 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16069 {
16070   if (RELAX_BRANCH_P (fragp->fr_subtype))
16071     {
16072       offsetT old_var = fragp->fr_var;
16073
16074       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16075
16076       return fragp->fr_var - old_var;
16077     }
16078
16079   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16080     {
16081       offsetT old_var = fragp->fr_var;
16082       offsetT new_var = 4;
16083
16084       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16085         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16086       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16087         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16088       fragp->fr_var = new_var;
16089
16090       return new_var - old_var;
16091     }
16092
16093   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16094     return 0;
16095
16096   if (mips16_extended_frag (fragp, NULL, stretch))
16097     {
16098       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16099         return 0;
16100       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16101       return 2;
16102     }
16103   else
16104     {
16105       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16106         return 0;
16107       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16108       return -2;
16109     }
16110
16111   return 0;
16112 }
16113
16114 /* Convert a machine dependent frag.  */
16115
16116 void
16117 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16118 {
16119   if (RELAX_BRANCH_P (fragp->fr_subtype))
16120     {
16121       char *buf;
16122       unsigned long insn;
16123       expressionS exp;
16124       fixS *fixp;
16125
16126       buf = fragp->fr_literal + fragp->fr_fix;
16127       insn = read_insn (buf);
16128
16129       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16130         {
16131           /* We generate a fixup instead of applying it right now
16132              because, if there are linker relaxations, we're going to
16133              need the relocations.  */
16134           exp.X_op = O_symbol;
16135           exp.X_add_symbol = fragp->fr_symbol;
16136           exp.X_add_number = fragp->fr_offset;
16137
16138           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16139                               BFD_RELOC_16_PCREL_S2);
16140           fixp->fx_file = fragp->fr_file;
16141           fixp->fx_line = fragp->fr_line;
16142
16143           buf = write_insn (buf, insn);
16144         }
16145       else
16146         {
16147           int i;
16148
16149           as_warn_where (fragp->fr_file, fragp->fr_line,
16150                          _("Relaxed out-of-range branch into a jump"));
16151
16152           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16153             goto uncond;
16154
16155           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16156             {
16157               /* Reverse the branch.  */
16158               switch ((insn >> 28) & 0xf)
16159                 {
16160                 case 4:
16161                   /* bc[0-3][tf]l? instructions can have the condition
16162                      reversed by tweaking a single TF bit, and their
16163                      opcodes all have 0x4???????.  */
16164                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16165                   insn ^= 0x00010000;
16166                   break;
16167
16168                 case 0:
16169                   /* bltz       0x04000000      bgez    0x04010000
16170                      bltzal     0x04100000      bgezal  0x04110000  */
16171                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16172                   insn ^= 0x00010000;
16173                   break;
16174
16175                 case 1:
16176                   /* beq        0x10000000      bne     0x14000000
16177                      blez       0x18000000      bgtz    0x1c000000  */
16178                   insn ^= 0x04000000;
16179                   break;
16180
16181                 default:
16182                   abort ();
16183                 }
16184             }
16185
16186           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16187             {
16188               /* Clear the and-link bit.  */
16189               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16190
16191               /* bltzal         0x04100000      bgezal  0x04110000
16192                  bltzall        0x04120000      bgezall 0x04130000  */
16193               insn &= ~0x00100000;
16194             }
16195
16196           /* Branch over the branch (if the branch was likely) or the
16197              full jump (not likely case).  Compute the offset from the
16198              current instruction to branch to.  */
16199           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16200             i = 16;
16201           else
16202             {
16203               /* How many bytes in instructions we've already emitted?  */
16204               i = buf - fragp->fr_literal - fragp->fr_fix;
16205               /* How many bytes in instructions from here to the end?  */
16206               i = fragp->fr_var - i;
16207             }
16208           /* Convert to instruction count.  */
16209           i >>= 2;
16210           /* Branch counts from the next instruction.  */
16211           i--;
16212           insn |= i;
16213           /* Branch over the jump.  */
16214           buf = write_insn (buf, insn);
16215
16216           /* nop */
16217           buf = write_insn (buf, 0);
16218
16219           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16220             {
16221               /* beql $0, $0, 2f */
16222               insn = 0x50000000;
16223               /* Compute the PC offset from the current instruction to
16224                  the end of the variable frag.  */
16225               /* How many bytes in instructions we've already emitted?  */
16226               i = buf - fragp->fr_literal - fragp->fr_fix;
16227               /* How many bytes in instructions from here to the end?  */
16228               i = fragp->fr_var - i;
16229               /* Convert to instruction count.  */
16230               i >>= 2;
16231               /* Don't decrement i, because we want to branch over the
16232                  delay slot.  */
16233               insn |= i;
16234
16235               buf = write_insn (buf, insn);
16236               buf = write_insn (buf, 0);
16237             }
16238
16239         uncond:
16240           if (mips_pic == NO_PIC)
16241             {
16242               /* j or jal.  */
16243               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16244                       ? 0x0c000000 : 0x08000000);
16245               exp.X_op = O_symbol;
16246               exp.X_add_symbol = fragp->fr_symbol;
16247               exp.X_add_number = fragp->fr_offset;
16248
16249               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16250                                   FALSE, BFD_RELOC_MIPS_JMP);
16251               fixp->fx_file = fragp->fr_file;
16252               fixp->fx_line = fragp->fr_line;
16253
16254               buf = write_insn (buf, insn);
16255             }
16256           else
16257             {
16258               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16259
16260               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16261               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16262               insn |= at << OP_SH_RT;
16263               exp.X_op = O_symbol;
16264               exp.X_add_symbol = fragp->fr_symbol;
16265               exp.X_add_number = fragp->fr_offset;
16266
16267               if (fragp->fr_offset)
16268                 {
16269                   exp.X_add_symbol = make_expr_symbol (&exp);
16270                   exp.X_add_number = 0;
16271                 }
16272
16273               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16274                                   FALSE, BFD_RELOC_MIPS_GOT16);
16275               fixp->fx_file = fragp->fr_file;
16276               fixp->fx_line = fragp->fr_line;
16277
16278               buf = write_insn (buf, insn);
16279
16280               if (mips_opts.isa == ISA_MIPS1)
16281                 /* nop */
16282                 buf = write_insn (buf, 0);
16283
16284               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16285               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16286               insn |= at << OP_SH_RS | at << OP_SH_RT;
16287
16288               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16289                                   FALSE, BFD_RELOC_LO16);
16290               fixp->fx_file = fragp->fr_file;
16291               fixp->fx_line = fragp->fr_line;
16292
16293               buf = write_insn (buf, insn);
16294
16295               /* j(al)r $at.  */
16296               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16297                 insn = 0x0000f809;
16298               else
16299                 insn = 0x00000008;
16300               insn |= at << OP_SH_RS;
16301
16302               buf = write_insn (buf, insn);
16303             }
16304         }
16305
16306       fragp->fr_fix += fragp->fr_var;
16307       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16308       return;
16309     }
16310
16311   /* Relax microMIPS branches.  */
16312   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16313     {
16314       char *buf = fragp->fr_literal + fragp->fr_fix;
16315       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16316       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16317       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16318       bfd_boolean short_ds;
16319       unsigned long insn;
16320       expressionS exp;
16321       fixS *fixp;
16322
16323       exp.X_op = O_symbol;
16324       exp.X_add_symbol = fragp->fr_symbol;
16325       exp.X_add_number = fragp->fr_offset;
16326
16327       fragp->fr_fix += fragp->fr_var;
16328
16329       /* Handle 16-bit branches that fit or are forced to fit.  */
16330       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16331         {
16332           /* We generate a fixup instead of applying it right now,
16333              because if there is linker relaxation, we're going to
16334              need the relocations.  */
16335           if (type == 'D')
16336             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16337                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16338           else if (type == 'E')
16339             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16340                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16341           else
16342             abort ();
16343
16344           fixp->fx_file = fragp->fr_file;
16345           fixp->fx_line = fragp->fr_line;
16346
16347           /* These relocations can have an addend that won't fit in
16348              2 octets.  */
16349           fixp->fx_no_overflow = 1;
16350
16351           return;
16352         }
16353
16354       /* Handle 32-bit branches that fit or are forced to fit.  */
16355       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16356           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16357         {
16358           /* We generate a fixup instead of applying it right now,
16359              because if there is linker relaxation, we're going to
16360              need the relocations.  */
16361           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16362                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16363           fixp->fx_file = fragp->fr_file;
16364           fixp->fx_line = fragp->fr_line;
16365
16366           if (type == 0)
16367             return;
16368         }
16369
16370       /* Relax 16-bit branches to 32-bit branches.  */
16371       if (type != 0)
16372         {
16373           insn = read_compressed_insn (buf, 2);
16374
16375           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16376             insn = 0x94000000;                          /* beq  */
16377           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16378             {
16379               unsigned long regno;
16380
16381               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16382               regno = micromips_to_32_reg_d_map [regno];
16383               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16384               insn |= regno << MICROMIPSOP_SH_RS;
16385             }
16386           else
16387             abort ();
16388
16389           /* Nothing else to do, just write it out.  */
16390           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16391               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16392             {
16393               buf = write_compressed_insn (buf, insn, 4);
16394               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16395               return;
16396             }
16397         }
16398       else
16399         insn = read_compressed_insn (buf, 4);
16400
16401       /* Relax 32-bit branches to a sequence of instructions.  */
16402       as_warn_where (fragp->fr_file, fragp->fr_line,
16403                      _("Relaxed out-of-range branch into a jump"));
16404
16405       /* Set the short-delay-slot bit.  */
16406       short_ds = al && (insn & 0x02000000) != 0;
16407
16408       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16409         {
16410           symbolS *l;
16411
16412           /* Reverse the branch.  */
16413           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16414               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16415             insn ^= 0x20000000;
16416           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16417                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16418                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16419                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16420                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16421                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16422                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16423                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16424                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16425                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16426             insn ^= 0x00400000;
16427           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16428                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16429                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16430                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16431             insn ^= 0x00200000;
16432           else
16433             abort ();
16434
16435           if (al)
16436             {
16437               /* Clear the and-link and short-delay-slot bits.  */
16438               gas_assert ((insn & 0xfda00000) == 0x40200000);
16439
16440               /* bltzal  0x40200000     bgezal  0x40600000  */
16441               /* bltzals 0x42200000     bgezals 0x42600000  */
16442               insn &= ~0x02200000;
16443             }
16444
16445           /* Make a label at the end for use with the branch.  */
16446           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16447           micromips_label_inc ();
16448           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16449
16450           /* Refer to it.  */
16451           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16452                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16453           fixp->fx_file = fragp->fr_file;
16454           fixp->fx_line = fragp->fr_line;
16455
16456           /* Branch over the jump.  */
16457           buf = write_compressed_insn (buf, insn, 4);
16458           if (!compact)
16459             /* nop */
16460             buf = write_compressed_insn (buf, 0x0c00, 2);
16461         }
16462
16463       if (mips_pic == NO_PIC)
16464         {
16465           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16466
16467           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16468           insn = al ? jal : 0xd4000000;
16469
16470           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16471                               BFD_RELOC_MICROMIPS_JMP);
16472           fixp->fx_file = fragp->fr_file;
16473           fixp->fx_line = fragp->fr_line;
16474
16475           buf = write_compressed_insn (buf, insn, 4);
16476           if (compact)
16477             /* nop */
16478             buf = write_compressed_insn (buf, 0x0c00, 2);
16479         }
16480       else
16481         {
16482           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16483           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16484           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16485
16486           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16487           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16488           insn |= at << MICROMIPSOP_SH_RT;
16489
16490           if (exp.X_add_number)
16491             {
16492               exp.X_add_symbol = make_expr_symbol (&exp);
16493               exp.X_add_number = 0;
16494             }
16495
16496           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16497                               BFD_RELOC_MICROMIPS_GOT16);
16498           fixp->fx_file = fragp->fr_file;
16499           fixp->fx_line = fragp->fr_line;
16500
16501           buf = write_compressed_insn (buf, insn, 4);
16502
16503           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16504           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16505           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16506
16507           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16508                               BFD_RELOC_MICROMIPS_LO16);
16509           fixp->fx_file = fragp->fr_file;
16510           fixp->fx_line = fragp->fr_line;
16511
16512           buf = write_compressed_insn (buf, insn, 4);
16513
16514           /* jr/jrc/jalr/jalrs $at  */
16515           insn = al ? jalr : jr;
16516           insn |= at << MICROMIPSOP_SH_MJ;
16517
16518           buf = write_compressed_insn (buf, insn, 2);
16519         }
16520
16521       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16522       return;
16523     }
16524
16525   if (RELAX_MIPS16_P (fragp->fr_subtype))
16526     {
16527       int type;
16528       const struct mips16_immed_operand *op;
16529       offsetT val;
16530       char *buf;
16531       unsigned int user_length, length;
16532       unsigned long insn;
16533       bfd_boolean ext;
16534
16535       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16536       op = mips16_immed_operands;
16537       while (op->type != type)
16538         ++op;
16539
16540       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
16541       val = resolve_symbol_value (fragp->fr_symbol);
16542       if (op->pcrel)
16543         {
16544           addressT addr;
16545
16546           addr = fragp->fr_address + fragp->fr_fix;
16547
16548           /* The rules for the base address of a PC relative reloc are
16549              complicated; see mips16_extended_frag.  */
16550           if (type == 'p' || type == 'q')
16551             {
16552               addr += 2;
16553               if (ext)
16554                 addr += 2;
16555               /* Ignore the low bit in the target, since it will be
16556                  set for a text label.  */
16557               if ((val & 1) != 0)
16558                 --val;
16559             }
16560           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16561             addr -= 4;
16562           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16563             addr -= 2;
16564
16565           addr &= ~ (addressT) ((1 << op->shift) - 1);
16566           val -= addr;
16567
16568           /* Make sure the section winds up with the alignment we have
16569              assumed.  */
16570           if (op->shift > 0)
16571             record_alignment (asec, op->shift);
16572         }
16573
16574       if (ext
16575           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
16576               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
16577         as_warn_where (fragp->fr_file, fragp->fr_line,
16578                        _("extended instruction in delay slot"));
16579
16580       buf = fragp->fr_literal + fragp->fr_fix;
16581
16582       insn = read_compressed_insn (buf, 2);
16583       if (ext)
16584         insn |= MIPS16_EXTEND;
16585
16586       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16587         user_length = 4;
16588       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16589         user_length = 2;
16590       else
16591         user_length = 0;
16592
16593       mips16_immed (fragp->fr_file, fragp->fr_line, type,
16594                     BFD_RELOC_UNUSED, val, user_length, &insn);
16595
16596       length = (ext ? 4 : 2);
16597       gas_assert (mips16_opcode_length (insn) == length);
16598       write_compressed_insn (buf, insn, length);
16599       fragp->fr_fix += length;
16600     }
16601   else
16602     {
16603       relax_substateT subtype = fragp->fr_subtype;
16604       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
16605       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
16606       int first, second;
16607       fixS *fixp;
16608
16609       first = RELAX_FIRST (subtype);
16610       second = RELAX_SECOND (subtype);
16611       fixp = (fixS *) fragp->fr_opcode;
16612
16613       /* If the delay slot chosen does not match the size of the instruction,
16614          then emit a warning.  */
16615       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
16616            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
16617         {
16618           relax_substateT s;
16619           const char *msg;
16620
16621           s = subtype & (RELAX_DELAY_SLOT_16BIT
16622                          | RELAX_DELAY_SLOT_SIZE_FIRST
16623                          | RELAX_DELAY_SLOT_SIZE_SECOND);
16624           msg = macro_warning (s);
16625           if (msg != NULL)
16626             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16627           subtype &= ~s;
16628         }
16629
16630       /* Possibly emit a warning if we've chosen the longer option.  */
16631       if (use_second == second_longer)
16632         {
16633           relax_substateT s;
16634           const char *msg;
16635
16636           s = (subtype
16637                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
16638           msg = macro_warning (s);
16639           if (msg != NULL)
16640             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
16641           subtype &= ~s;
16642         }
16643
16644       /* Go through all the fixups for the first sequence.  Disable them
16645          (by marking them as done) if we're going to use the second
16646          sequence instead.  */
16647       while (fixp
16648              && fixp->fx_frag == fragp
16649              && fixp->fx_where < fragp->fr_fix - second)
16650         {
16651           if (subtype & RELAX_USE_SECOND)
16652             fixp->fx_done = 1;
16653           fixp = fixp->fx_next;
16654         }
16655
16656       /* Go through the fixups for the second sequence.  Disable them if
16657          we're going to use the first sequence, otherwise adjust their
16658          addresses to account for the relaxation.  */
16659       while (fixp && fixp->fx_frag == fragp)
16660         {
16661           if (subtype & RELAX_USE_SECOND)
16662             fixp->fx_where -= first;
16663           else
16664             fixp->fx_done = 1;
16665           fixp = fixp->fx_next;
16666         }
16667
16668       /* Now modify the frag contents.  */
16669       if (subtype & RELAX_USE_SECOND)
16670         {
16671           char *start;
16672
16673           start = fragp->fr_literal + fragp->fr_fix - first - second;
16674           memmove (start, start + first, second);
16675           fragp->fr_fix -= first;
16676         }
16677       else
16678         fragp->fr_fix -= second;
16679     }
16680 }
16681
16682 /* This function is called after the relocs have been generated.
16683    We've been storing mips16 text labels as odd.  Here we convert them
16684    back to even for the convenience of the debugger.  */
16685
16686 void
16687 mips_frob_file_after_relocs (void)
16688 {
16689   asymbol **syms;
16690   unsigned int count, i;
16691
16692   syms = bfd_get_outsymbols (stdoutput);
16693   count = bfd_get_symcount (stdoutput);
16694   for (i = 0; i < count; i++, syms++)
16695     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
16696         && ((*syms)->value & 1) != 0)
16697       {
16698         (*syms)->value &= ~1;
16699         /* If the symbol has an odd size, it was probably computed
16700            incorrectly, so adjust that as well.  */
16701         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
16702           ++elf_symbol (*syms)->internal_elf_sym.st_size;
16703       }
16704 }
16705
16706 /* This function is called whenever a label is defined, including fake
16707    labels instantiated off the dot special symbol.  It is used when
16708    handling branch delays; if a branch has a label, we assume we cannot
16709    move it.  This also bumps the value of the symbol by 1 in compressed
16710    code.  */
16711
16712 static void
16713 mips_record_label (symbolS *sym)
16714 {
16715   segment_info_type *si = seg_info (now_seg);
16716   struct insn_label_list *l;
16717
16718   if (free_insn_labels == NULL)
16719     l = (struct insn_label_list *) xmalloc (sizeof *l);
16720   else
16721     {
16722       l = free_insn_labels;
16723       free_insn_labels = l->next;
16724     }
16725
16726   l->label = sym;
16727   l->next = si->label_list;
16728   si->label_list = l;
16729 }
16730
16731 /* This function is called as tc_frob_label() whenever a label is defined
16732    and adds a DWARF-2 record we only want for true labels.  */
16733
16734 void
16735 mips_define_label (symbolS *sym)
16736 {
16737   mips_record_label (sym);
16738   dwarf2_emit_label (sym);
16739 }
16740
16741 /* This function is called by tc_new_dot_label whenever a new dot symbol
16742    is defined.  */
16743
16744 void
16745 mips_add_dot_label (symbolS *sym)
16746 {
16747   mips_record_label (sym);
16748   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
16749     mips_compressed_mark_label (sym);
16750 }
16751 \f
16752 /* Some special processing for a MIPS ELF file.  */
16753
16754 void
16755 mips_elf_final_processing (void)
16756 {
16757   /* Write out the register information.  */
16758   if (mips_abi != N64_ABI)
16759     {
16760       Elf32_RegInfo s;
16761
16762       s.ri_gprmask = mips_gprmask;
16763       s.ri_cprmask[0] = mips_cprmask[0];
16764       s.ri_cprmask[1] = mips_cprmask[1];
16765       s.ri_cprmask[2] = mips_cprmask[2];
16766       s.ri_cprmask[3] = mips_cprmask[3];
16767       /* The gp_value field is set by the MIPS ELF backend.  */
16768
16769       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
16770                                        ((Elf32_External_RegInfo *)
16771                                         mips_regmask_frag));
16772     }
16773   else
16774     {
16775       Elf64_Internal_RegInfo s;
16776
16777       s.ri_gprmask = mips_gprmask;
16778       s.ri_pad = 0;
16779       s.ri_cprmask[0] = mips_cprmask[0];
16780       s.ri_cprmask[1] = mips_cprmask[1];
16781       s.ri_cprmask[2] = mips_cprmask[2];
16782       s.ri_cprmask[3] = mips_cprmask[3];
16783       /* The gp_value field is set by the MIPS ELF backend.  */
16784
16785       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
16786                                        ((Elf64_External_RegInfo *)
16787                                         mips_regmask_frag));
16788     }
16789
16790   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
16791      sort of BFD interface for this.  */
16792   if (mips_any_noreorder)
16793     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
16794   if (mips_pic != NO_PIC)
16795     {
16796       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
16797       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16798     }
16799   if (mips_abicalls)
16800     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
16801
16802   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
16803      defined at present; this might need to change in future.  */
16804   if (file_ase_mips16)
16805     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
16806   if (file_ase_micromips)
16807     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
16808   if (file_ase & ASE_MDMX)
16809     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
16810
16811   /* Set the MIPS ELF ABI flags.  */
16812   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
16813     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
16814   else if (mips_abi == O64_ABI)
16815     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
16816   else if (mips_abi == EABI_ABI)
16817     {
16818       if (!file_mips_gp32)
16819         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
16820       else
16821         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
16822     }
16823   else if (mips_abi == N32_ABI)
16824     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
16825
16826   /* Nothing to do for N64_ABI.  */
16827
16828   if (mips_32bitmode)
16829     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
16830
16831   if (mips_flag_nan2008)
16832     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
16833
16834 #if 0 /* XXX FIXME */
16835   /* 32 bit code with 64 bit FP registers.  */
16836   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
16837     elf_elfheader (stdoutput)->e_flags |= ???;
16838 #endif
16839 }
16840 \f
16841 typedef struct proc {
16842   symbolS *func_sym;
16843   symbolS *func_end_sym;
16844   unsigned long reg_mask;
16845   unsigned long reg_offset;
16846   unsigned long fpreg_mask;
16847   unsigned long fpreg_offset;
16848   unsigned long frame_offset;
16849   unsigned long frame_reg;
16850   unsigned long pc_reg;
16851 } procS;
16852
16853 static procS cur_proc;
16854 static procS *cur_proc_ptr;
16855 static int numprocs;
16856
16857 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
16858    as "2", and a normal nop as "0".  */
16859
16860 #define NOP_OPCODE_MIPS         0
16861 #define NOP_OPCODE_MIPS16       1
16862 #define NOP_OPCODE_MICROMIPS    2
16863
16864 char
16865 mips_nop_opcode (void)
16866 {
16867   if (seg_info (now_seg)->tc_segment_info_data.micromips)
16868     return NOP_OPCODE_MICROMIPS;
16869   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
16870     return NOP_OPCODE_MIPS16;
16871   else
16872     return NOP_OPCODE_MIPS;
16873 }
16874
16875 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
16876    32-bit microMIPS NOPs here (if applicable).  */
16877
16878 void
16879 mips_handle_align (fragS *fragp)
16880 {
16881   char nop_opcode;
16882   char *p;
16883   int bytes, size, excess;
16884   valueT opcode;
16885
16886   if (fragp->fr_type != rs_align_code)
16887     return;
16888
16889   p = fragp->fr_literal + fragp->fr_fix;
16890   nop_opcode = *p;
16891   switch (nop_opcode)
16892     {
16893     case NOP_OPCODE_MICROMIPS:
16894       opcode = micromips_nop32_insn.insn_opcode;
16895       size = 4;
16896       break;
16897     case NOP_OPCODE_MIPS16:
16898       opcode = mips16_nop_insn.insn_opcode;
16899       size = 2;
16900       break;
16901     case NOP_OPCODE_MIPS:
16902     default:
16903       opcode = nop_insn.insn_opcode;
16904       size = 4;
16905       break;
16906     }
16907
16908   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
16909   excess = bytes % size;
16910
16911   /* Handle the leading part if we're not inserting a whole number of
16912      instructions, and make it the end of the fixed part of the frag.
16913      Try to fit in a short microMIPS NOP if applicable and possible,
16914      and use zeroes otherwise.  */
16915   gas_assert (excess < 4);
16916   fragp->fr_fix += excess;
16917   switch (excess)
16918     {
16919     case 3:
16920       *p++ = '\0';
16921       /* Fall through.  */
16922     case 2:
16923       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
16924         {
16925           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
16926           break;
16927         }
16928       *p++ = '\0';
16929       /* Fall through.  */
16930     case 1:
16931       *p++ = '\0';
16932       /* Fall through.  */
16933     case 0:
16934       break;
16935     }
16936
16937   md_number_to_chars (p, opcode, size);
16938   fragp->fr_var = size;
16939 }
16940
16941 static void
16942 md_obj_begin (void)
16943 {
16944 }
16945
16946 static void
16947 md_obj_end (void)
16948 {
16949   /* Check for premature end, nesting errors, etc.  */
16950   if (cur_proc_ptr)
16951     as_warn (_("missing .end at end of assembly"));
16952 }
16953
16954 static long
16955 get_number (void)
16956 {
16957   int negative = 0;
16958   long val = 0;
16959
16960   if (*input_line_pointer == '-')
16961     {
16962       ++input_line_pointer;
16963       negative = 1;
16964     }
16965   if (!ISDIGIT (*input_line_pointer))
16966     as_bad (_("expected simple number"));
16967   if (input_line_pointer[0] == '0')
16968     {
16969       if (input_line_pointer[1] == 'x')
16970         {
16971           input_line_pointer += 2;
16972           while (ISXDIGIT (*input_line_pointer))
16973             {
16974               val <<= 4;
16975               val |= hex_value (*input_line_pointer++);
16976             }
16977           return negative ? -val : val;
16978         }
16979       else
16980         {
16981           ++input_line_pointer;
16982           while (ISDIGIT (*input_line_pointer))
16983             {
16984               val <<= 3;
16985               val |= *input_line_pointer++ - '0';
16986             }
16987           return negative ? -val : val;
16988         }
16989     }
16990   if (!ISDIGIT (*input_line_pointer))
16991     {
16992       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
16993               *input_line_pointer, *input_line_pointer);
16994       as_warn (_("invalid number"));
16995       return -1;
16996     }
16997   while (ISDIGIT (*input_line_pointer))
16998     {
16999       val *= 10;
17000       val += *input_line_pointer++ - '0';
17001     }
17002   return negative ? -val : val;
17003 }
17004
17005 /* The .file directive; just like the usual .file directive, but there
17006    is an initial number which is the ECOFF file index.  In the non-ECOFF
17007    case .file implies DWARF-2.  */
17008
17009 static void
17010 s_mips_file (int x ATTRIBUTE_UNUSED)
17011 {
17012   static int first_file_directive = 0;
17013
17014   if (ECOFF_DEBUGGING)
17015     {
17016       get_number ();
17017       s_app_file (0);
17018     }
17019   else
17020     {
17021       char *filename;
17022
17023       filename = dwarf2_directive_file (0);
17024
17025       /* Versions of GCC up to 3.1 start files with a ".file"
17026          directive even for stabs output.  Make sure that this
17027          ".file" is handled.  Note that you need a version of GCC
17028          after 3.1 in order to support DWARF-2 on MIPS.  */
17029       if (filename != NULL && ! first_file_directive)
17030         {
17031           (void) new_logical_line (filename, -1);
17032           s_app_file_string (filename, 0);
17033         }
17034       first_file_directive = 1;
17035     }
17036 }
17037
17038 /* The .loc directive, implying DWARF-2.  */
17039
17040 static void
17041 s_mips_loc (int x ATTRIBUTE_UNUSED)
17042 {
17043   if (!ECOFF_DEBUGGING)
17044     dwarf2_directive_loc (0);
17045 }
17046
17047 /* The .end directive.  */
17048
17049 static void
17050 s_mips_end (int x ATTRIBUTE_UNUSED)
17051 {
17052   symbolS *p;
17053
17054   /* Following functions need their own .frame and .cprestore directives.  */
17055   mips_frame_reg_valid = 0;
17056   mips_cprestore_valid = 0;
17057
17058   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17059     {
17060       p = get_symbol ();
17061       demand_empty_rest_of_line ();
17062     }
17063   else
17064     p = NULL;
17065
17066   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17067     as_warn (_(".end not in text section"));
17068
17069   if (!cur_proc_ptr)
17070     {
17071       as_warn (_(".end directive without a preceding .ent directive."));
17072       demand_empty_rest_of_line ();
17073       return;
17074     }
17075
17076   if (p != NULL)
17077     {
17078       gas_assert (S_GET_NAME (p));
17079       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17080         as_warn (_(".end symbol does not match .ent symbol."));
17081
17082       if (debug_type == DEBUG_STABS)
17083         stabs_generate_asm_endfunc (S_GET_NAME (p),
17084                                     S_GET_NAME (p));
17085     }
17086   else
17087     as_warn (_(".end directive missing or unknown symbol"));
17088
17089   /* Create an expression to calculate the size of the function.  */
17090   if (p && cur_proc_ptr)
17091     {
17092       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17093       expressionS *exp = xmalloc (sizeof (expressionS));
17094
17095       obj->size = exp;
17096       exp->X_op = O_subtract;
17097       exp->X_add_symbol = symbol_temp_new_now ();
17098       exp->X_op_symbol = p;
17099       exp->X_add_number = 0;
17100
17101       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17102     }
17103
17104   /* Generate a .pdr section.  */
17105   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17106     {
17107       segT saved_seg = now_seg;
17108       subsegT saved_subseg = now_subseg;
17109       expressionS exp;
17110       char *fragp;
17111
17112 #ifdef md_flush_pending_output
17113       md_flush_pending_output ();
17114 #endif
17115
17116       gas_assert (pdr_seg);
17117       subseg_set (pdr_seg, 0);
17118
17119       /* Write the symbol.  */
17120       exp.X_op = O_symbol;
17121       exp.X_add_symbol = p;
17122       exp.X_add_number = 0;
17123       emit_expr (&exp, 4);
17124
17125       fragp = frag_more (7 * 4);
17126
17127       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17128       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17129       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17130       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17131       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17132       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17133       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17134
17135       subseg_set (saved_seg, saved_subseg);
17136     }
17137
17138   cur_proc_ptr = NULL;
17139 }
17140
17141 /* The .aent and .ent directives.  */
17142
17143 static void
17144 s_mips_ent (int aent)
17145 {
17146   symbolS *symbolP;
17147
17148   symbolP = get_symbol ();
17149   if (*input_line_pointer == ',')
17150     ++input_line_pointer;
17151   SKIP_WHITESPACE ();
17152   if (ISDIGIT (*input_line_pointer)
17153       || *input_line_pointer == '-')
17154     get_number ();
17155
17156   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17157     as_warn (_(".ent or .aent not in text section."));
17158
17159   if (!aent && cur_proc_ptr)
17160     as_warn (_("missing .end"));
17161
17162   if (!aent)
17163     {
17164       /* This function needs its own .frame and .cprestore directives.  */
17165       mips_frame_reg_valid = 0;
17166       mips_cprestore_valid = 0;
17167
17168       cur_proc_ptr = &cur_proc;
17169       memset (cur_proc_ptr, '\0', sizeof (procS));
17170
17171       cur_proc_ptr->func_sym = symbolP;
17172
17173       ++numprocs;
17174
17175       if (debug_type == DEBUG_STABS)
17176         stabs_generate_asm_func (S_GET_NAME (symbolP),
17177                                  S_GET_NAME (symbolP));
17178     }
17179
17180   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17181
17182   demand_empty_rest_of_line ();
17183 }
17184
17185 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17186    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17187    s_mips_frame is used so that we can set the PDR information correctly.
17188    We can't use the ecoff routines because they make reference to the ecoff
17189    symbol table (in the mdebug section).  */
17190
17191 static void
17192 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17193 {
17194   if (ECOFF_DEBUGGING)
17195     s_ignore (ignore);
17196   else
17197     {
17198       long val;
17199
17200       if (cur_proc_ptr == (procS *) NULL)
17201         {
17202           as_warn (_(".frame outside of .ent"));
17203           demand_empty_rest_of_line ();
17204           return;
17205         }
17206
17207       cur_proc_ptr->frame_reg = tc_get_register (1);
17208
17209       SKIP_WHITESPACE ();
17210       if (*input_line_pointer++ != ','
17211           || get_absolute_expression_and_terminator (&val) != ',')
17212         {
17213           as_warn (_("Bad .frame directive"));
17214           --input_line_pointer;
17215           demand_empty_rest_of_line ();
17216           return;
17217         }
17218
17219       cur_proc_ptr->frame_offset = val;
17220       cur_proc_ptr->pc_reg = tc_get_register (0);
17221
17222       demand_empty_rest_of_line ();
17223     }
17224 }
17225
17226 /* The .fmask and .mask directives. If the mdebug section is present
17227    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17228    embedded targets, s_mips_mask is used so that we can set the PDR
17229    information correctly. We can't use the ecoff routines because they
17230    make reference to the ecoff symbol table (in the mdebug section).  */
17231
17232 static void
17233 s_mips_mask (int reg_type)
17234 {
17235   if (ECOFF_DEBUGGING)
17236     s_ignore (reg_type);
17237   else
17238     {
17239       long mask, off;
17240
17241       if (cur_proc_ptr == (procS *) NULL)
17242         {
17243           as_warn (_(".mask/.fmask outside of .ent"));
17244           demand_empty_rest_of_line ();
17245           return;
17246         }
17247
17248       if (get_absolute_expression_and_terminator (&mask) != ',')
17249         {
17250           as_warn (_("Bad .mask/.fmask directive"));
17251           --input_line_pointer;
17252           demand_empty_rest_of_line ();
17253           return;
17254         }
17255
17256       off = get_absolute_expression ();
17257
17258       if (reg_type == 'F')
17259         {
17260           cur_proc_ptr->fpreg_mask = mask;
17261           cur_proc_ptr->fpreg_offset = off;
17262         }
17263       else
17264         {
17265           cur_proc_ptr->reg_mask = mask;
17266           cur_proc_ptr->reg_offset = off;
17267         }
17268
17269       demand_empty_rest_of_line ();
17270     }
17271 }
17272
17273 /* A table describing all the processors gas knows about.  Names are
17274    matched in the order listed.
17275
17276    To ease comparison, please keep this table in the same order as
17277    gcc's mips_cpu_info_table[].  */
17278 static const struct mips_cpu_info mips_cpu_info_table[] =
17279 {
17280   /* Entries for generic ISAs */
17281   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17282   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17283   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17284   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17285   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17286   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17287   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17288   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17289   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17290
17291   /* MIPS I */
17292   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17293   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17294   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17295
17296   /* MIPS II */
17297   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17298
17299   /* MIPS III */
17300   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17301   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17302   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17303   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17304   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17305   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17306   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17307   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17308   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17309   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17310   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17311   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17312   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17313   /* ST Microelectronics Loongson 2E and 2F cores */
17314   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17315   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17316
17317   /* MIPS IV */
17318   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17319   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17320   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17321   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17322   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17323   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17324   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17325   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17326   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17327   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17328   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17329   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17330   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17331   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17332   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17333
17334   /* MIPS 32 */
17335   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17336   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17337   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17338   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17339
17340   /* MIPS 32 Release 2 */
17341   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17342   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17343   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17344   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17345   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17346   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17347   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17348   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17349   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17350                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17351   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17352                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17353   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17354   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17355   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17356   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17357   /* Deprecated forms of the above.  */
17358   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17359   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17360   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17361   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17362   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17363   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17364   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17365   /* Deprecated forms of the above.  */
17366   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17367   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17368   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17369   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17370   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17371   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17372   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17373   /* Deprecated forms of the above.  */
17374   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17375   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17376   /* 34Kn is a 34kc without DSP.  */
17377   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17378   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17379   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17380   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17381   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17382   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17383   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17384   /* Deprecated forms of the above.  */
17385   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17386   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17387   /* 1004K cores are multiprocessor versions of the 34K.  */
17388   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17389   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17390   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17391   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17392
17393   /* MIPS 64 */
17394   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17395   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17396   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17397   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17398
17399   /* Broadcom SB-1 CPU core */
17400   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17401   /* Broadcom SB-1A CPU core */
17402   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17403   
17404   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17405
17406   /* MIPS 64 Release 2 */
17407
17408   /* Cavium Networks Octeon CPU core */
17409   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17410   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17411   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17412
17413   /* RMI Xlr */
17414   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17415
17416   /* Broadcom XLP.
17417      XLP is mostly like XLR, with the prominent exception that it is
17418      MIPS64R2 rather than MIPS64.  */
17419   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17420
17421   /* End marker */
17422   { NULL, 0, 0, 0, 0 }
17423 };
17424
17425
17426 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17427    with a final "000" replaced by "k".  Ignore case.
17428
17429    Note: this function is shared between GCC and GAS.  */
17430
17431 static bfd_boolean
17432 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17433 {
17434   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17435     given++, canonical++;
17436
17437   return ((*given == 0 && *canonical == 0)
17438           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17439 }
17440
17441
17442 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17443    CPU name.  We've traditionally allowed a lot of variation here.
17444
17445    Note: this function is shared between GCC and GAS.  */
17446
17447 static bfd_boolean
17448 mips_matching_cpu_name_p (const char *canonical, const char *given)
17449 {
17450   /* First see if the name matches exactly, or with a final "000"
17451      turned into "k".  */
17452   if (mips_strict_matching_cpu_name_p (canonical, given))
17453     return TRUE;
17454
17455   /* If not, try comparing based on numerical designation alone.
17456      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17457   if (TOLOWER (*given) == 'r')
17458     given++;
17459   if (!ISDIGIT (*given))
17460     return FALSE;
17461
17462   /* Skip over some well-known prefixes in the canonical name,
17463      hoping to find a number there too.  */
17464   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17465     canonical += 2;
17466   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17467     canonical += 2;
17468   else if (TOLOWER (canonical[0]) == 'r')
17469     canonical += 1;
17470
17471   return mips_strict_matching_cpu_name_p (canonical, given);
17472 }
17473
17474
17475 /* Parse an option that takes the name of a processor as its argument.
17476    OPTION is the name of the option and CPU_STRING is the argument.
17477    Return the corresponding processor enumeration if the CPU_STRING is
17478    recognized, otherwise report an error and return null.
17479
17480    A similar function exists in GCC.  */
17481
17482 static const struct mips_cpu_info *
17483 mips_parse_cpu (const char *option, const char *cpu_string)
17484 {
17485   const struct mips_cpu_info *p;
17486
17487   /* 'from-abi' selects the most compatible architecture for the given
17488      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17489      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17490      version.  Look first at the -mgp options, if given, otherwise base
17491      the choice on MIPS_DEFAULT_64BIT.
17492
17493      Treat NO_ABI like the EABIs.  One reason to do this is that the
17494      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17495      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17496      'mips64', just as we did in the days before 'from-abi'.  */
17497   if (strcasecmp (cpu_string, "from-abi") == 0)
17498     {
17499       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17500         return mips_cpu_info_from_isa (ISA_MIPS1);
17501
17502       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17503         return mips_cpu_info_from_isa (ISA_MIPS3);
17504
17505       if (file_mips_gp32 >= 0)
17506         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17507
17508       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17509                                      ? ISA_MIPS3
17510                                      : ISA_MIPS1);
17511     }
17512
17513   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17514   if (strcasecmp (cpu_string, "default") == 0)
17515     return 0;
17516
17517   for (p = mips_cpu_info_table; p->name != 0; p++)
17518     if (mips_matching_cpu_name_p (p->name, cpu_string))
17519       return p;
17520
17521   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
17522   return 0;
17523 }
17524
17525 /* Return the canonical processor information for ISA (a member of the
17526    ISA_MIPS* enumeration).  */
17527
17528 static const struct mips_cpu_info *
17529 mips_cpu_info_from_isa (int isa)
17530 {
17531   int i;
17532
17533   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17534     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17535         && isa == mips_cpu_info_table[i].isa)
17536       return (&mips_cpu_info_table[i]);
17537
17538   return NULL;
17539 }
17540
17541 static const struct mips_cpu_info *
17542 mips_cpu_info_from_arch (int arch)
17543 {
17544   int i;
17545
17546   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17547     if (arch == mips_cpu_info_table[i].cpu)
17548       return (&mips_cpu_info_table[i]);
17549
17550   return NULL;
17551 }
17552 \f
17553 static void
17554 show (FILE *stream, const char *string, int *col_p, int *first_p)
17555 {
17556   if (*first_p)
17557     {
17558       fprintf (stream, "%24s", "");
17559       *col_p = 24;
17560     }
17561   else
17562     {
17563       fprintf (stream, ", ");
17564       *col_p += 2;
17565     }
17566
17567   if (*col_p + strlen (string) > 72)
17568     {
17569       fprintf (stream, "\n%24s", "");
17570       *col_p = 24;
17571     }
17572
17573   fprintf (stream, "%s", string);
17574   *col_p += strlen (string);
17575
17576   *first_p = 0;
17577 }
17578
17579 void
17580 md_show_usage (FILE *stream)
17581 {
17582   int column, first;
17583   size_t i;
17584
17585   fprintf (stream, _("\
17586 MIPS options:\n\
17587 -EB                     generate big endian output\n\
17588 -EL                     generate little endian output\n\
17589 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
17590 -G NUM                  allow referencing objects up to NUM bytes\n\
17591                         implicitly with the gp register [default 8]\n"));
17592   fprintf (stream, _("\
17593 -mips1                  generate MIPS ISA I instructions\n\
17594 -mips2                  generate MIPS ISA II instructions\n\
17595 -mips3                  generate MIPS ISA III instructions\n\
17596 -mips4                  generate MIPS ISA IV instructions\n\
17597 -mips5                  generate MIPS ISA V instructions\n\
17598 -mips32                 generate MIPS32 ISA instructions\n\
17599 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
17600 -mips64                 generate MIPS64 ISA instructions\n\
17601 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
17602 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
17603
17604   first = 1;
17605
17606   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17607     show (stream, mips_cpu_info_table[i].name, &column, &first);
17608   show (stream, "from-abi", &column, &first);
17609   fputc ('\n', stream);
17610
17611   fprintf (stream, _("\
17612 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
17613 -no-mCPU                don't generate code specific to CPU.\n\
17614                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
17615
17616   first = 1;
17617
17618   show (stream, "3900", &column, &first);
17619   show (stream, "4010", &column, &first);
17620   show (stream, "4100", &column, &first);
17621   show (stream, "4650", &column, &first);
17622   fputc ('\n', stream);
17623
17624   fprintf (stream, _("\
17625 -mips16                 generate mips16 instructions\n\
17626 -no-mips16              do not generate mips16 instructions\n"));
17627   fprintf (stream, _("\
17628 -mmicromips             generate microMIPS instructions\n\
17629 -mno-micromips          do not generate microMIPS instructions\n"));
17630   fprintf (stream, _("\
17631 -msmartmips             generate smartmips instructions\n\
17632 -mno-smartmips          do not generate smartmips instructions\n"));  
17633   fprintf (stream, _("\
17634 -mdsp                   generate DSP instructions\n\
17635 -mno-dsp                do not generate DSP instructions\n"));
17636   fprintf (stream, _("\
17637 -mdspr2                 generate DSP R2 instructions\n\
17638 -mno-dspr2              do not generate DSP R2 instructions\n"));
17639   fprintf (stream, _("\
17640 -mmt                    generate MT instructions\n\
17641 -mno-mt                 do not generate MT instructions\n"));
17642   fprintf (stream, _("\
17643 -mmcu                   generate MCU instructions\n\
17644 -mno-mcu                do not generate MCU instructions\n"));
17645   fprintf (stream, _("\
17646 -mvirt                  generate Virtualization instructions\n\
17647 -mno-virt               do not generate Virtualization instructions\n"));
17648   fprintf (stream, _("\
17649 -minsn32                only generate 32-bit microMIPS instructions\n\
17650 -mno-insn32             generate all microMIPS instructions\n"));
17651   fprintf (stream, _("\
17652 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
17653 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
17654 -mfix-vr4120            work around certain VR4120 errata\n\
17655 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
17656 -mfix-24k               insert a nop after ERET and DERET instructions\n\
17657 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
17658 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
17659 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
17660 -msym32                 assume all symbols have 32-bit values\n\
17661 -O0                     remove unneeded NOPs, do not swap branches\n\
17662 -O                      remove unneeded NOPs and swap branches\n\
17663 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
17664 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
17665   fprintf (stream, _("\
17666 -mhard-float            allow floating-point instructions\n\
17667 -msoft-float            do not allow floating-point instructions\n\
17668 -msingle-float          only allow 32-bit floating-point operations\n\
17669 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
17670 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
17671 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
17672 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
17673
17674   first = 1;
17675
17676   show (stream, "legacy", &column, &first);
17677   show (stream, "2008", &column, &first);
17678
17679   fputc ('\n', stream);
17680
17681   fprintf (stream, _("\
17682 -KPIC, -call_shared     generate SVR4 position independent code\n\
17683 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
17684 -mvxworks-pic           generate VxWorks position independent code\n\
17685 -non_shared             do not generate code that can operate with DSOs\n\
17686 -xgot                   assume a 32 bit GOT\n\
17687 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
17688 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
17689                         position dependent (non shared) code\n\
17690 -mabi=ABI               create ABI conformant object file for:\n"));
17691
17692   first = 1;
17693
17694   show (stream, "32", &column, &first);
17695   show (stream, "o64", &column, &first);
17696   show (stream, "n32", &column, &first);
17697   show (stream, "64", &column, &first);
17698   show (stream, "eabi", &column, &first);
17699
17700   fputc ('\n', stream);
17701
17702   fprintf (stream, _("\
17703 -32                     create o32 ABI object file (default)\n\
17704 -n32                    create n32 ABI object file\n\
17705 -64                     create 64 ABI object file\n"));
17706 }
17707
17708 #ifdef TE_IRIX
17709 enum dwarf2_format
17710 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
17711 {
17712   if (HAVE_64BIT_SYMBOLS)
17713     return dwarf2_format_64bit_irix;
17714   else
17715     return dwarf2_format_32bit;
17716 }
17717 #endif
17718
17719 int
17720 mips_dwarf2_addr_size (void)
17721 {
17722   if (HAVE_64BIT_OBJECTS)
17723     return 8;
17724   else
17725     return 4;
17726 }
17727
17728 /* Standard calling conventions leave the CFA at SP on entry.  */
17729 void
17730 mips_cfi_frame_initial_instructions (void)
17731 {
17732   cfi_add_CFA_def_cfa_register (SP);
17733 }
17734
17735 int
17736 tc_mips_regname_to_dw2regnum (char *regname)
17737 {
17738   unsigned int regnum = -1;
17739   unsigned int reg;
17740
17741   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
17742     regnum = reg;
17743
17744   return regnum;
17745 }