1/* tc-mips.c -- assemble code for a MIPS chip.
2   Copyright (C) 1993-2022 Free Software Foundation, Inc.
3   Contributed by the OSF and Ralph Campbell.
4   Written by Keith Knowles and Ralph Campbell, working independently.
5   Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6   Support.
7
8   This file is part of GAS.
9
10   GAS is free software; you can redistribute it and/or modify
11   it under the terms of the GNU General Public License as published by
12   the Free Software Foundation; either version 3, or (at your option)
13   any later version.
14
15   GAS is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   GNU General Public License for more details.
19
20   You should have received a copy of the GNU General Public License
21   along with GAS; see the file COPYING.  If not, write to the Free
22   Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23   02110-1301, USA.  */
24
25#include "as.h"
26#include "config.h"
27#include "subsegs.h"
28#include "safe-ctype.h"
29
30#include "opcode/mips.h"
31#include "itbl-ops.h"
32#include "dwarf2dbg.h"
33#include "dw2gencfi.h"
34
35/* Check assumptions made in this file.  */
36typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39#ifdef DEBUG
40#define DBG(x) printf x
41#else
42#define DBG(x)
43#endif
44
45#define streq(a, b)           (strcmp (a, b) == 0)
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.  */
51static int mips_output_flavor (void);
52static 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
78int 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
84int mips_flag_pdr = false;
85#else
86int mips_flag_pdr = true;
87#endif
88
89#include "ecoff.h"
90
91static char *mips_regmask_frag;
92static char *mips_flags_frag;
93
94#define ZERO 0
95#define ATREG 1
96#define S0  16
97#define S7  23
98#define TREG 24
99#define PIC_CALL_REG 25
100#define KT0 26
101#define KT1 27
102#define GP  28
103#define SP  29
104#define FP  30
105#define RA  31
106
107#define FCSR 31
108
109#define ILLEGAL_REG (32)
110
111#define AT  mips_opts.at
112
113extern int target_big_endian;
114
115/* The name of the readonly data section.  */
116#define RDATA_SECTION_NAME ".rodata"
117
118/* Ways in which an instruction can be "appended" to the output.  */
119enum append_method {
120  /* Just add it normally.  */
121  APPEND_ADD,
122
123  /* Add it normally and then add a nop.  */
124  APPEND_ADD_WITH_NOP,
125
126  /* Turn an instruction with a delay slot into a "compact" version.  */
127  APPEND_ADD_COMPACT,
128
129  /* Insert the instruction before the last one.  */
130  APPEND_SWAP
131};
132
133/* Information about an instruction, including its format, operands
134   and fixups.  */
135struct mips_cl_insn
136{
137  /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
138  const struct mips_opcode *insn_mo;
139
140  /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
141     a copy of INSN_MO->match with the operands filled in.  If we have
142     decided to use an extended MIPS16 instruction, this includes the
143     extension.  */
144  unsigned long insn_opcode;
145
146  /* The name if this is an label.  */
147  char label[16];
148
149  /* The target label name if this is an branch.  */
150  char target[16];
151
152  /* The frag that contains the instruction.  */
153  struct frag *frag;
154
155  /* The offset into FRAG of the first instruction byte.  */
156  long where;
157
158  /* The relocs associated with the instruction, if any.  */
159  fixS *fixp[3];
160
161  /* True if this entry cannot be moved from its current position.  */
162  unsigned int fixed_p : 1;
163
164  /* True if this instruction occurred in a .set noreorder block.  */
165  unsigned int noreorder_p : 1;
166
167  /* True for mips16 instructions that jump to an absolute address.  */
168  unsigned int mips16_absolute_jump_p : 1;
169
170  /* True if this instruction is complete.  */
171  unsigned int complete_p : 1;
172
173  /* True if this instruction is cleared from history by unconditional
174     branch.  */
175  unsigned int cleared_p : 1;
176};
177
178/* The ABI to use.  */
179enum mips_abi_level
180{
181  NO_ABI = 0,
182  O32_ABI,
183  O64_ABI,
184  N32_ABI,
185  N64_ABI,
186  EABI_ABI
187};
188
189/* MIPS ABI we are using for this output file.  */
190static enum mips_abi_level mips_abi = NO_ABI;
191
192/* Whether or not we have code that can call pic code.  */
193int mips_abicalls = false;
194
195/* Whether or not we have code which can be put into a shared
196   library.  */
197static bool mips_in_shared = true;
198
199/* This is the set of options which may be modified by the .set
200   pseudo-op.  We use a struct so that .set push and .set pop are more
201   reliable.  */
202
203struct mips_set_options
204{
205  /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
206     if it has not been initialized.  Changed by `.set mipsN', and the
207     -mipsN command line option, and the default CPU.  */
208  int isa;
209  /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
210     <asename>', by command line options, and based on the default
211     architecture.  */
212  int ase;
213  /* Whether we are assembling for the mips16 processor.  0 if we are
214     not, 1 if we are, and -1 if the value has not been initialized.
215     Changed by `.set mips16' and `.set nomips16', and the -mips16 and
216     -nomips16 command line options, and the default CPU.  */
217  int mips16;
218  /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
219     1 if we are, and -1 if the value has not been initialized.  Changed
220     by `.set micromips' and `.set nomicromips', and the -mmicromips
221     and -mno-micromips command line options, and the default CPU.  */
222  int micromips;
223  /* Non-zero if we should not reorder instructions.  Changed by `.set
224     reorder' and `.set noreorder'.  */
225  int noreorder;
226  /* Non-zero if we should not permit the register designated "assembler
227     temporary" to be used in instructions.  The value is the register
228     number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
229     (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
230  unsigned int at;
231  /* Non-zero if we should warn when a macro instruction expands into
232     more than one machine instruction.  Changed by `.set nomacro' and
233     `.set macro'.  */
234  int warn_about_macros;
235  /* Non-zero if we should not move instructions.  Changed by `.set
236     move', `.set volatile', `.set nomove', and `.set novolatile'.  */
237  int nomove;
238  /* Non-zero if we should not optimize branches by moving the target
239     of the branch into the delay slot.  Actually, we don't perform
240     this optimization anyhow.  Changed by `.set bopt' and `.set
241     nobopt'.  */
242  int nobopt;
243  /* Non-zero if we should not autoextend mips16 instructions.
244     Changed by `.set autoextend' and `.set noautoextend'.  */
245  int noautoextend;
246  /* True if we should only emit 32-bit microMIPS instructions.
247     Changed by `.set insn32' and `.set noinsn32', and the -minsn32
248     and -mno-insn32 command line options.  */
249  bool insn32;
250  /* Restrict general purpose registers and floating point registers
251     to 32 bit.  This is initially determined when -mgp32 or -mfp32
252     is passed but can changed if the assembler code uses .set mipsN.  */
253  int gp;
254  int fp;
255  /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
256     command line option, and the default CPU.  */
257  int arch;
258  /* True if ".set sym32" is in effect.  */
259  bool sym32;
260  /* True if floating-point operations are not allowed.  Changed by .set
261     softfloat or .set hardfloat, by command line options -msoft-float or
262     -mhard-float.  The default is false.  */
263  bool soft_float;
264
265  /* True if only single-precision floating-point operations are allowed.
266     Changed by .set singlefloat or .set doublefloat, command-line options
267     -msingle-float or -mdouble-float.  The default is false.  */
268  bool single_float;
269
270  /* 1 if single-precision operations on odd-numbered registers are
271     allowed.  */
272  int oddspreg;
273
274  /* The set of ASEs that should be enabled for the user specified
275     architecture.  This cannot be inferred from 'arch' for all cores
276     as processors only have a unique 'arch' if they add architecture
277     specific instructions (UDI).  */
278  int init_ase;
279};
280
281/* Specifies whether module level options have been checked yet.  */
282static bool file_mips_opts_checked = false;
283
284/* Do we support nan2008?  0 if we don't, 1 if we do, and -1 if the
285   value has not been initialized.  Changed by `.nan legacy' and
286   `.nan 2008', and the -mnan=legacy and -mnan=2008 command line
287   options, and the default CPU.  */
288static int mips_nan2008 = -1;
289
290/* This is the struct we use to hold the module level set of options.
291   Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
292   fp fields to -1 to indicate that they have not been initialized.  */
293
294static struct mips_set_options file_mips_opts =
295{
296  /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
297  /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
298  /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ false,
299  /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ false,
300  /* soft_float */ false, /* single_float */ false, /* oddspreg */ -1,
301  /* init_ase */ 0
302};
303
304/* This is similar to file_mips_opts, but for the current set of options.  */
305
306static struct mips_set_options mips_opts =
307{
308  /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
309  /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
310  /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ false,
311  /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ false,
312  /* soft_float */ false, /* single_float */ false, /* oddspreg */ -1,
313  /* init_ase */ 0
314};
315
316/* Which bits of file_ase were explicitly set or cleared by ASE options.  */
317static unsigned int file_ase_explicit;
318
319/* These variables are filled in with the masks of registers used.
320   The object format code reads them and puts them in the appropriate
321   place.  */
322unsigned long mips_gprmask;
323unsigned long mips_cprmask[4];
324
325/* True if any MIPS16 code was produced.  */
326static int file_ase_mips16;
327
328#define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32		\
329			      || mips_opts.isa == ISA_MIPS32R2		\
330			      || mips_opts.isa == ISA_MIPS32R3		\
331			      || mips_opts.isa == ISA_MIPS32R5		\
332			      || mips_opts.isa == ISA_MIPS64		\
333			      || mips_opts.isa == ISA_MIPS64R2		\
334			      || mips_opts.isa == ISA_MIPS64R3		\
335			      || mips_opts.isa == ISA_MIPS64R5)
336
337/* True if any microMIPS code was produced.  */
338static int file_ase_micromips;
339
340/* True if we want to create R_MIPS_JALR for jalr $25.  */
341#ifdef TE_IRIX
342#define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
343#else
344/* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
345   because there's no place for any addend, the only acceptable
346   expression is a bare symbol.  */
347#define MIPS_JALR_HINT_P(EXPR) \
348  (!HAVE_IN_PLACE_ADDENDS \
349   || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
350#endif
351
352/* The argument of the -march= flag.  The architecture we are assembling.  */
353static const char *mips_arch_string;
354
355/* The argument of the -mtune= flag.  The architecture for which we
356   are optimizing.  */
357static int mips_tune = CPU_UNKNOWN;
358static const char *mips_tune_string;
359
360/* True when generating 32-bit code for a 64-bit processor.  */
361static int mips_32bitmode = 0;
362
363/* True if the given ABI requires 32-bit registers.  */
364#define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
365
366/* Likewise 64-bit registers.  */
367#define ABI_NEEDS_64BIT_REGS(ABI)	\
368  ((ABI) == N32_ABI			\
369   || (ABI) == N64_ABI			\
370   || (ABI) == O64_ABI)
371
372#define ISA_IS_R6(ISA)			\
373  ((ISA) == ISA_MIPS32R6		\
374   || (ISA) == ISA_MIPS64R6)
375
376/*  Return true if ISA supports 64 bit wide gp registers.  */
377#define ISA_HAS_64BIT_REGS(ISA)		\
378  ((ISA) == ISA_MIPS3			\
379   || (ISA) == ISA_MIPS4		\
380   || (ISA) == ISA_MIPS5		\
381   || (ISA) == ISA_MIPS64		\
382   || (ISA) == ISA_MIPS64R2		\
383   || (ISA) == ISA_MIPS64R3		\
384   || (ISA) == ISA_MIPS64R5		\
385   || (ISA) == ISA_MIPS64R6)
386
387/*  Return true if ISA supports 64 bit wide float registers.  */
388#define ISA_HAS_64BIT_FPRS(ISA)		\
389  ((ISA) == ISA_MIPS3			\
390   || (ISA) == ISA_MIPS4		\
391   || (ISA) == ISA_MIPS5		\
392   || (ISA) == ISA_MIPS32R2		\
393   || (ISA) == ISA_MIPS32R3		\
394   || (ISA) == ISA_MIPS32R5		\
395   || (ISA) == ISA_MIPS32R6		\
396   || (ISA) == ISA_MIPS64		\
397   || (ISA) == ISA_MIPS64R2		\
398   || (ISA) == ISA_MIPS64R3		\
399   || (ISA) == ISA_MIPS64R5		\
400   || (ISA) == ISA_MIPS64R6)
401
402/* Return true if ISA supports 64-bit right rotate (dror et al.)
403   instructions.  */
404#define ISA_HAS_DROR(ISA)		\
405  ((ISA) == ISA_MIPS64R2		\
406   || (ISA) == ISA_MIPS64R3		\
407   || (ISA) == ISA_MIPS64R5		\
408   || (ISA) == ISA_MIPS64R6		\
409   || (mips_opts.micromips		\
410       && ISA_HAS_64BIT_REGS (ISA))	\
411   )
412
413/* Return true if ISA supports 32-bit right rotate (ror et al.)
414   instructions.  */
415#define ISA_HAS_ROR(ISA)		\
416  ((ISA) == ISA_MIPS32R2		\
417   || (ISA) == ISA_MIPS32R3		\
418   || (ISA) == ISA_MIPS32R5		\
419   || (ISA) == ISA_MIPS32R6		\
420   || (ISA) == ISA_MIPS64R2		\
421   || (ISA) == ISA_MIPS64R3		\
422   || (ISA) == ISA_MIPS64R5		\
423   || (ISA) == ISA_MIPS64R6		\
424   || (mips_opts.ase & ASE_SMARTMIPS)	\
425   || mips_opts.micromips		\
426   )
427
428/* Return true if ISA supports single-precision floats in odd registers.  */
429#define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
430  (((ISA) == ISA_MIPS32			\
431    || (ISA) == ISA_MIPS32R2		\
432    || (ISA) == ISA_MIPS32R3		\
433    || (ISA) == ISA_MIPS32R5		\
434    || (ISA) == ISA_MIPS32R6		\
435    || (ISA) == ISA_MIPS64		\
436    || (ISA) == ISA_MIPS64R2		\
437    || (ISA) == ISA_MIPS64R3		\
438    || (ISA) == ISA_MIPS64R5		\
439    || (ISA) == ISA_MIPS64R6		\
440    || (CPU) == CPU_R5900)		\
441   && ((CPU) != CPU_GS464		\
442    || (CPU) != CPU_GS464E		\
443    || (CPU) != CPU_GS264E))
444
445/* Return true if ISA supports move to/from high part of a 64-bit
446   floating-point register. */
447#define ISA_HAS_MXHC1(ISA)		\
448  ((ISA) == ISA_MIPS32R2		\
449   || (ISA) == ISA_MIPS32R3		\
450   || (ISA) == ISA_MIPS32R5		\
451   || (ISA) == ISA_MIPS32R6		\
452   || (ISA) == ISA_MIPS64R2		\
453   || (ISA) == ISA_MIPS64R3		\
454   || (ISA) == ISA_MIPS64R5		\
455   || (ISA) == ISA_MIPS64R6)
456
457/*  Return true if ISA supports legacy NAN.  */
458#define ISA_HAS_LEGACY_NAN(ISA)		\
459  ((ISA) == ISA_MIPS1			\
460   || (ISA) == ISA_MIPS2		\
461   || (ISA) == ISA_MIPS3		\
462   || (ISA) == ISA_MIPS4		\
463   || (ISA) == ISA_MIPS5		\
464   || (ISA) == ISA_MIPS32		\
465   || (ISA) == ISA_MIPS32R2		\
466   || (ISA) == ISA_MIPS32R3		\
467   || (ISA) == ISA_MIPS32R5		\
468   || (ISA) == ISA_MIPS64		\
469   || (ISA) == ISA_MIPS64R2		\
470   || (ISA) == ISA_MIPS64R3		\
471   || (ISA) == ISA_MIPS64R5)
472
473#define GPR_SIZE \
474    (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
475     ? 32 \
476     : mips_opts.gp)
477
478#define FPR_SIZE \
479    (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
480     ? 32 \
481     : mips_opts.fp)
482
483#define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
484
485#define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
486
487/* True if relocations are stored in-place.  */
488#define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
489
490/* The ABI-derived address size.  */
491#define HAVE_64BIT_ADDRESSES \
492  (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
493#define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
494
495/* The size of symbolic constants (i.e., expressions of the form
496   "SYMBOL" or "SYMBOL + OFFSET").  */
497#define HAVE_32BIT_SYMBOLS \
498  (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
499#define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
500
501/* Addresses are loaded in different ways, depending on the address size
502   in use.  The n32 ABI Documentation also mandates the use of additions
503   with overflow checking, but existing implementations don't follow it.  */
504#define ADDRESS_ADD_INSN						\
505   (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
506
507#define ADDRESS_ADDI_INSN						\
508   (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
509
510#define ADDRESS_LOAD_INSN						\
511   (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
512
513#define ADDRESS_STORE_INSN						\
514   (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
515
516/* Return true if the given CPU supports the MIPS16 ASE.  */
517#define CPU_HAS_MIPS16(cpu)						\
518   (startswith (TARGET_CPU, "mips16")					\
519    || startswith (TARGET_CANONICAL, "mips-lsi-elf"))
520
521/* Return true if the given CPU supports the microMIPS ASE.  */
522#define CPU_HAS_MICROMIPS(cpu)	0
523
524/* True if CPU has a dror instruction.  */
525#define CPU_HAS_DROR(CPU)	((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
526
527/* True if CPU has a ror instruction.  */
528#define CPU_HAS_ROR(CPU)	CPU_HAS_DROR (CPU)
529
530/* True if CPU is in the Octeon family.  */
531#define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
532			    || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
533
534/* True if CPU has seq/sne and seqi/snei instructions.  */
535#define CPU_HAS_SEQ(CPU)	(CPU_IS_OCTEON (CPU))
536
537/* True, if CPU has support for ldc1 and sdc1. */
538#define CPU_HAS_LDC1_SDC1(CPU)	\
539   ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
540
541/* True if mflo and mfhi can be immediately followed by instructions
542   which write to the HI and LO registers.
543
544   According to MIPS specifications, MIPS ISAs I, II, and III need
545   (at least) two instructions between the reads of HI/LO and
546   instructions which write them, and later ISAs do not.  Contradicting
547   the MIPS specifications, some MIPS IV processor user manuals (e.g.
548   the UM for the NEC Vr5000) document needing the instructions between
549   HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
550   MIPS64 and later ISAs to have the interlocks, plus any specific
551   earlier-ISA CPUs for which CPU documentation declares that the
552   instructions are really interlocked.  */
553#define hilo_interlocks \
554  (mips_opts.isa == ISA_MIPS32                        \
555   || mips_opts.isa == ISA_MIPS32R2                   \
556   || mips_opts.isa == ISA_MIPS32R3                   \
557   || mips_opts.isa == ISA_MIPS32R5                   \
558   || mips_opts.isa == ISA_MIPS32R6                   \
559   || mips_opts.isa == ISA_MIPS64                     \
560   || mips_opts.isa == ISA_MIPS64R2                   \
561   || mips_opts.isa == ISA_MIPS64R3                   \
562   || mips_opts.isa == ISA_MIPS64R5                   \
563   || mips_opts.isa == ISA_MIPS64R6                   \
564   || mips_opts.arch == CPU_R4010                     \
565   || mips_opts.arch == CPU_R5900                     \
566   || mips_opts.arch == CPU_R10000                    \
567   || mips_opts.arch == CPU_R12000                    \
568   || mips_opts.arch == CPU_R14000                    \
569   || mips_opts.arch == CPU_R16000                    \
570   || mips_opts.arch == CPU_RM7000                    \
571   || mips_opts.arch == CPU_VR5500                    \
572   || mips_opts.micromips                             \
573   )
574
575/* Whether the processor uses hardware interlocks to protect reads
576   from the GPRs after they are loaded from memory, and thus does not
577   require nops to be inserted.  This applies to instructions marked
578   INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
579   level I and microMIPS mode instructions are always interlocked.  */
580#define gpr_interlocks                                \
581  (mips_opts.isa != ISA_MIPS1                         \
582   || mips_opts.arch == CPU_R3900                     \
583   || mips_opts.arch == CPU_R5900                     \
584   || mips_opts.micromips                             \
585   )
586
587/* Whether the processor uses hardware interlocks to avoid delays
588   required by coprocessor instructions, and thus does not require
589   nops to be inserted.  This applies to instructions marked
590   INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
591   instructions marked INSN_WRITE_COND_CODE and ones marked
592   INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
593   levels I, II, and III and microMIPS mode instructions are always
594   interlocked.  */
595/* Itbl support may require additional care here.  */
596#define cop_interlocks                                \
597  ((mips_opts.isa != ISA_MIPS1                        \
598    && mips_opts.isa != ISA_MIPS2                     \
599    && mips_opts.isa != ISA_MIPS3)                    \
600   || mips_opts.arch == CPU_R4300                     \
601   || mips_opts.micromips                             \
602   )
603
604/* Whether the processor uses hardware interlocks to protect reads
605   from coprocessor registers after they are loaded from memory, and
606   thus does not require nops to be inserted.  This applies to
607   instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
608   requires at MIPS ISA level I and microMIPS mode instructions are
609   always interlocked.  */
610#define cop_mem_interlocks                            \
611  (mips_opts.isa != ISA_MIPS1                         \
612   || mips_opts.micromips                             \
613   )
614
615/* Is this a mfhi or mflo instruction?  */
616#define MF_HILO_INSN(PINFO) \
617  ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
618
619/* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
620   has been selected.  This implies, in particular, that addresses of text
621   labels have their LSB set.  */
622#define HAVE_CODE_COMPRESSION						\
623  ((mips_opts.mips16 | mips_opts.micromips) != 0)
624
625/* The minimum and maximum signed values that can be stored in a GPR.  */
626#define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
627#define GPR_SMIN (-GPR_SMAX - 1)
628
629/* MIPS PIC level.  */
630
631enum mips_pic_level mips_pic;
632
633/* 1 if we should generate 32 bit offsets from the $gp register in
634   SVR4_PIC mode.  Currently has no meaning in other modes.  */
635static int mips_big_got = 0;
636
637/* 1 if trap instructions should used for overflow rather than break
638   instructions.  */
639static int mips_trap = 0;
640
641/* 1 if double width floating point constants should not be constructed
642   by assembling two single width halves into two single width floating
643   point registers which just happen to alias the double width destination
644   register.  On some architectures this aliasing can be disabled by a bit
645   in the status register, and the setting of this bit cannot be determined
646   automatically at assemble time.  */
647static int mips_disable_float_construction;
648
649/* Non-zero if any .set noreorder directives were used.  */
650
651static int mips_any_noreorder;
652
653/* Non-zero if nops should be inserted when the register referenced in
654   an mfhi/mflo instruction is read in the next two instructions.  */
655static int mips_7000_hilo_fix;
656
657/* The size of objects in the small data section.  */
658static unsigned int g_switch_value = 8;
659/* Whether the -G option was used.  */
660static int g_switch_seen = 0;
661
662#define N_RMASK 0xc4
663#define N_VFP   0xd4
664
665/* If we can determine in advance that GP optimization won't be
666   possible, we can skip the relaxation stuff that tries to produce
667   GP-relative references.  This makes delay slot optimization work
668   better.
669
670   This function can only provide a guess, but it seems to work for
671   gcc output.  It needs to guess right for gcc, otherwise gcc
672   will put what it thinks is a GP-relative instruction in a branch
673   delay slot.
674
675   I don't know if a fix is needed for the SVR4_PIC mode.  I've only
676   fixed it for the non-PIC mode.  KR 95/04/07  */
677static int nopic_need_relax (symbolS *, int);
678
679/* Handle of the OPCODE hash table.  */
680static htab_t op_hash = NULL;
681
682/* The opcode hash table we use for the mips16.  */
683static htab_t mips16_op_hash = NULL;
684
685/* The opcode hash table we use for the microMIPS ASE.  */
686static htab_t micromips_op_hash = NULL;
687
688/* This array holds the chars that always start a comment.  If the
689    pre-processor is disabled, these aren't very useful.  */
690const char comment_chars[] = "#";
691
692/* This array holds the chars that only start a comment at the beginning of
693   a line.  If the line seems to have the form '# 123 filename'
694   .line and .file directives will appear in the pre-processed output.  */
695/* Note that input_file.c hand checks for '#' at the beginning of the
696   first line of the input file.  This is because the compiler outputs
697   #NO_APP at the beginning of its output.  */
698/* Also note that C style comments are always supported.  */
699const char line_comment_chars[] = "#";
700
701/* This array holds machine specific line separator characters.  */
702const char line_separator_chars[] = ";";
703
704/* Chars that can be used to separate mant from exp in floating point nums.  */
705const char EXP_CHARS[] = "eE";
706
707/* Chars that mean this number is a floating point constant.
708   As in 0f12.456
709   or    0d1.2345e12.  */
710const char FLT_CHARS[] = "rRsSfFdDxXpP";
711
712/* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
713   changed in read.c .  Ideally it shouldn't have to know about it at all,
714   but nothing is ideal around here.  */
715
716/* Types of printf format used for instruction-related error messages.
717   "I" means int ("%d") and "S" means string ("%s").  */
718enum mips_insn_error_format
719{
720  ERR_FMT_PLAIN,
721  ERR_FMT_I,
722  ERR_FMT_SS,
723};
724
725/* Information about an error that was found while assembling the current
726   instruction.  */
727struct mips_insn_error
728{
729  /* We sometimes need to match an instruction against more than one
730     opcode table entry.  Errors found during this matching are reported
731     against a particular syntactic argument rather than against the
732     instruction as a whole.  We grade these messages so that errors
733     against argument N have a greater priority than an error against
734     any argument < N, since the former implies that arguments up to N
735     were acceptable and that the opcode entry was therefore a closer match.
736     If several matches report an error against the same argument,
737     we only use that error if it is the same in all cases.
738
739     min_argnum is the minimum argument number for which an error message
740     should be accepted.  It is 0 if MSG is against the instruction as
741     a whole.  */
742  int min_argnum;
743
744  /* The printf()-style message, including its format and arguments.  */
745  enum mips_insn_error_format format;
746  const char *msg;
747  union
748  {
749    int i;
750    const char *ss[2];
751  } u;
752};
753
754/* The error that should be reported for the current instruction.  */
755static struct mips_insn_error insn_error;
756
757static int auto_align = 1;
758
759/* When outputting SVR4 PIC code, the assembler needs to know the
760   offset in the stack frame from which to restore the $gp register.
761   This is set by the .cprestore pseudo-op, and saved in this
762   variable.  */
763static offsetT mips_cprestore_offset = -1;
764
765/* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
766   more optimizations, it can use a register value instead of a memory-saved
767   offset and even an other register than $gp as global pointer.  */
768static offsetT mips_cpreturn_offset = -1;
769static int mips_cpreturn_register = -1;
770static int mips_gp_register = GP;
771static int mips_gprel_offset = 0;
772
773/* Whether mips_cprestore_offset has been set in the current function
774   (or whether it has already been warned about, if not).  */
775static int mips_cprestore_valid = 0;
776
777/* This is the register which holds the stack frame, as set by the
778   .frame pseudo-op.  This is needed to implement .cprestore.  */
779static int mips_frame_reg = SP;
780
781/* Whether mips_frame_reg has been set in the current function
782   (or whether it has already been warned about, if not).  */
783static int mips_frame_reg_valid = 0;
784
785/* To output NOP instructions correctly, we need to keep information
786   about the previous two instructions.  */
787
788/* Whether we are optimizing.  The default value of 2 means to remove
789   unneeded NOPs and swap branch instructions when possible.  A value
790   of 1 means to not swap branches.  A value of 0 means to always
791   insert NOPs.  */
792static int mips_optimize = 2;
793
794/* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
795   equivalent to seeing no -g option at all.  */
796static int mips_debug = 0;
797
798/* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
799#define MAX_VR4130_NOPS 4
800
801/* The maximum number of NOPs needed to fill delay slots.  */
802#define MAX_DELAY_NOPS 2
803
804/* The maximum number of NOPs needed for any purpose.  */
805#define MAX_NOPS 4
806
807/* The maximum range of context length of ll/sc.  */
808#define MAX_LLSC_RANGE 20
809
810/* A list of previous instructions, with index 0 being the most recent.
811   We need to look back MAX_NOPS instructions when filling delay slots
812   or working around processor errata.  We need to look back one
813   instruction further if we're thinking about using history[0] to
814   fill a branch delay slot.  */
815static struct mips_cl_insn history[1 + MAX_NOPS + MAX_LLSC_RANGE];
816
817/* The maximum number of LABELS detect for the same address.  */
818#define MAX_LABELS_SAME 10
819
820/* Arrays of operands for each instruction.  */
821#define MAX_OPERANDS 6
822struct mips_operand_array
823{
824  const struct mips_operand *operand[MAX_OPERANDS];
825};
826static struct mips_operand_array *mips_operands;
827static struct mips_operand_array *mips16_operands;
828static struct mips_operand_array *micromips_operands;
829
830/* Nop instructions used by emit_nop.  */
831static struct mips_cl_insn nop_insn;
832static struct mips_cl_insn mips16_nop_insn;
833static struct mips_cl_insn micromips_nop16_insn;
834static struct mips_cl_insn micromips_nop32_insn;
835
836/* Sync instructions used by insert sync.  */
837static struct mips_cl_insn sync_insn;
838
839/* The appropriate nop for the current mode.  */
840#define NOP_INSN (mips_opts.mips16					\
841		  ? &mips16_nop_insn					\
842		  : (mips_opts.micromips				\
843		     ? (mips_opts.insn32				\
844			? &micromips_nop32_insn				\
845			: &micromips_nop16_insn)			\
846		     : &nop_insn))
847
848/* The size of NOP_INSN in bytes.  */
849#define NOP_INSN_SIZE ((mips_opts.mips16				\
850			|| (mips_opts.micromips && !mips_opts.insn32))	\
851		       ? 2 : 4)
852
853/* If this is set, it points to a frag holding nop instructions which
854   were inserted before the start of a noreorder section.  If those
855   nops turn out to be unnecessary, the size of the frag can be
856   decreased.  */
857static fragS *prev_nop_frag;
858
859/* The number of nop instructions we created in prev_nop_frag.  */
860static int prev_nop_frag_holds;
861
862/* The number of nop instructions that we know we need in
863   prev_nop_frag.  */
864static int prev_nop_frag_required;
865
866/* The number of instructions we've seen since prev_nop_frag.  */
867static int prev_nop_frag_since;
868
869/* Relocations against symbols are sometimes done in two parts, with a HI
870   relocation and a LO relocation.  Each relocation has only 16 bits of
871   space to store an addend.  This means that in order for the linker to
872   handle carries correctly, it must be able to locate both the HI and
873   the LO relocation.  This means that the relocations must appear in
874   order in the relocation table.
875
876   In order to implement this, we keep track of each unmatched HI
877   relocation.  We then sort them so that they immediately precede the
878   corresponding LO relocation.  */
879
880struct mips_hi_fixup
881{
882  /* Next HI fixup.  */
883  struct mips_hi_fixup *next;
884  /* This fixup.  */
885  fixS *fixp;
886  /* The section this fixup is in.  */
887  segT seg;
888};
889
890/* The list of unmatched HI relocs.  */
891
892static struct mips_hi_fixup *mips_hi_fixup_list;
893
894/* Map mips16 register numbers to normal MIPS register numbers.  */
895
896static const unsigned int mips16_to_32_reg_map[] =
897{
898  16, 17, 2, 3, 4, 5, 6, 7
899};
900
901/* Map microMIPS register numbers to normal MIPS register numbers.  */
902
903#define micromips_to_32_reg_d_map	mips16_to_32_reg_map
904
905/* The microMIPS registers with type h.  */
906static const unsigned int micromips_to_32_reg_h_map1[] =
907{
908  5, 5, 6, 4, 4, 4, 4, 4
909};
910static const unsigned int micromips_to_32_reg_h_map2[] =
911{
912  6, 7, 7, 21, 22, 5, 6, 7
913};
914
915/* The microMIPS registers with type m.  */
916static const unsigned int micromips_to_32_reg_m_map[] =
917{
918  0, 17, 2, 3, 16, 18, 19, 20
919};
920
921#define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
922
923/* Classifies the kind of instructions we're interested in when
924   implementing -mfix-vr4120.  */
925enum fix_vr4120_class
926{
927  FIX_VR4120_MACC,
928  FIX_VR4120_DMACC,
929  FIX_VR4120_MULT,
930  FIX_VR4120_DMULT,
931  FIX_VR4120_DIV,
932  FIX_VR4120_MTHILO,
933  NUM_FIX_VR4120_CLASSES
934};
935
936/* ...likewise -mtrap-zero-jump.  */
937static bfd_boolean mips_trap_zero_jump;
938
939/* ...likewise -mfix-loongson2f-jump.  */
940static bool mips_fix_loongson2f_jump;
941
942/* ...likewise -mfix-loongson2f-nop.  */
943static bool mips_fix_loongson2f_nop;
944
945/* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
946static bool mips_fix_loongson2f;
947
948/* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
949   there must be at least one other instruction between an instruction
950   of type X and an instruction of type Y.  */
951static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
952
953/* True if -mfix-vr4120 is in force.  */
954static int mips_fix_vr4120;
955
956/* ...likewise -mfix-vr4130.  */
957static int mips_fix_vr4130;
958
959/* ...likewise -mfix-24k.  */
960static int mips_fix_24k;
961
962/* ...likewise -mfix-rm7000  */
963static int mips_fix_rm7000;
964
965/* ...likewise -mfix-cn63xxp1 */
966static bool mips_fix_cn63xxp1;
967
968/* ...likewise -mfix-r5900 */
969static bool mips_fix_r5900;
970static bool mips_fix_r5900_explicit;
971
972/* ...likewise -mfix-loongson3-llsc.  */
973static bool mips_fix_loongson3_llsc = DEFAULT_MIPS_FIX_LOONGSON3_LLSC;
974
975/* We don't relax branches by default, since this causes us to expand
976   `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
977   fail to compute the offset before expanding the macro to the most
978   efficient expansion.  */
979
980static int mips_relax_branch;
981
982static int mips_fix_loongson2f_btb;
983
984/* TRUE if checks are suppressed for invalid branches between ISA modes.
985   Needed for broken assembly produced by some GCC versions and some
986   sloppy code out there, where branches to data labels are present.  */
987static bool mips_ignore_branch_isa;
988
989/* The expansion of many macros depends on the type of symbol that
990   they refer to.  For example, when generating position-dependent code,
991   a macro that refers to a symbol may have two different expansions,
992   one which uses GP-relative addresses and one which uses absolute
993   addresses.  When generating SVR4-style PIC, a macro may have
994   different expansions for local and global symbols.
995
996   We handle these situations by generating both sequences and putting
997   them in variant frags.  In position-dependent code, the first sequence
998   will be the GP-relative one and the second sequence will be the
999   absolute one.  In SVR4 PIC, the first sequence will be for global
1000   symbols and the second will be for local symbols.
1001
1002   The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
1003   SECOND are the lengths of the two sequences in bytes.  These fields
1004   can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
1005   the subtype has the following flags:
1006
1007   RELAX_PIC
1008	Set if generating PIC code.
1009
1010   RELAX_USE_SECOND
1011	Set if it has been decided that we should use the second
1012	sequence instead of the first.
1013
1014   RELAX_SECOND_LONGER
1015	Set in the first variant frag if the macro's second implementation
1016	is longer than its first.  This refers to the macro as a whole,
1017	not an individual relaxation.
1018
1019   RELAX_NOMACRO
1020	Set in the first variant frag if the macro appeared in a .set nomacro
1021	block and if one alternative requires a warning but the other does not.
1022
1023   RELAX_DELAY_SLOT
1024	Like RELAX_NOMACRO, but indicates that the macro appears in a branch
1025	delay slot.
1026
1027   RELAX_DELAY_SLOT_16BIT
1028	Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
1029	16-bit instruction.
1030
1031   RELAX_DELAY_SLOT_SIZE_FIRST
1032	Like RELAX_DELAY_SLOT, but indicates that the first implementation of
1033	the macro is of the wrong size for the branch delay slot.
1034
1035   RELAX_DELAY_SLOT_SIZE_SECOND
1036	Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1037	the macro is of the wrong size for the branch delay slot.
1038
1039   The frag's "opcode" points to the first fixup for relaxable code.
1040
1041   Relaxable macros are generated using a sequence such as:
1042
1043      relax_start (SYMBOL);
1044      ... generate first expansion ...
1045      relax_switch ();
1046      ... generate second expansion ...
1047      relax_end ();
1048
1049   The code and fixups for the unwanted alternative are discarded
1050   by md_convert_frag.  */
1051#define RELAX_ENCODE(FIRST, SECOND, PIC)			\
1052  (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1053
1054#define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1055#define RELAX_SECOND(X) ((X) & 0xff)
1056#define RELAX_PIC(X) (((X) & 0x10000) != 0)
1057#define RELAX_USE_SECOND 0x20000
1058#define RELAX_SECOND_LONGER 0x40000
1059#define RELAX_NOMACRO 0x80000
1060#define RELAX_DELAY_SLOT 0x100000
1061#define RELAX_DELAY_SLOT_16BIT 0x200000
1062#define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1063#define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1064
1065/* Branch without likely bit.  If label is out of range, we turn:
1066
1067	beq reg1, reg2, label
1068	delay slot
1069
1070   into
1071
1072        bne reg1, reg2, 0f
1073        nop
1074        j label
1075     0: delay slot
1076
1077   with the following opcode replacements:
1078
1079	beq <-> bne
1080	blez <-> bgtz
1081	bltz <-> bgez
1082	bc1f <-> bc1t
1083
1084	bltzal <-> bgezal  (with jal label instead of j label)
1085
1086   Even though keeping the delay slot instruction in the delay slot of
1087   the branch would be more efficient, it would be very tricky to do
1088   correctly, because we'd have to introduce a variable frag *after*
1089   the delay slot instruction, and expand that instead.  Let's do it
1090   the easy way for now, even if the branch-not-taken case now costs
1091   one additional instruction.  Out-of-range branches are not supposed
1092   to be common, anyway.
1093
1094   Branch likely.  If label is out of range, we turn:
1095
1096	beql reg1, reg2, label
1097	delay slot (annulled if branch not taken)
1098
1099   into
1100
1101        beql reg1, reg2, 1f
1102        nop
1103        beql $0, $0, 2f
1104        nop
1105     1: j[al] label
1106        delay slot (executed only if branch taken)
1107     2:
1108
1109   It would be possible to generate a shorter sequence by losing the
1110   likely bit, generating something like:
1111
1112	bne reg1, reg2, 0f
1113	nop
1114	j[al] label
1115	delay slot (executed only if branch taken)
1116     0:
1117
1118	beql -> bne
1119	bnel -> beq
1120	blezl -> bgtz
1121	bgtzl -> blez
1122	bltzl -> bgez
1123	bgezl -> bltz
1124	bc1fl -> bc1t
1125	bc1tl -> bc1f
1126
1127	bltzall -> bgezal  (with jal label instead of j label)
1128	bgezall -> bltzal  (ditto)
1129
1130
1131   but it's not clear that it would actually improve performance.  */
1132#define RELAX_BRANCH_ENCODE(at, pic,				\
1133			    uncond, likely, link, toofar)	\
1134  ((relax_substateT)						\
1135   (0xc0000000							\
1136    | ((at) & 0x1f)						\
1137    | ((pic) ? 0x20 : 0)					\
1138    | ((toofar) ? 0x40 : 0)					\
1139    | ((link) ? 0x80 : 0)					\
1140    | ((likely) ? 0x100 : 0)					\
1141    | ((uncond) ? 0x200 : 0)))
1142#define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1143#define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1144#define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1145#define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1146#define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1147#define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1148#define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1149
1150/* For mips16 code, we use an entirely different form of relaxation.
1151   mips16 supports two versions of most instructions which take
1152   immediate values: a small one which takes some small value, and a
1153   larger one which takes a 16 bit value.  Since branches also follow
1154   this pattern, relaxing these values is required.
1155
1156   We can assemble both mips16 and normal MIPS code in a single
1157   object.  Therefore, we need to support this type of relaxation at
1158   the same time that we support the relaxation described above.  We
1159   use the high bit of the subtype field to distinguish these cases.
1160
1161   The information we store for this type of relaxation is the
1162   argument code found in the opcode file for this relocation, whether
1163   the user explicitly requested a small or extended form, and whether
1164   the relocation is in a jump or jal delay slot.  That tells us the
1165   size of the value, and how it should be stored.  We also store
1166   whether the fragment is considered to be extended or not.  We also
1167   store whether this is known to be a branch to a different section,
1168   whether we have tried to relax this frag yet, and whether we have
1169   ever extended a PC relative fragment because of a shift count.  */
1170#define RELAX_MIPS16_ENCODE(type, e2, pic, sym32, nomacro,	\
1171			    small, ext,				\
1172			    dslot, jal_dslot)			\
1173  (0x80000000							\
1174   | ((type) & 0xff)						\
1175   | ((e2) ? 0x100 : 0)						\
1176   | ((pic) ? 0x200 : 0)					\
1177   | ((sym32) ? 0x400 : 0)					\
1178   | ((nomacro) ? 0x800 : 0)					\
1179   | ((small) ? 0x1000 : 0)					\
1180   | ((ext) ? 0x2000 : 0)					\
1181   | ((dslot) ? 0x4000 : 0)					\
1182   | ((jal_dslot) ? 0x8000 : 0))
1183
1184#define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1185#define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1186#define RELAX_MIPS16_E2(i) (((i) & 0x100) != 0)
1187#define RELAX_MIPS16_PIC(i) (((i) & 0x200) != 0)
1188#define RELAX_MIPS16_SYM32(i) (((i) & 0x400) != 0)
1189#define RELAX_MIPS16_NOMACRO(i) (((i) & 0x800) != 0)
1190#define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x1000) != 0)
1191#define RELAX_MIPS16_USER_EXT(i) (((i) & 0x2000) != 0)
1192#define RELAX_MIPS16_DSLOT(i) (((i) & 0x4000) != 0)
1193#define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x8000) != 0)
1194
1195#define RELAX_MIPS16_EXTENDED(i) (((i) & 0x10000) != 0)
1196#define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x10000)
1197#define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x10000)
1198#define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x20000) != 0)
1199#define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x20000)
1200#define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x20000)
1201#define RELAX_MIPS16_MACRO(i) (((i) & 0x40000) != 0)
1202#define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x40000)
1203#define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x40000)
1204
1205/* For microMIPS code, we use relaxation similar to one we use for
1206   MIPS16 code.  Some instructions that take immediate values support
1207   two encodings: a small one which takes some small value, and a
1208   larger one which takes a 16 bit value.  As some branches also follow
1209   this pattern, relaxing these values is required.
1210
1211   We can assemble both microMIPS and normal MIPS code in a single
1212   object.  Therefore, we need to support this type of relaxation at
1213   the same time that we support the relaxation described above.  We
1214   use one of the high bits of the subtype field to distinguish these
1215   cases.
1216
1217   The information we store for this type of relaxation is the argument
1218   code found in the opcode file for this relocation, the register
1219   selected as the assembler temporary, whether in the 32-bit
1220   instruction mode, whether the branch is unconditional, whether it is
1221   compact, whether there is no delay-slot instruction available to fill
1222   in, whether it stores the link address implicitly in $ra, whether
1223   relaxation of out-of-range 32-bit branches to a sequence of
1224   instructions is enabled, and whether the displacement of a branch is
1225   too large to fit as an immediate argument of a 16-bit and a 32-bit
1226   branch, respectively.  */
1227#define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,		\
1228			       uncond, compact, link, nods,	\
1229			       relax32, toofar16, toofar32)	\
1230  (0x40000000							\
1231   | ((type) & 0xff)						\
1232   | (((at) & 0x1f) << 8)					\
1233   | ((insn32) ? 0x2000 : 0)					\
1234   | ((pic) ? 0x4000 : 0)					\
1235   | ((uncond) ? 0x8000 : 0)					\
1236   | ((compact) ? 0x10000 : 0)					\
1237   | ((link) ? 0x20000 : 0)					\
1238   | ((nods) ? 0x40000 : 0)					\
1239   | ((relax32) ? 0x80000 : 0)					\
1240   | ((toofar16) ? 0x100000 : 0)				\
1241   | ((toofar32) ? 0x200000 : 0))
1242#define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1243#define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1244#define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1245#define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1246#define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1247#define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1248#define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1249#define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1250#define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1251#define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1252
1253#define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1254#define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1255#define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1256#define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1257#define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1258#define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1259
1260/* Sign-extend 16-bit value X.  */
1261#define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1262
1263/* Is the given value a sign-extended 32-bit value?  */
1264#define IS_SEXT_32BIT_NUM(x)						\
1265  (((x) &~ (offsetT) 0x7fffffff) == 0					\
1266   || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1267
1268/* Is the given value a sign-extended 16-bit value?  */
1269#define IS_SEXT_16BIT_NUM(x)						\
1270  (((x) &~ (offsetT) 0x7fff) == 0					\
1271   || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1272
1273/* Is the given value a sign-extended 12-bit value?  */
1274#define IS_SEXT_12BIT_NUM(x)						\
1275  (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1276
1277/* Is the given value a sign-extended 9-bit value?  */
1278#define IS_SEXT_9BIT_NUM(x)						\
1279  (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1280
1281/* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1282#define IS_ZEXT_32BIT_NUM(x)						\
1283  (((x) &~ (offsetT) 0xffffffff) == 0					\
1284   || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1285
1286/* Extract bits MASK << SHIFT from STRUCT and shift them right
1287   SHIFT places.  */
1288#define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1289  (((STRUCT) >> (SHIFT)) & (MASK))
1290
1291/* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1292#define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1293  (!(MICROMIPS) \
1294   ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1295   : EXTRACT_BITS ((INSN).insn_opcode, \
1296		   MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1297#define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1298  EXTRACT_BITS ((INSN).insn_opcode, \
1299		MIPS16OP_MASK_##FIELD, \
1300		MIPS16OP_SH_##FIELD)
1301
1302/* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1303#define MIPS16_EXTEND (0xf000U << 16)
1304
1305/* Whether or not we are emitting a branch-likely macro.  */
1306static bool emit_branch_likely_macro = false;
1307
1308/* Global variables used when generating relaxable macros.  See the
1309   comment above RELAX_ENCODE for more details about how relaxation
1310   is used.  */
1311static struct {
1312  /* 0 if we're not emitting a relaxable macro.
1313     1 if we're emitting the first of the two relaxation alternatives.
1314     2 if we're emitting the second alternative.  */
1315  int sequence;
1316
1317  /* The first relaxable fixup in the current frag.  (In other words,
1318     the first fixup that refers to relaxable code.)  */
1319  fixS *first_fixup;
1320
1321  /* sizes[0] says how many bytes of the first alternative are stored in
1322     the current frag.  Likewise sizes[1] for the second alternative.  */
1323  unsigned int sizes[2];
1324
1325  /* The symbol on which the choice of sequence depends.  */
1326  symbolS *symbol;
1327} mips_relax;
1328
1329/* Global variables used to decide whether a macro needs a warning.  */
1330static struct {
1331  /* True if the macro is in a branch delay slot.  */
1332  bool delay_slot_p;
1333
1334  /* Set to the length in bytes required if the macro is in a delay slot
1335     that requires a specific length of instruction, otherwise zero.  */
1336  unsigned int delay_slot_length;
1337
1338  /* For relaxable macros, sizes[0] is the length of the first alternative
1339     in bytes and sizes[1] is the length of the second alternative.
1340     For non-relaxable macros, both elements give the length of the
1341     macro in bytes.  */
1342  unsigned int sizes[2];
1343
1344  /* For relaxable macros, first_insn_sizes[0] is the length of the first
1345     instruction of the first alternative in bytes and first_insn_sizes[1]
1346     is the length of the first instruction of the second alternative.
1347     For non-relaxable macros, both elements give the length of the first
1348     instruction in bytes.
1349
1350     Set to zero if we haven't yet seen the first instruction.  */
1351  unsigned int first_insn_sizes[2];
1352
1353  /* For relaxable macros, insns[0] is the number of instructions for the
1354     first alternative and insns[1] is the number of instructions for the
1355     second alternative.
1356
1357     For non-relaxable macros, both elements give the number of
1358     instructions for the macro.  */
1359  unsigned int insns[2];
1360
1361  /* The first variant frag for this macro.  */
1362  fragS *first_frag;
1363} mips_macro_warning;
1364
1365/* Prototypes for static functions.  */
1366
1367enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1368
1369static void append_insn
1370  (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1371   bool expansionp);
1372static void mips_no_prev_insn (void);
1373static void macro_build (expressionS *, const char *, const char *, ...);
1374static void mips16_macro_build
1375  (expressionS *, const char *, const char *, va_list *);
1376static void load_register (int, expressionS *, int);
1377static void macro_build (expressionS *, const char *, const char *, ...);
1378static void macro_start (void);
1379static void macro_end (void);
1380static void macro (struct mips_cl_insn *ip, char *str);
1381static void mips16_macro (struct mips_cl_insn * ip);
1382static void mips_ip (char *str, struct mips_cl_insn * ip);
1383static void mips16_ip (char *str, struct mips_cl_insn * ip);
1384static unsigned long mips16_immed_extend (offsetT, unsigned int);
1385static void mips16_immed
1386  (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1387   unsigned int, unsigned long *);
1388static size_t my_getSmallExpression
1389  (expressionS *, bfd_reloc_code_real_type *, char *);
1390static void my_getExpression (expressionS *, char *);
1391static void s_align (int);
1392static void s_change_sec (int);
1393static void s_change_section (int);
1394static void s_cons (int);
1395static void s_float_cons (int);
1396static void s_mips_globl (int);
1397static void s_option (int);
1398static void s_mipsset (int);
1399static void s_abicalls (int);
1400static void s_cpload (int);
1401static void s_cpsetup (int);
1402static void s_cplocal (int);
1403static void s_cprestore (int);
1404static void s_cpreturn (int);
1405static void s_dtprelword (int);
1406static void s_dtpreldword (int);
1407static void s_tprelword (int);
1408static void s_tpreldword (int);
1409static void s_gpvalue (int);
1410static void s_gpword (int);
1411static void s_gpdword (int);
1412static void s_ehword (int);
1413static void s_cpadd (int);
1414static void s_insn (int);
1415static void s_nan (int);
1416static void s_module (int);
1417static void s_mips_ent (int);
1418static void s_mips_end (int);
1419static void s_mips_frame (int);
1420static void s_mips_mask (int reg_type);
1421static void s_mips_stab (int);
1422static void s_mips_weakext (int);
1423static void s_mips_file (int);
1424static void s_mips_loc (int);
1425static bool pic_need_relax (symbolS *);
1426static int relaxed_branch_length (fragS *, asection *, int);
1427static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1428static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1429static void file_mips_check_options (void);
1430
1431/* Table and functions used to map between CPU/ISA names, and
1432   ISA levels, and CPU numbers.  */
1433
1434struct mips_cpu_info
1435{
1436  const char *name;           /* CPU or ISA name.  */
1437  int flags;                  /* MIPS_CPU_* flags.  */
1438  int ase;                    /* Set of ASEs implemented by the CPU.  */
1439  int isa;                    /* ISA level.  */
1440  int cpu;                    /* CPU number (default CPU if ISA).  */
1441};
1442
1443#define MIPS_CPU_IS_ISA		0x0001	/* Is this an ISA?  (If 0, a CPU.) */
1444
1445static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1446static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1447static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1448
1449/* Command-line options.  */
1450const char *md_shortopts = "O::g::G:";
1451
1452enum options
1453  {
1454    OPTION_MARCH = OPTION_MD_BASE,
1455    OPTION_MTUNE,
1456    OPTION_MIPS1,
1457    OPTION_MIPS2,
1458    OPTION_MIPS3,
1459    OPTION_MIPS4,
1460    OPTION_MIPS5,
1461    OPTION_MIPS32,
1462    OPTION_MIPS64,
1463    OPTION_MIPS32R2,
1464    OPTION_MIPS32R3,
1465    OPTION_MIPS32R5,
1466    OPTION_MIPS32R6,
1467    OPTION_MIPS64R2,
1468    OPTION_MIPS64R3,
1469    OPTION_MIPS64R5,
1470    OPTION_MIPS64R6,
1471    OPTION_MIPS16,
1472    OPTION_NO_MIPS16,
1473    OPTION_MIPS3D,
1474    OPTION_NO_MIPS3D,
1475    OPTION_MDMX,
1476    OPTION_NO_MDMX,
1477    OPTION_DSP,
1478    OPTION_NO_DSP,
1479    OPTION_MT,
1480    OPTION_NO_MT,
1481    OPTION_VIRT,
1482    OPTION_NO_VIRT,
1483    OPTION_MSA,
1484    OPTION_NO_MSA,
1485    OPTION_SMARTMIPS,
1486    OPTION_NO_SMARTMIPS,
1487    OPTION_DSPR2,
1488    OPTION_NO_DSPR2,
1489    OPTION_DSPR3,
1490    OPTION_NO_DSPR3,
1491    OPTION_EVA,
1492    OPTION_NO_EVA,
1493    OPTION_XPA,
1494    OPTION_NO_XPA,
1495    OPTION_MICROMIPS,
1496    OPTION_NO_MICROMIPS,
1497    OPTION_MCU,
1498    OPTION_NO_MCU,
1499    OPTION_MIPS16E2,
1500    OPTION_NO_MIPS16E2,
1501    OPTION_CRC,
1502    OPTION_NO_CRC,
1503    OPTION_M4650,
1504    OPTION_NO_M4650,
1505    OPTION_M4010,
1506    OPTION_NO_M4010,
1507    OPTION_M4100,
1508    OPTION_NO_M4100,
1509    OPTION_M3900,
1510    OPTION_NO_M3900,
1511    OPTION_M7000_HILO_FIX,
1512    OPTION_MNO_7000_HILO_FIX,
1513    OPTION_FIX_24K,
1514    OPTION_NO_FIX_24K,
1515    OPTION_FIX_RM7000,
1516    OPTION_NO_FIX_RM7000,
1517    OPTION_FIX_LOONGSON3_LLSC,
1518    OPTION_NO_FIX_LOONGSON3_LLSC,
1519    OPTION_FIX_LOONGSON2F_JUMP,
1520    OPTION_NO_FIX_LOONGSON2F_JUMP,
1521    OPTION_FIX_LOONGSON2F_NOP,
1522    OPTION_NO_FIX_LOONGSON2F_NOP,
1523    OPTION_FIX_VR4120,
1524    OPTION_NO_FIX_VR4120,
1525    OPTION_FIX_VR4130,
1526    OPTION_NO_FIX_VR4130,
1527    OPTION_FIX_CN63XXP1,
1528    OPTION_NO_FIX_CN63XXP1,
1529    OPTION_FIX_R5900,
1530    OPTION_NO_FIX_R5900,
1531    OPTION_TRAP,
1532    OPTION_BREAK,
1533    OPTION_EB,
1534    OPTION_EL,
1535    OPTION_FP32,
1536    OPTION_GP32,
1537    OPTION_CONSTRUCT_FLOATS,
1538    OPTION_NO_CONSTRUCT_FLOATS,
1539    OPTION_FP64,
1540    OPTION_FPXX,
1541    OPTION_GP64,
1542    OPTION_RELAX_BRANCH,
1543    OPTION_NO_RELAX_BRANCH,
1544    OPTION_IGNORE_BRANCH_ISA,
1545    OPTION_NO_IGNORE_BRANCH_ISA,
1546    OPTION_INSN32,
1547    OPTION_NO_INSN32,
1548    OPTION_MSHARED,
1549    OPTION_MNO_SHARED,
1550    OPTION_MSYM32,
1551    OPTION_MNO_SYM32,
1552    OPTION_SOFT_FLOAT,
1553    OPTION_HARD_FLOAT,
1554    OPTION_SINGLE_FLOAT,
1555    OPTION_DOUBLE_FLOAT,
1556    OPTION_32,
1557    OPTION_CALL_SHARED,
1558    OPTION_CALL_NONPIC,
1559    OPTION_NON_SHARED,
1560    OPTION_XGOT,
1561    OPTION_MABI,
1562    OPTION_N32,
1563    OPTION_64,
1564    OPTION_MDEBUG,
1565    OPTION_NO_MDEBUG,
1566    OPTION_PDR,
1567    OPTION_NO_PDR,
1568    OPTION_MVXWORKS_PIC,
1569    OPTION_NAN,
1570    OPTION_ODD_SPREG,
1571    OPTION_NO_ODD_SPREG,
1572    OPTION_GINV,
1573    OPTION_NO_GINV,
1574    OPTION_LOONGSON_MMI,
1575    OPTION_NO_LOONGSON_MMI,
1576    OPTION_LOONGSON_CAM,
1577    OPTION_NO_LOONGSON_CAM,
1578    OPTION_LOONGSON_EXT,
1579    OPTION_NO_LOONGSON_EXT,
1580    OPTION_LOONGSON_EXT2,
1581    OPTION_NO_LOONGSON_EXT2,
1582    OPTION_FIX_LOONGSON2F_BTB,
1583    OPTION_NO_FIX_LOONGSON2F_BTB,
1584    OPTION_END_OF_ENUM
1585  };
1586
1587struct option md_longopts[] =
1588{
1589  /* Options which specify architecture.  */
1590  {"march", required_argument, NULL, OPTION_MARCH},
1591  {"mtune", required_argument, NULL, OPTION_MTUNE},
1592  {"mips0", no_argument, NULL, OPTION_MIPS1},
1593  {"mips1", no_argument, NULL, OPTION_MIPS1},
1594  {"mips2", no_argument, NULL, OPTION_MIPS2},
1595  {"mips3", no_argument, NULL, OPTION_MIPS3},
1596  {"mips4", no_argument, NULL, OPTION_MIPS4},
1597  {"mips5", no_argument, NULL, OPTION_MIPS5},
1598  {"mips32", no_argument, NULL, OPTION_MIPS32},
1599  {"mips64", no_argument, NULL, OPTION_MIPS64},
1600  {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1601  {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1602  {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1603  {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1604  {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1605  {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1606  {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1607  {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1608
1609  /* Options which specify Application Specific Extensions (ASEs).  */
1610  {"mips16", no_argument, NULL, OPTION_MIPS16},
1611  {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1612  {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1613  {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1614  {"mdmx", no_argument, NULL, OPTION_MDMX},
1615  {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1616  {"mdsp", no_argument, NULL, OPTION_DSP},
1617  {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1618  {"mmt", no_argument, NULL, OPTION_MT},
1619  {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1620  {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1621  {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1622  {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1623  {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1624  {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1625  {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1626  {"meva", no_argument, NULL, OPTION_EVA},
1627  {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1628  {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1629  {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1630  {"mmcu", no_argument, NULL, OPTION_MCU},
1631  {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1632  {"mvirt", no_argument, NULL, OPTION_VIRT},
1633  {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1634  {"mmsa", no_argument, NULL, OPTION_MSA},
1635  {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1636  {"mxpa", no_argument, NULL, OPTION_XPA},
1637  {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1638  {"mmips16e2", no_argument, NULL, OPTION_MIPS16E2},
1639  {"mno-mips16e2", no_argument, NULL, OPTION_NO_MIPS16E2},
1640  {"mcrc", no_argument, NULL, OPTION_CRC},
1641  {"mno-crc", no_argument, NULL, OPTION_NO_CRC},
1642  {"mginv", no_argument, NULL, OPTION_GINV},
1643  {"mno-ginv", no_argument, NULL, OPTION_NO_GINV},
1644  {"mloongson-mmi", no_argument, NULL, OPTION_LOONGSON_MMI},
1645  {"mno-loongson-mmi", no_argument, NULL, OPTION_NO_LOONGSON_MMI},
1646  {"mloongson-cam", no_argument, NULL, OPTION_LOONGSON_CAM},
1647  {"mno-loongson-cam", no_argument, NULL, OPTION_NO_LOONGSON_CAM},
1648  {"mloongson-ext", no_argument, NULL, OPTION_LOONGSON_EXT},
1649  {"mno-loongson-ext", no_argument, NULL, OPTION_NO_LOONGSON_EXT},
1650  {"mloongson-ext2", no_argument, NULL, OPTION_LOONGSON_EXT2},
1651  {"mno-loongson-ext2", no_argument, NULL, OPTION_NO_LOONGSON_EXT2},
1652
1653  /* Old-style architecture options.  Don't add more of these.  */
1654  {"m4650", no_argument, NULL, OPTION_M4650},
1655  {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1656  {"m4010", no_argument, NULL, OPTION_M4010},
1657  {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1658  {"m4100", no_argument, NULL, OPTION_M4100},
1659  {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1660  {"m3900", no_argument, NULL, OPTION_M3900},
1661  {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1662
1663  /* Options which enable bug fixes.  */
1664  {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1665  {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1666  {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1667  {"mfix-loongson3-llsc",   no_argument, NULL, OPTION_FIX_LOONGSON3_LLSC},
1668  {"mno-fix-loongson3-llsc", no_argument, NULL, OPTION_NO_FIX_LOONGSON3_LLSC},
1669  {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1670  {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1671  {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1672  {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1673  {"mfix-loongson2f-btb", no_argument, NULL, OPTION_FIX_LOONGSON2F_BTB},
1674  {"mno-fix-loongson2f-btb", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_BTB},
1675  {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1676  {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1677  {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1678  {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1679  {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1680  {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1681  {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1682  {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1683  {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1684  {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1685  {"mfix-r5900", no_argument, NULL, OPTION_FIX_R5900},
1686  {"mno-fix-r5900", no_argument, NULL, OPTION_NO_FIX_R5900},
1687
1688  /* Miscellaneous options.  */
1689  {"trap", no_argument, NULL, OPTION_TRAP},
1690  {"no-break", no_argument, NULL, OPTION_TRAP},
1691  {"break", no_argument, NULL, OPTION_BREAK},
1692  {"no-trap", no_argument, NULL, OPTION_BREAK},
1693  {"EB", no_argument, NULL, OPTION_EB},
1694  {"EL", no_argument, NULL, OPTION_EL},
1695  {"mfp32", no_argument, NULL, OPTION_FP32},
1696  {"mgp32", no_argument, NULL, OPTION_GP32},
1697  {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1698  {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1699  {"mfp64", no_argument, NULL, OPTION_FP64},
1700  {"mfpxx", no_argument, NULL, OPTION_FPXX},
1701  {"mgp64", no_argument, NULL, OPTION_GP64},
1702  {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1703  {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1704  {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1705  {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1706  {"minsn32", no_argument, NULL, OPTION_INSN32},
1707  {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1708  {"mshared", no_argument, NULL, OPTION_MSHARED},
1709  {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1710  {"msym32", no_argument, NULL, OPTION_MSYM32},
1711  {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1712  {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1713  {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1714  {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1715  {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1716  {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1717  {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1718
1719  /* Strictly speaking this next option is ELF specific,
1720     but we allow it for other ports as well in order to
1721     make testing easier.  */
1722  {"32", no_argument, NULL, OPTION_32},
1723
1724  /* ELF-specific options.  */
1725  {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1726  {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1727  {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1728  {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1729  {"xgot", no_argument, NULL, OPTION_XGOT},
1730  {"mabi", required_argument, NULL, OPTION_MABI},
1731  {"n32", no_argument, NULL, OPTION_N32},
1732  {"64", no_argument, NULL, OPTION_64},
1733  {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1734  {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1735  {"mpdr", no_argument, NULL, OPTION_PDR},
1736  {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1737  {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1738  {"mnan", required_argument, NULL, OPTION_NAN},
1739
1740  {NULL, no_argument, NULL, 0}
1741};
1742size_t md_longopts_size = sizeof (md_longopts);
1743
1744/* Information about either an Application Specific Extension or an
1745   optional architecture feature that, for simplicity, we treat in the
1746   same way as an ASE.  */
1747struct mips_ase
1748{
1749  /* The name of the ASE, used in both the command-line and .set options.  */
1750  const char *name;
1751
1752  /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1753     and 64-bit architectures, the flags here refer to the subset that
1754     is available on both.  */
1755  unsigned int flags;
1756
1757  /* The ASE_* flag used for instructions that are available on 64-bit
1758     architectures but that are not included in FLAGS.  */
1759  unsigned int flags64;
1760
1761  /* The command-line options that turn the ASE on and off.  */
1762  int option_on;
1763  int option_off;
1764
1765  /* The minimum required architecture revisions for MIPS32, MIPS64,
1766     microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1767  int mips32_rev;
1768  int mips64_rev;
1769  int micromips32_rev;
1770  int micromips64_rev;
1771
1772  /* The architecture where the ASE was removed or -1 if the extension has not
1773     been removed.  */
1774  int rem_rev;
1775};
1776
1777/* A table of all supported ASEs.  */
1778static const struct mips_ase mips_ases[] = {
1779  { "dsp", ASE_DSP, ASE_DSP64,
1780    OPTION_DSP, OPTION_NO_DSP,
1781    2, 2, 2, 2,
1782    -1 },
1783
1784  { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1785    OPTION_DSPR2, OPTION_NO_DSPR2,
1786    2, 2, 2, 2,
1787    -1 },
1788
1789  { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1790    OPTION_DSPR3, OPTION_NO_DSPR3,
1791    6, 6, -1, -1,
1792    -1 },
1793
1794  { "eva", ASE_EVA, 0,
1795    OPTION_EVA, OPTION_NO_EVA,
1796     2,  2,  2,  2,
1797    -1 },
1798
1799  { "mcu", ASE_MCU, 0,
1800    OPTION_MCU, OPTION_NO_MCU,
1801     2,  2,  2,  2,
1802    -1 },
1803
1804  /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1805  { "mdmx", ASE_MDMX, 0,
1806    OPTION_MDMX, OPTION_NO_MDMX,
1807    -1, 1, -1, -1,
1808     6 },
1809
1810  /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1811  { "mips3d", ASE_MIPS3D, 0,
1812    OPTION_MIPS3D, OPTION_NO_MIPS3D,
1813    2, 1, -1, -1,
1814    6 },
1815
1816  { "mt", ASE_MT, 0,
1817    OPTION_MT, OPTION_NO_MT,
1818     2,  2, -1, -1,
1819    -1 },
1820
1821  { "smartmips", ASE_SMARTMIPS, 0,
1822    OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1823    1, -1, -1, -1,
1824    6 },
1825
1826  { "virt", ASE_VIRT, ASE_VIRT64,
1827    OPTION_VIRT, OPTION_NO_VIRT,
1828     2,  2,  2,  2,
1829    -1 },
1830
1831  { "msa", ASE_MSA, ASE_MSA64,
1832    OPTION_MSA, OPTION_NO_MSA,
1833     2,  2,  2,  2,
1834    -1 },
1835
1836  { "xpa", ASE_XPA, 0,
1837    OPTION_XPA, OPTION_NO_XPA,
1838    2, 2, 2, 2,
1839    -1 },
1840
1841  { "mips16e2", ASE_MIPS16E2, 0,
1842    OPTION_MIPS16E2, OPTION_NO_MIPS16E2,
1843    2,  2, -1, -1,
1844    6 },
1845
1846  { "crc", ASE_CRC, ASE_CRC64,
1847    OPTION_CRC, OPTION_NO_CRC,
1848    6,  6, -1, -1,
1849    -1 },
1850
1851  { "ginv", ASE_GINV, 0,
1852    OPTION_GINV, OPTION_NO_GINV,
1853    6,  6, 6, 6,
1854    -1 },
1855
1856  { "loongson-mmi", ASE_LOONGSON_MMI, 0,
1857    OPTION_LOONGSON_MMI, OPTION_NO_LOONGSON_MMI,
1858    0, 0, -1, -1,
1859    -1 },
1860
1861  { "loongson-cam", ASE_LOONGSON_CAM, 0,
1862    OPTION_LOONGSON_CAM, OPTION_NO_LOONGSON_CAM,
1863    0, 0, -1, -1,
1864    -1 },
1865
1866  { "loongson-ext", ASE_LOONGSON_EXT, 0,
1867    OPTION_LOONGSON_EXT, OPTION_NO_LOONGSON_EXT,
1868    0, 0, -1, -1,
1869    -1 },
1870
1871  { "loongson-ext2", ASE_LOONGSON_EXT | ASE_LOONGSON_EXT2, 0,
1872    OPTION_LOONGSON_EXT2, OPTION_NO_LOONGSON_EXT2,
1873    0, 0, -1, -1,
1874    -1 },
1875};
1876
1877/* The set of ASEs that require -mfp64.  */
1878#define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1879
1880/* Groups of ASE_* flags that represent different revisions of an ASE.  */
1881static const unsigned int mips_ase_groups[] = {
1882  ASE_DSP | ASE_DSPR2 | ASE_DSPR3,
1883  ASE_LOONGSON_EXT | ASE_LOONGSON_EXT2
1884};
1885
1886/* Pseudo-op table.
1887
1888   The following pseudo-ops from the Kane and Heinrich MIPS book
1889   should be defined here, but are currently unsupported: .alias,
1890   .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1891
1892   The following pseudo-ops from the Kane and Heinrich MIPS book are
1893   specific to the type of debugging information being generated, and
1894   should be defined by the object format: .aent, .begin, .bend,
1895   .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1896   .vreg.
1897
1898   The following pseudo-ops from the Kane and Heinrich MIPS book are
1899   not MIPS CPU specific, but are also not specific to the object file
1900   format.  This file is probably the best place to define them, but
1901   they are not currently supported: .asm0, .endr, .lab, .struct.  */
1902
1903static const pseudo_typeS mips_pseudo_table[] =
1904{
1905  /* MIPS specific pseudo-ops.  */
1906  {"option", s_option, 0},
1907  {"set", s_mipsset, 0},
1908  {"rdata", s_change_sec, 'r'},
1909  {"sdata", s_change_sec, 's'},
1910  {"livereg", s_ignore, 0},
1911  {"abicalls", s_abicalls, 0},
1912  {"cpload", s_cpload, 0},
1913  {"cpsetup", s_cpsetup, 0},
1914  {"cplocal", s_cplocal, 0},
1915  {"cprestore", s_cprestore, 0},
1916  {"cpreturn", s_cpreturn, 0},
1917  {"dtprelword", s_dtprelword, 0},
1918  {"dtpreldword", s_dtpreldword, 0},
1919  {"tprelword", s_tprelword, 0},
1920  {"tpreldword", s_tpreldword, 0},
1921  {"gpvalue", s_gpvalue, 0},
1922  {"gpword", s_gpword, 0},
1923  {"gpdword", s_gpdword, 0},
1924  {"ehword", s_ehword, 0},
1925  {"cpadd", s_cpadd, 0},
1926  {"insn", s_insn, 0},
1927  {"nan", s_nan, 0},
1928  {"module", s_module, 0},
1929
1930  /* Relatively generic pseudo-ops that happen to be used on MIPS
1931     chips.  */
1932  {"asciiz", stringer, 8 + 1},
1933  {"bss", s_change_sec, 'b'},
1934  {"err", s_err, 0},
1935  {"half", s_cons, 1},
1936  {"dword", s_cons, 3},
1937  {"weakext", s_mips_weakext, 0},
1938  {"origin", s_org, 0},
1939  {"repeat", s_rept, 0},
1940
1941  /* For MIPS this is non-standard, but we define it for consistency.  */
1942  {"sbss", s_change_sec, 'B'},
1943
1944  /* These pseudo-ops are defined in read.c, but must be overridden
1945     here for one reason or another.  */
1946  {"align", s_align, 0},
1947  {"byte", s_cons, 0},
1948  {"data", s_change_sec, 'd'},
1949  {"double", s_float_cons, 'd'},
1950  {"float", s_float_cons, 'f'},
1951  {"globl", s_mips_globl, 0},
1952  {"global", s_mips_globl, 0},
1953  {"hword", s_cons, 1},
1954  {"int", s_cons, 2},
1955  {"long", s_cons, 2},
1956  {"octa", s_cons, 4},
1957  {"quad", s_cons, 3},
1958  {"section", s_change_section, 0},
1959  {"short", s_cons, 1},
1960  {"single", s_float_cons, 'f'},
1961  {"stabd", s_mips_stab, 'd'},
1962  {"stabn", s_mips_stab, 'n'},
1963  {"stabs", s_mips_stab, 's'},
1964  {"text", s_change_sec, 't'},
1965  {"word", s_cons, 2},
1966
1967  { "extern", ecoff_directive_extern, 0},
1968
1969  { NULL, NULL, 0 },
1970};
1971
1972static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1973{
1974  /* These pseudo-ops should be defined by the object file format.
1975     However, a.out doesn't support them, so we have versions here.  */
1976  {"aent", s_mips_ent, 1},
1977  {"bgnb", s_ignore, 0},
1978  {"end", s_mips_end, 0},
1979  {"endb", s_ignore, 0},
1980  {"ent", s_mips_ent, 0},
1981  {"file", s_mips_file, 0},
1982  {"fmask", s_mips_mask, 'F'},
1983  {"frame", s_mips_frame, 0},
1984  {"loc", s_mips_loc, 0},
1985  {"mask", s_mips_mask, 'R'},
1986  {"verstamp", s_ignore, 0},
1987  { NULL, NULL, 0 },
1988};
1989
1990/* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1991   purpose of the `.dc.a' internal pseudo-op.  */
1992
1993int
1994mips_address_bytes (void)
1995{
1996  file_mips_check_options ();
1997  return HAVE_64BIT_ADDRESSES ? 8 : 4;
1998}
1999
2000extern void pop_insert (const pseudo_typeS *);
2001
2002void
2003mips_pop_insert (void)
2004{
2005  pop_insert (mips_pseudo_table);
2006  if (! ECOFF_DEBUGGING)
2007    pop_insert (mips_nonecoff_pseudo_table);
2008}
2009
2010/* Symbols labelling the current insn.  */
2011
2012struct insn_label_list
2013{
2014  struct insn_label_list *next;
2015  symbolS *label;
2016};
2017
2018static struct insn_label_list *free_insn_labels;
2019#define label_list tc_segment_info_data.labels
2020
2021static void mips_clear_insn_labels (void);
2022static void mips_mark_labels (void);
2023static void mips_compressed_mark_labels (void);
2024
2025static inline void
2026mips_clear_insn_labels (void)
2027{
2028  struct insn_label_list **pl;
2029  segment_info_type *si;
2030
2031  if (now_seg)
2032    {
2033      for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
2034	;
2035
2036      si = seg_info (now_seg);
2037      *pl = si->label_list;
2038      si->label_list = NULL;
2039    }
2040}
2041
2042/* Mark instruction labels in MIPS16/microMIPS mode.  */
2043
2044static inline void
2045mips_mark_labels (void)
2046{
2047  if (HAVE_CODE_COMPRESSION)
2048    mips_compressed_mark_labels ();
2049}
2050
2051static char *expr_end;
2052
2053/* An expression in a macro instruction.  This is set by mips_ip and
2054   mips16_ip and when populated is always an O_constant.  */
2055
2056static expressionS imm_expr;
2057
2058/* The relocatable field in an instruction and the relocs associated
2059   with it.  These variables are used for instructions like LUI and
2060   JAL as well as true offsets.  They are also used for address
2061   operands in macros.  */
2062
2063static expressionS offset_expr;
2064static bfd_reloc_code_real_type offset_reloc[3]
2065  = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2066
2067/* This is set to the resulting size of the instruction to be produced
2068   by mips16_ip if an explicit extension is used or by mips_ip if an
2069   explicit size is supplied.  */
2070
2071static unsigned int forced_insn_length;
2072
2073/* True if we are assembling an instruction.  All dot symbols defined during
2074   this time should be treated as code labels.  */
2075
2076static bool mips_assembling_insn;
2077
2078/* The pdr segment for per procedure frame/regmask info.  Not used for
2079   ECOFF debugging.  */
2080
2081static segT pdr_seg;
2082
2083/* The default target format to use.  */
2084
2085#if defined (TE_FreeBSD)
2086#define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
2087#elif defined (TE_TMIPS)
2088#define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
2089#else
2090#define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
2091#endif
2092
2093const char *
2094mips_target_format (void)
2095{
2096  switch (OUTPUT_FLAVOR)
2097    {
2098    case bfd_target_elf_flavour:
2099#ifdef TE_VXWORKS
2100      if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
2101	return (target_big_endian
2102		? "elf32-bigmips-vxworks"
2103		: "elf32-littlemips-vxworks");
2104#endif
2105      return (target_big_endian
2106	      ? (HAVE_64BIT_OBJECTS
2107		 ? ELF_TARGET ("elf64-", "big")
2108		 : (HAVE_NEWABI
2109		    ? ELF_TARGET ("elf32-n", "big")
2110		    : ELF_TARGET ("elf32-", "big")))
2111	      : (HAVE_64BIT_OBJECTS
2112		 ? ELF_TARGET ("elf64-", "little")
2113		 : (HAVE_NEWABI
2114		    ? ELF_TARGET ("elf32-n", "little")
2115		    : ELF_TARGET ("elf32-", "little"))));
2116    default:
2117      abort ();
2118      return NULL;
2119    }
2120}
2121
2122/* Return the ISA revision that is currently in use, or 0 if we are
2123   generating code for MIPS V or below.  */
2124
2125static int
2126mips_isa_rev (void)
2127{
2128  if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2129    return 2;
2130
2131  if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2132    return 3;
2133
2134  if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2135    return 5;
2136
2137  if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2138    return 6;
2139
2140  /* microMIPS implies revision 2 or above.  */
2141  if (mips_opts.micromips)
2142    return 2;
2143
2144  if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2145    return 1;
2146
2147  return 0;
2148}
2149
2150/* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2151
2152static unsigned int
2153mips_ase_mask (unsigned int flags)
2154{
2155  unsigned int i;
2156
2157  for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2158    if (flags & mips_ase_groups[i])
2159      flags |= mips_ase_groups[i];
2160  return flags;
2161}
2162
2163/* Check whether the current ISA supports ASE.  Issue a warning if
2164   appropriate.  */
2165
2166static void
2167mips_check_isa_supports_ase (const struct mips_ase *ase)
2168{
2169  const char *base;
2170  int min_rev, size;
2171  static unsigned int warned_isa;
2172  static unsigned int warned_fp32;
2173
2174  if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2175    min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2176  else
2177    min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2178  if ((min_rev < 0 || mips_isa_rev () < min_rev)
2179      && (warned_isa & ase->flags) != ase->flags)
2180    {
2181      warned_isa |= ase->flags;
2182      base = mips_opts.micromips ? "microMIPS" : "MIPS";
2183      size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2184      if (min_rev < 0)
2185	as_warn (_("the %d-bit %s architecture does not support the"
2186		   " `%s' extension"), size, base, ase->name);
2187      else
2188	as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2189		 ase->name, base, size, min_rev);
2190    }
2191  else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2192	   && (warned_isa & ase->flags) != ase->flags)
2193    {
2194      warned_isa |= ase->flags;
2195      base = mips_opts.micromips ? "microMIPS" : "MIPS";
2196      size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2197      as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2198	       ase->name, base, size, ase->rem_rev);
2199    }
2200
2201  if ((ase->flags & FP64_ASES)
2202      && mips_opts.fp != 64
2203      && (warned_fp32 & ase->flags) != ase->flags)
2204    {
2205      warned_fp32 |= ase->flags;
2206      as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2207    }
2208}
2209
2210/* Check all enabled ASEs to see whether they are supported by the
2211   chosen architecture.  */
2212
2213static void
2214mips_check_isa_supports_ases (void)
2215{
2216  unsigned int i, mask;
2217
2218  for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2219    {
2220      mask = mips_ase_mask (mips_ases[i].flags);
2221      if ((mips_opts.ase & mask) == mips_ases[i].flags)
2222	mips_check_isa_supports_ase (&mips_ases[i]);
2223    }
2224}
2225
2226/* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2227   that were affected.  */
2228
2229static unsigned int
2230mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2231	      bool enabled_p)
2232{
2233  unsigned int mask;
2234
2235  mask = mips_ase_mask (ase->flags);
2236  opts->ase &= ~mask;
2237
2238  /* Clear combination ASE flags, which need to be recalculated based on
2239     updated regular ASE settings.  */
2240  opts->ase &= ~(ASE_MIPS16E2_MT | ASE_XPA_VIRT | ASE_EVA_R6);
2241
2242  if (enabled_p)
2243    opts->ase |= ase->flags;
2244
2245  /* The Virtualization ASE has eXtended Physical Addressing (XPA)
2246     instructions which are only valid when both ASEs are enabled.
2247     This sets the ASE_XPA_VIRT flag when both ASEs are present.  */
2248  if ((opts->ase & (ASE_XPA | ASE_VIRT)) == (ASE_XPA | ASE_VIRT))
2249    {
2250      opts->ase |= ASE_XPA_VIRT;
2251      mask |= ASE_XPA_VIRT;
2252    }
2253  if ((opts->ase & (ASE_MIPS16E2 | ASE_MT)) == (ASE_MIPS16E2 | ASE_MT))
2254    {
2255      opts->ase |= ASE_MIPS16E2_MT;
2256      mask |= ASE_MIPS16E2_MT;
2257    }
2258
2259  /* The EVA Extension has instructions which are only valid when the R6 ISA
2260     is enabled.  This sets the ASE_EVA_R6 flag when both EVA and R6 ISA are
2261     present.  */
2262  if (((opts->ase & ASE_EVA) != 0) && ISA_IS_R6 (opts->isa))
2263    {
2264      opts->ase |= ASE_EVA_R6;
2265      mask |= ASE_EVA_R6;
2266    }
2267
2268  return mask;
2269}
2270
2271/* Return the ASE called NAME, or null if none.  */
2272
2273static const struct mips_ase *
2274mips_lookup_ase (const char *name)
2275{
2276  unsigned int i;
2277
2278  for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2279    if (strcmp (name, mips_ases[i].name) == 0)
2280      return &mips_ases[i];
2281  return NULL;
2282}
2283
2284/* Return the length of a microMIPS instruction in bytes.  If bits of
2285   the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2286   otherwise it is a 32-bit instruction.  */
2287
2288static inline unsigned int
2289micromips_insn_length (const struct mips_opcode *mo)
2290{
2291  return mips_opcode_32bit_p (mo) ? 4 : 2;
2292}
2293
2294/* Return the length of MIPS16 instruction OPCODE.  */
2295
2296static inline unsigned int
2297mips16_opcode_length (unsigned long opcode)
2298{
2299  return (opcode >> 16) == 0 ? 2 : 4;
2300}
2301
2302/* Return the length of instruction INSN.  */
2303
2304static inline unsigned int
2305insn_length (const struct mips_cl_insn *insn)
2306{
2307  if (mips_opts.micromips)
2308    return micromips_insn_length (insn->insn_mo);
2309  else if (mips_opts.mips16)
2310    return mips16_opcode_length (insn->insn_opcode);
2311  else
2312    return 4;
2313}
2314
2315/* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2316
2317static void
2318create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2319{
2320  size_t i;
2321
2322  insn->insn_mo = mo;
2323  insn->insn_opcode = mo->match;
2324  insn->frag = NULL;
2325  insn->where = 0;
2326  for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2327    insn->fixp[i] = NULL;
2328  insn->fixed_p = (mips_opts.noreorder > 0);
2329  insn->noreorder_p = (mips_opts.noreorder > 0);
2330  insn->mips16_absolute_jump_p = 0;
2331  insn->complete_p = 0;
2332  insn->cleared_p = 0;
2333}
2334
2335/* Get a list of all the operands in INSN.  */
2336
2337static const struct mips_operand_array *
2338insn_operands (const struct mips_cl_insn *insn)
2339{
2340  if (insn->insn_mo >= &mips_opcodes[0]
2341      && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2342    return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2343
2344  if (insn->insn_mo >= &mips16_opcodes[0]
2345      && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2346    return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2347
2348  if (insn->insn_mo >= &micromips_opcodes[0]
2349      && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2350    return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2351
2352  abort ();
2353}
2354
2355/* Get a description of operand OPNO of INSN.  */
2356
2357static const struct mips_operand *
2358insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2359{
2360  const struct mips_operand_array *operands;
2361
2362  operands = insn_operands (insn);
2363  if (opno >= MAX_OPERANDS || !operands->operand[opno])
2364    abort ();
2365  return operands->operand[opno];
2366}
2367
2368/* Install UVAL as the value of OPERAND in INSN.  */
2369
2370static inline void
2371insn_insert_operand (struct mips_cl_insn *insn,
2372		     const struct mips_operand *operand, unsigned int uval)
2373{
2374  if (mips_opts.mips16
2375      && operand->type == OP_INT && operand->lsb == 0
2376      && mips_opcode_32bit_p (insn->insn_mo))
2377    insn->insn_opcode |= mips16_immed_extend (uval, operand->size);
2378  else
2379    insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2380}
2381
2382/* Extract the value of OPERAND from INSN.  */
2383
2384static inline unsigned
2385insn_extract_operand (const struct mips_cl_insn *insn,
2386		      const struct mips_operand *operand)
2387{
2388  return mips_extract_operand (operand, insn->insn_opcode);
2389}
2390
2391/* Record the current MIPS16/microMIPS mode in now_seg.  */
2392
2393static void
2394mips_record_compressed_mode (void)
2395{
2396  segment_info_type *si;
2397
2398  si = seg_info (now_seg);
2399  if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2400    si->tc_segment_info_data.mips16 = mips_opts.mips16;
2401  if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2402    si->tc_segment_info_data.micromips = mips_opts.micromips;
2403}
2404
2405/* Read a standard MIPS instruction from BUF.  */
2406
2407static unsigned long
2408read_insn (char *buf)
2409{
2410  if (target_big_endian)
2411    return bfd_getb32 ((bfd_byte *) buf);
2412  else
2413    return bfd_getl32 ((bfd_byte *) buf);
2414}
2415
2416/* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2417   the next byte.  */
2418
2419static char *
2420write_insn (char *buf, unsigned int insn)
2421{
2422  md_number_to_chars (buf, insn, 4);
2423  return buf + 4;
2424}
2425
2426/* Read a microMIPS or MIPS16 opcode from BUF, given that it
2427   has length LENGTH.  */
2428
2429static unsigned long
2430read_compressed_insn (char *buf, unsigned int length)
2431{
2432  unsigned long insn;
2433  unsigned int i;
2434
2435  insn = 0;
2436  for (i = 0; i < length; i += 2)
2437    {
2438      insn <<= 16;
2439      if (target_big_endian)
2440	insn |= bfd_getb16 ((char *) buf);
2441      else
2442	insn |= bfd_getl16 ((char *) buf);
2443      buf += 2;
2444    }
2445  return insn;
2446}
2447
2448/* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2449   instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2450
2451static char *
2452write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2453{
2454  unsigned int i;
2455
2456  for (i = 0; i < length; i += 2)
2457    md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2458  return buf + length;
2459}
2460
2461/* Install INSN at the location specified by its "frag" and "where" fields.  */
2462
2463static void
2464install_insn (const struct mips_cl_insn *insn)
2465{
2466  char *f = insn->frag->fr_literal + insn->where;
2467  if (HAVE_CODE_COMPRESSION)
2468    write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2469  else
2470    write_insn (f, insn->insn_opcode);
2471  mips_record_compressed_mode ();
2472}
2473
2474/* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2475   and install the opcode in the new location.  */
2476
2477static void
2478move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2479{
2480  size_t i;
2481
2482  insn->frag = frag;
2483  insn->where = where;
2484  for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2485    if (insn->fixp[i] != NULL)
2486      {
2487	insn->fixp[i]->fx_frag = frag;
2488	insn->fixp[i]->fx_where = where;
2489      }
2490  install_insn (insn);
2491}
2492
2493/* Add INSN to the end of the output.  */
2494
2495static void
2496add_fixed_insn (struct mips_cl_insn *insn)
2497{
2498  char *f = frag_more (insn_length (insn));
2499  move_insn (insn, frag_now, f - frag_now->fr_literal);
2500}
2501
2502/* Start a variant frag and move INSN to the start of the variant part,
2503   marking it as fixed.  The other arguments are as for frag_var.  */
2504
2505static void
2506add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2507		  relax_substateT subtype, symbolS *symbol, offsetT offset)
2508{
2509  frag_grow (max_chars);
2510  move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2511  insn->fixed_p = 1;
2512  frag_var (rs_machine_dependent, max_chars, var,
2513	    subtype, symbol, offset, NULL);
2514}
2515
2516/* Insert N copies of INSN into the history buffer, starting at
2517   position FIRST.  Neither FIRST nor N need to be clipped.  */
2518
2519static void
2520insert_into_history (unsigned int first, unsigned int n,
2521		     const struct mips_cl_insn *insn)
2522{
2523  if (mips_relax.sequence != 2)
2524    {
2525      unsigned int i;
2526
2527      for (i = ARRAY_SIZE (history); i-- > first;)
2528	if (i >= first + n)
2529	  history[i] = history[i - n];
2530	else
2531	  history[i] = *insn;
2532    }
2533}
2534
2535/* Clear the error in insn_error.  */
2536
2537static void
2538clear_insn_error (void)
2539{
2540  memset (&insn_error, 0, sizeof (insn_error));
2541}
2542
2543/* Possibly record error message MSG for the current instruction.
2544   If the error is about a particular argument, ARGNUM is the 1-based
2545   number of that argument, otherwise it is 0.  FORMAT is the format
2546   of MSG.  Return true if MSG was used, false if the current message
2547   was kept.  */
2548
2549static bool
2550set_insn_error_format (int argnum, enum mips_insn_error_format format,
2551		       const char *msg)
2552{
2553  if (argnum == 0)
2554    {
2555      /* Give priority to errors against specific arguments, and to
2556	 the first whole-instruction message.  */
2557      if (insn_error.msg)
2558	return false;
2559    }
2560  else
2561    {
2562      /* Keep insn_error if it is against a later argument.  */
2563      if (argnum < insn_error.min_argnum)
2564	return false;
2565
2566      /* If both errors are against the same argument but are different,
2567	 give up on reporting a specific error for this argument.
2568	 See the comment about mips_insn_error for details.  */
2569      if (argnum == insn_error.min_argnum
2570	  && insn_error.msg
2571	  && strcmp (insn_error.msg, msg) != 0)
2572	{
2573	  insn_error.msg = 0;
2574	  insn_error.min_argnum += 1;
2575	  return false;
2576	}
2577    }
2578  insn_error.min_argnum = argnum;
2579  insn_error.format = format;
2580  insn_error.msg = msg;
2581  return true;
2582}
2583
2584/* Record an instruction error with no % format fields.  ARGNUM and MSG are
2585   as for set_insn_error_format.  */
2586
2587static void
2588set_insn_error (int argnum, const char *msg)
2589{
2590  set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2591}
2592
2593/* Record an instruction error with one %d field I.  ARGNUM and MSG are
2594   as for set_insn_error_format.  */
2595
2596static void
2597set_insn_error_i (int argnum, const char *msg, int i)
2598{
2599  if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2600    insn_error.u.i = i;
2601}
2602
2603/* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2604   are as for set_insn_error_format.  */
2605
2606static void
2607set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2608{
2609  if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2610    {
2611      insn_error.u.ss[0] = s1;
2612      insn_error.u.ss[1] = s2;
2613    }
2614}
2615
2616/* Report the error in insn_error, which is against assembly code STR.  */
2617
2618static void
2619report_insn_error (const char *str)
2620{
2621  const char *msg = concat (insn_error.msg, " `%s'", NULL);
2622
2623  switch (insn_error.format)
2624    {
2625    case ERR_FMT_PLAIN:
2626      as_bad (msg, str);
2627      break;
2628
2629    case ERR_FMT_I:
2630      as_bad (msg, insn_error.u.i, str);
2631      break;
2632
2633    case ERR_FMT_SS:
2634      as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2635      break;
2636    }
2637
2638  free ((char *) msg);
2639}
2640
2641/* Initialize vr4120_conflicts.  There is a bit of duplication here:
2642   the idea is to make it obvious at a glance that each errata is
2643   included.  */
2644
2645static void
2646init_vr4120_conflicts (void)
2647{
2648#define CONFLICT(FIRST, SECOND) \
2649    vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2650
2651  /* Errata 21 - [D]DIV[U] after [D]MACC */
2652  CONFLICT (MACC, DIV);
2653  CONFLICT (DMACC, DIV);
2654
2655  /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2656  CONFLICT (DMULT, DMULT);
2657  CONFLICT (DMULT, DMACC);
2658  CONFLICT (DMACC, DMULT);
2659  CONFLICT (DMACC, DMACC);
2660
2661  /* Errata 24 - MT{LO,HI} after [D]MACC */
2662  CONFLICT (MACC, MTHILO);
2663  CONFLICT (DMACC, MTHILO);
2664
2665  /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2666     instruction is executed immediately after a MACC or DMACC
2667     instruction, the result of [either instruction] is incorrect."  */
2668  CONFLICT (MACC, MULT);
2669  CONFLICT (MACC, DMULT);
2670  CONFLICT (DMACC, MULT);
2671  CONFLICT (DMACC, DMULT);
2672
2673  /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2674     executed immediately after a DMULT, DMULTU, DIV, DIVU,
2675     DDIV or DDIVU instruction, the result of the MACC or
2676     DMACC instruction is incorrect.".  */
2677  CONFLICT (DMULT, MACC);
2678  CONFLICT (DMULT, DMACC);
2679  CONFLICT (DIV, MACC);
2680  CONFLICT (DIV, DMACC);
2681
2682#undef CONFLICT
2683}
2684
2685struct regname {
2686  const char *name;
2687  unsigned int num;
2688};
2689
2690#define RNUM_MASK	0x00000ff
2691#define RTYPE_MASK	0x0ffff00
2692#define RTYPE_NUM	0x0000100
2693#define RTYPE_FPU	0x0000200
2694#define RTYPE_FCC	0x0000400
2695#define RTYPE_VEC	0x0000800
2696#define RTYPE_GP	0x0001000
2697#define RTYPE_CP0	0x0002000
2698#define RTYPE_PC	0x0004000
2699#define RTYPE_ACC	0x0008000
2700#define RTYPE_CCC	0x0010000
2701#define RTYPE_VI	0x0020000
2702#define RTYPE_VF	0x0040000
2703#define RTYPE_R5900_I	0x0080000
2704#define RTYPE_R5900_Q	0x0100000
2705#define RTYPE_R5900_R	0x0200000
2706#define RTYPE_R5900_ACC	0x0400000
2707#define RTYPE_MSA	0x0800000
2708#define RWARN		0x8000000
2709
2710#define GENERIC_REGISTER_NUMBERS \
2711    {"$0",	RTYPE_NUM | 0},  \
2712    {"$1",	RTYPE_NUM | 1},  \
2713    {"$2",	RTYPE_NUM | 2},  \
2714    {"$3",	RTYPE_NUM | 3},  \
2715    {"$4",	RTYPE_NUM | 4},  \
2716    {"$5",	RTYPE_NUM | 5},  \
2717    {"$6",	RTYPE_NUM | 6},  \
2718    {"$7",	RTYPE_NUM | 7},  \
2719    {"$8",	RTYPE_NUM | 8},  \
2720    {"$9",	RTYPE_NUM | 9},  \
2721    {"$10",	RTYPE_NUM | 10}, \
2722    {"$11",	RTYPE_NUM | 11}, \
2723    {"$12",	RTYPE_NUM | 12}, \
2724    {"$13",	RTYPE_NUM | 13}, \
2725    {"$14",	RTYPE_NUM | 14}, \
2726    {"$15",	RTYPE_NUM | 15}, \
2727    {"$16",	RTYPE_NUM | 16}, \
2728    {"$17",	RTYPE_NUM | 17}, \
2729    {"$18",	RTYPE_NUM | 18}, \
2730    {"$19",	RTYPE_NUM | 19}, \
2731    {"$20",	RTYPE_NUM | 20}, \
2732    {"$21",	RTYPE_NUM | 21}, \
2733    {"$22",	RTYPE_NUM | 22}, \
2734    {"$23",	RTYPE_NUM | 23}, \
2735    {"$24",	RTYPE_NUM | 24}, \
2736    {"$25",	RTYPE_NUM | 25}, \
2737    {"$26",	RTYPE_NUM | 26}, \
2738    {"$27",	RTYPE_NUM | 27}, \
2739    {"$28",	RTYPE_NUM | 28}, \
2740    {"$29",	RTYPE_NUM | 29}, \
2741    {"$30",	RTYPE_NUM | 30}, \
2742    {"$31",	RTYPE_NUM | 31}
2743
2744#define FPU_REGISTER_NAMES       \
2745    {"$f0",	RTYPE_FPU | 0},  \
2746    {"$f1",	RTYPE_FPU | 1},  \
2747    {"$f2",	RTYPE_FPU | 2},  \
2748    {"$f3",	RTYPE_FPU | 3},  \
2749    {"$f4",	RTYPE_FPU | 4},  \
2750    {"$f5",	RTYPE_FPU | 5},  \
2751    {"$f6",	RTYPE_FPU | 6},  \
2752    {"$f7",	RTYPE_FPU | 7},  \
2753    {"$f8",	RTYPE_FPU | 8},  \
2754    {"$f9",	RTYPE_FPU | 9},  \
2755    {"$f10",	RTYPE_FPU | 10}, \
2756    {"$f11",	RTYPE_FPU | 11}, \
2757    {"$f12",	RTYPE_FPU | 12}, \
2758    {"$f13",	RTYPE_FPU | 13}, \
2759    {"$f14",	RTYPE_FPU | 14}, \
2760    {"$f15",	RTYPE_FPU | 15}, \
2761    {"$f16",	RTYPE_FPU | 16}, \
2762    {"$f17",	RTYPE_FPU | 17}, \
2763    {"$f18",	RTYPE_FPU | 18}, \
2764    {"$f19",	RTYPE_FPU | 19}, \
2765    {"$f20",	RTYPE_FPU | 20}, \
2766    {"$f21",	RTYPE_FPU | 21}, \
2767    {"$f22",	RTYPE_FPU | 22}, \
2768    {"$f23",	RTYPE_FPU | 23}, \
2769    {"$f24",	RTYPE_FPU | 24}, \
2770    {"$f25",	RTYPE_FPU | 25}, \
2771    {"$f26",	RTYPE_FPU | 26}, \
2772    {"$f27",	RTYPE_FPU | 27}, \
2773    {"$f28",	RTYPE_FPU | 28}, \
2774    {"$f29",	RTYPE_FPU | 29}, \
2775    {"$f30",	RTYPE_FPU | 30}, \
2776    {"$f31",	RTYPE_FPU | 31}
2777
2778#define FPU_CONDITION_CODE_NAMES \
2779    {"$fcc0",	RTYPE_FCC | 0},  \
2780    {"$fcc1",	RTYPE_FCC | 1},  \
2781    {"$fcc2",	RTYPE_FCC | 2},  \
2782    {"$fcc3",	RTYPE_FCC | 3},  \
2783    {"$fcc4",	RTYPE_FCC | 4},  \
2784    {"$fcc5",	RTYPE_FCC | 5},  \
2785    {"$fcc6",	RTYPE_FCC | 6},  \
2786    {"$fcc7",	RTYPE_FCC | 7}
2787
2788#define COPROC_CONDITION_CODE_NAMES         \
2789    {"$cc0",	RTYPE_FCC | RTYPE_CCC | 0}, \
2790    {"$cc1",	RTYPE_FCC | RTYPE_CCC | 1}, \
2791    {"$cc2",	RTYPE_FCC | RTYPE_CCC | 2}, \
2792    {"$cc3",	RTYPE_FCC | RTYPE_CCC | 3}, \
2793    {"$cc4",	RTYPE_FCC | RTYPE_CCC | 4}, \
2794    {"$cc5",	RTYPE_FCC | RTYPE_CCC | 5}, \
2795    {"$cc6",	RTYPE_FCC | RTYPE_CCC | 6}, \
2796    {"$cc7",	RTYPE_FCC | RTYPE_CCC | 7}
2797
2798#define N32N64_SYMBOLIC_REGISTER_NAMES \
2799    {"$a4",	RTYPE_GP | 8},  \
2800    {"$a5",	RTYPE_GP | 9},  \
2801    {"$a6",	RTYPE_GP | 10}, \
2802    {"$a7",	RTYPE_GP | 11}, \
2803    {"$ta0",	RTYPE_GP | 8},  /* alias for $a4 */ \
2804    {"$ta1",	RTYPE_GP | 9},  /* alias for $a5 */ \
2805    {"$ta2",	RTYPE_GP | 10}, /* alias for $a6 */ \
2806    {"$ta3",	RTYPE_GP | 11}, /* alias for $a7 */ \
2807    {"$t0",	RTYPE_GP | 12}, \
2808    {"$t1",	RTYPE_GP | 13}, \
2809    {"$t2",	RTYPE_GP | 14}, \
2810    {"$t3",	RTYPE_GP | 15}
2811
2812#define O32_SYMBOLIC_REGISTER_NAMES \
2813    {"$t0",	RTYPE_GP | 8},  \
2814    {"$t1",	RTYPE_GP | 9},  \
2815    {"$t2",	RTYPE_GP | 10}, \
2816    {"$t3",	RTYPE_GP | 11}, \
2817    {"$t4",	RTYPE_GP | 12}, \
2818    {"$t5",	RTYPE_GP | 13}, \
2819    {"$t6",	RTYPE_GP | 14}, \
2820    {"$t7",	RTYPE_GP | 15}, \
2821    {"$ta0",	RTYPE_GP | 12}, /* alias for $t4 */ \
2822    {"$ta1",	RTYPE_GP | 13}, /* alias for $t5 */ \
2823    {"$ta2",	RTYPE_GP | 14}, /* alias for $t6 */ \
2824    {"$ta3",	RTYPE_GP | 15}  /* alias for $t7 */
2825
2826/* Remaining symbolic register names.  */
2827#define SYMBOLIC_REGISTER_NAMES \
2828    {"$zero",	RTYPE_GP | 0},  \
2829    {"$at",	RTYPE_GP | 1},  \
2830    {"$AT",	RTYPE_GP | 1},  \
2831    {"$v0",	RTYPE_GP | 2},  \
2832    {"$v1",	RTYPE_GP | 3},  \
2833    {"$a0",	RTYPE_GP | 4},  \
2834    {"$a1",	RTYPE_GP | 5},  \
2835    {"$a2",	RTYPE_GP | 6},  \
2836    {"$a3",	RTYPE_GP | 7},  \
2837    {"$s0",	RTYPE_GP | 16}, \
2838    {"$s1",	RTYPE_GP | 17}, \
2839    {"$s2",	RTYPE_GP | 18}, \
2840    {"$s3",	RTYPE_GP | 19}, \
2841    {"$s4",	RTYPE_GP | 20}, \
2842    {"$s5",	RTYPE_GP | 21}, \
2843    {"$s6",	RTYPE_GP | 22}, \
2844    {"$s7",	RTYPE_GP | 23}, \
2845    {"$t8",	RTYPE_GP | 24}, \
2846    {"$t9",	RTYPE_GP | 25}, \
2847    {"$k0",	RTYPE_GP | 26}, \
2848    {"$kt0",	RTYPE_GP | 26}, \
2849    {"$k1",	RTYPE_GP | 27}, \
2850    {"$kt1",	RTYPE_GP | 27}, \
2851    {"$gp",	RTYPE_GP | 28}, \
2852    {"$sp",	RTYPE_GP | 29}, \
2853    {"$s8",	RTYPE_GP | 30}, \
2854    {"$fp",	RTYPE_GP | 30}, \
2855    {"$ra",	RTYPE_GP | 31}
2856
2857#define MIPS16_SPECIAL_REGISTER_NAMES \
2858    {"$pc",	RTYPE_PC | 0}
2859
2860#define MDMX_VECTOR_REGISTER_NAMES \
2861    /* {"$v0",	RTYPE_VEC | 0},  Clash with REG 2 above.  */ \
2862    /* {"$v1",	RTYPE_VEC | 1},  Clash with REG 3 above.  */ \
2863    {"$v2",	RTYPE_VEC | 2},  \
2864    {"$v3",	RTYPE_VEC | 3},  \
2865    {"$v4",	RTYPE_VEC | 4},  \
2866    {"$v5",	RTYPE_VEC | 5},  \
2867    {"$v6",	RTYPE_VEC | 6},  \
2868    {"$v7",	RTYPE_VEC | 7},  \
2869    {"$v8",	RTYPE_VEC | 8},  \
2870    {"$v9",	RTYPE_VEC | 9},  \
2871    {"$v10",	RTYPE_VEC | 10}, \
2872    {"$v11",	RTYPE_VEC | 11}, \
2873    {"$v12",	RTYPE_VEC | 12}, \
2874    {"$v13",	RTYPE_VEC | 13}, \
2875    {"$v14",	RTYPE_VEC | 14}, \
2876    {"$v15",	RTYPE_VEC | 15}, \
2877    {"$v16",	RTYPE_VEC | 16}, \
2878    {"$v17",	RTYPE_VEC | 17}, \
2879    {"$v18",	RTYPE_VEC | 18}, \
2880    {"$v19",	RTYPE_VEC | 19}, \
2881    {"$v20",	RTYPE_VEC | 20}, \
2882    {"$v21",	RTYPE_VEC | 21}, \
2883    {"$v22",	RTYPE_VEC | 22}, \
2884    {"$v23",	RTYPE_VEC | 23}, \
2885    {"$v24",	RTYPE_VEC | 24}, \
2886    {"$v25",	RTYPE_VEC | 25}, \
2887    {"$v26",	RTYPE_VEC | 26}, \
2888    {"$v27",	RTYPE_VEC | 27}, \
2889    {"$v28",	RTYPE_VEC | 28}, \
2890    {"$v29",	RTYPE_VEC | 29}, \
2891    {"$v30",	RTYPE_VEC | 30}, \
2892    {"$v31",	RTYPE_VEC | 31}
2893
2894#define R5900_I_NAMES \
2895    {"$I",	RTYPE_R5900_I | 0}
2896
2897#define R5900_Q_NAMES \
2898    {"$Q",	RTYPE_R5900_Q | 0}
2899
2900#define R5900_R_NAMES \
2901    {"$R",	RTYPE_R5900_R | 0}
2902
2903#define R5900_ACC_NAMES \
2904    {"$ACC",	RTYPE_R5900_ACC | 0 }
2905
2906#define MIPS_DSP_ACCUMULATOR_NAMES \
2907    {"$ac0",	RTYPE_ACC | 0}, \
2908    {"$ac1",	RTYPE_ACC | 1}, \
2909    {"$ac2",	RTYPE_ACC | 2}, \
2910    {"$ac3",	RTYPE_ACC | 3}
2911
2912static const struct regname reg_names[] = {
2913  GENERIC_REGISTER_NUMBERS,
2914  FPU_REGISTER_NAMES,
2915  FPU_CONDITION_CODE_NAMES,
2916  COPROC_CONDITION_CODE_NAMES,
2917
2918  /* The $txx registers depends on the abi,
2919     these will be added later into the symbol table from
2920     one of the tables below once mips_abi is set after
2921     parsing of arguments from the command line. */
2922  SYMBOLIC_REGISTER_NAMES,
2923
2924  MIPS16_SPECIAL_REGISTER_NAMES,
2925  MDMX_VECTOR_REGISTER_NAMES,
2926  R5900_I_NAMES,
2927  R5900_Q_NAMES,
2928  R5900_R_NAMES,
2929  R5900_ACC_NAMES,
2930  MIPS_DSP_ACCUMULATOR_NAMES,
2931  {0, 0}
2932};
2933
2934static const struct regname reg_names_o32[] = {
2935  O32_SYMBOLIC_REGISTER_NAMES,
2936  {0, 0}
2937};
2938
2939static const struct regname reg_names_n32n64[] = {
2940  N32N64_SYMBOLIC_REGISTER_NAMES,
2941  {0, 0}
2942};
2943
2944/* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2945   interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2946   of these register symbols, return the associated vector register,
2947   otherwise return SYMVAL itself.  */
2948
2949static unsigned int
2950mips_prefer_vec_regno (unsigned int symval)
2951{
2952  if ((symval & -2) == (RTYPE_GP | 2))
2953    return RTYPE_VEC | (symval & 1);
2954  return symval;
2955}
2956
2957/* Return true if string [S, E) is a valid register name, storing its
2958   symbol value in *SYMVAL_PTR if so.  */
2959
2960static bool
2961mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2962{
2963  char save_c;
2964  symbolS *symbol;
2965
2966  /* Terminate name.  */
2967  save_c = *e;
2968  *e = '\0';
2969
2970  /* Look up the name.  */
2971  symbol = symbol_find (s);
2972  *e = save_c;
2973
2974  if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2975    return false;
2976
2977  *symval_ptr = S_GET_VALUE (symbol);
2978  return true;
2979}
2980
2981/* Return true if the string at *SPTR is a valid register name.  Allow it
2982   to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2983   is nonnull.
2984
2985   When returning true, move *SPTR past the register, store the
2986   register's symbol value in *SYMVAL_PTR and the channel mask in
2987   *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2988   number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2989   is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2990
2991static bool
2992mips_parse_register (char **sptr, unsigned int *symval_ptr,
2993		     unsigned int *channels_ptr)
2994{
2995  char *s, *e, *m;
2996  const char *q;
2997  unsigned int channels, symval, bit;
2998
2999  /* Find end of name.  */
3000  s = e = *sptr;
3001  if (is_name_beginner (*e))
3002    ++e;
3003  while (is_part_of_name (*e))
3004    ++e;
3005
3006  channels = 0;
3007  if (!mips_parse_register_1 (s, e, &symval))
3008    {
3009      if (!channels_ptr)
3010	return false;
3011
3012      /* Eat characters from the end of the string that are valid
3013	 channel suffixes.  The preceding register must be $ACC or
3014	 end with a digit, so there is no ambiguity.  */
3015      bit = 1;
3016      m = e;
3017      for (q = "wzyx"; *q; q++, bit <<= 1)
3018	if (m > s && m[-1] == *q)
3019	  {
3020	    --m;
3021	    channels |= bit;
3022	  }
3023
3024      if (channels == 0
3025	  || !mips_parse_register_1 (s, m, &symval)
3026	  || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
3027	return false;
3028    }
3029
3030  *sptr = e;
3031  *symval_ptr = symval;
3032  if (channels_ptr)
3033    *channels_ptr = channels;
3034  return true;
3035}
3036
3037/* Check if SPTR points at a valid register specifier according to TYPES.
3038   If so, then return 1, advance S to consume the specifier and store
3039   the register's number in REGNOP, otherwise return 0.  */
3040
3041static int
3042reg_lookup (char **s, unsigned int types, unsigned int *regnop)
3043{
3044  unsigned int regno;
3045
3046  if (mips_parse_register (s, &regno, NULL))
3047    {
3048      if (types & RTYPE_VEC)
3049	regno = mips_prefer_vec_regno (regno);
3050      if (regno & types)
3051	regno &= RNUM_MASK;
3052      else
3053	regno = ~0;
3054    }
3055  else
3056    {
3057      if (types & RWARN)
3058	as_warn (_("unrecognized register name `%s'"), *s);
3059      regno = ~0;
3060    }
3061  if (regnop)
3062    *regnop = regno;
3063  return regno <= RNUM_MASK;
3064}
3065
3066/* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
3067   mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
3068
3069static char *
3070mips_parse_vu0_channels (char *s, unsigned int *channels)
3071{
3072  unsigned int i;
3073
3074  *channels = 0;
3075  for (i = 0; i < 4; i++)
3076    if (*s == "xyzw"[i])
3077      {
3078	*channels |= 1 << (3 - i);
3079	++s;
3080      }
3081  return s;
3082}
3083
3084/* Token types for parsed operand lists.  */
3085enum mips_operand_token_type {
3086  /* A plain register, e.g. $f2.  */
3087  OT_REG,
3088
3089  /* A 4-bit XYZW channel mask.  */
3090  OT_CHANNELS,
3091
3092  /* A constant vector index, e.g. [1].  */
3093  OT_INTEGER_INDEX,
3094
3095  /* A register vector index, e.g. [$2].  */
3096  OT_REG_INDEX,
3097
3098  /* A continuous range of registers, e.g. $s0-$s4.  */
3099  OT_REG_RANGE,
3100
3101  /* A (possibly relocated) expression.  */
3102  OT_INTEGER,
3103
3104  /* A floating-point value.  */
3105  OT_FLOAT,
3106
3107  /* A single character.  This can be '(', ')' or ',', but '(' only appears
3108     before OT_REGs.  */
3109  OT_CHAR,
3110
3111  /* A doubled character, either "--" or "++".  */
3112  OT_DOUBLE_CHAR,
3113
3114  /* The end of the operand list.  */
3115  OT_END
3116};
3117
3118/* A parsed operand token.  */
3119struct mips_operand_token
3120{
3121  /* The type of token.  */
3122  enum mips_operand_token_type type;
3123  union
3124  {
3125    /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
3126    unsigned int regno;
3127
3128    /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
3129    unsigned int channels;
3130
3131    /* The integer value of an OT_INTEGER_INDEX.  */
3132    addressT index;
3133
3134    /* The two register symbol values involved in an OT_REG_RANGE.  */
3135    struct {
3136      unsigned int regno1;
3137      unsigned int regno2;
3138    } reg_range;
3139
3140    /* The value of an OT_INTEGER.  The value is represented as an
3141       expression and the relocation operators that were applied to
3142       that expression.  The reloc entries are BFD_RELOC_UNUSED if no
3143       relocation operators were used.  */
3144    struct {
3145      expressionS value;
3146      bfd_reloc_code_real_type relocs[3];
3147    } integer;
3148
3149    /* The binary data for an OT_FLOAT constant, and the number of bytes
3150       in the constant.  */
3151    struct {
3152      unsigned char data[8];
3153      int length;
3154    } flt;
3155
3156    /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3157    char ch;
3158  } u;
3159};
3160
3161/* An obstack used to construct lists of mips_operand_tokens.  */
3162static struct obstack mips_operand_tokens;
3163
3164/* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3165
3166static void
3167mips_add_token (struct mips_operand_token *token,
3168		enum mips_operand_token_type type)
3169{
3170  token->type = type;
3171  obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3172}
3173
3174/* Check whether S is '(' followed by a register name.  Add OT_CHAR
3175   and OT_REG tokens for them if so, and return a pointer to the first
3176   unconsumed character.  Return null otherwise.  */
3177
3178static char *
3179mips_parse_base_start (char *s)
3180{
3181  struct mips_operand_token token;
3182  unsigned int regno, channels;
3183  bool decrement_p;
3184
3185  if (*s != '(')
3186    return 0;
3187
3188  ++s;
3189  SKIP_SPACE_TABS (s);
3190
3191  /* Only match "--" as part of a base expression.  In other contexts "--X"
3192     is a double negative.  */
3193  decrement_p = (s[0] == '-' && s[1] == '-');
3194  if (decrement_p)
3195    {
3196      s += 2;
3197      SKIP_SPACE_TABS (s);
3198    }
3199
3200  /* Allow a channel specifier because that leads to better error messages
3201     than treating something like "$vf0x++" as an expression.  */
3202  if (!mips_parse_register (&s, &regno, &channels))
3203    return 0;
3204
3205  token.u.ch = '(';
3206  mips_add_token (&token, OT_CHAR);
3207
3208  if (decrement_p)
3209    {
3210      token.u.ch = '-';
3211      mips_add_token (&token, OT_DOUBLE_CHAR);
3212    }
3213
3214  token.u.regno = regno;
3215  mips_add_token (&token, OT_REG);
3216
3217  if (channels)
3218    {
3219      token.u.channels = channels;
3220      mips_add_token (&token, OT_CHANNELS);
3221    }
3222
3223  /* For consistency, only match "++" as part of base expressions too.  */
3224  SKIP_SPACE_TABS (s);
3225  if (s[0] == '+' && s[1] == '+')
3226    {
3227      s += 2;
3228      token.u.ch = '+';
3229      mips_add_token (&token, OT_DOUBLE_CHAR);
3230    }
3231
3232  return s;
3233}
3234
3235/* Parse one or more tokens from S.  Return a pointer to the first
3236   unconsumed character on success.  Return null if an error was found
3237   and store the error text in insn_error.  FLOAT_FORMAT is as for
3238   mips_parse_arguments.  */
3239
3240static char *
3241mips_parse_argument_token (char *s, char float_format)
3242{
3243  char *end, *save_in;
3244  const char *err;
3245  unsigned int regno1, regno2, channels;
3246  struct mips_operand_token token;
3247
3248  /* First look for "($reg", since we want to treat that as an
3249     OT_CHAR and OT_REG rather than an expression.  */
3250  end = mips_parse_base_start (s);
3251  if (end)
3252    return end;
3253
3254  /* Handle other characters that end up as OT_CHARs.  */
3255  if (*s == ')' || *s == ',')
3256    {
3257      token.u.ch = *s;
3258      mips_add_token (&token, OT_CHAR);
3259      ++s;
3260      return s;
3261    }
3262
3263  /* Handle tokens that start with a register.  */
3264  if (mips_parse_register (&s, &regno1, &channels))
3265    {
3266      if (channels)
3267	{
3268	  /* A register and a VU0 channel suffix.  */
3269	  token.u.regno = regno1;
3270	  mips_add_token (&token, OT_REG);
3271
3272	  token.u.channels = channels;
3273	  mips_add_token (&token, OT_CHANNELS);
3274	  return s;
3275	}
3276
3277      SKIP_SPACE_TABS (s);
3278      if (*s == '-')
3279	{
3280	  /* A register range.  */
3281	  ++s;
3282	  SKIP_SPACE_TABS (s);
3283	  if (!mips_parse_register (&s, &regno2, NULL))
3284	    {
3285	      set_insn_error (0, _("invalid register range"));
3286	      return 0;
3287	    }
3288
3289	  token.u.reg_range.regno1 = regno1;
3290	  token.u.reg_range.regno2 = regno2;
3291	  mips_add_token (&token, OT_REG_RANGE);
3292	  return s;
3293	}
3294
3295      /* Add the register itself.  */
3296      token.u.regno = regno1;
3297      mips_add_token (&token, OT_REG);
3298
3299      /* Check for a vector index.  */
3300      if (*s == '[')
3301	{
3302	  ++s;
3303	  SKIP_SPACE_TABS (s);
3304	  if (mips_parse_register (&s, &token.u.regno, NULL))
3305	    mips_add_token (&token, OT_REG_INDEX);
3306	  else
3307	    {
3308	      expressionS element;
3309
3310	      my_getExpression (&element, s);
3311	      if (element.X_op != O_constant)
3312		{
3313		  set_insn_error (0, _("vector element must be constant"));
3314		  return 0;
3315		}
3316	      s = expr_end;
3317	      token.u.index = element.X_add_number;
3318	      mips_add_token (&token, OT_INTEGER_INDEX);
3319	    }
3320	  SKIP_SPACE_TABS (s);
3321	  if (*s != ']')
3322	    {
3323	      set_insn_error (0, _("missing `]'"));
3324	      return 0;
3325	    }
3326	  ++s;
3327	}
3328      return s;
3329    }
3330
3331  if (float_format)
3332    {
3333      /* First try to treat expressions as floats.  */
3334      save_in = input_line_pointer;
3335      input_line_pointer = s;
3336      err = md_atof (float_format, (char *) token.u.flt.data,
3337		     &token.u.flt.length);
3338      end = input_line_pointer;
3339      input_line_pointer = save_in;
3340      if (err && *err)
3341	{
3342	  set_insn_error (0, err);
3343	  return 0;
3344	}
3345      if (s != end)
3346	{
3347	  mips_add_token (&token, OT_FLOAT);
3348	  return end;
3349	}
3350    }
3351
3352  /* Treat everything else as an integer expression.  */
3353  token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3354  token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3355  token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3356  my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3357  s = expr_end;
3358  mips_add_token (&token, OT_INTEGER);
3359  return s;
3360}
3361
3362/* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3363   if expressions should be treated as 32-bit floating-point constants,
3364   'd' if they should be treated as 64-bit floating-point constants,
3365   or 0 if they should be treated as integer expressions (the usual case).
3366
3367   Return a list of tokens on success, otherwise return 0.  The caller
3368   must obstack_free the list after use.  */
3369
3370static struct mips_operand_token *
3371mips_parse_arguments (char *s, char float_format)
3372{
3373  struct mips_operand_token token;
3374
3375  SKIP_SPACE_TABS (s);
3376  while (*s)
3377    {
3378      s = mips_parse_argument_token (s, float_format);
3379      if (!s)
3380	{
3381	  obstack_free (&mips_operand_tokens,
3382			obstack_finish (&mips_operand_tokens));
3383	  return 0;
3384	}
3385      SKIP_SPACE_TABS (s);
3386    }
3387  mips_add_token (&token, OT_END);
3388  return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3389}
3390
3391/* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3392   and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3393
3394static bool
3395is_opcode_valid (const struct mips_opcode *mo)
3396{
3397  int isa = mips_opts.isa;
3398  int ase = mips_opts.ase;
3399  int fp_s, fp_d;
3400  unsigned int i;
3401
3402  if (ISA_HAS_64BIT_REGS (isa))
3403    for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3404      if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3405	ase |= mips_ases[i].flags64;
3406
3407  if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3408    return false;
3409
3410  /* Check whether the instruction or macro requires single-precision or
3411     double-precision floating-point support.  Note that this information is
3412     stored differently in the opcode table for insns and macros.  */
3413  if (mo->pinfo == INSN_MACRO)
3414    {
3415      fp_s = mo->pinfo2 & INSN2_M_FP_S;
3416      fp_d = mo->pinfo2 & INSN2_M_FP_D;
3417    }
3418  else
3419    {
3420      fp_s = mo->pinfo & FP_S;
3421      fp_d = mo->pinfo & FP_D;
3422    }
3423
3424  if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3425    return false;
3426
3427  if (fp_s && mips_opts.soft_float)
3428    return false;
3429
3430  return true;
3431}
3432
3433/* Return TRUE if the MIPS16 opcode MO is valid on the currently
3434   selected ISA and architecture.  */
3435
3436static bool
3437is_opcode_valid_16 (const struct mips_opcode *mo)
3438{
3439  int isa = mips_opts.isa;
3440  int ase = mips_opts.ase;
3441  unsigned int i;
3442
3443  if (ISA_HAS_64BIT_REGS (isa))
3444    for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3445      if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3446	ase |= mips_ases[i].flags64;
3447
3448  return opcode_is_member (mo, isa, ase, mips_opts.arch);
3449}
3450
3451/* Return TRUE if the size of the microMIPS opcode MO matches one
3452   explicitly requested.  Always TRUE in the standard MIPS mode.
3453   Use is_size_valid_16 for MIPS16 opcodes.  */
3454
3455static bool
3456is_size_valid (const struct mips_opcode *mo)
3457{
3458  if (!mips_opts.micromips)
3459    return true;
3460
3461  if (mips_opts.insn32)
3462    {
3463      if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3464	return false;
3465      if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3466	return false;
3467    }
3468  if (!forced_insn_length)
3469    return true;
3470  if (mo->pinfo == INSN_MACRO)
3471    return false;
3472  return forced_insn_length == micromips_insn_length (mo);
3473}
3474
3475/* Return TRUE if the size of the MIPS16 opcode MO matches one
3476   explicitly requested.  */
3477
3478static bool
3479is_size_valid_16 (const struct mips_opcode *mo)
3480{
3481  if (!forced_insn_length)
3482    return true;
3483  if (mo->pinfo == INSN_MACRO)
3484    return false;
3485  if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3486    return false;
3487  if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3488    return false;
3489  return true;
3490}
3491
3492/* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3493   of the preceding instruction.  Always TRUE in the standard MIPS mode.
3494
3495   We don't accept macros in 16-bit delay slots to avoid a case where
3496   a macro expansion fails because it relies on a preceding 32-bit real
3497   instruction to have matched and does not handle the operands correctly.
3498   The only macros that may expand to 16-bit instructions are JAL that
3499   cannot be placed in a delay slot anyway, and corner cases of BALIGN
3500   and BGT (that likewise cannot be placed in a delay slot) that decay to
3501   a NOP.  In all these cases the macros precede any corresponding real
3502   instruction definitions in the opcode table, so they will match in the
3503   second pass where the size of the delay slot is ignored and therefore
3504   produce correct code.  */
3505
3506static bool
3507is_delay_slot_valid (const struct mips_opcode *mo)
3508{
3509  if (!mips_opts.micromips)
3510    return true;
3511
3512  if (mo->pinfo == INSN_MACRO)
3513    return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3514  if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3515      && micromips_insn_length (mo) != 4)
3516    return false;
3517  if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3518      && micromips_insn_length (mo) != 2)
3519    return false;
3520
3521  return true;
3522}
3523
3524/* For consistency checking, verify that all bits of OPCODE are specified
3525   either by the match/mask part of the instruction definition, or by the
3526   operand list.  Also build up a list of operands in OPERANDS.
3527
3528   INSN_BITS says which bits of the instruction are significant.
3529   If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3530   provides the mips_operand description of each operand.  DECODE_OPERAND
3531   is null for MIPS16 instructions.  */
3532
3533static int
3534validate_mips_insn (const struct mips_opcode *opcode,
3535		    unsigned long insn_bits,
3536		    const struct mips_operand *(*decode_operand) (const char *),
3537		    struct mips_operand_array *operands)
3538{
3539  const char *s;
3540  unsigned long used_bits, doubled, undefined, opno, mask;
3541  const struct mips_operand *operand;
3542
3543  mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3544  if ((mask & opcode->match) != opcode->match)
3545    {
3546      as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3547	      opcode->name, opcode->args);
3548      return 0;
3549    }
3550  used_bits = 0;
3551  opno = 0;
3552  if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3553    used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3554  for (s = opcode->args; *s; ++s)
3555    switch (*s)
3556      {
3557      case ',':
3558      case '(':
3559      case ')':
3560	break;
3561
3562      case '#':
3563	s++;
3564	break;
3565
3566      default:
3567	if (!decode_operand)
3568	  operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3569	else
3570	  operand = decode_operand (s);
3571	if (!operand && opcode->pinfo != INSN_MACRO)
3572	  {
3573	    as_bad (_("internal: unknown operand type: %s %s"),
3574		    opcode->name, opcode->args);
3575	    return 0;
3576	  }
3577	gas_assert (opno < MAX_OPERANDS);
3578	operands->operand[opno] = operand;
3579	if (!decode_operand && operand
3580	    && operand->type == OP_INT && operand->lsb == 0
3581	    && mips_opcode_32bit_p (opcode))
3582	  used_bits |= mips16_immed_extend (-1, operand->size);
3583	else if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3584	  {
3585	    used_bits = mips_insert_operand (operand, used_bits, -1);
3586	    if (operand->type == OP_MDMX_IMM_REG)
3587	      /* Bit 5 is the format selector (OB vs QH).  The opcode table
3588		 has separate entries for each format.  */
3589	      used_bits &= ~(1 << (operand->lsb + 5));
3590	    if (operand->type == OP_ENTRY_EXIT_LIST)
3591	      used_bits &= ~(mask & 0x700);
3592	    /* interAptiv MR2 SAVE/RESTORE instructions have a discontiguous
3593	       operand field that cannot be fully described with LSB/SIZE.  */
3594	    if (operand->type == OP_SAVE_RESTORE_LIST && operand->lsb == 6)
3595	      used_bits &= ~0x6000;
3596	  }
3597	/* Skip prefix characters.  */
3598	if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3599	  ++s;
3600	opno += 1;
3601	break;
3602      }
3603  doubled = used_bits & mask & insn_bits;
3604  if (doubled)
3605    {
3606      as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3607		" %s %s"), doubled, opcode->name, opcode->args);
3608      return 0;
3609    }
3610  used_bits |= mask;
3611  undefined = ~used_bits & insn_bits;
3612  if (opcode->pinfo != INSN_MACRO && undefined)
3613    {
3614      as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3615	      undefined, opcode->name, opcode->args);
3616      return 0;
3617    }
3618  used_bits &= ~insn_bits;
3619  if (used_bits)
3620    {
3621      as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3622	      used_bits, opcode->name, opcode->args);
3623      return 0;
3624    }
3625  return 1;
3626}
3627
3628/* The MIPS16 version of validate_mips_insn.  */
3629
3630static int
3631validate_mips16_insn (const struct mips_opcode *opcode,
3632		      struct mips_operand_array *operands)
3633{
3634  unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3635
3636  return validate_mips_insn (opcode, insn_bits, 0, operands);
3637}
3638
3639/* The microMIPS version of validate_mips_insn.  */
3640
3641static int
3642validate_micromips_insn (const struct mips_opcode *opc,
3643			 struct mips_operand_array *operands)
3644{
3645  unsigned long insn_bits;
3646  unsigned long major;
3647  unsigned int length;
3648
3649  if (opc->pinfo == INSN_MACRO)
3650    return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3651			       operands);
3652
3653  length = micromips_insn_length (opc);
3654  if (length != 2 && length != 4)
3655    {
3656      as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3657		"%s %s"), length, opc->name, opc->args);
3658      return 0;
3659    }
3660  major = opc->match >> (10 + 8 * (length - 2));
3661  if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3662      || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3663    {
3664      as_bad (_("internal error: bad microMIPS opcode "
3665		"(opcode/length mismatch): %s %s"), opc->name, opc->args);
3666      return 0;
3667    }
3668
3669  /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3670  insn_bits = 1 << 4 * length;
3671  insn_bits <<= 4 * length;
3672  insn_bits -= 1;
3673  return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3674			     operands);
3675}
3676
3677/* This function is called once, at assembler startup time.  It should set up
3678   all the tables, etc. that the MD part of the assembler will need.  */
3679
3680void
3681md_begin (void)
3682{
3683  int i = 0;
3684  int broken = 0;
3685
3686  if (mips_pic != NO_PIC)
3687    {
3688      if (g_switch_seen && g_switch_value != 0)
3689	as_bad (_("-G may not be used in position-independent code"));
3690      g_switch_value = 0;
3691    }
3692  else if (mips_abicalls)
3693    {
3694      if (g_switch_seen && g_switch_value != 0)
3695	as_bad (_("-G may not be used with abicalls"));
3696      g_switch_value = 0;
3697    }
3698
3699  if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3700    as_warn (_("could not set architecture and machine"));
3701
3702  op_hash = str_htab_create ();
3703
3704  mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3705  for (i = 0; i < NUMOPCODES;)
3706    {
3707      const char *name = mips_opcodes[i].name;
3708
3709      if (str_hash_insert (op_hash, name, &mips_opcodes[i], 0) != NULL)
3710	as_fatal (_("duplicate %s"), name);
3711      do
3712	{
3713	  if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3714				   decode_mips_operand, &mips_operands[i]))
3715	    broken = 1;
3716
3717	  if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3718	    {
3719	      create_insn (&nop_insn, mips_opcodes + i);
3720	      if (mips_fix_loongson2f_nop)
3721		nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3722	      nop_insn.fixed_p = 1;
3723	    }
3724
3725          if (sync_insn.insn_mo == NULL && strcmp (name, "sync") == 0)
3726	    create_insn (&sync_insn, mips_opcodes + i);
3727
3728	  ++i;
3729	}
3730      while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3731    }
3732
3733  mips16_op_hash = str_htab_create ();
3734  mips16_operands = XCNEWVEC (struct mips_operand_array,
3735			      bfd_mips16_num_opcodes);
3736
3737  i = 0;
3738  while (i < bfd_mips16_num_opcodes)
3739    {
3740      const char *name = mips16_opcodes[i].name;
3741
3742      if (str_hash_insert (mips16_op_hash, name, &mips16_opcodes[i], 0))
3743	as_fatal (_("duplicate %s"), name);
3744      do
3745	{
3746	  if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3747	    broken = 1;
3748	  if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3749	    {
3750	      create_insn (&mips16_nop_insn, mips16_opcodes + i);
3751	      mips16_nop_insn.fixed_p = 1;
3752	    }
3753	  ++i;
3754	}
3755      while (i < bfd_mips16_num_opcodes
3756	     && strcmp (mips16_opcodes[i].name, name) == 0);
3757    }
3758
3759  micromips_op_hash = str_htab_create ();
3760  micromips_operands = XCNEWVEC (struct mips_operand_array,
3761				 bfd_micromips_num_opcodes);
3762
3763  i = 0;
3764  while (i < bfd_micromips_num_opcodes)
3765    {
3766      const char *name = micromips_opcodes[i].name;
3767
3768      if (str_hash_insert (micromips_op_hash, name, &micromips_opcodes[i], 0))
3769	as_fatal (_("duplicate %s"), name);
3770      do
3771	{
3772	  struct mips_cl_insn *micromips_nop_insn;
3773
3774	  if (!validate_micromips_insn (&micromips_opcodes[i],
3775					&micromips_operands[i]))
3776	    broken = 1;
3777
3778	  if (micromips_opcodes[i].pinfo != INSN_MACRO)
3779	    {
3780	      if (micromips_insn_length (micromips_opcodes + i) == 2)
3781		micromips_nop_insn = &micromips_nop16_insn;
3782	      else if (micromips_insn_length (micromips_opcodes + i) == 4)
3783		micromips_nop_insn = &micromips_nop32_insn;
3784	      else
3785		continue;
3786
3787	      if (micromips_nop_insn->insn_mo == NULL
3788		  && strcmp (name, "nop") == 0)
3789		{
3790		  create_insn (micromips_nop_insn, micromips_opcodes + i);
3791		  micromips_nop_insn->fixed_p = 1;
3792		}
3793	    }
3794	}
3795      while (++i < bfd_micromips_num_opcodes
3796	     && strcmp (micromips_opcodes[i].name, name) == 0);
3797    }
3798
3799  if (broken)
3800    as_fatal (_("broken assembler, no assembly attempted"));
3801
3802  /* We add all the general register names to the symbol table.  This
3803     helps us detect invalid uses of them.  */
3804  for (i = 0; reg_names[i].name; i++)
3805    symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3806				     &zero_address_frag,
3807				     reg_names[i].num));
3808  if (HAVE_NEWABI)
3809    for (i = 0; reg_names_n32n64[i].name; i++)
3810      symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3811				       &zero_address_frag,
3812				       reg_names_n32n64[i].num));
3813  else
3814    for (i = 0; reg_names_o32[i].name; i++)
3815      symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3816				       &zero_address_frag,
3817				       reg_names_o32[i].num));
3818
3819  for (i = 0; i < 32; i++)
3820    {
3821      char regname[16];
3822
3823      /* R5900 VU0 floating-point register.  */
3824      sprintf (regname, "$vf%d", i);
3825      symbol_table_insert (symbol_new (regname, reg_section,
3826				       &zero_address_frag, RTYPE_VF | i));
3827
3828      /* R5900 VU0 integer register.  */
3829      sprintf (regname, "$vi%d", i);
3830      symbol_table_insert (symbol_new (regname, reg_section,
3831				       &zero_address_frag, RTYPE_VI | i));
3832
3833      /* MSA register.  */
3834      sprintf (regname, "$w%d", i);
3835      symbol_table_insert (symbol_new (regname, reg_section,
3836				       &zero_address_frag, RTYPE_MSA | i));
3837    }
3838
3839  obstack_init (&mips_operand_tokens);
3840
3841  mips_no_prev_insn ();
3842
3843  mips_gprmask = 0;
3844  mips_cprmask[0] = 0;
3845  mips_cprmask[1] = 0;
3846  mips_cprmask[2] = 0;
3847  mips_cprmask[3] = 0;
3848
3849  /* set the default alignment for the text section (2**2) */
3850  record_alignment (text_section, 2);
3851
3852  bfd_set_gp_size (stdoutput, g_switch_value);
3853
3854  /* On a native system other than VxWorks, sections must be aligned
3855     to 16 byte boundaries.  When configured for an embedded ELF
3856     target, we don't bother.  */
3857  if (!startswith (TARGET_OS, "elf")
3858      && !startswith (TARGET_OS, "vxworks"))
3859    {
3860      bfd_set_section_alignment (text_section, 4);
3861      bfd_set_section_alignment (data_section, 4);
3862      bfd_set_section_alignment (bss_section, 4);
3863    }
3864
3865  /* Create a .reginfo section for register masks and a .mdebug
3866     section for debugging information.  */
3867  {
3868    segT seg;
3869    subsegT subseg;
3870    flagword flags;
3871    segT sec;
3872
3873    seg = now_seg;
3874    subseg = now_subseg;
3875
3876    /* The ABI says this section should be loaded so that the
3877       running program can access it.  However, we don't load it
3878       if we are configured for an embedded target.  */
3879    flags = SEC_READONLY | SEC_DATA;
3880    if (!startswith (TARGET_OS, "elf"))
3881      flags |= SEC_ALLOC | SEC_LOAD;
3882
3883    if (mips_abi != N64_ABI)
3884      {
3885	sec = subseg_new (".reginfo", (subsegT) 0);
3886
3887	bfd_set_section_flags (sec, flags);
3888	bfd_set_section_alignment (sec, HAVE_NEWABI ? 3 : 2);
3889
3890	mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3891      }
3892    else
3893      {
3894	/* The 64-bit ABI uses a .MIPS.options section rather than
3895	   .reginfo section.  */
3896	sec = subseg_new (".MIPS.options", (subsegT) 0);
3897	bfd_set_section_flags (sec, flags);
3898	bfd_set_section_alignment (sec, 3);
3899
3900	/* Set up the option header.  */
3901	{
3902	  Elf_Internal_Options opthdr;
3903	  char *f;
3904
3905	  opthdr.kind = ODK_REGINFO;
3906	  opthdr.size = (sizeof (Elf_External_Options)
3907			 + sizeof (Elf64_External_RegInfo));
3908	  opthdr.section = 0;
3909	  opthdr.info = 0;
3910	  f = frag_more (sizeof (Elf_External_Options));
3911	  bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3912					 (Elf_External_Options *) f);
3913
3914	  mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3915	}
3916      }
3917
3918    sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3919    bfd_set_section_flags (sec,
3920			   SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3921    bfd_set_section_alignment (sec, 3);
3922    mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3923
3924    if (ECOFF_DEBUGGING)
3925      {
3926	sec = subseg_new (".mdebug", (subsegT) 0);
3927	bfd_set_section_flags (sec, SEC_HAS_CONTENTS | SEC_READONLY);
3928	bfd_set_section_alignment (sec, 2);
3929      }
3930    else if (mips_flag_pdr)
3931      {
3932	pdr_seg = subseg_new (".pdr", (subsegT) 0);
3933	bfd_set_section_flags (pdr_seg,
3934			       SEC_READONLY | SEC_RELOC | SEC_DEBUGGING);
3935	bfd_set_section_alignment (pdr_seg, 2);
3936      }
3937
3938    subseg_set (seg, subseg);
3939  }
3940
3941  if (mips_fix_vr4120)
3942    init_vr4120_conflicts ();
3943}
3944
3945static inline void
3946fpabi_incompatible_with (int fpabi, const char *what)
3947{
3948  as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3949	   Tag_GNU_MIPS_ABI_FP, fpabi, what);
3950}
3951
3952static inline void
3953fpabi_requires (int fpabi, const char *what)
3954{
3955  as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3956	   Tag_GNU_MIPS_ABI_FP, fpabi, what);
3957}
3958
3959/* Check -mabi and register sizes against the specified FP ABI.  */
3960static void
3961check_fpabi (int fpabi)
3962{
3963  switch (fpabi)
3964    {
3965    case Val_GNU_MIPS_ABI_FP_DOUBLE:
3966      if (file_mips_opts.soft_float)
3967	fpabi_incompatible_with (fpabi, "softfloat");
3968      else if (file_mips_opts.single_float)
3969	fpabi_incompatible_with (fpabi, "singlefloat");
3970      if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3971	fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3972      else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3973	fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3974      break;
3975
3976    case Val_GNU_MIPS_ABI_FP_XX:
3977      if (mips_abi != O32_ABI)
3978	fpabi_requires (fpabi, "-mabi=32");
3979      else if (file_mips_opts.soft_float)
3980	fpabi_incompatible_with (fpabi, "softfloat");
3981      else if (file_mips_opts.single_float)
3982	fpabi_incompatible_with (fpabi, "singlefloat");
3983      else if (file_mips_opts.fp != 0)
3984	fpabi_requires (fpabi, "fp=xx");
3985      break;
3986
3987    case Val_GNU_MIPS_ABI_FP_64A:
3988    case Val_GNU_MIPS_ABI_FP_64:
3989      if (mips_abi != O32_ABI)
3990	fpabi_requires (fpabi, "-mabi=32");
3991      else if (file_mips_opts.soft_float)
3992	fpabi_incompatible_with (fpabi, "softfloat");
3993      else if (file_mips_opts.single_float)
3994	fpabi_incompatible_with (fpabi, "singlefloat");
3995      else if (file_mips_opts.fp != 64)
3996	fpabi_requires (fpabi, "fp=64");
3997      else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3998	fpabi_incompatible_with (fpabi, "nooddspreg");
3999      else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
4000	fpabi_requires (fpabi, "nooddspreg");
4001      break;
4002
4003    case Val_GNU_MIPS_ABI_FP_SINGLE:
4004      if (file_mips_opts.soft_float)
4005	fpabi_incompatible_with (fpabi, "softfloat");
4006      else if (!file_mips_opts.single_float)
4007	fpabi_requires (fpabi, "singlefloat");
4008      break;
4009
4010    case Val_GNU_MIPS_ABI_FP_SOFT:
4011      if (!file_mips_opts.soft_float)
4012	fpabi_requires (fpabi, "softfloat");
4013      break;
4014
4015    case Val_GNU_MIPS_ABI_FP_OLD_64:
4016      as_warn (_(".gnu_attribute %d,%d is no longer supported"),
4017	       Tag_GNU_MIPS_ABI_FP, fpabi);
4018      break;
4019
4020    case Val_GNU_MIPS_ABI_FP_NAN2008:
4021      /* Silently ignore compatibility value.  */
4022      break;
4023
4024    default:
4025      as_warn (_(".gnu_attribute %d,%d is not a recognized"
4026	         " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
4027      break;
4028    }
4029}
4030
4031/* Perform consistency checks on the current options.  */
4032
4033static void
4034mips_check_options (struct mips_set_options *opts, bool abi_checks)
4035{
4036  /* Check the size of integer registers agrees with the ABI and ISA.  */
4037  if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
4038    as_bad (_("`gp=64' used with a 32-bit processor"));
4039  else if (abi_checks
4040	   && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
4041    as_bad (_("`gp=32' used with a 64-bit ABI"));
4042  else if (abi_checks
4043	   && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
4044    as_bad (_("`gp=64' used with a 32-bit ABI"));
4045
4046  /* Check the size of the float registers agrees with the ABI and ISA.  */
4047  switch (opts->fp)
4048    {
4049    case 0:
4050      if (!CPU_HAS_LDC1_SDC1 (opts->arch))
4051	as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
4052      else if (opts->single_float == 1)
4053	as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
4054      break;
4055    case 64:
4056      if (!ISA_HAS_64BIT_FPRS (opts->isa))
4057	as_bad (_("`fp=64' used with a 32-bit fpu"));
4058      else if (abi_checks
4059	       && ABI_NEEDS_32BIT_REGS (mips_abi)
4060	       && !ISA_HAS_MXHC1 (opts->isa))
4061	as_warn (_("`fp=64' used with a 32-bit ABI"));
4062      break;
4063    case 32:
4064      if (abi_checks
4065	  && ABI_NEEDS_64BIT_REGS (mips_abi))
4066	as_warn (_("`fp=32' used with a 64-bit ABI"));
4067      if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
4068	as_bad (_("`fp=32' used with a MIPS R6 cpu"));
4069      break;
4070    default:
4071      as_bad (_("Unknown size of floating point registers"));
4072      break;
4073    }
4074
4075  if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
4076    as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
4077
4078  if (opts->micromips == 1 && opts->mips16 == 1)
4079    as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
4080  else if (ISA_IS_R6 (opts->isa)
4081	   && (opts->micromips == 1
4082	       || opts->mips16 == 1))
4083    as_fatal (_("`%s' cannot be used with `%s'"),
4084	      opts->micromips ? "micromips" : "mips16",
4085	      mips_cpu_info_from_isa (opts->isa)->name);
4086
4087  if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
4088    as_fatal (_("branch relaxation is not supported in `%s'"),
4089	      mips_cpu_info_from_isa (opts->isa)->name);
4090}
4091
4092/* Perform consistency checks on the module level options exactly once.
4093   This is a deferred check that happens:
4094     at the first .set directive
4095     or, at the first pseudo op that generates code (inc .dc.a)
4096     or, at the first instruction
4097     or, at the end.  */
4098
4099static void
4100file_mips_check_options (void)
4101{
4102  if (file_mips_opts_checked)
4103    return;
4104
4105  /* The following code determines the register size.
4106     Similar code was added to GCC 3.3 (see override_options() in
4107     config/mips/mips.c).  The GAS and GCC code should be kept in sync
4108     as much as possible.  */
4109
4110  if (file_mips_opts.gp < 0)
4111    {
4112      /* Infer the integer register size from the ABI and processor.
4113	 Restrict ourselves to 32-bit registers if that's all the
4114	 processor has, or if the ABI cannot handle 64-bit registers.  */
4115      file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
4116			   || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
4117			  ? 32 : 64;
4118    }
4119
4120  if (file_mips_opts.fp < 0)
4121    {
4122      /* No user specified float register size.
4123	 ??? GAS treats single-float processors as though they had 64-bit
4124	 float registers (although it complains when double-precision
4125	 instructions are used).  As things stand, saying they have 32-bit
4126	 registers would lead to spurious "register must be even" messages.
4127	 So here we assume float registers are never smaller than the
4128	 integer ones.  */
4129      if (file_mips_opts.gp == 64)
4130	/* 64-bit integer registers implies 64-bit float registers.  */
4131	file_mips_opts.fp = 64;
4132      else if ((file_mips_opts.ase & FP64_ASES)
4133	       && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
4134	/* Handle ASEs that require 64-bit float registers, if possible.  */
4135	file_mips_opts.fp = 64;
4136      else if (ISA_IS_R6 (mips_opts.isa))
4137	/* R6 implies 64-bit float registers.  */
4138	file_mips_opts.fp = 64;
4139      else
4140	/* 32-bit float registers.  */
4141	file_mips_opts.fp = 32;
4142    }
4143
4144  /* Disable operations on odd-numbered floating-point registers by default
4145     when using the FPXX ABI.  */
4146  if (file_mips_opts.oddspreg < 0)
4147    {
4148      if (file_mips_opts.fp == 0)
4149	file_mips_opts.oddspreg = 0;
4150      else
4151	file_mips_opts.oddspreg = 1;
4152    }
4153
4154  /* End of GCC-shared inference code.  */
4155
4156  /* This flag is set when we have a 64-bit capable CPU but use only
4157     32-bit wide registers.  Note that EABI does not use it.  */
4158  if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4159      && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4160	  || mips_abi == O32_ABI))
4161    mips_32bitmode = 1;
4162
4163  if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4164    as_bad (_("trap exception not supported at ISA 1"));
4165
4166  /* If the selected architecture includes support for ASEs, enable
4167     generation of code for them.  */
4168  if (file_mips_opts.mips16 == -1)
4169    file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4170  if (file_mips_opts.micromips == -1)
4171    file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4172				? 1 : 0;
4173
4174  if (mips_nan2008 == -1)
4175    mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4176  else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4177    as_fatal (_("`%s' does not support legacy NaN"),
4178	      mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4179
4180  /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4181     being selected implicitly.  */
4182  if (file_mips_opts.fp != 64)
4183    file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4184
4185  /* If the user didn't explicitly select or deselect a particular ASE,
4186     use the default setting for the CPU.  */
4187  file_mips_opts.ase |= (file_mips_opts.init_ase & ~file_ase_explicit);
4188
4189  /* Set up the current options.  These may change throughout assembly.  */
4190  mips_opts = file_mips_opts;
4191
4192  mips_check_isa_supports_ases ();
4193  mips_check_options (&file_mips_opts, true);
4194  file_mips_opts_checked = true;
4195
4196  if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4197    as_warn (_("could not set architecture and machine"));
4198}
4199
4200void
4201md_assemble (char *str)
4202{
4203  struct mips_cl_insn insn;
4204  bfd_reloc_code_real_type unused_reloc[3]
4205    = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4206
4207  file_mips_check_options ();
4208
4209  imm_expr.X_op = O_absent;
4210  offset_expr.X_op = O_absent;
4211  offset_reloc[0] = BFD_RELOC_UNUSED;
4212  offset_reloc[1] = BFD_RELOC_UNUSED;
4213  offset_reloc[2] = BFD_RELOC_UNUSED;
4214
4215  mips_mark_labels ();
4216  mips_assembling_insn = true;
4217  clear_insn_error ();
4218
4219  if (mips_opts.mips16)
4220    mips16_ip (str, &insn);
4221  else
4222    {
4223      mips_ip (str, &insn);
4224      DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4225	    str, insn.insn_opcode));
4226    }
4227
4228  if (insn_error.msg)
4229    report_insn_error (str);
4230  else if (insn.insn_mo->pinfo == INSN_MACRO)
4231    {
4232      macro_start ();
4233      if (mips_opts.mips16)
4234	mips16_macro (&insn);
4235      else
4236	macro (&insn, str);
4237      macro_end ();
4238    }
4239  else
4240    {
4241      if (offset_expr.X_op != O_absent)
4242	append_insn (&insn, &offset_expr, offset_reloc, false);
4243      else
4244	append_insn (&insn, NULL, unused_reloc, false);
4245    }
4246
4247  mips_assembling_insn = false;
4248}
4249
4250/* Convenience functions for abstracting away the differences between
4251   MIPS16 and non-MIPS16 relocations.  */
4252
4253static inline bool
4254mips16_reloc_p (bfd_reloc_code_real_type reloc)
4255{
4256  switch (reloc)
4257    {
4258    case BFD_RELOC_MIPS16_JMP:
4259    case BFD_RELOC_MIPS16_GPREL:
4260    case BFD_RELOC_MIPS16_GOT16:
4261    case BFD_RELOC_MIPS16_CALL16:
4262    case BFD_RELOC_MIPS16_HI16_S:
4263    case BFD_RELOC_MIPS16_HI16:
4264    case BFD_RELOC_MIPS16_LO16:
4265    case BFD_RELOC_MIPS16_16_PCREL_S1:
4266      return true;
4267
4268    default:
4269      return false;
4270    }
4271}
4272
4273static inline bool
4274micromips_reloc_p (bfd_reloc_code_real_type reloc)
4275{
4276  switch (reloc)
4277    {
4278    case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4279    case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4280    case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4281    case BFD_RELOC_MICROMIPS_GPREL16:
4282    case BFD_RELOC_MICROMIPS_JMP:
4283    case BFD_RELOC_MICROMIPS_HI16:
4284    case BFD_RELOC_MICROMIPS_HI16_S:
4285    case BFD_RELOC_MICROMIPS_LO16:
4286    case BFD_RELOC_MICROMIPS_LITERAL:
4287    case BFD_RELOC_MICROMIPS_GOT16:
4288    case BFD_RELOC_MICROMIPS_CALL16:
4289    case BFD_RELOC_MICROMIPS_GOT_HI16:
4290    case BFD_RELOC_MICROMIPS_GOT_LO16:
4291    case BFD_RELOC_MICROMIPS_CALL_HI16:
4292    case BFD_RELOC_MICROMIPS_CALL_LO16:
4293    case BFD_RELOC_MICROMIPS_SUB:
4294    case BFD_RELOC_MICROMIPS_GOT_PAGE:
4295    case BFD_RELOC_MICROMIPS_GOT_OFST:
4296    case BFD_RELOC_MICROMIPS_GOT_DISP:
4297    case BFD_RELOC_MICROMIPS_HIGHEST:
4298    case BFD_RELOC_MICROMIPS_HIGHER:
4299    case BFD_RELOC_MICROMIPS_SCN_DISP:
4300    case BFD_RELOC_MICROMIPS_JALR:
4301      return true;
4302
4303    default:
4304      return false;
4305    }
4306}
4307
4308static inline bool
4309jmp_reloc_p (bfd_reloc_code_real_type reloc)
4310{
4311  return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4312}
4313
4314static inline bool
4315b_reloc_p (bfd_reloc_code_real_type reloc)
4316{
4317  return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4318	  || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4319	  || reloc == BFD_RELOC_16_PCREL_S2
4320	  || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4321	  || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4322	  || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4323	  || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4324}
4325
4326static inline bool
4327got16_reloc_p (bfd_reloc_code_real_type reloc)
4328{
4329  return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4330	  || reloc == BFD_RELOC_MICROMIPS_GOT16);
4331}
4332
4333static inline bool
4334hi16_reloc_p (bfd_reloc_code_real_type reloc)
4335{
4336  return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4337	  || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4338}
4339
4340static inline bool
4341lo16_reloc_p (bfd_reloc_code_real_type reloc)
4342{
4343  return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4344	  || reloc == BFD_RELOC_MICROMIPS_LO16);
4345}
4346
4347static inline bool
4348jalr_reloc_p (bfd_reloc_code_real_type reloc)
4349{
4350  return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4351}
4352
4353static inline bool
4354gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4355{
4356  return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4357	  || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4358}
4359
4360/* Return true if RELOC is a PC-relative relocation that does not have
4361   full address range.  */
4362
4363static inline bool
4364limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4365{
4366  switch (reloc)
4367    {
4368    case BFD_RELOC_16_PCREL_S2:
4369    case BFD_RELOC_MIPS16_16_PCREL_S1:
4370    case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4371    case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4372    case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4373    case BFD_RELOC_MIPS_21_PCREL_S2:
4374    case BFD_RELOC_MIPS_26_PCREL_S2:
4375    case BFD_RELOC_MIPS_18_PCREL_S3:
4376    case BFD_RELOC_MIPS_19_PCREL_S2:
4377      return true;
4378
4379    case BFD_RELOC_32_PCREL:
4380    case BFD_RELOC_HI16_S_PCREL:
4381    case BFD_RELOC_LO16_PCREL:
4382      return HAVE_64BIT_ADDRESSES;
4383
4384    default:
4385      return false;
4386    }
4387}
4388
4389/* Return true if the given relocation might need a matching %lo().
4390   This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4391   need a matching %lo() when applied to local symbols.  */
4392
4393static inline bool
4394reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4395{
4396  return (HAVE_IN_PLACE_ADDENDS
4397	  && (hi16_reloc_p (reloc)
4398	      /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4399		 all GOT16 relocations evaluate to "G".  */
4400	      || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4401}
4402
4403/* Return the type of %lo() reloc needed by RELOC, given that
4404   reloc_needs_lo_p.  */
4405
4406static inline bfd_reloc_code_real_type
4407matching_lo_reloc (bfd_reloc_code_real_type reloc)
4408{
4409  return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4410	  : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4411	     : BFD_RELOC_LO16));
4412}
4413
4414/* Return true if the given fixup is followed by a matching R_MIPS_LO16
4415   relocation.  */
4416
4417static inline bool
4418fixup_has_matching_lo_p (fixS *fixp)
4419{
4420  return (fixp->fx_next != NULL
4421	  && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4422	  && fixp->fx_addsy == fixp->fx_next->fx_addsy
4423	  && fixp->fx_offset == fixp->fx_next->fx_offset);
4424}
4425
4426/* Move all labels in LABELS to the current insertion point.  TEXT_P
4427   says whether the labels refer to text or data.  */
4428
4429static void
4430mips_move_labels (struct insn_label_list *labels, bool text_p)
4431{
4432  struct insn_label_list *l;
4433  valueT val;
4434
4435  for (l = labels; l != NULL; l = l->next)
4436    {
4437      gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4438      symbol_set_frag (l->label, frag_now);
4439      val = (valueT) frag_now_fix ();
4440      /* MIPS16/microMIPS text labels are stored as odd.
4441	 We just carry the ISA mode bit forward.  */
4442      if (text_p && HAVE_CODE_COMPRESSION)
4443	val |= (S_GET_VALUE (l->label) & 0x1);
4444      S_SET_VALUE (l->label, val);
4445    }
4446}
4447
4448/* Move all labels in insn_labels to the current insertion point
4449   and treat them as text labels.  */
4450
4451static void
4452mips_move_text_labels (void)
4453{
4454  mips_move_labels (seg_info (now_seg)->label_list, true);
4455}
4456
4457/* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4458
4459static bool
4460s_is_linkonce (symbolS *sym, segT from_seg)
4461{
4462  bool linkonce = false;
4463  segT symseg = S_GET_SEGMENT (sym);
4464
4465  if (symseg != from_seg && !S_IS_LOCAL (sym))
4466    {
4467      if ((bfd_section_flags (symseg) & SEC_LINK_ONCE))
4468	linkonce = true;
4469      /* The GNU toolchain uses an extension for ELF: a section
4470	 beginning with the magic string .gnu.linkonce is a
4471	 linkonce section.  */
4472      if (startswith (segment_name (symseg), ".gnu.linkonce"))
4473	linkonce = true;
4474    }
4475  return linkonce;
4476}
4477
4478/* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4479   linker to handle them specially, such as generating jalx instructions
4480   when needed.  We also make them odd for the duration of the assembly,
4481   in order to generate the right sort of code.  We will make them even
4482   in the adjust_symtab routine, while leaving them marked.  This is
4483   convenient for the debugger and the disassembler.  The linker knows
4484   to make them odd again.  */
4485
4486static void
4487mips_compressed_mark_label (symbolS *label)
4488{
4489  gas_assert (HAVE_CODE_COMPRESSION);
4490
4491  if (mips_opts.mips16)
4492    S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4493  else
4494    S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4495  if ((S_GET_VALUE (label) & 1) == 0
4496      /* Don't adjust the address if the label is global or weak, or
4497	 in a link-once section, since we'll be emitting symbol reloc
4498	 references to it which will be patched up by the linker, and
4499	 the final value of the symbol may or may not be MIPS16/microMIPS.  */
4500      && !S_IS_WEAK (label)
4501      && !S_IS_EXTERNAL (label)
4502      && !s_is_linkonce (label, now_seg))
4503    S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4504}
4505
4506/* Mark preceding MIPS16 or microMIPS instruction labels.  */
4507
4508static void
4509mips_compressed_mark_labels (void)
4510{
4511  struct insn_label_list *l;
4512
4513  for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4514    mips_compressed_mark_label (l->label);
4515}
4516
4517/* End the current frag.  Make it a variant frag and record the
4518   relaxation info.  */
4519
4520static void
4521relax_close_frag (void)
4522{
4523  mips_macro_warning.first_frag = frag_now;
4524  frag_var (rs_machine_dependent, 0, 0,
4525	    RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4526			  mips_pic != NO_PIC),
4527	    mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4528
4529  memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4530  mips_relax.first_fixup = 0;
4531}
4532
4533/* Start a new relaxation sequence whose expansion depends on SYMBOL.
4534   See the comment above RELAX_ENCODE for more details.  */
4535
4536static void
4537relax_start (symbolS *symbol)
4538{
4539  gas_assert (mips_relax.sequence == 0);
4540  mips_relax.sequence = 1;
4541  mips_relax.symbol = symbol;
4542}
4543
4544/* Start generating the second version of a relaxable sequence.
4545   See the comment above RELAX_ENCODE for more details.  */
4546
4547static void
4548relax_switch (void)
4549{
4550  gas_assert (mips_relax.sequence == 1);
4551  mips_relax.sequence = 2;
4552}
4553
4554/* End the current relaxable sequence.  */
4555
4556static void
4557relax_end (void)
4558{
4559  gas_assert (mips_relax.sequence == 2);
4560  relax_close_frag ();
4561  mips_relax.sequence = 0;
4562}
4563
4564/* Return true if IP is a delayed branch or jump.  */
4565
4566static inline bool
4567delayed_branch_p (const struct mips_cl_insn *ip)
4568{
4569  return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4570				| INSN_COND_BRANCH_DELAY
4571				| INSN_COND_BRANCH_LIKELY)) != 0;
4572}
4573
4574/* Return true if IP is a compact branch or jump.  */
4575
4576static inline bool
4577compact_branch_p (const struct mips_cl_insn *ip)
4578{
4579  return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4580				 | INSN2_COND_BRANCH)) != 0;
4581}
4582
4583/* Return true if IP is an unconditional branch or jump.  */
4584
4585static inline bool
4586uncond_branch_p (const struct mips_cl_insn *ip)
4587{
4588  return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4589	  || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4590}
4591
4592/* Return true if IP is a branch-likely instruction.  */
4593
4594static inline bool
4595branch_likely_p (const struct mips_cl_insn *ip)
4596{
4597  return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4598}
4599
4600/* Return the type of nop that should be used to fill the delay slot
4601   of delayed branch IP.  */
4602
4603static struct mips_cl_insn *
4604get_delay_slot_nop (const struct mips_cl_insn *ip)
4605{
4606  if (mips_opts.micromips
4607      && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4608    return &micromips_nop32_insn;
4609  return NOP_INSN;
4610}
4611
4612/* Return a mask that has bit N set if OPCODE reads the register(s)
4613   in operand N.  */
4614
4615static unsigned int
4616insn_read_mask (const struct mips_opcode *opcode)
4617{
4618  return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4619}
4620
4621/* Return a mask that has bit N set if OPCODE writes to the register(s)
4622   in operand N.  */
4623
4624static unsigned int
4625insn_write_mask (const struct mips_opcode *opcode)
4626{
4627  return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4628}
4629
4630/* Return a mask of the registers specified by operand OPERAND of INSN.
4631   Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4632   is set.  */
4633
4634static unsigned int
4635operand_reg_mask (const struct mips_cl_insn *insn,
4636		  const struct mips_operand *operand,
4637		  unsigned int type_mask)
4638{
4639  unsigned int uval, vsel;
4640
4641  switch (operand->type)
4642    {
4643    case OP_INT:
4644    case OP_MAPPED_INT:
4645    case OP_MSB:
4646    case OP_PCREL:
4647    case OP_PERF_REG:
4648    case OP_ADDIUSP_INT:
4649    case OP_ENTRY_EXIT_LIST:
4650    case OP_REPEAT_DEST_REG:
4651    case OP_REPEAT_PREV_REG:
4652    case OP_PC:
4653    case OP_VU0_SUFFIX:
4654    case OP_VU0_MATCH_SUFFIX:
4655    case OP_IMM_INDEX:
4656      abort ();
4657
4658    case OP_REG28:
4659      return 1 << 28;
4660
4661    case OP_REG:
4662    case OP_OPTIONAL_REG:
4663      {
4664	const struct mips_reg_operand *reg_op;
4665
4666	reg_op = (const struct mips_reg_operand *) operand;
4667	if (!(type_mask & (1 << reg_op->reg_type)))
4668	  return 0;
4669	uval = insn_extract_operand (insn, operand);
4670	return 1u << mips_decode_reg_operand (reg_op, uval);
4671      }
4672
4673    case OP_REG_PAIR:
4674      {
4675	const struct mips_reg_pair_operand *pair_op;
4676
4677	pair_op = (const struct mips_reg_pair_operand *) operand;
4678	if (!(type_mask & (1 << pair_op->reg_type)))
4679	  return 0;
4680	uval = insn_extract_operand (insn, operand);
4681	return (1u << pair_op->reg1_map[uval]) | (1u << pair_op->reg2_map[uval]);
4682      }
4683
4684    case OP_CLO_CLZ_DEST:
4685      if (!(type_mask & (1 << OP_REG_GP)))
4686	return 0;
4687      uval = insn_extract_operand (insn, operand);
4688      return (1u << (uval & 31)) | (1u << (uval >> 5));
4689
4690    case OP_SAME_RS_RT:
4691      if (!(type_mask & (1 << OP_REG_GP)))
4692	return 0;
4693      uval = insn_extract_operand (insn, operand);
4694      gas_assert ((uval & 31) == (uval >> 5));
4695      return 1u << (uval & 31);
4696
4697    case OP_CHECK_PREV:
4698    case OP_NON_ZERO_REG:
4699      if (!(type_mask & (1 << OP_REG_GP)))
4700	return 0;
4701      uval = insn_extract_operand (insn, operand);
4702      return 1u << (uval & 31);
4703
4704    case OP_LWM_SWM_LIST:
4705      abort ();
4706
4707    case OP_SAVE_RESTORE_LIST:
4708      abort ();
4709
4710    case OP_MDMX_IMM_REG:
4711      if (!(type_mask & (1 << OP_REG_VEC)))
4712	return 0;
4713      uval = insn_extract_operand (insn, operand);
4714      vsel = uval >> 5;
4715      if ((vsel & 0x18) == 0x18)
4716	return 0;
4717      return 1u << (uval & 31);
4718
4719    case OP_REG_INDEX:
4720      if (!(type_mask & (1 << OP_REG_GP)))
4721	return 0;
4722      return 1u << insn_extract_operand (insn, operand);
4723    }
4724  abort ();
4725}
4726
4727/* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4728   where bit N of OPNO_MASK is set if operand N should be included.
4729   Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4730   is set.  */
4731
4732static unsigned int
4733insn_reg_mask (const struct mips_cl_insn *insn,
4734	       unsigned int type_mask, unsigned int opno_mask)
4735{
4736  unsigned int opno, reg_mask;
4737
4738  opno = 0;
4739  reg_mask = 0;
4740  while (opno_mask != 0)
4741    {
4742      if (opno_mask & 1)
4743	reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4744      opno_mask >>= 1;
4745      opno += 1;
4746    }
4747  return reg_mask;
4748}
4749
4750/* Return the mask of core registers that IP reads.  */
4751
4752static unsigned int
4753gpr_read_mask (const struct mips_cl_insn *ip)
4754{
4755  unsigned long pinfo, pinfo2;
4756  unsigned int mask;
4757
4758  mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4759  pinfo = ip->insn_mo->pinfo;
4760  pinfo2 = ip->insn_mo->pinfo2;
4761  if (pinfo & INSN_UDI)
4762    {
4763      /* UDI instructions have traditionally been assumed to read RS
4764	 and RT.  */
4765      mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4766      mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4767    }
4768  if (pinfo & INSN_READ_GPR_24)
4769    mask |= 1 << 24;
4770  if (pinfo2 & INSN2_READ_GPR_16)
4771    mask |= 1 << 16;
4772  if (pinfo2 & INSN2_READ_SP)
4773    mask |= 1 << SP;
4774  if (pinfo2 & INSN2_READ_GPR_31)
4775    mask |= 1u << 31;
4776  /* Don't include register 0.  */
4777  return mask & ~1;
4778}
4779
4780/* Return the mask of core registers that IP writes.  */
4781
4782static unsigned int
4783gpr_write_mask (const struct mips_cl_insn *ip)
4784{
4785  unsigned long pinfo, pinfo2;
4786  unsigned int mask;
4787
4788  mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4789  pinfo = ip->insn_mo->pinfo;
4790  pinfo2 = ip->insn_mo->pinfo2;
4791  if (pinfo & INSN_WRITE_GPR_24)
4792    mask |= 1 << 24;
4793  if (pinfo & INSN_WRITE_GPR_31)
4794    mask |= 1u << 31;
4795  if (pinfo & INSN_UDI)
4796    /* UDI instructions have traditionally been assumed to write to RD.  */
4797    mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4798  if (pinfo2 & INSN2_WRITE_SP)
4799    mask |= 1 << SP;
4800  /* Don't include register 0.  */
4801  return mask & ~1;
4802}
4803
4804/* Return the mask of floating-point registers that IP reads.  */
4805
4806static unsigned int
4807fpr_read_mask (const struct mips_cl_insn *ip)
4808{
4809  unsigned long pinfo;
4810  unsigned int mask;
4811
4812  mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4813			     | (1 << OP_REG_MSA)),
4814			insn_read_mask (ip->insn_mo));
4815  pinfo = ip->insn_mo->pinfo;
4816  /* Conservatively treat all operands to an FP_D instruction are doubles.
4817     (This is overly pessimistic for things like cvt.d.s.)  */
4818  if (FPR_SIZE != 64 && (pinfo & FP_D))
4819    mask |= mask << 1;
4820  return mask;
4821}
4822
4823/* Return the mask of floating-point registers that IP writes.  */
4824
4825static unsigned int
4826fpr_write_mask (const struct mips_cl_insn *ip)
4827{
4828  unsigned long pinfo;
4829  unsigned int mask;
4830
4831  mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4832			     | (1 << OP_REG_MSA)),
4833			insn_write_mask (ip->insn_mo));
4834  pinfo = ip->insn_mo->pinfo;
4835  /* Conservatively treat all operands to an FP_D instruction are doubles.
4836     (This is overly pessimistic for things like cvt.s.d.)  */
4837  if (FPR_SIZE != 64 && (pinfo & FP_D))
4838    mask |= mask << 1;
4839  return mask;
4840}
4841
4842/* Operand OPNUM of INSN is an odd-numbered floating-point register.
4843   Check whether that is allowed.  */
4844
4845static bool
4846mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4847{
4848  const char *s = insn->name;
4849  bool oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4850		   || FPR_SIZE == 64) && mips_opts.oddspreg;
4851
4852  if (insn->pinfo == INSN_MACRO)
4853    /* Let a macro pass, we'll catch it later when it is expanded.  */
4854    return true;
4855
4856  /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4857     otherwise it depends on oddspreg.  */
4858  if ((insn->pinfo & FP_S)
4859      && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4860			 | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4861    return FPR_SIZE == 32 || oddspreg;
4862
4863  /* Allow odd registers for single-precision ops and double-precision if the
4864     floating-point registers are 64-bit wide.  */
4865  switch (insn->pinfo & (FP_S | FP_D))
4866    {
4867    case FP_S:
4868    case 0:
4869      return oddspreg;
4870    case FP_D:
4871      return FPR_SIZE == 64;
4872    default:
4873      break;
4874    }
4875
4876  /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4877  s = strchr (insn->name, '.');
4878  if (s != NULL && opnum == 2)
4879    s = strchr (s + 1, '.');
4880  if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4881    return oddspreg;
4882
4883  return FPR_SIZE == 64;
4884}
4885
4886/* Information about an instruction argument that we're trying to match.  */
4887struct mips_arg_info
4888{
4889  /* The instruction so far.  */
4890  struct mips_cl_insn *insn;
4891
4892  /* The first unconsumed operand token.  */
4893  struct mips_operand_token *token;
4894
4895  /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4896  int opnum;
4897
4898  /* The 1-based argument number, for error reporting.  This does not
4899     count elided optional registers, etc..  */
4900  int argnum;
4901
4902  /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4903  unsigned int last_regno;
4904
4905  /* If the first operand was an OP_REG, this is the register that it
4906     specified, otherwise it is ILLEGAL_REG.  */
4907  unsigned int dest_regno;
4908
4909  /* The value of the last OP_INT operand.  Only used for OP_MSB,
4910     where it gives the lsb position.  */
4911  unsigned int last_op_int;
4912
4913  /* If true, match routines should assume that no later instruction
4914     alternative matches and should therefore be as accommodating as
4915     possible.  Match routines should not report errors if something
4916     is only invalid for !LAX_MATCH.  */
4917  bool lax_match;
4918
4919  /* True if a reference to the current AT register was seen.  */
4920  bool seen_at;
4921};
4922
4923/* Record that the argument is out of range.  */
4924
4925static void
4926match_out_of_range (struct mips_arg_info *arg)
4927{
4928  set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4929}
4930
4931/* Record that the argument isn't constant but needs to be.  */
4932
4933static void
4934match_not_constant (struct mips_arg_info *arg)
4935{
4936  set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4937		    arg->argnum);
4938}
4939
4940/* Try to match an OT_CHAR token for character CH.  Consume the token
4941   and return true on success, otherwise return false.  */
4942
4943static bool
4944match_char (struct mips_arg_info *arg, char ch)
4945{
4946  if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4947    {
4948      ++arg->token;
4949      if (ch == ',')
4950	arg->argnum += 1;
4951      return true;
4952    }
4953  return false;
4954}
4955
4956/* Try to get an expression from the next tokens in ARG.  Consume the
4957   tokens and return true on success, storing the expression value in
4958   VALUE and relocation types in R.  */
4959
4960static bool
4961match_expression (struct mips_arg_info *arg, expressionS *value,
4962		  bfd_reloc_code_real_type *r)
4963{
4964  /* If the next token is a '(' that was parsed as being part of a base
4965     expression, assume we have an elided offset.  The later match will fail
4966     if this turns out to be wrong.  */
4967  if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4968    {
4969      value->X_op = O_constant;
4970      value->X_add_number = 0;
4971      r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4972      return true;
4973    }
4974
4975  /* Reject register-based expressions such as "0+$2" and "(($2))".
4976     For plain registers the default error seems more appropriate.  */
4977  if (arg->token->type == OT_INTEGER
4978      && arg->token->u.integer.value.X_op == O_register)
4979    {
4980      set_insn_error (arg->argnum, _("register value used as expression"));
4981      return false;
4982    }
4983
4984  if (arg->token->type == OT_INTEGER)
4985    {
4986      *value = arg->token->u.integer.value;
4987      memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4988      ++arg->token;
4989      return true;
4990    }
4991
4992  set_insn_error_i
4993    (arg->argnum, _("operand %d must be an immediate expression"),
4994     arg->argnum);
4995  return false;
4996}
4997
4998/* Try to get a constant expression from the next tokens in ARG.  Consume
4999   the tokens and return true on success, storing the constant value
5000   in *VALUE.  */
5001
5002static bool
5003match_const_int (struct mips_arg_info *arg, offsetT *value)
5004{
5005  expressionS ex;
5006  bfd_reloc_code_real_type r[3];
5007
5008  if (!match_expression (arg, &ex, r))
5009    return false;
5010
5011  if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
5012    *value = ex.X_add_number;
5013  else
5014    {
5015      if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_big)
5016	match_out_of_range (arg);
5017      else
5018	match_not_constant (arg);
5019      return false;
5020    }
5021  return true;
5022}
5023
5024/* Return the RTYPE_* flags for a register operand of type TYPE that
5025   appears in instruction OPCODE.  */
5026
5027static unsigned int
5028convert_reg_type (const struct mips_opcode *opcode,
5029		  enum mips_reg_operand_type type)
5030{
5031  switch (type)
5032    {
5033    case OP_REG_GP:
5034      return RTYPE_NUM | RTYPE_GP;
5035
5036    case OP_REG_FP:
5037      /* Allow vector register names for MDMX if the instruction is a 64-bit
5038	 FPR load, store or move (including moves to and from GPRs).  */
5039      if ((mips_opts.ase & ASE_MDMX)
5040	  && (opcode->pinfo & FP_D)
5041	  && (opcode->pinfo & (INSN_COPROC_MOVE
5042			       | INSN_COPROC_MEMORY_DELAY
5043			       | INSN_LOAD_COPROC
5044			       | INSN_LOAD_MEMORY
5045			       | INSN_STORE_MEMORY)))
5046	return RTYPE_FPU | RTYPE_VEC;
5047      return RTYPE_FPU;
5048
5049    case OP_REG_CCC:
5050      if (opcode->pinfo & (FP_D | FP_S))
5051	return RTYPE_CCC | RTYPE_FCC;
5052      return RTYPE_CCC;
5053
5054    case OP_REG_VEC:
5055      if (opcode->membership & INSN_5400)
5056	return RTYPE_FPU;
5057      return RTYPE_FPU | RTYPE_VEC;
5058
5059    case OP_REG_ACC:
5060      return RTYPE_ACC;
5061
5062    case OP_REG_COPRO:
5063    case OP_REG_CONTROL:
5064      if (opcode->name[strlen (opcode->name) - 1] == '0')
5065	return RTYPE_NUM | RTYPE_CP0;
5066      return RTYPE_NUM;
5067
5068    case OP_REG_HW:
5069      return RTYPE_NUM;
5070
5071    case OP_REG_VI:
5072      return RTYPE_NUM | RTYPE_VI;
5073
5074    case OP_REG_VF:
5075      return RTYPE_NUM | RTYPE_VF;
5076
5077    case OP_REG_R5900_I:
5078      return RTYPE_R5900_I;
5079
5080    case OP_REG_R5900_Q:
5081      return RTYPE_R5900_Q;
5082
5083    case OP_REG_R5900_R:
5084      return RTYPE_R5900_R;
5085
5086    case OP_REG_R5900_ACC:
5087      return RTYPE_R5900_ACC;
5088
5089    case OP_REG_MSA:
5090      return RTYPE_MSA;
5091
5092    case OP_REG_MSA_CTRL:
5093      return RTYPE_NUM;
5094    }
5095  abort ();
5096}
5097
5098/* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
5099
5100static void
5101check_regno (struct mips_arg_info *arg,
5102	     enum mips_reg_operand_type type, unsigned int regno)
5103{
5104  if (AT && type == OP_REG_GP && regno == AT)
5105    arg->seen_at = true;
5106
5107  if (type == OP_REG_FP
5108      && (regno & 1) != 0
5109      && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
5110    {
5111      /* This was a warning prior to introducing O32 FPXX and FP64 support
5112	 so maintain a warning for FP32 but raise an error for the new
5113	 cases.  */
5114      if (FPR_SIZE == 32)
5115	as_warn (_("float register should be even, was %d"), regno);
5116      else
5117	as_bad (_("float register should be even, was %d"), regno);
5118    }
5119
5120  if (type == OP_REG_CCC)
5121    {
5122      const char *name;
5123      size_t length;
5124
5125      name = arg->insn->insn_mo->name;
5126      length = strlen (name);
5127      if ((regno & 1) != 0
5128	  && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
5129	      || (length >= 5 && startswith (name + length - 5, "any2"))))
5130	as_warn (_("condition code register should be even for %s, was %d"),
5131		 name, regno);
5132
5133      if ((regno & 3) != 0
5134	  && (length >= 5 && startswith (name + length - 5, "any4")))
5135	as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
5136		 name, regno);
5137    }
5138}
5139
5140/* ARG is a register with symbol value SYMVAL.  Try to interpret it as
5141   a register of type TYPE.  Return true on success, storing the register
5142   number in *REGNO and warning about any dubious uses.  */
5143
5144static bool
5145match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5146	     unsigned int symval, unsigned int *regno)
5147{
5148  if (type == OP_REG_VEC)
5149    symval = mips_prefer_vec_regno (symval);
5150  if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
5151    return false;
5152
5153  *regno = symval & RNUM_MASK;
5154  check_regno (arg, type, *regno);
5155  return true;
5156}
5157
5158/* Try to interpret the next token in ARG as a register of type TYPE.
5159   Consume the token and return true on success, storing the register
5160   number in *REGNO.  Return false on failure.  */
5161
5162static bool
5163match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5164	   unsigned int *regno)
5165{
5166  if (arg->token->type == OT_REG
5167      && match_regno (arg, type, arg->token->u.regno, regno))
5168    {
5169      ++arg->token;
5170      return true;
5171    }
5172  return false;
5173}
5174
5175/* Try to interpret the next token in ARG as a range of registers of type TYPE.
5176   Consume the token and return true on success, storing the register numbers
5177   in *REGNO1 and *REGNO2.  Return false on failure.  */
5178
5179static bool
5180match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5181		 unsigned int *regno1, unsigned int *regno2)
5182{
5183  if (match_reg (arg, type, regno1))
5184    {
5185      *regno2 = *regno1;
5186      return true;
5187    }
5188  if (arg->token->type == OT_REG_RANGE
5189      && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5190      && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5191      && *regno1 <= *regno2)
5192    {
5193      ++arg->token;
5194      return true;
5195    }
5196  return false;
5197}
5198
5199/* OP_INT matcher.  */
5200
5201static bool
5202match_int_operand (struct mips_arg_info *arg,
5203		   const struct mips_operand *operand_base)
5204{
5205  const struct mips_int_operand *operand;
5206  unsigned int uval;
5207  int min_val, max_val, factor;
5208  offsetT sval;
5209
5210  operand = (const struct mips_int_operand *) operand_base;
5211  factor = 1 << operand->shift;
5212  min_val = mips_int_operand_min (operand);
5213  max_val = mips_int_operand_max (operand);
5214
5215  if (operand_base->lsb == 0
5216      && operand_base->size == 16
5217      && operand->shift == 0
5218      && operand->bias == 0
5219      && (operand->max_val == 32767 || operand->max_val == 65535))
5220    {
5221      /* The operand can be relocated.  */
5222      if (!match_expression (arg, &offset_expr, offset_reloc))
5223	return false;
5224
5225      if (offset_expr.X_op == O_big)
5226	{
5227	  match_out_of_range (arg);
5228	  return false;
5229	}
5230
5231      if (offset_reloc[0] != BFD_RELOC_UNUSED)
5232	/* Relocation operators were used.  Accept the argument and
5233	   leave the relocation value in offset_expr and offset_relocs
5234	   for the caller to process.  */
5235	return true;
5236
5237      if (offset_expr.X_op != O_constant)
5238	{
5239	  /* Accept non-constant operands if no later alternative matches,
5240	     leaving it for the caller to process.  */
5241	  if (!arg->lax_match)
5242	    {
5243	      match_not_constant (arg);
5244	      return false;
5245	    }
5246	  offset_reloc[0] = BFD_RELOC_LO16;
5247	  return true;
5248	}
5249
5250      /* Clear the global state; we're going to install the operand
5251	 ourselves.  */
5252      sval = offset_expr.X_add_number;
5253      offset_expr.X_op = O_absent;
5254
5255      /* For compatibility with older assemblers, we accept
5256	 0x8000-0xffff as signed 16-bit numbers when only
5257	 signed numbers are allowed.  */
5258      if (sval > max_val)
5259	{
5260	  max_val = ((1 << operand_base->size) - 1) << operand->shift;
5261	  if (!arg->lax_match && sval <= max_val)
5262	    {
5263	      match_out_of_range (arg);
5264	      return false;
5265	    }
5266	}
5267    }
5268  else
5269    {
5270      if (!match_const_int (arg, &sval))
5271	return false;
5272    }
5273
5274  arg->last_op_int = sval;
5275
5276  if (sval < min_val || sval > max_val || sval % factor)
5277    {
5278      match_out_of_range (arg);
5279      return false;
5280    }
5281
5282  uval = (unsigned int) sval >> operand->shift;
5283  uval -= operand->bias;
5284
5285  /* Handle -mfix-cn63xxp1.  */
5286  if (arg->opnum == 1
5287      && mips_fix_cn63xxp1
5288      && !mips_opts.micromips
5289      && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5290    switch (uval)
5291      {
5292      case 5:
5293      case 25:
5294      case 26:
5295      case 27:
5296      case 28:
5297      case 29:
5298      case 30:
5299      case 31:
5300	/* These are ok.  */
5301	break;
5302
5303      default:
5304	/* The rest must be changed to 28.  */
5305	uval = 28;
5306	break;
5307      }
5308
5309  insn_insert_operand (arg->insn, operand_base, uval);
5310  return true;
5311}
5312
5313/* OP_MAPPED_INT matcher.  */
5314
5315static bool
5316match_mapped_int_operand (struct mips_arg_info *arg,
5317			  const struct mips_operand *operand_base)
5318{
5319  const struct mips_mapped_int_operand *operand;
5320  unsigned int uval, num_vals;
5321  offsetT sval;
5322
5323  operand = (const struct mips_mapped_int_operand *) operand_base;
5324  if (!match_const_int (arg, &sval))
5325    return false;
5326
5327  num_vals = 1 << operand_base->size;
5328  for (uval = 0; uval < num_vals; uval++)
5329    if (operand->int_map[uval] == sval)
5330      break;
5331  if (uval == num_vals)
5332    {
5333      match_out_of_range (arg);
5334      return false;
5335    }
5336
5337  insn_insert_operand (arg->insn, operand_base, uval);
5338  return true;
5339}
5340
5341/* OP_MSB matcher.  */
5342
5343static bool
5344match_msb_operand (struct mips_arg_info *arg,
5345		   const struct mips_operand *operand_base)
5346{
5347  const struct mips_msb_operand *operand;
5348  int min_val, max_val, max_high;
5349  offsetT size, sval, high;
5350
5351  operand = (const struct mips_msb_operand *) operand_base;
5352  min_val = operand->bias;
5353  max_val = min_val + (1 << operand_base->size) - 1;
5354  max_high = operand->opsize;
5355
5356  if (!match_const_int (arg, &size))
5357    return false;
5358
5359  high = size + arg->last_op_int;
5360  sval = operand->add_lsb ? high : size;
5361
5362  if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5363    {
5364      match_out_of_range (arg);
5365      return false;
5366    }
5367  insn_insert_operand (arg->insn, operand_base, sval - min_val);
5368  return true;
5369}
5370
5371/* OP_REG matcher.  */
5372
5373static bool
5374match_reg_operand (struct mips_arg_info *arg,
5375		   const struct mips_operand *operand_base)
5376{
5377  const struct mips_reg_operand *operand;
5378  unsigned int regno, uval, num_vals;
5379
5380  operand = (const struct mips_reg_operand *) operand_base;
5381  if (!match_reg (arg, operand->reg_type, &regno))
5382    return false;
5383
5384  if (operand->reg_map)
5385    {
5386      num_vals = 1 << operand->root.size;
5387      for (uval = 0; uval < num_vals; uval++)
5388	if (operand->reg_map[uval] == regno)
5389	  break;
5390      if (num_vals == uval)
5391	return false;
5392    }
5393  else
5394    uval = regno;
5395
5396  arg->last_regno = regno;
5397  if (arg->opnum == 1)
5398    arg->dest_regno = regno;
5399  insn_insert_operand (arg->insn, operand_base, uval);
5400  return true;
5401}
5402
5403/* OP_REG_PAIR matcher.  */
5404
5405static bool
5406match_reg_pair_operand (struct mips_arg_info *arg,
5407			const struct mips_operand *operand_base)
5408{
5409  const struct mips_reg_pair_operand *operand;
5410  unsigned int regno1, regno2, uval, num_vals;
5411
5412  operand = (const struct mips_reg_pair_operand *) operand_base;
5413  if (!match_reg (arg, operand->reg_type, &regno1)
5414      || !match_char (arg, ',')
5415      || !match_reg (arg, operand->reg_type, &regno2))
5416    return false;
5417
5418  num_vals = 1 << operand_base->size;
5419  for (uval = 0; uval < num_vals; uval++)
5420    if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5421      break;
5422  if (uval == num_vals)
5423    return false;
5424
5425  insn_insert_operand (arg->insn, operand_base, uval);
5426  return true;
5427}
5428
5429/* OP_PCREL matcher.  The caller chooses the relocation type.  */
5430
5431static bool
5432match_pcrel_operand (struct mips_arg_info *arg)
5433{
5434  bfd_reloc_code_real_type r[3];
5435
5436  return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5437}
5438
5439/* OP_PERF_REG matcher.  */
5440
5441static bool
5442match_perf_reg_operand (struct mips_arg_info *arg,
5443			const struct mips_operand *operand)
5444{
5445  offsetT sval;
5446
5447  if (!match_const_int (arg, &sval))
5448    return false;
5449
5450  if (sval != 0
5451      && (sval != 1
5452	  || (mips_opts.arch == CPU_R5900
5453	      && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5454		  || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5455    {
5456      set_insn_error (arg->argnum, _("invalid performance register"));
5457      return false;
5458    }
5459
5460  insn_insert_operand (arg->insn, operand, sval);
5461  return true;
5462}
5463
5464/* OP_ADDIUSP matcher.  */
5465
5466static bool
5467match_addiusp_operand (struct mips_arg_info *arg,
5468		       const struct mips_operand *operand)
5469{
5470  offsetT sval;
5471  unsigned int uval;
5472
5473  if (!match_const_int (arg, &sval))
5474    return false;
5475
5476  if (sval % 4)
5477    {
5478      match_out_of_range (arg);
5479      return false;
5480    }
5481
5482  sval /= 4;
5483  if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5484    {
5485      match_out_of_range (arg);
5486      return false;
5487    }
5488
5489  uval = (unsigned int) sval;
5490  uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5491  insn_insert_operand (arg->insn, operand, uval);
5492  return true;
5493}
5494
5495/* OP_CLO_CLZ_DEST matcher.  */
5496
5497static bool
5498match_clo_clz_dest_operand (struct mips_arg_info *arg,
5499			    const struct mips_operand *operand)
5500{
5501  unsigned int regno;
5502
5503  if (!match_reg (arg, OP_REG_GP, &regno))
5504    return false;
5505
5506  insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5507  return true;
5508}
5509
5510/* OP_CHECK_PREV matcher.  */
5511
5512static bool
5513match_check_prev_operand (struct mips_arg_info *arg,
5514			  const struct mips_operand *operand_base)
5515{
5516  const struct mips_check_prev_operand *operand;
5517  unsigned int regno;
5518
5519  operand = (const struct mips_check_prev_operand *) operand_base;
5520
5521  if (!match_reg (arg, OP_REG_GP, &regno))
5522    return false;
5523
5524  if (!operand->zero_ok && regno == 0)
5525    return false;
5526
5527  if ((operand->less_than_ok && regno < arg->last_regno)
5528      || (operand->greater_than_ok && regno > arg->last_regno)
5529      || (operand->equal_ok && regno == arg->last_regno))
5530    {
5531      arg->last_regno = regno;
5532      insn_insert_operand (arg->insn, operand_base, regno);
5533      return true;
5534    }
5535
5536  return false;
5537}
5538
5539/* OP_SAME_RS_RT matcher.  */
5540
5541static bool
5542match_same_rs_rt_operand (struct mips_arg_info *arg,
5543			  const struct mips_operand *operand)
5544{
5545  unsigned int regno;
5546
5547  if (!match_reg (arg, OP_REG_GP, &regno))
5548    return false;
5549
5550  if (regno == 0)
5551    {
5552      set_insn_error (arg->argnum, _("the source register must not be $0"));
5553      return false;
5554    }
5555
5556  arg->last_regno = regno;
5557
5558  insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5559  return true;
5560}
5561
5562/* OP_LWM_SWM_LIST matcher.  */
5563
5564static bool
5565match_lwm_swm_list_operand (struct mips_arg_info *arg,
5566			    const struct mips_operand *operand)
5567{
5568  unsigned int reglist, sregs, ra, regno1, regno2;
5569  struct mips_arg_info reset;
5570
5571  reglist = 0;
5572  if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5573    return false;
5574  do
5575    {
5576      if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5577	{
5578	  reglist |= 1 << FP;
5579	  regno2 = S7;
5580	}
5581      reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5582      reset = *arg;
5583    }
5584  while (match_char (arg, ',')
5585	 && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5586  *arg = reset;
5587
5588  if (operand->size == 2)
5589    {
5590      /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5591
5592	 s0, ra
5593	 s0, s1, ra, s2, s3
5594	 s0-s2, ra
5595
5596	 and any permutations of these.  */
5597      if ((reglist & 0xfff1ffff) != 0x80010000)
5598	return false;
5599
5600      sregs = (reglist >> 17) & 7;
5601      ra = 0;
5602    }
5603  else
5604    {
5605      /* The list must include at least one of ra and s0-sN,
5606	 for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5607	 which are $23 and $30 respectively.)  E.g.:
5608
5609	 ra
5610	 s0
5611	 ra, s0, s1, s2
5612	 s0-s8
5613	 s0-s5, ra
5614
5615	 and any permutations of these.  */
5616      if ((reglist & 0x3f00ffff) != 0)
5617	return false;
5618
5619
5620/* Fix NOP issue: Replace nops by "or at,at,zero".  */
5621      ra = (reglist >> 27) & 0x10;
5622      sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5623    }
5624  sregs += 1;
5625  if ((sregs & -sregs) != sregs)
5626    return false;
5627
5628  insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5629  return true;
5630}
5631
5632static void
5633trap_zero_jump (struct mips_cl_insn * ip)
5634{
5635  if (strcmp (ip->insn_mo->name, "j") == 0
5636      || strcmp (ip->insn_mo->name, "jr") == 0
5637      || strcmp (ip->insn_mo->name, "jalr") == 0)
5638    {
5639      int sreg;
5640
5641      if (mips_opts.warn_about_macros)
5642        return;
5643
5644      sreg = EXTRACT_OPERAND (0, RS, *ip);
5645      if (mips_opts.isa == ISA_MIPS32
5646          || mips_opts.isa == ISA_MIPS32R2
5647          || mips_opts.isa == ISA_MIPS64
5648          || mips_opts.isa == ISA_MIPS64R2)
5649	{
5650	  expressionS ep;
5651	  ep.X_op = O_constant;
5652	  ep.X_add_number = 4096;
5653	  macro_build (&ep, "tltiu", "s,j", sreg, BFD_RELOC_LO16);
5654	}
5655      else if (mips_opts.isa != ISA_UNKNOWN
5656	       && mips_opts.isa != ISA_MIPS1)
5657	macro_build (NULL, "teq", "s,t", sreg, 0);
5658  }
5659}
5660
5661/* OP_ENTRY_EXIT_LIST matcher.  */
5662
5663static unsigned int
5664match_entry_exit_operand (struct mips_arg_info *arg,
5665			  const struct mips_operand *operand)
5666{
5667  unsigned int mask;
5668  bool is_exit;
5669
5670  /* The format is the same for both ENTRY and EXIT, but the constraints
5671     are different.  */
5672  is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5673  mask = (is_exit ? 7 << 3 : 0);
5674  do
5675    {
5676      unsigned int regno1, regno2;
5677      bool is_freg;
5678
5679      if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5680	is_freg = false;
5681      else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5682	is_freg = true;
5683      else
5684	return false;
5685
5686      if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5687	{
5688	  mask &= ~(7 << 3);
5689	  mask |= (5 + regno2) << 3;
5690	}
5691      else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5692	mask |= (regno2 - 3) << 3;
5693      else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5694	mask |= (regno2 - 15) << 1;
5695      else if (regno1 == RA && regno2 == RA)
5696	mask |= 1;
5697      else
5698	return false;
5699    }
5700  while (match_char (arg, ','));
5701
5702  insn_insert_operand (arg->insn, operand, mask);
5703  return true;
5704}
5705
5706/* Encode regular MIPS SAVE/RESTORE instruction operands according to
5707   the argument register mask AMASK, the number of static registers
5708   saved NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5709   respectively, and the frame size FRAME_SIZE.  */
5710
5711static unsigned int
5712mips_encode_save_restore (unsigned int amask, unsigned int nsreg,
5713			  unsigned int ra, unsigned int s0, unsigned int s1,
5714			  unsigned int frame_size)
5715{
5716  return ((nsreg << 23) | ((frame_size & 0xf0) << 15) | (amask << 15)
5717	  | (ra << 12) | (s0 << 11) | (s1 << 10) | ((frame_size & 0xf) << 6));
5718}
5719
5720/* Encode MIPS16 SAVE/RESTORE instruction operands according to the
5721   argument register mask AMASK, the number of static registers saved
5722   NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5723   respectively, and the frame size FRAME_SIZE.  */
5724
5725static unsigned int
5726mips16_encode_save_restore (unsigned int amask, unsigned int nsreg,
5727			    unsigned int ra, unsigned int s0, unsigned int s1,
5728			    unsigned int frame_size)
5729{
5730  unsigned int args;
5731
5732  args = (ra << 6) | (s0 << 5) | (s1 << 4) | (frame_size & 0xf);
5733  if (nsreg || amask || frame_size == 0 || frame_size > 16)
5734    args |= (MIPS16_EXTEND | (nsreg << 24) | (amask << 16)
5735	     | ((frame_size & 0xf0) << 16));
5736  return args;
5737}
5738
5739/* OP_SAVE_RESTORE_LIST matcher.  */
5740
5741static bool
5742match_save_restore_list_operand (struct mips_arg_info *arg)
5743{
5744  unsigned int opcode, args, statics, sregs;
5745  unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5746  unsigned int arg_mask, ra, s0, s1;
5747  offsetT frame_size;
5748
5749  opcode = arg->insn->insn_opcode;
5750  frame_size = 0;
5751  num_frame_sizes = 0;
5752  args = 0;
5753  statics = 0;
5754  sregs = 0;
5755  ra = 0;
5756  s0 = 0;
5757  s1 = 0;
5758  do
5759    {
5760      unsigned int regno1, regno2;
5761
5762      if (arg->token->type == OT_INTEGER)
5763	{
5764	  /* Handle the frame size.  */
5765	  if (!match_const_int (arg, &frame_size))
5766	    return false;
5767	  num_frame_sizes += 1;
5768	}
5769      else
5770	{
5771	  if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5772	    return false;
5773
5774	  while (regno1 <= regno2)
5775	    {
5776	      if (regno1 >= 4 && regno1 <= 7)
5777		{
5778		  if (num_frame_sizes == 0)
5779		    /* args $a0-$a3 */
5780		    args |= 1 << (regno1 - 4);
5781		  else
5782		    /* statics $a0-$a3 */
5783		    statics |= 1 << (regno1 - 4);
5784		}
5785	      else if (regno1 >= 16 && regno1 <= 23)
5786		/* $s0-$s7 */
5787		sregs |= 1 << (regno1 - 16);
5788	      else if (regno1 == 30)
5789		/* $s8 */
5790		sregs |= 1 << 8;
5791	      else if (regno1 == 31)
5792		/* Add $ra to insn.  */
5793		ra = 1;
5794	      else
5795		return false;
5796	      regno1 += 1;
5797	      if (regno1 == 24)
5798		regno1 = 30;
5799	    }
5800	}
5801    }
5802  while (match_char (arg, ','));
5803
5804  /* Encode args/statics combination.  */
5805  if (args & statics)
5806    return false;
5807  else if (args == 0xf)
5808    /* All $a0-$a3 are args.  */
5809    arg_mask = MIPS_SVRS_ALL_ARGS;
5810  else if (statics == 0xf)
5811    /* All $a0-$a3 are statics.  */
5812    arg_mask = MIPS_SVRS_ALL_STATICS;
5813  else
5814    {
5815      /* Count arg registers.  */
5816      num_args = 0;
5817      while (args & 0x1)
5818	{
5819	  args >>= 1;
5820	  num_args += 1;
5821	}
5822      if (args != 0)
5823	return false;
5824
5825      /* Count static registers.  */
5826      num_statics = 0;
5827      while (statics & 0x8)
5828	{
5829	  statics = (statics << 1) & 0xf;
5830	  num_statics += 1;
5831	}
5832      if (statics != 0)
5833	return false;
5834
5835      /* Encode args/statics.  */
5836      arg_mask = (num_args << 2) | num_statics;
5837    }
5838
5839  /* Encode $s0/$s1.  */
5840  if (sregs & (1 << 0))		/* $s0 */
5841    s0 = 1;
5842  if (sregs & (1 << 1))		/* $s1 */
5843    s1 = 1;
5844  sregs >>= 2;
5845
5846  /* Encode $s2-$s8. */
5847  num_sregs = 0;
5848  while (sregs & 1)
5849    {
5850      sregs >>= 1;
5851      num_sregs += 1;
5852    }
5853  if (sregs != 0)
5854    return false;
5855
5856  /* Encode frame size.  */
5857  if (num_frame_sizes == 0)
5858    {
5859      set_insn_error (arg->argnum, _("missing frame size"));
5860      return false;
5861    }
5862  if (num_frame_sizes > 1)
5863    {
5864      set_insn_error (arg->argnum, _("frame size specified twice"));
5865      return false;
5866    }
5867  if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5868    {
5869      set_insn_error (arg->argnum, _("invalid frame size"));
5870      return false;
5871    }
5872  frame_size /= 8;
5873
5874  /* Finally build the instruction.  */
5875  if (mips_opts.mips16)
5876    opcode |= mips16_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5877					  frame_size);
5878  else if (!mips_opts.micromips)
5879    opcode |= mips_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5880					frame_size);
5881  else
5882    abort ();
5883
5884  arg->insn->insn_opcode = opcode;
5885  return true;
5886}
5887
5888/* OP_MDMX_IMM_REG matcher.  */
5889
5890static bool
5891match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5892			    const struct mips_operand *operand)
5893{
5894  unsigned int regno, uval;
5895  bool is_qh;
5896  const struct mips_opcode *opcode;
5897
5898  /* The mips_opcode records whether this is an octobyte or quadhalf
5899     instruction.  Start out with that bit in place.  */
5900  opcode = arg->insn->insn_mo;
5901  uval = mips_extract_operand (operand, opcode->match);
5902  is_qh = (uval != 0);
5903
5904  if (arg->token->type == OT_REG)
5905    {
5906      if ((opcode->membership & INSN_5400)
5907	  && strcmp (opcode->name, "rzu.ob") == 0)
5908	{
5909	  set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5910			    arg->argnum);
5911	  return false;
5912	}
5913
5914      if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5915	return false;
5916      ++arg->token;
5917
5918      /* Check whether this is a vector register or a broadcast of
5919	 a single element.  */
5920      if (arg->token->type == OT_INTEGER_INDEX)
5921	{
5922	  if (arg->token->u.index > (is_qh ? 3 : 7))
5923	    {
5924	      set_insn_error (arg->argnum, _("invalid element selector"));
5925	      return false;
5926	    }
5927	  uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5928	  ++arg->token;
5929	}
5930      else
5931	{
5932	  /* A full vector.  */
5933	  if ((opcode->membership & INSN_5400)
5934	      && (strcmp (opcode->name, "sll.ob") == 0
5935		  || strcmp (opcode->name, "srl.ob") == 0))
5936	    {
5937	      set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5938				arg->argnum);
5939	      return false;
5940	    }
5941
5942	  if (is_qh)
5943	    uval |= MDMX_FMTSEL_VEC_QH << 5;
5944	  else
5945	    uval |= MDMX_FMTSEL_VEC_OB << 5;
5946	}
5947      uval |= regno;
5948    }
5949  else
5950    {
5951      offsetT sval;
5952
5953      if (!match_const_int (arg, &sval))
5954	return false;
5955      if (sval < 0 || sval > 31)
5956	{
5957	  match_out_of_range (arg);
5958	  return false;
5959	}
5960      uval |= (sval & 31);
5961      if (is_qh)
5962	uval |= MDMX_FMTSEL_IMM_QH << 5;
5963      else
5964	uval |= MDMX_FMTSEL_IMM_OB << 5;
5965    }
5966  insn_insert_operand (arg->insn, operand, uval);
5967  return true;
5968}
5969
5970/* OP_IMM_INDEX matcher.  */
5971
5972static bool
5973match_imm_index_operand (struct mips_arg_info *arg,
5974			 const struct mips_operand *operand)
5975{
5976  unsigned int max_val;
5977
5978  if (arg->token->type != OT_INTEGER_INDEX)
5979    return false;
5980
5981  max_val = (1 << operand->size) - 1;
5982  if (arg->token->u.index > max_val)
5983    {
5984      match_out_of_range (arg);
5985      return false;
5986    }
5987  insn_insert_operand (arg->insn, operand, arg->token->u.index);
5988  ++arg->token;
5989  return true;
5990}
5991
5992/* OP_REG_INDEX matcher.  */
5993
5994static bool
5995match_reg_index_operand (struct mips_arg_info *arg,
5996			 const struct mips_operand *operand)
5997{
5998  unsigned int regno;
5999
6000  if (arg->token->type != OT_REG_INDEX)
6001    return false;
6002
6003  if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
6004    return false;
6005
6006  insn_insert_operand (arg->insn, operand, regno);
6007  ++arg->token;
6008  return true;
6009}
6010
6011/* OP_PC matcher.  */
6012
6013static bool
6014match_pc_operand (struct mips_arg_info *arg)
6015{
6016  if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
6017    {
6018      ++arg->token;
6019      return true;
6020    }
6021  return false;
6022}
6023
6024/* OP_REG28 matcher.  */
6025
6026static bool
6027match_reg28_operand (struct mips_arg_info *arg)
6028{
6029  unsigned int regno;
6030
6031  if (arg->token->type == OT_REG
6032      && match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno)
6033      && regno == GP)
6034    {
6035      ++arg->token;
6036      return true;
6037    }
6038  return false;
6039}
6040
6041/* OP_NON_ZERO_REG matcher.  */
6042
6043static bool
6044match_non_zero_reg_operand (struct mips_arg_info *arg,
6045			    const struct mips_operand *operand)
6046{
6047  unsigned int regno;
6048
6049  if (!match_reg (arg, OP_REG_GP, &regno))
6050    return false;
6051
6052  if (regno == 0)
6053    {
6054      set_insn_error (arg->argnum, _("the source register must not be $0"));
6055      return false;
6056    }
6057
6058  arg->last_regno = regno;
6059  insn_insert_operand (arg->insn, operand, regno);
6060  return true;
6061}
6062
6063/* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
6064   register that we need to match.  */
6065
6066static bool
6067match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
6068{
6069  unsigned int regno;
6070
6071  return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
6072}
6073
6074/* Try to match a floating-point constant from ARG for LI.S or LI.D.
6075   LENGTH is the length of the value in bytes (4 for float, 8 for double)
6076   and USING_GPRS says whether the destination is a GPR rather than an FPR.
6077
6078   Return the constant in IMM and OFFSET as follows:
6079
6080   - If the constant should be loaded via memory, set IMM to O_absent and
6081     OFFSET to the memory address.
6082
6083   - Otherwise, if the constant should be loaded into two 32-bit registers,
6084     set IMM to the O_constant to load into the high register and OFFSET
6085     to the corresponding value for the low register.
6086
6087   - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
6088
6089   These constants only appear as the last operand in an instruction,
6090   and every instruction that accepts them in any variant accepts them
6091   in all variants.  This means we don't have to worry about backing out
6092   any changes if the instruction does not match.  We just match
6093   unconditionally and report an error if the constant is invalid.  */
6094
6095static bool
6096match_float_constant (struct mips_arg_info *arg, expressionS *imm,
6097		      expressionS *offset, int length, bool using_gprs)
6098{
6099  char *p;
6100  segT seg, new_seg;
6101  subsegT subseg;
6102  const char *newname;
6103  unsigned char *data;
6104
6105  /* Where the constant is placed is based on how the MIPS assembler
6106     does things:
6107
6108     length == 4 && using_gprs  -- immediate value only
6109     length == 8 && using_gprs  -- .rdata or immediate value
6110     length == 4 && !using_gprs -- .lit4 or immediate value
6111     length == 8 && !using_gprs -- .lit8 or immediate value
6112
6113     The .lit4 and .lit8 sections are only used if permitted by the
6114     -G argument.  */
6115  if (arg->token->type != OT_FLOAT)
6116    {
6117      set_insn_error (arg->argnum, _("floating-point expression required"));
6118      return false;
6119    }
6120
6121  gas_assert (arg->token->u.flt.length == length);
6122  data = arg->token->u.flt.data;
6123  ++arg->token;
6124
6125  /* Handle 32-bit constants for which an immediate value is best.  */
6126  if (length == 4
6127      && (using_gprs
6128	  || g_switch_value < 4
6129	  || (data[0] == 0 && data[1] == 0)
6130	  || (data[2] == 0 && data[3] == 0)))
6131    {
6132      imm->X_op = O_constant;
6133      if (!target_big_endian)
6134	imm->X_add_number = bfd_getl32 (data);
6135      else
6136	imm->X_add_number = bfd_getb32 (data);
6137      offset->X_op = O_absent;
6138      return true;
6139    }
6140
6141  /* Handle 64-bit constants for which an immediate value is best.  */
6142  if (length == 8
6143      && !mips_disable_float_construction
6144      /* Constants can only be constructed in GPRs and copied to FPRs if the
6145	 GPRs are at least as wide as the FPRs or MTHC1 is available.
6146	 Unlike most tests for 32-bit floating-point registers this check
6147	 specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
6148	 permit 64-bit moves without MXHC1.
6149	 Force the constant into memory otherwise.  */
6150      && (using_gprs
6151	  || GPR_SIZE == 64
6152	  || ISA_HAS_MXHC1 (mips_opts.isa)
6153	  || FPR_SIZE == 32)
6154      && ((data[0] == 0 && data[1] == 0)
6155	  || (data[2] == 0 && data[3] == 0))
6156      && ((data[4] == 0 && data[5] == 0)
6157	  || (data[6] == 0 && data[7] == 0)))
6158    {
6159      /* The value is simple enough to load with a couple of instructions.
6160	 If using 32-bit registers, set IMM to the high order 32 bits and
6161	 OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
6162	 64 bit constant.  */
6163      if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
6164	{
6165	  imm->X_op = O_constant;
6166	  offset->X_op = O_constant;
6167	  if (!target_big_endian)
6168	    {
6169	      imm->X_add_number = bfd_getl32 (data + 4);
6170	      offset->X_add_number = bfd_getl32 (data);
6171	    }
6172	  else
6173	    {
6174	      imm->X_add_number = bfd_getb32 (data);
6175	      offset->X_add_number = bfd_getb32 (data + 4);
6176	    }
6177	  if (offset->X_add_number == 0)
6178	    offset->X_op = O_absent;
6179	}
6180      else
6181	{
6182	  imm->X_op = O_constant;
6183	  if (!target_big_endian)
6184	    imm->X_add_number = bfd_getl64 (data);
6185	  else
6186	    imm->X_add_number = bfd_getb64 (data);
6187	  offset->X_op = O_absent;
6188	}
6189      return true;
6190    }
6191
6192  /* Switch to the right section.  */
6193  seg = now_seg;
6194  subseg = now_subseg;
6195  if (length == 4)
6196    {
6197      gas_assert (!using_gprs && g_switch_value >= 4);
6198      newname = ".lit4";
6199    }
6200  else
6201    {
6202      if (using_gprs || g_switch_value < 8)
6203	newname = RDATA_SECTION_NAME;
6204      else
6205	newname = ".lit8";
6206    }
6207
6208  new_seg = subseg_new (newname, (subsegT) 0);
6209  bfd_set_section_flags (new_seg,
6210			 SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
6211  frag_align (length == 4 ? 2 : 3, 0, 0);
6212  if (!startswith (TARGET_OS, "elf"))
6213    record_alignment (new_seg, 4);
6214  else
6215    record_alignment (new_seg, length == 4 ? 2 : 3);
6216  if (seg == now_seg)
6217    as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
6218
6219  /* Set the argument to the current address in the section.  */
6220  imm->X_op = O_absent;
6221  offset->X_op = O_symbol;
6222  offset->X_add_symbol = symbol_temp_new_now ();
6223  offset->X_add_number = 0;
6224
6225  /* Put the floating point number into the section.  */
6226  p = frag_more (length);
6227  memcpy (p, data, length);
6228
6229  /* Switch back to the original section.  */
6230  subseg_set (seg, subseg);
6231  return true;
6232}
6233
6234/* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
6235   them.  */
6236
6237static bool
6238match_vu0_suffix_operand (struct mips_arg_info *arg,
6239			  const struct mips_operand *operand,
6240			  bool match_p)
6241{
6242  unsigned int uval;
6243
6244  /* The operand can be an XYZW mask or a single 2-bit channel index
6245     (with X being 0).  */
6246  gas_assert (operand->size == 2 || operand->size == 4);
6247
6248  /* The suffix can be omitted when it is already part of the opcode.  */
6249  if (arg->token->type != OT_CHANNELS)
6250    return match_p;
6251
6252  uval = arg->token->u.channels;
6253  if (operand->size == 2)
6254    {
6255      /* Check that a single bit is set and convert it into a 2-bit index.  */
6256      if ((uval & -uval) != uval)
6257	return false;
6258      uval = 4 - ffs (uval);
6259    }
6260
6261  if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6262    return false;
6263
6264  ++arg->token;
6265  if (!match_p)
6266    insn_insert_operand (arg->insn, operand, uval);
6267  return true;
6268}
6269
6270/* Try to match a token from ARG against OPERAND.  Consume the token
6271   and return true on success, otherwise return false.  */
6272
6273static bool
6274match_operand (struct mips_arg_info *arg,
6275	       const struct mips_operand *operand)
6276{
6277  switch (operand->type)
6278    {
6279    case OP_INT:
6280      return match_int_operand (arg, operand);
6281
6282    case OP_MAPPED_INT:
6283      return match_mapped_int_operand (arg, operand);
6284
6285    case OP_MSB:
6286      return match_msb_operand (arg, operand);
6287
6288    case OP_REG:
6289    case OP_OPTIONAL_REG:
6290      return match_reg_operand (arg, operand);
6291
6292    case OP_REG_PAIR:
6293      return match_reg_pair_operand (arg, operand);
6294
6295    case OP_PCREL:
6296      return match_pcrel_operand (arg);
6297
6298    case OP_PERF_REG:
6299      return match_perf_reg_operand (arg, operand);
6300
6301    case OP_ADDIUSP_INT:
6302      return match_addiusp_operand (arg, operand);
6303
6304    case OP_CLO_CLZ_DEST:
6305      return match_clo_clz_dest_operand (arg, operand);
6306
6307    case OP_LWM_SWM_LIST:
6308      return match_lwm_swm_list_operand (arg, operand);
6309
6310    case OP_ENTRY_EXIT_LIST:
6311      return match_entry_exit_operand (arg, operand);
6312
6313    case OP_SAVE_RESTORE_LIST:
6314      return match_save_restore_list_operand (arg);
6315
6316    case OP_MDMX_IMM_REG:
6317      return match_mdmx_imm_reg_operand (arg, operand);
6318
6319    case OP_REPEAT_DEST_REG:
6320      return match_tied_reg_operand (arg, arg->dest_regno);
6321
6322    case OP_REPEAT_PREV_REG:
6323      return match_tied_reg_operand (arg, arg->last_regno);
6324
6325    case OP_PC:
6326      return match_pc_operand (arg);
6327
6328    case OP_REG28:
6329      return match_reg28_operand (arg);
6330
6331    case OP_VU0_SUFFIX:
6332      return match_vu0_suffix_operand (arg, operand, false);
6333
6334    case OP_VU0_MATCH_SUFFIX:
6335      return match_vu0_suffix_operand (arg, operand, true);
6336
6337    case OP_IMM_INDEX:
6338      return match_imm_index_operand (arg, operand);
6339
6340    case OP_REG_INDEX:
6341      return match_reg_index_operand (arg, operand);
6342
6343    case OP_SAME_RS_RT:
6344      return match_same_rs_rt_operand (arg, operand);
6345
6346    case OP_CHECK_PREV:
6347      return match_check_prev_operand (arg, operand);
6348
6349    case OP_NON_ZERO_REG:
6350      return match_non_zero_reg_operand (arg, operand);
6351    }
6352  abort ();
6353}
6354
6355/* ARG is the state after successfully matching an instruction.
6356   Issue any queued-up warnings.  */
6357
6358static void
6359check_completed_insn (struct mips_arg_info *arg)
6360{
6361  if (arg->seen_at)
6362    {
6363      if (AT == ATREG)
6364	as_warn (_("used $at without \".set noat\""));
6365      else
6366	as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6367    }
6368}
6369
6370/* Return true if modifying general-purpose register REG needs a delay.  */
6371
6372static bool
6373reg_needs_delay (unsigned int reg)
6374{
6375  unsigned long prev_pinfo;
6376
6377  prev_pinfo = history[0].insn_mo->pinfo;
6378  if (!mips_opts.noreorder
6379      && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6380	  || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6381      && (gpr_write_mask (&history[0]) & (1 << reg)))
6382    return true;
6383
6384  return false;
6385}
6386
6387/* Classify an instruction according to the FIX_VR4120_* enumeration.
6388   Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6389   by VR4120 errata.  */
6390
6391static unsigned int
6392classify_vr4120_insn (const char *name)
6393{
6394  if (startswith (name, "macc"))
6395    return FIX_VR4120_MACC;
6396  if (startswith (name, "dmacc"))
6397    return FIX_VR4120_DMACC;
6398  if (startswith (name, "mult"))
6399    return FIX_VR4120_MULT;
6400  if (startswith (name, "dmult"))
6401    return FIX_VR4120_DMULT;
6402  if (strstr (name, "div"))
6403    return FIX_VR4120_DIV;
6404  if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6405    return FIX_VR4120_MTHILO;
6406  return NUM_FIX_VR4120_CLASSES;
6407}
6408
6409#define INSN_ERET	0x42000018
6410#define INSN_DERET	0x4200001f
6411#define INSN_DMULT	0x1c
6412#define INSN_DMULTU	0x1d
6413
6414/* Return the number of instructions that must separate INSN1 and INSN2,
6415   where INSN1 is the earlier instruction.  Return the worst-case value
6416   for any INSN2 if INSN2 is null.  */
6417
6418static unsigned int
6419insns_between (const struct mips_cl_insn *insn1,
6420	       const struct mips_cl_insn *insn2)
6421{
6422  unsigned long pinfo1, pinfo2;
6423  unsigned int mask;
6424
6425  /* If INFO2 is null, pessimistically assume that all flags are set for
6426     the second instruction.  */
6427  pinfo1 = insn1->insn_mo->pinfo;
6428  pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6429
6430  /* For most targets, write-after-read dependencies on the HI and LO
6431     registers must be separated by at least two instructions.  */
6432  if (!hilo_interlocks)
6433    {
6434      if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6435	return 2;
6436      if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6437	return 2;
6438    }
6439
6440  /* If we're working around r7000 errata, there must be two instructions
6441     between an mfhi or mflo and any instruction that uses the result.  */
6442  if (mips_7000_hilo_fix
6443      && !mips_opts.micromips
6444      && MF_HILO_INSN (pinfo1)
6445      && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6446    return 2;
6447
6448  /* If we're working around 24K errata, one instruction is required
6449     if an ERET or DERET is followed by a branch instruction.  */
6450  if (mips_fix_24k && !mips_opts.micromips)
6451    {
6452      if (insn1->insn_opcode == INSN_ERET
6453	  || insn1->insn_opcode == INSN_DERET)
6454	{
6455	  if (insn2 == NULL
6456	      || insn2->insn_opcode == INSN_ERET
6457	      || insn2->insn_opcode == INSN_DERET
6458	      || delayed_branch_p (insn2))
6459	    return 1;
6460	}
6461    }
6462
6463  /* If we're working around PMC RM7000 errata, there must be three
6464     nops between a dmult and a load instruction.  */
6465  if (mips_fix_rm7000 && !mips_opts.micromips)
6466    {
6467      if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6468	  || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6469	{
6470	  if (pinfo2 & INSN_LOAD_MEMORY)
6471	   return 3;
6472	}
6473    }
6474
6475  /* If working around VR4120 errata, check for combinations that need
6476     a single intervening instruction.  */
6477  if (mips_fix_vr4120 && !mips_opts.micromips)
6478    {
6479      unsigned int class1, class2;
6480
6481      class1 = classify_vr4120_insn (insn1->insn_mo->name);
6482      if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6483	{
6484	  if (insn2 == NULL)
6485	    return 1;
6486	  class2 = classify_vr4120_insn (insn2->insn_mo->name);
6487	  if (vr4120_conflicts[class1] & (1 << class2))
6488	    return 1;
6489	}
6490    }
6491
6492  if (!HAVE_CODE_COMPRESSION)
6493    {
6494      /* Check for GPR or coprocessor load delays.  All such delays
6495	 are on the RT register.  */
6496      /* Itbl support may require additional care here.  */
6497      if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6498	  || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6499	{
6500	  if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6501	    return 1;
6502	}
6503
6504      /* Check for generic coprocessor hazards.
6505
6506	 This case is not handled very well.  There is no special
6507	 knowledge of CP0 handling, and the coprocessors other than
6508	 the floating point unit are not distinguished at all.  */
6509      /* Itbl support may require additional care here. FIXME!
6510	 Need to modify this to include knowledge about
6511	 user specified delays!  */
6512      if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6513	 || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6514	{
6515	  /* Handle cases where INSN1 writes to a known general coprocessor
6516	     register.  There must be a one instruction delay before INSN2
6517	     if INSN2 reads that register, otherwise no delay is needed.  */
6518	  mask = fpr_write_mask (insn1);
6519	  if (mask != 0)
6520	    {
6521	      if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6522		return 1;
6523	    }
6524	  else
6525	    {
6526	      /* Read-after-write dependencies on the control registers
6527		 require a two-instruction gap.  */
6528	      if ((pinfo1 & INSN_WRITE_COND_CODE)
6529		  && (pinfo2 & INSN_READ_COND_CODE))
6530		return 2;
6531
6532	      /* We don't know exactly what INSN1 does.  If INSN2 is
6533		 also a coprocessor instruction, assume there must be
6534		 a one instruction gap.  */
6535	      if (pinfo2 & INSN_COP)
6536		return 1;
6537	    }
6538	}
6539
6540      /* Check for read-after-write dependencies on the coprocessor
6541	 control registers in cases where INSN1 does not need a general
6542	 coprocessor delay.  This means that INSN1 is a floating point
6543	 comparison instruction.  */
6544      /* Itbl support may require additional care here.  */
6545      else if (!cop_interlocks
6546	       && (pinfo1 & INSN_WRITE_COND_CODE)
6547	       && (pinfo2 & INSN_READ_COND_CODE))
6548	return 1;
6549    }
6550
6551  /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6552     CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6553     and pause.  */
6554  if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6555      && ((pinfo2 & INSN_NO_DELAY_SLOT)
6556	  || (insn2 && delayed_branch_p (insn2))))
6557    return 1;
6558
6559  return 0;
6560}
6561
6562/* Return the number of nops that would be needed to work around the
6563   VR4130 mflo/mfhi errata if instruction INSN immediately followed
6564   the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6565   that are contained within the first IGNORE instructions of HIST.  */
6566
6567static int
6568nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6569		 const struct mips_cl_insn *insn)
6570{
6571  int i, j;
6572  unsigned int mask;
6573
6574  /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6575     are not affected by the errata.  */
6576  if (insn != 0
6577      && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6578	  || strcmp (insn->insn_mo->name, "mtlo") == 0
6579	  || strcmp (insn->insn_mo->name, "mthi") == 0))
6580    return 0;
6581
6582  /* Search for the first MFLO or MFHI.  */
6583  for (i = 0; i < MAX_VR4130_NOPS; i++)
6584    if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6585      {
6586	/* Extract the destination register.  */
6587	mask = gpr_write_mask (&hist[i]);
6588
6589	/* No nops are needed if INSN reads that register.  */
6590	if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6591	  return 0;
6592
6593	/* ...or if any of the intervening instructions do.  */
6594	for (j = 0; j < i; j++)
6595	  if (gpr_read_mask (&hist[j]) & mask)
6596	    return 0;
6597
6598	if (i >= ignore)
6599	  return MAX_VR4130_NOPS - i;
6600      }
6601  return 0;
6602}
6603
6604#define BASE_REG_EQ(INSN1, INSN2)	\
6605  ((((INSN1) >> OP_SH_RS) & OP_MASK_RS)	\
6606      == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6607
6608/* Return the minimum alignment for this store instruction.  */
6609
6610static int
6611fix_24k_align_to (const struct mips_opcode *mo)
6612{
6613  if (strcmp (mo->name, "sh") == 0)
6614    return 2;
6615
6616  if (strcmp (mo->name, "swc1") == 0
6617      || strcmp (mo->name, "swc2") == 0
6618      || strcmp (mo->name, "sw") == 0
6619      || strcmp (mo->name, "sc") == 0
6620      || strcmp (mo->name, "s.s") == 0)
6621    return 4;
6622
6623  if (strcmp (mo->name, "sdc1") == 0
6624      || strcmp (mo->name, "sdc2") == 0
6625      || strcmp (mo->name, "s.d") == 0)
6626    return 8;
6627
6628  /* sb, swl, swr */
6629  return 1;
6630}
6631
6632struct fix_24k_store_info
6633  {
6634    /* Immediate offset, if any, for this store instruction.  */
6635    short off;
6636    /* Alignment required by this store instruction.  */
6637    int align_to;
6638    /* True for register offsets.  */
6639    int register_offset;
6640  };
6641
6642/* Comparison function used by qsort.  */
6643
6644static int
6645fix_24k_sort (const void *a, const void *b)
6646{
6647  const struct fix_24k_store_info *pos1 = a;
6648  const struct fix_24k_store_info *pos2 = b;
6649
6650  return (pos1->off - pos2->off);
6651}
6652
6653/* INSN is a store instruction.  Try to record the store information
6654   in STINFO.  Return false if the information isn't known.  */
6655
6656static bool
6657fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6658			   const struct mips_cl_insn *insn)
6659{
6660  /* The instruction must have a known offset.  */
6661  if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6662    return false;
6663
6664  stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6665  stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6666  return true;
6667}
6668
6669/* Return the number of nops that would be needed to work around the 24k
6670   "lost data on stores during refill" errata if instruction INSN
6671   immediately followed the 2 instructions described by HIST.
6672   Ignore hazards that are contained within the first IGNORE
6673   instructions of HIST.
6674
6675   Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6676   for the data cache refills and store data. The following describes
6677   the scenario where the store data could be lost.
6678
6679   * A data cache miss, due to either a load or a store, causing fill
6680     data to be supplied by the memory subsystem
6681   * The first three doublewords of fill data are returned and written
6682     into the cache
6683   * A sequence of four stores occurs in consecutive cycles around the
6684     final doubleword of the fill:
6685   * Store A
6686   * Store B
6687   * Store C
6688   * Zero, One or more instructions
6689   * Store D
6690
6691   The four stores A-D must be to different doublewords of the line that
6692   is being filled. The fourth instruction in the sequence above permits
6693   the fill of the final doubleword to be transferred from the FSB into
6694   the cache. In the sequence above, the stores may be either integer
6695   (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6696   swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6697   different doublewords on the line. If the floating point unit is
6698   running in 1:2 mode, it is not possible to create the sequence above
6699   using only floating point store instructions.
6700
6701   In this case, the cache line being filled is incorrectly marked
6702   invalid, thereby losing the data from any store to the line that
6703   occurs between the original miss and the completion of the five
6704   cycle sequence shown above.
6705
6706   The workarounds are:
6707
6708   * Run the data cache in write-through mode.
6709   * Insert a non-store instruction between
6710     Store A and Store B or Store B and Store C.  */
6711
6712static int
6713nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6714	      const struct mips_cl_insn *insn)
6715{
6716  struct fix_24k_store_info pos[3];
6717  int align, i, base_offset;
6718
6719  if (ignore >= 2)
6720    return 0;
6721
6722  /* If the previous instruction wasn't a store, there's nothing to
6723     worry about.  */
6724  if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6725    return 0;
6726
6727  /* If the instructions after the previous one are unknown, we have
6728     to assume the worst.  */
6729  if (!insn)
6730    return 1;
6731
6732  /* Check whether we are dealing with three consecutive stores.  */
6733  if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6734      || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6735    return 0;
6736
6737  /* If we don't know the relationship between the store addresses,
6738     assume the worst.  */
6739  if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6740      || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6741    return 1;
6742
6743  if (!fix_24k_record_store_info (&pos[0], insn)
6744      || !fix_24k_record_store_info (&pos[1], &hist[0])
6745      || !fix_24k_record_store_info (&pos[2], &hist[1]))
6746    return 1;
6747
6748  qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6749
6750  /* Pick a value of ALIGN and X such that all offsets are adjusted by
6751     X bytes and such that the base register + X is known to be aligned
6752     to align bytes.  */
6753
6754  if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6755    align = 8;
6756  else
6757    {
6758      align = pos[0].align_to;
6759      base_offset = pos[0].off;
6760      for (i = 1; i < 3; i++)
6761	if (align < pos[i].align_to)
6762	  {
6763	    align = pos[i].align_to;
6764	    base_offset = pos[i].off;
6765	  }
6766      for (i = 0; i < 3; i++)
6767	pos[i].off -= base_offset;
6768    }
6769
6770  pos[0].off &= ~align + 1;
6771  pos[1].off &= ~align + 1;
6772  pos[2].off &= ~align + 1;
6773
6774  /* If any two stores write to the same chunk, they also write to the
6775     same doubleword.  The offsets are still sorted at this point.  */
6776  if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6777    return 0;
6778
6779  /* A range of at least 9 bytes is needed for the stores to be in
6780     non-overlapping doublewords.  */
6781  if (pos[2].off - pos[0].off <= 8)
6782    return 0;
6783
6784  if (pos[2].off - pos[1].off >= 24
6785      || pos[1].off - pos[0].off >= 24
6786      || pos[2].off - pos[0].off >= 32)
6787    return 0;
6788
6789  return 1;
6790}
6791
6792/* Return the number of nops that would be needed if instruction INSN
6793   immediately followed the MAX_NOPS instructions given by HIST,
6794   where HIST[0] is the most recent instruction.  Ignore hazards
6795   between INSN and the first IGNORE instructions in HIST.
6796
6797   If INSN is null, return the worse-case number of nops for any
6798   instruction.  */
6799
6800static int
6801nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6802	       const struct mips_cl_insn *insn)
6803{
6804  int i, nops, tmp_nops;
6805
6806  nops = 0;
6807  for (i = ignore; i < MAX_DELAY_NOPS; i++)
6808    {
6809      tmp_nops = insns_between (hist + i, insn) - i;
6810      if (tmp_nops > nops)
6811	nops = tmp_nops;
6812    }
6813
6814  if (mips_fix_vr4130 && !mips_opts.micromips)
6815    {
6816      tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6817      if (tmp_nops > nops)
6818	nops = tmp_nops;
6819    }
6820
6821  if (mips_fix_24k && !mips_opts.micromips)
6822    {
6823      tmp_nops = nops_for_24k (ignore, hist, insn);
6824      if (tmp_nops > nops)
6825	nops = tmp_nops;
6826    }
6827
6828  return nops;
6829}
6830
6831/* The variable arguments provide NUM_INSNS extra instructions that
6832   might be added to HIST.  Return the largest number of nops that
6833   would be needed after the extended sequence, ignoring hazards
6834   in the first IGNORE instructions.  */
6835
6836static int
6837nops_for_sequence (int num_insns, int ignore,
6838		   const struct mips_cl_insn *hist, ...)
6839{
6840  va_list args;
6841  struct mips_cl_insn buffer[MAX_NOPS];
6842  struct mips_cl_insn *cursor;
6843  int nops;
6844
6845  va_start (args, hist);
6846  cursor = buffer + num_insns;
6847  memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6848  while (cursor > buffer)
6849    *--cursor = *va_arg (args, const struct mips_cl_insn *);
6850
6851  nops = nops_for_insn (ignore, buffer, NULL);
6852  va_end (args);
6853  return nops;
6854}
6855
6856/* Like nops_for_insn, but if INSN is a branch, take into account the
6857   worst-case delay for the branch target.  */
6858
6859static int
6860nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6861			 const struct mips_cl_insn *insn)
6862{
6863  int nops, tmp_nops;
6864
6865  nops = nops_for_insn (ignore, hist, insn);
6866  if (delayed_branch_p (insn))
6867    {
6868      tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6869				    hist, insn, get_delay_slot_nop (insn));
6870      if (tmp_nops > nops)
6871	nops = tmp_nops;
6872    }
6873  else if (compact_branch_p (insn))
6874    {
6875      tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6876      if (tmp_nops > nops)
6877	nops = tmp_nops;
6878    }
6879  return nops;
6880}
6881
6882/* Fix NOP issue: Replace nops by "or at,at,zero".  */
6883
6884static void
6885fix_loongson2f_nop (struct mips_cl_insn * ip)
6886{
6887  gas_assert (!HAVE_CODE_COMPRESSION);
6888  if (strcmp (ip->insn_mo->name, "nop") == 0)
6889    ip->insn_opcode = LOONGSON2F_NOP_INSN;
6890}
6891
6892/* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6893                   jr target pc &= 'hffff_ffff_cfff_ffff.  */
6894
6895static void
6896fix_loongson2f_jump (struct mips_cl_insn * ip)
6897{
6898  gas_assert (!HAVE_CODE_COMPRESSION);
6899  if (strcmp (ip->insn_mo->name, "j") == 0
6900      || strcmp (ip->insn_mo->name, "jr") == 0
6901      || strcmp (ip->insn_mo->name, "jalr") == 0)
6902    {
6903      int sreg;
6904      expressionS ep;
6905
6906      if (! mips_opts.at)
6907        return;
6908
6909      sreg = EXTRACT_OPERAND (0, RS, *ip);
6910      if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6911        return;
6912
6913      ep.X_op = O_constant;
6914      ep.X_add_number = 0xcfff0000;
6915      macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6916      ep.X_add_number = 0xffff;
6917      macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6918      macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6919    }
6920}
6921
6922static void
6923fix_loongson2f (struct mips_cl_insn * ip)
6924{
6925  if (mips_fix_loongson2f_nop)
6926    fix_loongson2f_nop (ip);
6927
6928  if (mips_fix_loongson2f_jump)
6929    fix_loongson2f_jump (ip);
6930}
6931
6932static bool
6933has_label_name (const char *arr[], size_t len ,const char *s)
6934{
6935  unsigned long i;
6936  for (i = 0; i < len; i++)
6937    {
6938      if (!arr[i])
6939	return false;
6940      if (streq (arr[i], s))
6941	return true;
6942    }
6943  return false;
6944}
6945
6946/* Fix loongson3 llsc errata: Insert sync before ll/lld.  */
6947
6948static void
6949fix_loongson3_llsc (struct mips_cl_insn * ip)
6950{
6951  gas_assert (!HAVE_CODE_COMPRESSION);
6952
6953  /* If is an local label and the insn is not sync,
6954     look forward that whether an branch between ll/sc jump to here
6955     if so, insert a sync.  */
6956  if (seg_info (now_seg)->label_list
6957      && S_IS_LOCAL (seg_info (now_seg)->label_list->label)
6958      && (strcmp (ip->insn_mo->name, "sync") != 0))
6959    {
6960      unsigned long i;
6961      valueT label_value;
6962      const char *label_names[MAX_LABELS_SAME];
6963      const char *label_name;
6964
6965      label_name = S_GET_NAME (seg_info (now_seg)->label_list->label);
6966      label_names[0] = label_name;
6967      struct insn_label_list *llist = seg_info (now_seg)->label_list;
6968      label_value = S_GET_VALUE (llist->label);
6969
6970      for (i = 1; i < MAX_LABELS_SAME; i++)
6971	{
6972	  llist = llist->next;
6973	  if (!llist)
6974	    break;
6975	  if (S_GET_VALUE (llist->label) == label_value)
6976	    label_names[i] = S_GET_NAME (llist->label);
6977	  else
6978	    break;
6979	}
6980      for (; i < MAX_LABELS_SAME; i++)
6981	label_names[i] = NULL;
6982
6983      unsigned long lookback = ARRAY_SIZE (history);
6984      for (i = 0; i < lookback; i++)
6985	{
6986	  if (streq (history[i].insn_mo->name, "ll")
6987	      || streq (history[i].insn_mo->name, "lld"))
6988	    break;
6989
6990	  if (streq (history[i].insn_mo->name, "sc")
6991	      || streq (history[i].insn_mo->name, "scd"))
6992	    {
6993	      unsigned long j;
6994
6995	      for (j = i + 1; j < lookback; j++)
6996		{
6997		  if (streq (history[i].insn_mo->name, "ll")
6998		      || streq (history[i].insn_mo->name, "lld"))
6999		    break;
7000
7001		  if (delayed_branch_p (&history[j]))
7002		    {
7003		      if (has_label_name (label_names,
7004					  MAX_LABELS_SAME,
7005					  history[j].target))
7006			{
7007			  add_fixed_insn (&sync_insn);
7008			  insert_into_history (0, 1, &sync_insn);
7009			  i = lookback;
7010			  break;
7011			}
7012		    }
7013		}
7014	    }
7015	}
7016    }
7017  /* If we find a sc, we look forward to look for an branch insn,
7018     and see whether it jump back and out of ll/sc.  */
7019  else if (streq (ip->insn_mo->name, "sc") || streq (ip->insn_mo->name, "scd"))
7020    {
7021      unsigned long lookback = ARRAY_SIZE (history) - 1;
7022      unsigned long i;
7023
7024      for (i = 0; i < lookback; i++)
7025	{
7026	  if (streq (history[i].insn_mo->name, "ll")
7027	      || streq (history[i].insn_mo->name, "lld"))
7028	    break;
7029
7030	  if (delayed_branch_p (&history[i]))
7031	    {
7032	      unsigned long j;
7033
7034	      for (j = i + 1; j < lookback; j++)
7035		{
7036		  if (streq (history[j].insn_mo->name, "ll")
7037		      || streq (history[i].insn_mo->name, "lld"))
7038		    break;
7039		}
7040
7041	      for (; j < lookback; j++)
7042		{
7043		  if (history[j].label[0] != '\0'
7044		      && streq (history[j].label, history[i].target)
7045		      && strcmp (history[j+1].insn_mo->name, "sync") != 0)
7046		    {
7047		      add_fixed_insn (&sync_insn);
7048		      insert_into_history (++j, 1, &sync_insn);
7049		    }
7050		}
7051	    }
7052	}
7053    }
7054
7055  /* Skip if there is a sync before ll/lld.  */
7056  if ((strcmp (ip->insn_mo->name, "ll") == 0
7057       || strcmp (ip->insn_mo->name, "lld") == 0)
7058      && (strcmp (history[0].insn_mo->name, "sync") != 0))
7059    {
7060      add_fixed_insn (&sync_insn);
7061      insert_into_history (0, 1, &sync_insn);
7062    }
7063}
7064
7065/* IP is a branch that has a delay slot, and we need to fill it
7066   automatically.   Return true if we can do that by swapping IP
7067   with the previous instruction.
7068   ADDRESS_EXPR is an operand of the instruction to be used with
7069   RELOC_TYPE.  */
7070
7071static bool
7072can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
7073		   bfd_reloc_code_real_type *reloc_type)
7074{
7075  unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
7076  unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
7077  unsigned int fpr_read, prev_fpr_write;
7078
7079  /* -O2 and above is required for this optimization.  */
7080  if (mips_optimize < 2)
7081    return false;
7082
7083  /* If we have seen .set volatile or .set nomove, don't optimize.  */
7084  if (mips_opts.nomove)
7085    return false;
7086
7087  /* We can't swap if the previous instruction's position is fixed.  */
7088  if (history[0].fixed_p)
7089    return false;
7090
7091  /* If the previous previous insn was in a .set noreorder, we can't
7092     swap.  Actually, the MIPS assembler will swap in this situation.
7093     However, gcc configured -with-gnu-as will generate code like
7094
7095	.set	noreorder
7096	lw	$4,XXX
7097	.set	reorder
7098	INSN
7099	bne	$4,$0,foo
7100
7101     in which we can not swap the bne and INSN.  If gcc is not configured
7102     -with-gnu-as, it does not output the .set pseudo-ops.  */
7103  if (history[1].noreorder_p)
7104    return false;
7105
7106  /* If the previous instruction had a fixup in mips16 mode, we can not swap.
7107     This means that the previous instruction was a 4-byte one anyhow.  */
7108  if (mips_opts.mips16 && history[0].fixp[0])
7109    return false;
7110
7111  if (mips_fix_loongson2f)
7112    fix_loongson2f (ip);
7113  if (mips_trap_zero_jump)
7114    trap_zero_jump (ip);
7115
7116  /* If the branch is itself the target of a branch, we can not swap.
7117     We cheat on this; all we check for is whether there is a label on
7118     this instruction.  If there are any branches to anything other than
7119     a label, users must use .set noreorder.  */
7120  if (seg_info (now_seg)->label_list)
7121    return false;
7122
7123  /* If the previous instruction is in a variant frag other than this
7124     branch's one, we cannot do the swap.  This does not apply to
7125     MIPS16 code, which uses variant frags for different purposes.  */
7126  if (!mips_opts.mips16
7127      && history[0].frag
7128      && history[0].frag->fr_type == rs_machine_dependent)
7129    return false;
7130
7131  /* We do not swap with instructions that cannot architecturally
7132     be placed in a branch delay slot, such as SYNC or ERET.  We
7133     also refrain from swapping with a trap instruction, since it
7134     complicates trap handlers to have the trap instruction be in
7135     a delay slot.  */
7136  prev_pinfo = history[0].insn_mo->pinfo;
7137  if (prev_pinfo & INSN_NO_DELAY_SLOT)
7138    return false;
7139
7140  /* Check for conflicts between the branch and the instructions
7141     before the candidate delay slot.  */
7142  if (nops_for_insn (0, history + 1, ip) > 0)
7143    return false;
7144
7145  /* Check for conflicts between the swapped sequence and the
7146     target of the branch.  */
7147  if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
7148    return false;
7149
7150  /* If the branch reads a register that the previous
7151     instruction sets, we can not swap.  */
7152  gpr_read = gpr_read_mask (ip);
7153  prev_gpr_write = gpr_write_mask (&history[0]);
7154  if (gpr_read & prev_gpr_write)
7155    return false;
7156
7157  fpr_read = fpr_read_mask (ip);
7158  prev_fpr_write = fpr_write_mask (&history[0]);
7159  if (fpr_read & prev_fpr_write)
7160    return false;
7161
7162  /* If the branch writes a register that the previous
7163     instruction sets, we can not swap.  */
7164  gpr_write = gpr_write_mask (ip);
7165  if (gpr_write & prev_gpr_write)
7166    return false;
7167
7168  /* If the branch writes a register that the previous
7169     instruction reads, we can not swap.  */
7170  prev_gpr_read = gpr_read_mask (&history[0]);
7171  if (gpr_write & prev_gpr_read)
7172    return false;
7173
7174  /* If one instruction sets a condition code and the
7175     other one uses a condition code, we can not swap.  */
7176  pinfo = ip->insn_mo->pinfo;
7177  if ((pinfo & INSN_READ_COND_CODE)
7178      && (prev_pinfo & INSN_WRITE_COND_CODE))
7179    return false;
7180  if ((pinfo & INSN_WRITE_COND_CODE)
7181      && (prev_pinfo & INSN_READ_COND_CODE))
7182    return false;
7183
7184  /* If the previous instruction uses the PC, we can not swap.  */
7185  prev_pinfo2 = history[0].insn_mo->pinfo2;
7186  if (prev_pinfo2 & INSN2_READ_PC)
7187    return false;
7188
7189  /* If the previous instruction has an incorrect size for a fixed
7190     branch delay slot in microMIPS mode, we cannot swap.  */
7191  pinfo2 = ip->insn_mo->pinfo2;
7192  if (mips_opts.micromips
7193      && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
7194      && insn_length (history) != 2)
7195    return false;
7196  if (mips_opts.micromips
7197      && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
7198      && insn_length (history) != 4)
7199    return false;
7200
7201  /* On the R5900 short loops need to be fixed by inserting a NOP in the
7202     branch delay slot.
7203
7204     The short loop bug under certain conditions causes loops to execute
7205     only once or twice.  We must ensure that the assembler never
7206     generates loops that satisfy all of the following conditions:
7207
7208     - a loop consists of less than or equal to six instructions
7209       (including the branch delay slot);
7210     - a loop contains only one conditional branch instruction at the end
7211       of the loop;
7212     - a loop does not contain any other branch or jump instructions;
7213     - a branch delay slot of the loop is not NOP (EE 2.9 or later).
7214
7215     We need to do this because of a hardware bug in the R5900 chip.  */
7216  if (mips_fix_r5900
7217      /* Check if instruction has a parameter, ignore "j $31". */
7218      && (address_expr != NULL)
7219      /* Parameter must be 16 bit. */
7220      && (*reloc_type == BFD_RELOC_16_PCREL_S2)
7221      /* Branch to same segment. */
7222      && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
7223      /* Branch to same code fragment. */
7224      && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
7225      /* Can only calculate branch offset if value is known. */
7226      && symbol_constant_p (address_expr->X_add_symbol)
7227      /* Check if branch is really conditional. */
7228      && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
7229	|| (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
7230	|| (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
7231    {
7232      int distance;
7233      /* Check if loop is shorter than or equal to 6 instructions
7234         including branch and delay slot.  */
7235      distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
7236      if (distance <= 20)
7237        {
7238          int i;
7239          int rv;
7240
7241          rv = false;
7242          /* When the loop includes branches or jumps,
7243             it is not a short loop. */
7244          for (i = 0; i < (distance / 4); i++)
7245            {
7246              if ((history[i].cleared_p)
7247                  || delayed_branch_p (&history[i]))
7248                {
7249                  rv = true;
7250                  break;
7251                }
7252            }
7253          if (!rv)
7254            {
7255              /* Insert nop after branch to fix short loop. */
7256              return false;
7257            }
7258        }
7259    }
7260
7261  return true;
7262}
7263
7264/* Fix jump through register issue on loongson2f processor for kernel code:
7265   force a BTB clear before the jump to prevent it from being incorrectly
7266   prefetched by the branch prediction engine. */
7267
7268static void
7269macro_build_jrpatch (expressionS *ep, unsigned int sreg)
7270{
7271  if (!mips_fix_loongson2f_btb)
7272    return;
7273
7274  if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == AT)
7275    return;
7276
7277  if (!mips_opts.at)
7278    {
7279      as_warn (_("unable to apply loongson2f BTB workaround when .set noat"));
7280      return;
7281    }
7282
7283  /* li $at, COP_0_BTB_CLEAR | COP_0_RAS_DISABLE */
7284  ep->X_op = O_constant;
7285  ep->X_add_number = 3;
7286  macro_build (ep, "ori", "t,r,i", AT, ZERO, BFD_RELOC_LO16);
7287
7288  /* dmtc0 $at, COP_0_DIAG */
7289  macro_build (NULL, "dmtc0", "t,G", AT, 22);
7290
7291  /* Hide these two instructions to avoid getting a ``macro expanded into
7292     multiple instructions'' warning. */
7293  if (mips_relax.sequence != 2) {
7294    mips_macro_warning.sizes[0] -= 2 * 4;
7295    mips_macro_warning.insns[0] -= 2;
7296  }
7297  if (mips_relax.sequence != 1) {
7298    mips_macro_warning.sizes[1] -= 2 * 4;
7299    mips_macro_warning.insns[1] -= 2;
7300  }
7301}
7302
7303/* Decide how we should add IP to the instruction stream.
7304   ADDRESS_EXPR is an operand of the instruction to be used with
7305   RELOC_TYPE.  */
7306
7307static enum append_method
7308get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
7309		   bfd_reloc_code_real_type *reloc_type)
7310{
7311  /* The relaxed version of a macro sequence must be inherently
7312     hazard-free.  */
7313  if (mips_relax.sequence == 2)
7314    return APPEND_ADD;
7315
7316  /* We must not dabble with instructions in a ".set noreorder" block.  */
7317  if (mips_opts.noreorder)
7318    return APPEND_ADD;
7319
7320  /* Otherwise, it's our responsibility to fill branch delay slots.  */
7321  if (delayed_branch_p (ip))
7322    {
7323      if (!branch_likely_p (ip)
7324	  && can_swap_branch_p (ip, address_expr, reloc_type))
7325	return APPEND_SWAP;
7326
7327      if (mips_opts.mips16
7328	  && ISA_SUPPORTS_MIPS16E
7329	  && gpr_read_mask (ip) != 0)
7330	return APPEND_ADD_COMPACT;
7331
7332      if (mips_opts.micromips
7333	  && ((ip->insn_opcode & 0xffe0) == 0x4580
7334	      || (!forced_insn_length
7335		  && ((ip->insn_opcode & 0xfc00) == 0xcc00
7336		      || (ip->insn_opcode & 0xdc00) == 0x8c00))
7337	      || (ip->insn_opcode & 0xdfe00000) == 0x94000000
7338	      || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
7339	return APPEND_ADD_COMPACT;
7340
7341      return APPEND_ADD_WITH_NOP;
7342    }
7343
7344  return APPEND_ADD;
7345}
7346
7347/* IP is an instruction whose opcode we have just changed, END points
7348   to the end of the opcode table processed.  Point IP->insn_mo to the
7349   new opcode's definition.  */
7350
7351static void
7352find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
7353{
7354  const struct mips_opcode *mo;
7355
7356  for (mo = ip->insn_mo; mo < end; mo++)
7357    if (mo->pinfo != INSN_MACRO
7358	&& (ip->insn_opcode & mo->mask) == mo->match)
7359      {
7360	ip->insn_mo = mo;
7361	return;
7362      }
7363  abort ();
7364}
7365
7366/* IP is a MIPS16 instruction whose opcode we have just changed.
7367   Point IP->insn_mo to the new opcode's definition.  */
7368
7369static void
7370find_altered_mips16_opcode (struct mips_cl_insn *ip)
7371{
7372  find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
7373}
7374
7375/* IP is a microMIPS instruction whose opcode we have just changed.
7376   Point IP->insn_mo to the new opcode's definition.  */
7377
7378static void
7379find_altered_micromips_opcode (struct mips_cl_insn *ip)
7380{
7381  find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
7382}
7383
7384/* For microMIPS macros, we need to generate a local number label
7385   as the target of branches.  */
7386#define MICROMIPS_LABEL_CHAR		'\037'
7387static unsigned long micromips_target_label;
7388static char micromips_target_name[32];
7389
7390static char *
7391micromips_label_name (void)
7392{
7393  char *p = micromips_target_name;
7394  char symbol_name_temporary[24];
7395  unsigned long l;
7396  int i;
7397
7398  if (*p)
7399    return p;
7400
7401  i = 0;
7402  l = micromips_target_label;
7403#ifdef LOCAL_LABEL_PREFIX
7404  *p++ = LOCAL_LABEL_PREFIX;
7405#endif
7406  *p++ = 'L';
7407  *p++ = MICROMIPS_LABEL_CHAR;
7408  do
7409    {
7410      symbol_name_temporary[i++] = l % 10 + '0';
7411      l /= 10;
7412    }
7413  while (l != 0);
7414  while (i > 0)
7415    *p++ = symbol_name_temporary[--i];
7416  *p = '\0';
7417
7418  return micromips_target_name;
7419}
7420
7421static void
7422micromips_label_expr (expressionS *label_expr)
7423{
7424  label_expr->X_op = O_symbol;
7425  label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
7426  label_expr->X_add_number = 0;
7427}
7428
7429static void
7430micromips_label_inc (void)
7431{
7432  micromips_target_label++;
7433  *micromips_target_name = '\0';
7434}
7435
7436static void
7437micromips_add_label (void)
7438{
7439  symbolS *s;
7440
7441  s = colon (micromips_label_name ());
7442  micromips_label_inc ();
7443  S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
7444}
7445
7446/* If assembling microMIPS code, then return the microMIPS reloc
7447   corresponding to the requested one if any.  Otherwise return
7448   the reloc unchanged.  */
7449
7450static bfd_reloc_code_real_type
7451micromips_map_reloc (bfd_reloc_code_real_type reloc)
7452{
7453  static const bfd_reloc_code_real_type relocs[][2] =
7454    {
7455      /* Keep sorted incrementally by the left-hand key.  */
7456      { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7457      { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7458      { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7459      { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7460      { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7461      { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7462      { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7463      { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7464      { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7465      { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7466      { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7467      { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7468      { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7469      { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7470      { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7471      { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7472      { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7473      { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7474      { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7475      { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7476      { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7477      { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7478      { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7479      { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7480      { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7481      { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7482      { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7483    };
7484  bfd_reloc_code_real_type r;
7485  size_t i;
7486
7487  if (!mips_opts.micromips)
7488    return reloc;
7489  for (i = 0; i < ARRAY_SIZE (relocs); i++)
7490    {
7491      r = relocs[i][0];
7492      if (r > reloc)
7493	return reloc;
7494      if (r == reloc)
7495	return relocs[i][1];
7496    }
7497  return reloc;
7498}
7499
7500/* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7501   Return true on success, storing the resolved value in RESULT.  */
7502
7503static bool
7504calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7505		 offsetT *result)
7506{
7507  switch (reloc)
7508    {
7509    case BFD_RELOC_MIPS_HIGHEST:
7510    case BFD_RELOC_MICROMIPS_HIGHEST:
7511      *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7512      return true;
7513
7514    case BFD_RELOC_MIPS_HIGHER:
7515    case BFD_RELOC_MICROMIPS_HIGHER:
7516      *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7517      return true;
7518
7519    case BFD_RELOC_HI16_S:
7520    case BFD_RELOC_HI16_S_PCREL:
7521    case BFD_RELOC_MICROMIPS_HI16_S:
7522    case BFD_RELOC_MIPS16_HI16_S:
7523      *result = ((operand + 0x8000) >> 16) & 0xffff;
7524      return true;
7525
7526    case BFD_RELOC_HI16:
7527    case BFD_RELOC_MICROMIPS_HI16:
7528    case BFD_RELOC_MIPS16_HI16:
7529      *result = (operand >> 16) & 0xffff;
7530      return true;
7531
7532    case BFD_RELOC_LO16:
7533    case BFD_RELOC_LO16_PCREL:
7534    case BFD_RELOC_MICROMIPS_LO16:
7535    case BFD_RELOC_MIPS16_LO16:
7536      *result = operand & 0xffff;
7537      return true;
7538
7539    case BFD_RELOC_UNUSED:
7540      *result = operand;
7541      return true;
7542
7543    default:
7544      return false;
7545    }
7546}
7547
7548/* Output an instruction.  IP is the instruction information.
7549   ADDRESS_EXPR is an operand of the instruction to be used with
7550   RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7551   a macro expansion.  */
7552
7553static void
7554append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7555	     bfd_reloc_code_real_type *reloc_type, bool expansionp)
7556{
7557  unsigned long prev_pinfo2, pinfo;
7558  bool relaxed_branch = false;
7559  enum append_method method;
7560  bool relax32;
7561  int branch_disp;
7562
7563  if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7564    fix_loongson2f (ip);
7565
7566  ip->target[0] = '\0';
7567  if (offset_expr.X_op == O_symbol)
7568    strncpy (ip->target, S_GET_NAME (offset_expr.X_add_symbol), 15);
7569  ip->label[0] = '\0';
7570  if (seg_info (now_seg)->label_list)
7571    strncpy (ip->label, S_GET_NAME (seg_info (now_seg)->label_list->label), 15);
7572  if (mips_fix_loongson3_llsc && !HAVE_CODE_COMPRESSION)
7573    fix_loongson3_llsc (ip);
7574
7575  file_ase_mips16 |= mips_opts.mips16;
7576  file_ase_micromips |= mips_opts.micromips;
7577
7578  prev_pinfo2 = history[0].insn_mo->pinfo2;
7579  pinfo = ip->insn_mo->pinfo;
7580
7581  /* Don't raise alarm about `nods' frags as they'll fill in the right
7582     kind of nop in relaxation if required.  */
7583  if (mips_opts.micromips
7584      && !expansionp
7585      && !(history[0].frag
7586	   && history[0].frag->fr_type == rs_machine_dependent
7587	   && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7588	   && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7589      && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7590	   && micromips_insn_length (ip->insn_mo) != 2)
7591	  || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7592	      && micromips_insn_length (ip->insn_mo) != 4)))
7593    as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7594	     (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7595
7596  if (address_expr == NULL)
7597    ip->complete_p = 1;
7598  else if (reloc_type[0] <= BFD_RELOC_UNUSED
7599	   && reloc_type[1] == BFD_RELOC_UNUSED
7600	   && reloc_type[2] == BFD_RELOC_UNUSED
7601	   && address_expr->X_op == O_constant)
7602    {
7603      switch (*reloc_type)
7604	{
7605	case BFD_RELOC_MIPS_JMP:
7606	  {
7607	    int shift;
7608
7609	    /* Shift is 2, unusually, for microMIPS JALX.  */
7610	    shift = (mips_opts.micromips
7611		     && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7612	    if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7613	      as_bad (_("jump to misaligned address (0x%lx)"),
7614		      (unsigned long) address_expr->X_add_number);
7615	    ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7616				& 0x3ffffff);
7617	    ip->complete_p = 1;
7618	  }
7619	  break;
7620
7621	case BFD_RELOC_MIPS16_JMP:
7622	  if ((address_expr->X_add_number & 3) != 0)
7623	    as_bad (_("jump to misaligned address (0x%lx)"),
7624	            (unsigned long) address_expr->X_add_number);
7625	  ip->insn_opcode |=
7626	    (((address_expr->X_add_number & 0x7c0000) << 3)
7627	       | ((address_expr->X_add_number & 0xf800000) >> 7)
7628	       | ((address_expr->X_add_number & 0x3fffc) >> 2));
7629	  ip->complete_p = 1;
7630	  break;
7631
7632	case BFD_RELOC_16_PCREL_S2:
7633	  {
7634	    int shift;
7635
7636	    shift = mips_opts.micromips ? 1 : 2;
7637	    if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7638	      as_bad (_("branch to misaligned address (0x%lx)"),
7639		      (unsigned long) address_expr->X_add_number);
7640	    if (!mips_relax_branch)
7641	      {
7642		if ((address_expr->X_add_number + (1 << (shift + 15)))
7643		    & ~((1 << (shift + 16)) - 1))
7644		  as_bad (_("branch address range overflow (0x%lx)"),
7645			  (unsigned long) address_expr->X_add_number);
7646		ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7647				    & 0xffff);
7648	      }
7649	  }
7650	  break;
7651
7652	case BFD_RELOC_MIPS_21_PCREL_S2:
7653	  {
7654	    int shift;
7655
7656	    shift = 2;
7657	    if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7658	      as_bad (_("branch to misaligned address (0x%lx)"),
7659		      (unsigned long) address_expr->X_add_number);
7660	    if ((address_expr->X_add_number + (1 << (shift + 20)))
7661		& ~((1 << (shift + 21)) - 1))
7662	      as_bad (_("branch address range overflow (0x%lx)"),
7663		      (unsigned long) address_expr->X_add_number);
7664	    ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7665				& 0x1fffff);
7666	  }
7667	  break;
7668
7669	case BFD_RELOC_MIPS_26_PCREL_S2:
7670	  {
7671	    int shift;
7672
7673	    shift = 2;
7674	    if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7675	      as_bad (_("branch to misaligned address (0x%lx)"),
7676		      (unsigned long) address_expr->X_add_number);
7677	    if ((address_expr->X_add_number + (1 << (shift + 25)))
7678		& ~((1 << (shift + 26)) - 1))
7679	      as_bad (_("branch address range overflow (0x%lx)"),
7680		      (unsigned long) address_expr->X_add_number);
7681	    ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7682				& 0x3ffffff);
7683	  }
7684	  break;
7685
7686	default:
7687	  {
7688	    offsetT value;
7689
7690	    if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7691				 &value))
7692	      {
7693		ip->insn_opcode |= value & 0xffff;
7694		ip->complete_p = 1;
7695	      }
7696	  }
7697	  break;
7698	}
7699    }
7700
7701  if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7702    {
7703      /* There are a lot of optimizations we could do that we don't.
7704	 In particular, we do not, in general, reorder instructions.
7705	 If you use gcc with optimization, it will reorder
7706	 instructions and generally do much more optimization then we
7707	 do here; repeating all that work in the assembler would only
7708	 benefit hand written assembly code, and does not seem worth
7709	 it.  */
7710      int nops = (mips_optimize == 0
7711		  ? nops_for_insn (0, history, NULL)
7712		  : nops_for_insn_or_target (0, history, ip));
7713      if (nops > 0)
7714	{
7715	  fragS *old_frag;
7716	  unsigned long old_frag_offset;
7717	  int i;
7718
7719	  old_frag = frag_now;
7720	  old_frag_offset = frag_now_fix ();
7721
7722	  for (i = 0; i < nops; i++)
7723	    add_fixed_insn (NOP_INSN);
7724	  insert_into_history (0, nops, NOP_INSN);
7725
7726	  if (listing)
7727	    {
7728	      listing_prev_line ();
7729	      /* We may be at the start of a variant frag.  In case we
7730                 are, make sure there is enough space for the frag
7731                 after the frags created by listing_prev_line.  The
7732                 argument to frag_grow here must be at least as large
7733                 as the argument to all other calls to frag_grow in
7734                 this file.  We don't have to worry about being in the
7735                 middle of a variant frag, because the variants insert
7736                 all needed nop instructions themselves.  */
7737	      frag_grow (40);
7738	    }
7739
7740	  mips_move_text_labels ();
7741
7742#ifndef NO_ECOFF_DEBUGGING
7743	  if (ECOFF_DEBUGGING)
7744	    ecoff_fix_loc (old_frag, old_frag_offset);
7745#endif
7746	}
7747    }
7748  else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7749    {
7750      int nops;
7751
7752      /* Work out how many nops in prev_nop_frag are needed by IP,
7753	 ignoring hazards generated by the first prev_nop_frag_since
7754	 instructions.  */
7755      nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7756      gas_assert (nops <= prev_nop_frag_holds);
7757
7758      /* Enforce NOPS as a minimum.  */
7759      if (nops > prev_nop_frag_required)
7760	prev_nop_frag_required = nops;
7761
7762      if (prev_nop_frag_holds == prev_nop_frag_required)
7763	{
7764	  /* Settle for the current number of nops.  Update the history
7765	     accordingly (for the benefit of any future .set reorder code).  */
7766	  prev_nop_frag = NULL;
7767	  insert_into_history (prev_nop_frag_since,
7768			       prev_nop_frag_holds, NOP_INSN);
7769	}
7770      else
7771	{
7772	  /* Allow this instruction to replace one of the nops that was
7773	     tentatively added to prev_nop_frag.  */
7774	  prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7775	  prev_nop_frag_holds--;
7776	  prev_nop_frag_since++;
7777	}
7778    }
7779
7780  method = get_append_method (ip, address_expr, reloc_type);
7781  branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7782
7783  dwarf2_emit_insn (0);
7784  /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7785     so "move" the instruction address accordingly.
7786
7787     Also, it doesn't seem appropriate for the assembler to reorder .loc
7788     entries.  If this instruction is a branch that we are going to swap
7789     with the previous instruction, the two instructions should be
7790     treated as a unit, and the debug information for both instructions
7791     should refer to the start of the branch sequence.  Using the
7792     current position is certainly wrong when swapping a 32-bit branch
7793     and a 16-bit delay slot, since the current position would then be
7794     in the middle of a branch.  */
7795  dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7796
7797  relax32 = (mips_relax_branch
7798	     /* Don't try branch relaxation within .set nomacro, or within
7799	        .set noat if we use $at for PIC computations.  If it turns
7800	        out that the branch was out-of-range, we'll get an error.  */
7801	     && !mips_opts.warn_about_macros
7802	     && (mips_opts.at || mips_pic == NO_PIC)
7803	     /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7804	        as they have no complementing branches.  */
7805	     && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7806
7807  if (!HAVE_CODE_COMPRESSION
7808      && address_expr
7809      && relax32
7810      && *reloc_type == BFD_RELOC_16_PCREL_S2
7811      && delayed_branch_p (ip))
7812    {
7813      relaxed_branch = true;
7814      add_relaxed_insn (ip, (relaxed_branch_length
7815			     (NULL, NULL,
7816			      uncond_branch_p (ip) ? -1
7817			      : branch_likely_p (ip) ? 1
7818			      : 0)), 4,
7819			RELAX_BRANCH_ENCODE
7820			(AT, mips_pic != NO_PIC,
7821			 uncond_branch_p (ip),
7822			 branch_likely_p (ip),
7823			 pinfo & INSN_WRITE_GPR_31,
7824			 0),
7825			address_expr->X_add_symbol,
7826			address_expr->X_add_number);
7827      *reloc_type = BFD_RELOC_UNUSED;
7828    }
7829  else if (mips_opts.micromips
7830	   && address_expr
7831	   && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7832	       || *reloc_type > BFD_RELOC_UNUSED)
7833	   && (delayed_branch_p (ip) || compact_branch_p (ip))
7834	   /* Don't try branch relaxation when users specify
7835	      16-bit/32-bit instructions.  */
7836	   && !forced_insn_length)
7837    {
7838      bool relax16 = (method != APPEND_ADD_COMPACT
7839		      && *reloc_type > BFD_RELOC_UNUSED);
7840      int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7841      int uncond = uncond_branch_p (ip) ? -1 : 0;
7842      int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7843      int nods = method == APPEND_ADD_WITH_NOP;
7844      int al = pinfo & INSN_WRITE_GPR_31;
7845      int length32 = nods ? 8 : 4;
7846
7847      gas_assert (address_expr != NULL);
7848      gas_assert (!mips_relax.sequence);
7849
7850      relaxed_branch = true;
7851      if (nods)
7852	method = APPEND_ADD;
7853      if (relax32)
7854	length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7855      add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7856			RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7857						mips_pic != NO_PIC,
7858						uncond, compact, al, nods,
7859						relax32, 0, 0),
7860			address_expr->X_add_symbol,
7861			address_expr->X_add_number);
7862      *reloc_type = BFD_RELOC_UNUSED;
7863    }
7864  else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7865    {
7866      bool require_unextended;
7867      bool require_extended;
7868      symbolS *symbol;
7869      offsetT offset;
7870
7871      if (forced_insn_length != 0)
7872	{
7873	  require_unextended = forced_insn_length == 2;
7874	  require_extended = forced_insn_length == 4;
7875	}
7876      else
7877	{
7878	  require_unextended = (mips_opts.noautoextend
7879				&& !mips_opcode_32bit_p (ip->insn_mo));
7880	  require_extended = 0;
7881	}
7882
7883      /* We need to set up a variant frag.  */
7884      gas_assert (address_expr != NULL);
7885      /* Pass any `O_symbol' expression unchanged as an `expr_section'
7886         symbol created by `make_expr_symbol' may not get a necessary
7887         external relocation produced.  */
7888      if (address_expr->X_op == O_symbol)
7889	{
7890	  symbol = address_expr->X_add_symbol;
7891	  offset = address_expr->X_add_number;
7892	}
7893      else
7894	{
7895	  symbol = make_expr_symbol (address_expr);
7896	  symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7897	  offset = 0;
7898	}
7899      add_relaxed_insn (ip, 12, 0,
7900			RELAX_MIPS16_ENCODE
7901			(*reloc_type - BFD_RELOC_UNUSED,
7902			 mips_opts.ase & ASE_MIPS16E2,
7903			 mips_pic != NO_PIC,
7904			 HAVE_32BIT_SYMBOLS,
7905			 mips_opts.warn_about_macros,
7906			 require_unextended, require_extended,
7907			 delayed_branch_p (&history[0]),
7908			 history[0].mips16_absolute_jump_p),
7909			symbol, offset);
7910    }
7911  else if (mips_opts.mips16 && insn_length (ip) == 2)
7912    {
7913      if (!delayed_branch_p (ip))
7914	/* Make sure there is enough room to swap this instruction with
7915	   a following jump instruction.  */
7916	frag_grow (6);
7917      add_fixed_insn (ip);
7918    }
7919  else
7920    {
7921      if (mips_opts.mips16
7922	  && mips_opts.noreorder
7923	  && delayed_branch_p (&history[0]))
7924	as_warn (_("extended instruction in delay slot"));
7925
7926      if (mips_relax.sequence)
7927	{
7928	  /* If we've reached the end of this frag, turn it into a variant
7929	     frag and record the information for the instructions we've
7930	     written so far.  */
7931	  if (frag_room () < 4)
7932	    relax_close_frag ();
7933	  mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7934	}
7935
7936      if (mips_relax.sequence != 2)
7937	{
7938	  if (mips_macro_warning.first_insn_sizes[0] == 0)
7939	    mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7940	  mips_macro_warning.sizes[0] += insn_length (ip);
7941	  mips_macro_warning.insns[0]++;
7942	}
7943      if (mips_relax.sequence != 1)
7944	{
7945	  if (mips_macro_warning.first_insn_sizes[1] == 0)
7946	    mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7947	  mips_macro_warning.sizes[1] += insn_length (ip);
7948	  mips_macro_warning.insns[1]++;
7949	}
7950
7951      if (mips_opts.mips16)
7952	{
7953	  ip->fixed_p = 1;
7954	  ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7955	}
7956      add_fixed_insn (ip);
7957    }
7958
7959  if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7960    {
7961      bfd_reloc_code_real_type final_type[3];
7962      reloc_howto_type *howto0;
7963      reloc_howto_type *howto;
7964      int i;
7965
7966      /* Perform any necessary conversion to microMIPS relocations
7967	 and find out how many relocations there actually are.  */
7968      for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7969	final_type[i] = micromips_map_reloc (reloc_type[i]);
7970
7971      /* In a compound relocation, it is the final (outermost)
7972	 operator that determines the relocated field.  */
7973      howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7974      if (!howto)
7975	abort ();
7976
7977      if (i > 1)
7978	howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7979      ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7980				 bfd_get_reloc_size (howto),
7981				 address_expr,
7982				 howto0 && howto0->pc_relative,
7983				 final_type[0]);
7984      /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7985      ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7986
7987      /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7988      if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7989	*symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7990
7991      /* These relocations can have an addend that won't fit in
7992	 4 octets for 64bit assembly.  */
7993      if (GPR_SIZE == 64
7994	  && ! howto->partial_inplace
7995	  && (reloc_type[0] == BFD_RELOC_16
7996	      || reloc_type[0] == BFD_RELOC_32
7997	      || reloc_type[0] == BFD_RELOC_MIPS_JMP
7998	      || reloc_type[0] == BFD_RELOC_GPREL16
7999	      || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
8000	      || reloc_type[0] == BFD_RELOC_GPREL32
8001	      || reloc_type[0] == BFD_RELOC_64
8002	      || reloc_type[0] == BFD_RELOC_CTOR
8003	      || reloc_type[0] == BFD_RELOC_MIPS_SUB
8004	      || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
8005	      || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
8006	      || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
8007	      || reloc_type[0] == BFD_RELOC_MIPS_16
8008	      || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
8009	      || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
8010	      || hi16_reloc_p (reloc_type[0])
8011	      || lo16_reloc_p (reloc_type[0])))
8012	ip->fixp[0]->fx_no_overflow = 1;
8013
8014      /* These relocations can have an addend that won't fit in 2 octets.  */
8015      if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
8016	  || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
8017	ip->fixp[0]->fx_no_overflow = 1;
8018
8019      if (mips_relax.sequence)
8020	{
8021	  if (mips_relax.first_fixup == 0)
8022	    mips_relax.first_fixup = ip->fixp[0];
8023	}
8024      else if (reloc_needs_lo_p (*reloc_type))
8025	{
8026	  struct mips_hi_fixup *hi_fixup;
8027
8028	  /* Reuse the last entry if it already has a matching %lo.  */
8029	  hi_fixup = mips_hi_fixup_list;
8030	  if (hi_fixup == 0
8031	      || !fixup_has_matching_lo_p (hi_fixup->fixp))
8032	    {
8033	      hi_fixup = XNEW (struct mips_hi_fixup);
8034	      hi_fixup->next = mips_hi_fixup_list;
8035	      mips_hi_fixup_list = hi_fixup;
8036	    }
8037	  hi_fixup->fixp = ip->fixp[0];
8038	  hi_fixup->seg = now_seg;
8039	}
8040
8041      /* Add fixups for the second and third relocations, if given.
8042	 Note that the ABI allows the second relocation to be
8043	 against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
8044	 moment we only use RSS_UNDEF, but we could add support
8045	 for the others if it ever becomes necessary.  */
8046      for (i = 1; i < 3; i++)
8047	if (reloc_type[i] != BFD_RELOC_UNUSED)
8048	  {
8049	    ip->fixp[i] = fix_new (ip->frag, ip->where,
8050				   ip->fixp[0]->fx_size, NULL, 0,
8051				   false, final_type[i]);
8052
8053	    /* Use fx_tcbit to mark compound relocs.  */
8054	    ip->fixp[0]->fx_tcbit = 1;
8055	    ip->fixp[i]->fx_tcbit = 1;
8056	  }
8057    }
8058
8059  /* Update the register mask information.  */
8060  mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
8061  mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
8062
8063  switch (method)
8064    {
8065    case APPEND_ADD:
8066      insert_into_history (0, 1, ip);
8067      break;
8068
8069    case APPEND_ADD_WITH_NOP:
8070      {
8071	struct mips_cl_insn *nop;
8072
8073	insert_into_history (0, 1, ip);
8074	nop = get_delay_slot_nop (ip);
8075	add_fixed_insn (nop);
8076	insert_into_history (0, 1, nop);
8077	if (mips_relax.sequence)
8078	  mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
8079      }
8080      break;
8081
8082    case APPEND_ADD_COMPACT:
8083      /* Convert MIPS16 jr/jalr into a "compact" jump.  */
8084      if (mips_opts.mips16)
8085	{
8086	  ip->insn_opcode |= 0x0080;
8087	  find_altered_mips16_opcode (ip);
8088	}
8089      /* Convert microMIPS instructions.  */
8090      else if (mips_opts.micromips)
8091	{
8092	  /* jr16->jrc */
8093	  if ((ip->insn_opcode & 0xffe0) == 0x4580)
8094	    ip->insn_opcode |= 0x0020;
8095	  /* b16->bc */
8096	  else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
8097	    ip->insn_opcode = 0x40e00000;
8098	  /* beqz16->beqzc, bnez16->bnezc */
8099	  else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
8100	    {
8101	      unsigned long regno;
8102
8103	      regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
8104	      regno &= MICROMIPSOP_MASK_MD;
8105	      regno = micromips_to_32_reg_d_map[regno];
8106	      ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
8107				 | (regno << MICROMIPSOP_SH_RS)
8108				 | 0x40a00000) ^ 0x00400000;
8109	    }
8110	  /* beqz->beqzc, bnez->bnezc */
8111	  else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
8112	    ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
8113			       | ((ip->insn_opcode >> 7) & 0x00400000)
8114			       | 0x40a00000) ^ 0x00400000;
8115	  /* beq $0->beqzc, bne $0->bnezc */
8116	  else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
8117	    ip->insn_opcode = (((ip->insn_opcode >>
8118				 (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
8119				& (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
8120			       | ((ip->insn_opcode >> 7) & 0x00400000)
8121			       | 0x40a00000) ^ 0x00400000;
8122	  else
8123	    abort ();
8124	  find_altered_micromips_opcode (ip);
8125	}
8126      else
8127	abort ();
8128      install_insn (ip);
8129      insert_into_history (0, 1, ip);
8130      break;
8131
8132    case APPEND_SWAP:
8133      {
8134	struct mips_cl_insn delay = history[0];
8135
8136	if (relaxed_branch || delay.frag != ip->frag)
8137	  {
8138	    /* Add the delay slot instruction to the end of the
8139	       current frag and shrink the fixed part of the
8140	       original frag.  If the branch occupies the tail of
8141	       the latter, move it backwards to cover the gap.  */
8142	    delay.frag->fr_fix -= branch_disp;
8143	    if (delay.frag == ip->frag)
8144	      move_insn (ip, ip->frag, ip->where - branch_disp);
8145	    add_fixed_insn (&delay);
8146	  }
8147	else
8148	  {
8149	    /* If this is not a relaxed branch and we are in the
8150	       same frag, then just swap the instructions.  */
8151	    move_insn (ip, delay.frag, delay.where);
8152	    move_insn (&delay, ip->frag, ip->where + insn_length (ip));
8153	  }
8154	history[0] = *ip;
8155	delay.fixed_p = 1;
8156	insert_into_history (0, 1, &delay);
8157      }
8158      break;
8159    }
8160
8161  /* If we have just completed an unconditional branch, clear the history.  */
8162  if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
8163      || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
8164    {
8165      unsigned int i;
8166
8167      mips_no_prev_insn ();
8168
8169      for (i = 0; i < ARRAY_SIZE (history); i++)
8170	history[i].cleared_p = 1;
8171    }
8172
8173  /* We need to emit a label at the end of branch-likely macros.  */
8174  if (emit_branch_likely_macro)
8175    {
8176      emit_branch_likely_macro = false;
8177      micromips_add_label ();
8178    }
8179
8180  /* We just output an insn, so the next one doesn't have a label.  */
8181  mips_clear_insn_labels ();
8182}
8183
8184/* Forget that there was any previous instruction or label.
8185   When BRANCH is true, the branch history is also flushed.  */
8186
8187static void
8188mips_no_prev_insn (void)
8189{
8190  prev_nop_frag = NULL;
8191  insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
8192  mips_clear_insn_labels ();
8193}
8194
8195/* This function must be called before we emit something other than
8196   instructions.  It is like mips_no_prev_insn except that it inserts
8197   any NOPS that might be needed by previous instructions.  */
8198
8199void
8200mips_emit_delays (void)
8201{
8202  if (! mips_opts.noreorder)
8203    {
8204      int nops = nops_for_insn (0, history, NULL);
8205      if (nops > 0)
8206	{
8207	  while (nops-- > 0)
8208	    add_fixed_insn (NOP_INSN);
8209	  mips_move_text_labels ();
8210	}
8211    }
8212  mips_no_prev_insn ();
8213}
8214
8215/* Start a (possibly nested) noreorder block.  */
8216
8217static void
8218start_noreorder (void)
8219{
8220  if (mips_opts.noreorder == 0)
8221    {
8222      unsigned int i;
8223      int nops;
8224
8225      /* None of the instructions before the .set noreorder can be moved.  */
8226      for (i = 0; i < ARRAY_SIZE (history); i++)
8227	history[i].fixed_p = 1;
8228
8229      /* Insert any nops that might be needed between the .set noreorder
8230	 block and the previous instructions.  We will later remove any
8231	 nops that turn out not to be needed.  */
8232      nops = nops_for_insn (0, history, NULL);
8233      if (nops > 0)
8234	{
8235	  if (mips_optimize != 0)
8236	    {
8237	      /* Record the frag which holds the nop instructions, so
8238                 that we can remove them if we don't need them.  */
8239	      frag_grow (nops * NOP_INSN_SIZE);
8240	      prev_nop_frag = frag_now;
8241	      prev_nop_frag_holds = nops;
8242	      prev_nop_frag_required = 0;
8243	      prev_nop_frag_since = 0;
8244	    }
8245
8246	  for (; nops > 0; --nops)
8247	    add_fixed_insn (NOP_INSN);
8248
8249	  /* Move on to a new frag, so that it is safe to simply
8250	     decrease the size of prev_nop_frag.  */
8251	  frag_wane (frag_now);
8252	  frag_new (0);
8253	  mips_move_text_labels ();
8254	}
8255      mips_mark_labels ();
8256      mips_clear_insn_labels ();
8257    }
8258  mips_opts.noreorder++;
8259  mips_any_noreorder = 1;
8260}
8261
8262/* End a nested noreorder block.  */
8263
8264static void
8265end_noreorder (void)
8266{
8267  mips_opts.noreorder--;
8268  if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
8269    {
8270      /* Commit to inserting prev_nop_frag_required nops and go back to
8271	 handling nop insertion the .set reorder way.  */
8272      prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
8273				* NOP_INSN_SIZE);
8274      insert_into_history (prev_nop_frag_since,
8275			   prev_nop_frag_required, NOP_INSN);
8276      prev_nop_frag = NULL;
8277    }
8278}
8279
8280/* Sign-extend 32-bit mode constants that have bit 31 set and all
8281   higher bits unset.  */
8282
8283static void
8284normalize_constant_expr (expressionS *ex)
8285{
8286  if (ex->X_op == O_constant
8287      && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8288    ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8289			- 0x80000000);
8290}
8291
8292/* Sign-extend 32-bit mode address offsets that have bit 31 set and
8293   all higher bits unset.  */
8294
8295static void
8296normalize_address_expr (expressionS *ex)
8297{
8298  if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
8299	|| (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
8300      && IS_ZEXT_32BIT_NUM (ex->X_add_number))
8301    ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
8302			- 0x80000000);
8303}
8304
8305/* Try to match TOKENS against OPCODE, storing the result in INSN.
8306   Return true if the match was successful.
8307
8308   OPCODE_EXTRA is a value that should be ORed into the opcode
8309   (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
8310   there are more alternatives after OPCODE and SOFT_MATCH is
8311   as for mips_arg_info.  */
8312
8313static bool
8314match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8315	    struct mips_operand_token *tokens, unsigned int opcode_extra,
8316	    bool lax_match, bool complete_p)
8317{
8318  const char *args;
8319  struct mips_arg_info arg;
8320  const struct mips_operand *operand;
8321  char c;
8322
8323  imm_expr.X_op = O_absent;
8324  offset_expr.X_op = O_absent;
8325  offset_reloc[0] = BFD_RELOC_UNUSED;
8326  offset_reloc[1] = BFD_RELOC_UNUSED;
8327  offset_reloc[2] = BFD_RELOC_UNUSED;
8328
8329  create_insn (insn, opcode);
8330  /* When no opcode suffix is specified, assume ".xyzw". */
8331  if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
8332    insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
8333  else
8334    insn->insn_opcode |= opcode_extra;
8335  memset (&arg, 0, sizeof (arg));
8336  arg.insn = insn;
8337  arg.token = tokens;
8338  arg.argnum = 1;
8339  arg.last_regno = ILLEGAL_REG;
8340  arg.dest_regno = ILLEGAL_REG;
8341  arg.lax_match = lax_match;
8342  for (args = opcode->args;; ++args)
8343    {
8344      if (arg.token->type == OT_END)
8345	{
8346	  /* Handle unary instructions in which only one operand is given.
8347	     The source is then the same as the destination.  */
8348	  if (arg.opnum == 1 && *args == ',')
8349	    {
8350	      operand = (mips_opts.micromips
8351			 ? decode_micromips_operand (args + 1)
8352			 : decode_mips_operand (args + 1));
8353	      if (operand && mips_optional_operand_p (operand))
8354		{
8355		  arg.token = tokens;
8356		  arg.argnum = 1;
8357		  continue;
8358		}
8359	    }
8360
8361	  /* Treat elided base registers as $0.  */
8362	  if (strcmp (args, "(b)") == 0)
8363	    args += 3;
8364
8365	  if (args[0] == '+')
8366	    switch (args[1])
8367	      {
8368	      case 'K':
8369	      case 'N':
8370		/* The register suffix is optional. */
8371		args += 2;
8372		break;
8373	      }
8374
8375	  /* Fail the match if there were too few operands.  */
8376	  if (*args)
8377	    return false;
8378
8379	  /* Successful match.  */
8380	  if (!complete_p)
8381	    return true;
8382	  clear_insn_error ();
8383	  if (arg.dest_regno == arg.last_regno
8384	      && startswith (insn->insn_mo->name, "jalr"))
8385	    {
8386	      if (arg.opnum == 2)
8387		set_insn_error
8388		  (0, _("source and destination must be different"));
8389	      else if (arg.last_regno == 31)
8390		set_insn_error
8391		  (0, _("a destination register must be supplied"));
8392	    }
8393	  else if (arg.last_regno == 31
8394		   && (startswith (insn->insn_mo->name, "bltzal")
8395		       || startswith (insn->insn_mo->name, "bgezal")))
8396	    set_insn_error (0, _("the source register must not be $31"));
8397	  check_completed_insn (&arg);
8398	  return true;
8399	}
8400
8401      /* Fail the match if the line has too many operands.   */
8402      if (*args == 0)
8403	return false;
8404
8405      /* Handle characters that need to match exactly.  */
8406      if (*args == '(' || *args == ')' || *args == ',')
8407	{
8408	  if (match_char (&arg, *args))
8409	    continue;
8410	  return false;
8411	}
8412      if (*args == '#')
8413	{
8414	  ++args;
8415	  if (arg.token->type == OT_DOUBLE_CHAR
8416	      && arg.token->u.ch == *args)
8417	    {
8418	      ++arg.token;
8419	      continue;
8420	    }
8421	  return false;
8422	}
8423
8424      /* Handle special macro operands.  Work out the properties of
8425	 other operands.  */
8426      arg.opnum += 1;
8427      switch (*args)
8428	{
8429	case '-':
8430	  switch (args[1])
8431	    {
8432	    case 'A':
8433	      *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
8434	      break;
8435
8436	    case 'B':
8437	      *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
8438	      break;
8439	    }
8440	  break;
8441
8442	case '+':
8443	  switch (args[1])
8444	    {
8445	    case 'i':
8446	      *offset_reloc = BFD_RELOC_MIPS_JMP;
8447	      break;
8448
8449	    case '\'':
8450	      *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
8451	      break;
8452
8453	    case '\"':
8454	      *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
8455	      break;
8456	    }
8457	  break;
8458
8459	case 'I':
8460	  if (!match_const_int (&arg, &imm_expr.X_add_number))
8461	    return false;
8462	  imm_expr.X_op = O_constant;
8463	  if (GPR_SIZE == 32)
8464	    normalize_constant_expr (&imm_expr);
8465	  continue;
8466
8467	case 'A':
8468	  if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8469	    {
8470	      /* Assume that the offset has been elided and that what
8471		 we saw was a base register.  The match will fail later
8472		 if that assumption turns out to be wrong.  */
8473	      offset_expr.X_op = O_constant;
8474	      offset_expr.X_add_number = 0;
8475	    }
8476	  else
8477	    {
8478	      if (!match_expression (&arg, &offset_expr, offset_reloc))
8479		return false;
8480	      normalize_address_expr (&offset_expr);
8481	    }
8482	  continue;
8483
8484	case 'F':
8485	  if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8486				     8, true))
8487	    return false;
8488	  continue;
8489
8490	case 'L':
8491	  if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8492				     8, false))
8493	    return false;
8494	  continue;
8495
8496	case 'f':
8497	  if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8498				     4, true))
8499	    return false;
8500	  continue;
8501
8502	case 'l':
8503	  if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8504				     4, false))
8505	    return false;
8506	  continue;
8507
8508	case 'p':
8509	  *offset_reloc = BFD_RELOC_16_PCREL_S2;
8510	  break;
8511
8512	case 'a':
8513	  *offset_reloc = BFD_RELOC_MIPS_JMP;
8514	  break;
8515
8516	case 'm':
8517	  gas_assert (mips_opts.micromips);
8518	  c = args[1];
8519	  switch (c)
8520	    {
8521	    case 'D':
8522	    case 'E':
8523	      if (!forced_insn_length)
8524		*offset_reloc = (int) BFD_RELOC_UNUSED + c;
8525	      else if (c == 'D')
8526		*offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8527	      else
8528		*offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8529	      break;
8530	    }
8531	  break;
8532	}
8533
8534      operand = (mips_opts.micromips
8535		 ? decode_micromips_operand (args)
8536		 : decode_mips_operand (args));
8537      if (!operand)
8538	abort ();
8539
8540      /* Skip prefixes.  */
8541      if (*args == '+' || *args == 'm' || *args == '-')
8542	args++;
8543
8544      if (mips_optional_operand_p (operand)
8545	  && args[1] == ','
8546	  && (arg.token[0].type != OT_REG
8547	      || arg.token[1].type == OT_END))
8548	{
8549	  /* Assume that the register has been elided and is the
8550	     same as the first operand.  */
8551	  arg.token = tokens;
8552	  arg.argnum = 1;
8553	}
8554
8555      if (!match_operand (&arg, operand))
8556	return false;
8557    }
8558}
8559
8560/* Like match_insn, but for MIPS16.  */
8561
8562static bool
8563match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8564		   struct mips_operand_token *tokens)
8565{
8566  const char *args;
8567  const struct mips_operand *operand;
8568  const struct mips_operand *ext_operand;
8569  bool pcrel = false;
8570  int required_insn_length;
8571  struct mips_arg_info arg;
8572  int relax_char;
8573
8574  if (forced_insn_length)
8575    required_insn_length = forced_insn_length;
8576  else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8577    required_insn_length = 2;
8578  else
8579    required_insn_length = 0;
8580
8581  create_insn (insn, opcode);
8582  imm_expr.X_op = O_absent;
8583  offset_expr.X_op = O_absent;
8584  offset_reloc[0] = BFD_RELOC_UNUSED;
8585  offset_reloc[1] = BFD_RELOC_UNUSED;
8586  offset_reloc[2] = BFD_RELOC_UNUSED;
8587  relax_char = 0;
8588
8589  memset (&arg, 0, sizeof (arg));
8590  arg.insn = insn;
8591  arg.token = tokens;
8592  arg.argnum = 1;
8593  arg.last_regno = ILLEGAL_REG;
8594  arg.dest_regno = ILLEGAL_REG;
8595  relax_char = 0;
8596  for (args = opcode->args;; ++args)
8597    {
8598      int c;
8599
8600      if (arg.token->type == OT_END)
8601	{
8602	  offsetT value;
8603
8604	  /* Handle unary instructions in which only one operand is given.
8605	     The source is then the same as the destination.  */
8606	  if (arg.opnum == 1 && *args == ',')
8607	    {
8608	      operand = decode_mips16_operand (args[1], false);
8609	      if (operand && mips_optional_operand_p (operand))
8610		{
8611		  arg.token = tokens;
8612		  arg.argnum = 1;
8613		  continue;
8614		}
8615	    }
8616
8617	  /* Fail the match if there were too few operands.  */
8618	  if (*args)
8619	    return false;
8620
8621	  /* Successful match.  Stuff the immediate value in now, if
8622	     we can.  */
8623	  clear_insn_error ();
8624	  if (opcode->pinfo == INSN_MACRO)
8625	    {
8626	      gas_assert (relax_char == 0 || relax_char == 'p');
8627	      gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8628	    }
8629	  else if (relax_char
8630		   && offset_expr.X_op == O_constant
8631		   && !pcrel
8632		   && calculate_reloc (*offset_reloc,
8633				       offset_expr.X_add_number,
8634				       &value))
8635	    {
8636	      mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8637			    required_insn_length, &insn->insn_opcode);
8638	      offset_expr.X_op = O_absent;
8639	      *offset_reloc = BFD_RELOC_UNUSED;
8640	    }
8641	  else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8642	    {
8643	      if (required_insn_length == 2)
8644		set_insn_error (0, _("invalid unextended operand value"));
8645	      else if (!mips_opcode_32bit_p (opcode))
8646		{
8647		  forced_insn_length = 4;
8648		  insn->insn_opcode |= MIPS16_EXTEND;
8649		}
8650	    }
8651	  else if (relax_char)
8652	    *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8653
8654	  check_completed_insn (&arg);
8655	  return true;
8656	}
8657
8658      /* Fail the match if the line has too many operands.   */
8659      if (*args == 0)
8660	return false;
8661
8662      /* Handle characters that need to match exactly.  */
8663      if (*args == '(' || *args == ')' || *args == ',')
8664	{
8665	  if (match_char (&arg, *args))
8666	    continue;
8667	  return false;
8668	}
8669
8670      arg.opnum += 1;
8671      c = *args;
8672      switch (c)
8673	{
8674	case 'p':
8675	case 'q':
8676	case 'A':
8677	case 'B':
8678	case 'E':
8679	case 'V':
8680	case 'u':
8681	  relax_char = c;
8682	  break;
8683
8684	case 'I':
8685	  if (!match_const_int (&arg, &imm_expr.X_add_number))
8686	    return false;
8687	  imm_expr.X_op = O_constant;
8688	  if (GPR_SIZE == 32)
8689	    normalize_constant_expr (&imm_expr);
8690	  continue;
8691
8692	case 'a':
8693	case 'i':
8694	  *offset_reloc = BFD_RELOC_MIPS16_JMP;
8695	  break;
8696	}
8697
8698      operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8699      if (!operand)
8700	abort ();
8701
8702      if (operand->type == OP_PCREL)
8703	pcrel = true;
8704      else
8705	{
8706	  ext_operand = decode_mips16_operand (c, true);
8707	  if (operand != ext_operand)
8708	    {
8709	      if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8710		{
8711		  offset_expr.X_op = O_constant;
8712		  offset_expr.X_add_number = 0;
8713		  relax_char = c;
8714		  continue;
8715		}
8716
8717	      if (!match_expression (&arg, &offset_expr, offset_reloc))
8718		return false;
8719
8720	      /* '8' is used for SLTI(U) and has traditionally not
8721		 been allowed to take relocation operators.  */
8722	      if (offset_reloc[0] != BFD_RELOC_UNUSED
8723		  && (ext_operand->size != 16 || c == '8'))
8724		{
8725		  match_not_constant (&arg);
8726		  return false;
8727		}
8728
8729	      if (offset_expr.X_op == O_big)
8730		{
8731		  match_out_of_range (&arg);
8732		  return false;
8733		}
8734
8735	      relax_char = c;
8736	      continue;
8737	    }
8738	}
8739
8740      if (mips_optional_operand_p (operand)
8741	  && args[1] == ','
8742	  && (arg.token[0].type != OT_REG
8743	      || arg.token[1].type == OT_END))
8744	{
8745	  /* Assume that the register has been elided and is the
8746	     same as the first operand.  */
8747	  arg.token = tokens;
8748	  arg.argnum = 1;
8749	}
8750
8751      if (!match_operand (&arg, operand))
8752	return false;
8753    }
8754}
8755
8756/* Record that the current instruction is invalid for the current ISA.  */
8757
8758static void
8759match_invalid_for_isa (void)
8760{
8761  set_insn_error_ss
8762    (0, _("opcode not supported on this processor: %s (%s)"),
8763     mips_cpu_info_from_arch (mips_opts.arch)->name,
8764     mips_cpu_info_from_isa (mips_opts.isa)->name);
8765}
8766
8767/* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8768   Return true if a definite match or failure was found, storing any match
8769   in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8770   (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8771   tried and failed to match under normal conditions and now want to try a
8772   more relaxed match.  */
8773
8774static bool
8775match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8776	     const struct mips_opcode *past, struct mips_operand_token *tokens,
8777	     int opcode_extra, bool lax_match)
8778{
8779  const struct mips_opcode *opcode;
8780  const struct mips_opcode *invalid_delay_slot;
8781  bool seen_valid_for_isa, seen_valid_for_size;
8782
8783  /* Search for a match, ignoring alternatives that don't satisfy the
8784     current ISA or forced_length.  */
8785  invalid_delay_slot = 0;
8786  seen_valid_for_isa = false;
8787  seen_valid_for_size = false;
8788  opcode = first;
8789  do
8790    {
8791      gas_assert (strcmp (opcode->name, first->name) == 0);
8792      if (is_opcode_valid (opcode))
8793	{
8794	  seen_valid_for_isa = true;
8795	  if (is_size_valid (opcode))
8796	    {
8797	      bool delay_slot_ok;
8798
8799	      seen_valid_for_size = true;
8800	      delay_slot_ok = is_delay_slot_valid (opcode);
8801	      if (match_insn (insn, opcode, tokens, opcode_extra,
8802			      lax_match, delay_slot_ok))
8803		{
8804		  if (!delay_slot_ok)
8805		    {
8806		      if (!invalid_delay_slot)
8807			invalid_delay_slot = opcode;
8808		    }
8809		  else
8810		    return true;
8811		}
8812	    }
8813	}
8814      ++opcode;
8815    }
8816  while (opcode < past && strcmp (opcode->name, first->name) == 0);
8817
8818  /* If the only matches we found had the wrong length for the delay slot,
8819     pick the first such match.  We'll issue an appropriate warning later.  */
8820  if (invalid_delay_slot)
8821    {
8822      if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8823		      lax_match, true))
8824	return true;
8825      abort ();
8826    }
8827
8828  /* Handle the case where we didn't try to match an instruction because
8829     all the alternatives were incompatible with the current ISA.  */
8830  if (!seen_valid_for_isa)
8831    {
8832      match_invalid_for_isa ();
8833      return true;
8834    }
8835
8836  /* Handle the case where we didn't try to match an instruction because
8837     all the alternatives were of the wrong size.  */
8838  if (!seen_valid_for_size)
8839    {
8840      if (mips_opts.insn32)
8841	set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8842      else
8843	set_insn_error_i
8844	  (0, _("unrecognized %d-bit version of microMIPS opcode"),
8845	   8 * forced_insn_length);
8846      return true;
8847    }
8848
8849  return false;
8850}
8851
8852/* Like match_insns, but for MIPS16.  */
8853
8854static bool
8855match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8856		    struct mips_operand_token *tokens)
8857{
8858  const struct mips_opcode *opcode;
8859  bool seen_valid_for_isa;
8860  bool seen_valid_for_size;
8861
8862  /* Search for a match, ignoring alternatives that don't satisfy the
8863     current ISA.  There are no separate entries for extended forms so
8864     we deal with forced_length later.  */
8865  seen_valid_for_isa = false;
8866  seen_valid_for_size = false;
8867  opcode = first;
8868  do
8869    {
8870      gas_assert (strcmp (opcode->name, first->name) == 0);
8871      if (is_opcode_valid_16 (opcode))
8872	{
8873	  seen_valid_for_isa = true;
8874	  if (is_size_valid_16 (opcode))
8875	    {
8876	      seen_valid_for_size = true;
8877	      if (match_mips16_insn (insn, opcode, tokens))
8878		return true;
8879	    }
8880	}
8881      ++opcode;
8882    }
8883  while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8884	 && strcmp (opcode->name, first->name) == 0);
8885
8886  /* Handle the case where we didn't try to match an instruction because
8887     all the alternatives were incompatible with the current ISA.  */
8888  if (!seen_valid_for_isa)
8889    {
8890      match_invalid_for_isa ();
8891      return true;
8892    }
8893
8894  /* Handle the case where we didn't try to match an instruction because
8895     all the alternatives were of the wrong size.  */
8896  if (!seen_valid_for_size)
8897    {
8898      if (forced_insn_length == 2)
8899	set_insn_error
8900	  (0, _("unrecognized unextended version of MIPS16 opcode"));
8901      else
8902	set_insn_error
8903	  (0, _("unrecognized extended version of MIPS16 opcode"));
8904      return true;
8905    }
8906
8907  return false;
8908}
8909
8910/* Set up global variables for the start of a new macro.  */
8911
8912static void
8913macro_start (void)
8914{
8915  memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8916  memset (&mips_macro_warning.first_insn_sizes, 0,
8917	  sizeof (mips_macro_warning.first_insn_sizes));
8918  memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8919  mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8920				     && delayed_branch_p (&history[0]));
8921  if (history[0].frag
8922      && history[0].frag->fr_type == rs_machine_dependent
8923      && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8924      && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8925    mips_macro_warning.delay_slot_length = 0;
8926  else
8927    switch (history[0].insn_mo->pinfo2
8928	    & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8929      {
8930      case INSN2_BRANCH_DELAY_32BIT:
8931	mips_macro_warning.delay_slot_length = 4;
8932	break;
8933      case INSN2_BRANCH_DELAY_16BIT:
8934	mips_macro_warning.delay_slot_length = 2;
8935	break;
8936      default:
8937	mips_macro_warning.delay_slot_length = 0;
8938	break;
8939      }
8940  mips_macro_warning.first_frag = NULL;
8941}
8942
8943/* Given that a macro is longer than one instruction or of the wrong size,
8944   return the appropriate warning for it.  Return null if no warning is
8945   needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8946   RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8947   and RELAX_NOMACRO.  */
8948
8949static const char *
8950macro_warning (relax_substateT subtype)
8951{
8952  if (subtype & RELAX_DELAY_SLOT)
8953    return _("macro instruction expanded into multiple instructions"
8954	     " in a branch delay slot");
8955  else if (subtype & RELAX_NOMACRO)
8956    return _("macro instruction expanded into multiple instructions");
8957  else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8958		      | RELAX_DELAY_SLOT_SIZE_SECOND))
8959    return ((subtype & RELAX_DELAY_SLOT_16BIT)
8960	    ? _("macro instruction expanded into a wrong size instruction"
8961		" in a 16-bit branch delay slot")
8962	    : _("macro instruction expanded into a wrong size instruction"
8963		" in a 32-bit branch delay slot"));
8964  else
8965    return 0;
8966}
8967
8968/* Finish up a macro.  Emit warnings as appropriate.  */
8969
8970static void
8971macro_end (void)
8972{
8973  /* Relaxation warning flags.  */
8974  relax_substateT subtype = 0;
8975
8976  /* Check delay slot size requirements.  */
8977  if (mips_macro_warning.delay_slot_length == 2)
8978    subtype |= RELAX_DELAY_SLOT_16BIT;
8979  if (mips_macro_warning.delay_slot_length != 0)
8980    {
8981      if (mips_macro_warning.delay_slot_length
8982	  != mips_macro_warning.first_insn_sizes[0])
8983	subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8984      if (mips_macro_warning.delay_slot_length
8985	  != mips_macro_warning.first_insn_sizes[1])
8986	subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8987    }
8988
8989  /* Check instruction count requirements.  */
8990  if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8991    {
8992      if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8993	subtype |= RELAX_SECOND_LONGER;
8994      if (mips_opts.warn_about_macros)
8995	subtype |= RELAX_NOMACRO;
8996      if (mips_macro_warning.delay_slot_p)
8997	subtype |= RELAX_DELAY_SLOT;
8998    }
8999
9000  /* If both alternatives fail to fill a delay slot correctly,
9001     emit the warning now.  */
9002  if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
9003      && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
9004    {
9005      relax_substateT s;
9006      const char *msg;
9007
9008      s = subtype & (RELAX_DELAY_SLOT_16BIT
9009		     | RELAX_DELAY_SLOT_SIZE_FIRST
9010		     | RELAX_DELAY_SLOT_SIZE_SECOND);
9011      msg = macro_warning (s);
9012      if (msg != NULL)
9013	as_warn ("%s", msg);
9014      subtype &= ~s;
9015    }
9016
9017  /* If both implementations are longer than 1 instruction, then emit the
9018     warning now.  */
9019  if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
9020    {
9021      relax_substateT s;
9022      const char *msg;
9023
9024      s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
9025      msg = macro_warning (s);
9026      if (msg != NULL)
9027	as_warn ("%s", msg);
9028      subtype &= ~s;
9029    }
9030
9031  /* If any flags still set, then one implementation might need a warning
9032     and the other either will need one of a different kind or none at all.
9033     Pass any remaining flags over to relaxation.  */
9034  if (mips_macro_warning.first_frag != NULL)
9035    mips_macro_warning.first_frag->fr_subtype |= subtype;
9036}
9037
9038/* Instruction operand formats used in macros that vary between
9039   standard MIPS and microMIPS code.  */
9040
9041static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
9042static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
9043static const char * const jalr_fmt[2] = { "d,s", "t,s" };
9044static const char * const lui_fmt[2] = { "t,u", "s,u" };
9045static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
9046static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
9047static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
9048static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
9049
9050#define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
9051#define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
9052					     : cop12_fmt[mips_opts.micromips])
9053#define JALR_FMT (jalr_fmt[mips_opts.micromips])
9054#define LUI_FMT (lui_fmt[mips_opts.micromips])
9055#define MEM12_FMT (mem12_fmt[mips_opts.micromips])
9056#define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
9057					     : mem12_fmt[mips_opts.micromips])
9058#define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
9059#define SHFT_FMT (shft_fmt[mips_opts.micromips])
9060#define TRAP_FMT (trap_fmt[mips_opts.micromips])
9061
9062/* Read a macro's relocation codes from *ARGS and store them in *R.
9063   The first argument in *ARGS will be either the code for a single
9064   relocation or -1 followed by the three codes that make up a
9065   composite relocation.  */
9066
9067static void
9068macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
9069{
9070  int i, next;
9071
9072  next = va_arg (*args, int);
9073  if (next >= 0)
9074    r[0] = (bfd_reloc_code_real_type) next;
9075  else
9076    {
9077      for (i = 0; i < 3; i++)
9078	r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
9079      /* This function is only used for 16-bit relocation fields.
9080	 To make the macro code simpler, treat an unrelocated value
9081	 in the same way as BFD_RELOC_LO16.  */
9082      if (r[0] == BFD_RELOC_UNUSED)
9083	r[0] = BFD_RELOC_LO16;
9084    }
9085}
9086
9087/* Build an instruction created by a macro expansion.  This is passed
9088   a pointer to the count of instructions created so far, an
9089   expression, the name of the instruction to build, an operand format
9090   string, and corresponding arguments.  */
9091
9092static void
9093macro_build (expressionS *ep, const char *name, const char *fmt, ...)
9094{
9095  const struct mips_opcode *mo = NULL;
9096  bfd_reloc_code_real_type r[3];
9097  const struct mips_opcode *amo;
9098  const struct mips_operand *operand;
9099  htab_t hash;
9100  struct mips_cl_insn insn;
9101  va_list args;
9102  unsigned int uval;
9103
9104  va_start (args, fmt);
9105
9106  if (mips_opts.mips16)
9107    {
9108      mips16_macro_build (ep, name, fmt, &args);
9109      va_end (args);
9110      return;
9111    }
9112
9113  r[0] = BFD_RELOC_UNUSED;
9114  r[1] = BFD_RELOC_UNUSED;
9115  r[2] = BFD_RELOC_UNUSED;
9116  hash = mips_opts.micromips ? micromips_op_hash : op_hash;
9117  amo = (struct mips_opcode *) str_hash_find (hash, name);
9118  gas_assert (amo);
9119  gas_assert (strcmp (name, amo->name) == 0);
9120
9121  do
9122    {
9123      /* Search until we get a match for NAME.  It is assumed here that
9124	 macros will never generate MDMX, MIPS-3D, or MT instructions.
9125	 We try to match an instruction that fulfills the branch delay
9126	 slot instruction length requirement (if any) of the previous
9127	 instruction.  While doing this we record the first instruction
9128	 seen that matches all the other conditions and use it anyway
9129	 if the requirement cannot be met; we will issue an appropriate
9130	 warning later on.  */
9131      if (strcmp (fmt, amo->args) == 0
9132	  && amo->pinfo != INSN_MACRO
9133	  && is_opcode_valid (amo)
9134	  && is_size_valid (amo))
9135	{
9136	  if (is_delay_slot_valid (amo))
9137	    {
9138	      mo = amo;
9139	      break;
9140	    }
9141	  else if (!mo)
9142	    mo = amo;
9143	}
9144
9145      ++amo;
9146      gas_assert (amo->name);
9147    }
9148  while (strcmp (name, amo->name) == 0);
9149
9150  gas_assert (mo);
9151  create_insn (&insn, mo);
9152  for (; *fmt; ++fmt)
9153    {
9154      switch (*fmt)
9155	{
9156	case ',':
9157	case '(':
9158	case ')':
9159	case 'z':
9160	  break;
9161
9162	case 'i':
9163	case 'j':
9164	  macro_read_relocs (&args, r);
9165	  gas_assert (*r == BFD_RELOC_GPREL16
9166		      || *r == BFD_RELOC_MIPS_HIGHER
9167		      || *r == BFD_RELOC_HI16_S
9168		      || *r == BFD_RELOC_LO16
9169		      || *r == BFD_RELOC_MIPS_GOT_OFST
9170		      || (mips_opts.micromips
9171			  && (*r == BFD_RELOC_MIPS_16
9172			      || *r == BFD_RELOC_MIPS_GOT16
9173			      || *r == BFD_RELOC_MIPS_CALL16
9174			      || *r == BFD_RELOC_MIPS_GOT_HI16
9175			      || *r == BFD_RELOC_MIPS_GOT_LO16
9176			      || *r == BFD_RELOC_MIPS_CALL_HI16
9177			      || *r == BFD_RELOC_MIPS_CALL_LO16
9178			      || *r == BFD_RELOC_MIPS_SUB
9179			      || *r == BFD_RELOC_MIPS_GOT_PAGE
9180			      || *r == BFD_RELOC_MIPS_HIGHEST
9181			      || *r == BFD_RELOC_MIPS_GOT_DISP
9182			      || *r == BFD_RELOC_MIPS_TLS_GD
9183			      || *r == BFD_RELOC_MIPS_TLS_LDM
9184			      || *r == BFD_RELOC_MIPS_TLS_DTPREL_HI16
9185			      || *r == BFD_RELOC_MIPS_TLS_DTPREL_LO16
9186			      || *r == BFD_RELOC_MIPS_TLS_GOTTPREL
9187			      || *r == BFD_RELOC_MIPS_TLS_TPREL_HI16
9188			      || *r == BFD_RELOC_MIPS_TLS_TPREL_LO16)));
9189	  break;
9190
9191	case 'o':
9192	  macro_read_relocs (&args, r);
9193	  break;
9194
9195	case 'u':
9196	  macro_read_relocs (&args, r);
9197	  gas_assert (ep != NULL
9198		      && (ep->X_op == O_constant
9199			  || (ep->X_op == O_symbol
9200			      && (*r == BFD_RELOC_MIPS_HIGHEST
9201				  || *r == BFD_RELOC_HI16_S
9202				  || *r == BFD_RELOC_HI16
9203				  || *r == BFD_RELOC_GPREL16
9204				  || *r == BFD_RELOC_MIPS_GOT_HI16
9205				  || *r == BFD_RELOC_MIPS_CALL_HI16))));
9206	  break;
9207
9208	case 'p':
9209	  gas_assert (ep != NULL);
9210
9211	  /*
9212	   * This allows macro() to pass an immediate expression for
9213	   * creating short branches without creating a symbol.
9214	   *
9215	   * We don't allow branch relaxation for these branches, as
9216	   * they should only appear in ".set nomacro" anyway.
9217	   */
9218	  if (ep->X_op == O_constant)
9219	    {
9220	      /* For microMIPS we always use relocations for branches.
9221	         So we should not resolve immediate values.  */
9222	      gas_assert (!mips_opts.micromips);
9223
9224	      if ((ep->X_add_number & 3) != 0)
9225		as_bad (_("branch to misaligned address (0x%lx)"),
9226			(unsigned long) ep->X_add_number);
9227	      if ((ep->X_add_number + 0x20000) & ~0x3ffff)
9228		as_bad (_("branch address range overflow (0x%lx)"),
9229			(unsigned long) ep->X_add_number);
9230	      insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
9231	      ep = NULL;
9232	    }
9233	  else
9234	    *r = BFD_RELOC_16_PCREL_S2;
9235	  break;
9236
9237	case 'a':
9238	  gas_assert (ep != NULL);
9239	  *r = BFD_RELOC_MIPS_JMP;
9240	  break;
9241
9242	default:
9243	  operand = (mips_opts.micromips
9244		     ? decode_micromips_operand (fmt)
9245		     : decode_mips_operand (fmt));
9246	  if (!operand)
9247	    abort ();
9248
9249	  uval = va_arg (args, int);
9250	  if (operand->type == OP_CLO_CLZ_DEST)
9251	    uval |= (uval << 5);
9252	  insn_insert_operand (&insn, operand, uval);
9253
9254	  if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
9255	    ++fmt;
9256	  break;
9257	}
9258    }
9259  va_end (args);
9260  gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
9261
9262  append_insn (&insn, ep, r, true);
9263}
9264
9265static void
9266mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
9267		    va_list *args)
9268{
9269  struct mips_opcode *mo;
9270  struct mips_cl_insn insn;
9271  const struct mips_operand *operand;
9272  bfd_reloc_code_real_type r[3]
9273    = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
9274
9275  mo = (struct mips_opcode *) str_hash_find (mips16_op_hash, name);
9276  gas_assert (mo);
9277  gas_assert (strcmp (name, mo->name) == 0);
9278
9279  while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
9280    {
9281      ++mo;
9282      gas_assert (mo->name);
9283      gas_assert (strcmp (name, mo->name) == 0);
9284    }
9285
9286  create_insn (&insn, mo);
9287  for (; *fmt; ++fmt)
9288    {
9289      int c;
9290
9291      c = *fmt;
9292      switch (c)
9293	{
9294	case ',':
9295	case '(':
9296	case ')':
9297	  break;
9298
9299	case '.':
9300	case 'S':
9301	case 'P':
9302	case 'R':
9303	  break;
9304
9305	case '<':
9306	case '5':
9307	case 'F':
9308	case 'H':
9309	case 'W':
9310	case 'D':
9311	case 'j':
9312	case '8':
9313	case 'V':
9314	case 'C':
9315	case 'U':
9316	case 'k':
9317	case 'K':
9318	case 'p':
9319	case 'q':
9320	  {
9321	    offsetT value;
9322
9323	    gas_assert (ep != NULL);
9324
9325	    if (ep->X_op != O_constant)
9326	      *r = (int) BFD_RELOC_UNUSED + c;
9327	    else if (calculate_reloc (*r, ep->X_add_number, &value))
9328	      {
9329		mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
9330		ep = NULL;
9331		*r = BFD_RELOC_UNUSED;
9332	      }
9333	  }
9334	  break;
9335
9336	default:
9337	  operand = decode_mips16_operand (c, false);
9338	  if (!operand)
9339	    abort ();
9340
9341	  insn_insert_operand (&insn, operand, va_arg (*args, int));
9342	  break;
9343	}
9344    }
9345
9346  gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
9347
9348  append_insn (&insn, ep, r, true);
9349}
9350
9351/*
9352 * Generate a "jalr" instruction with a relocation hint to the called
9353 * function.  This occurs in NewABI PIC code.
9354 */
9355static void
9356macro_build_jalr (expressionS *ep, int cprestore)
9357{
9358  static const bfd_reloc_code_real_type jalr_relocs[2]
9359    = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
9360  bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
9361  const char *jalr;
9362  char *f = NULL;
9363
9364  if (MIPS_JALR_HINT_P (ep))
9365    {
9366      frag_grow (8);
9367      f = frag_more (0);
9368    }
9369  if (mips_opts.micromips)
9370    {
9371      jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
9372	      ? "jalr" : "jalrs");
9373      if (MIPS_JALR_HINT_P (ep)
9374	  || mips_opts.insn32
9375	  || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9376	macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
9377      else
9378	macro_build (NULL, jalr, "mj", PIC_CALL_REG);
9379    }
9380  else
9381    macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
9382  if (MIPS_JALR_HINT_P (ep))
9383    fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, false, jalr_reloc);
9384}
9385
9386/*
9387 * Generate a "lui" instruction.
9388 */
9389static void
9390macro_build_lui (expressionS *ep, int regnum)
9391{
9392  gas_assert (! mips_opts.mips16);
9393
9394  if (ep->X_op != O_constant)
9395    {
9396      gas_assert (ep->X_op == O_symbol);
9397      /* _gp_disp is a special case, used from s_cpload.
9398	 __gnu_local_gp is used if mips_no_shared.  */
9399      gas_assert (mips_pic == NO_PIC
9400	      || (! HAVE_NEWABI
9401		  && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
9402	      || (! mips_in_shared
9403		  && strcmp (S_GET_NAME (ep->X_add_symbol),
9404                             "__gnu_local_gp") == 0));
9405    }
9406
9407  macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
9408}
9409
9410/* Generate a sequence of instructions to do a load or store from a constant
9411   offset off of a base register (breg) into/from a target register (treg),
9412   using AT if necessary.  */
9413static void
9414macro_build_ldst_constoffset (expressionS *ep, const char *op,
9415			      int treg, int breg, int dbl)
9416{
9417  gas_assert (ep->X_op == O_constant);
9418
9419  /* Sign-extending 32-bit constants makes their handling easier.  */
9420  if (!dbl)
9421    normalize_constant_expr (ep);
9422
9423  /* Right now, this routine can only handle signed 32-bit constants.  */
9424  if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
9425    as_warn (_("operand overflow"));
9426
9427  if (IS_SEXT_16BIT_NUM(ep->X_add_number))
9428    {
9429      /* Signed 16-bit offset will fit in the op.  Easy!  */
9430      macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
9431    }
9432  else
9433    {
9434      /* 32-bit offset, need multiple instructions and AT, like:
9435	   lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
9436	   addu     $tempreg,$tempreg,$breg
9437           <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
9438         to handle the complete offset.  */
9439      macro_build_lui (ep, AT);
9440      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
9441      macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
9442
9443      if (!mips_opts.at)
9444	as_bad (_("macro used $at after \".set noat\""));
9445    }
9446}
9447
9448/*			set_at()
9449 * Generates code to set the $at register to true (one)
9450 * if reg is less than the immediate expression.
9451 */
9452static void
9453set_at (int reg, int unsignedp)
9454{
9455  if (imm_expr.X_add_number >= -0x8000
9456      && imm_expr.X_add_number < 0x8000)
9457    macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
9458		 AT, reg, BFD_RELOC_LO16);
9459  else
9460    {
9461      load_register (AT, &imm_expr, GPR_SIZE == 64);
9462      macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
9463    }
9464}
9465
9466/* Count the leading zeroes by performing a binary chop. This is a
9467   bulky bit of source, but performance is a LOT better for the
9468   majority of values than a simple loop to count the bits:
9469       for (lcnt = 0; (lcnt < 32); lcnt++)
9470         if ((v) & (1 << (31 - lcnt)))
9471           break;
9472  However it is not code size friendly, and the gain will drop a bit
9473  on certain cached systems.
9474*/
9475#define COUNT_TOP_ZEROES(v)             \
9476  (((v) & ~0xffff) == 0                 \
9477   ? ((v) & ~0xff) == 0                 \
9478     ? ((v) & ~0xf) == 0                \
9479       ? ((v) & ~0x3) == 0              \
9480         ? ((v) & ~0x1) == 0            \
9481           ? !(v)                       \
9482             ? 32                       \
9483             : 31                       \
9484           : 30                         \
9485         : ((v) & ~0x7) == 0            \
9486           ? 29                         \
9487           : 28                         \
9488       : ((v) & ~0x3f) == 0             \
9489         ? ((v) & ~0x1f) == 0           \
9490           ? 27                         \
9491           : 26                         \
9492         : ((v) & ~0x7f) == 0           \
9493           ? 25                         \
9494           : 24                         \
9495     : ((v) & ~0xfff) == 0              \
9496       ? ((v) & ~0x3ff) == 0            \
9497         ? ((v) & ~0x1ff) == 0          \
9498           ? 23                         \
9499           : 22                         \
9500         : ((v) & ~0x7ff) == 0          \
9501           ? 21                         \
9502           : 20                         \
9503       : ((v) & ~0x3fff) == 0           \
9504         ? ((v) & ~0x1fff) == 0         \
9505           ? 19                         \
9506           : 18                         \
9507         : ((v) & ~0x7fff) == 0         \
9508           ? 17                         \
9509           : 16                         \
9510   : ((v) & ~0xffffff) == 0             \
9511     ? ((v) & ~0xfffff) == 0            \
9512       ? ((v) & ~0x3ffff) == 0          \
9513         ? ((v) & ~0x1ffff) == 0        \
9514           ? 15                         \
9515           : 14                         \
9516         : ((v) & ~0x7ffff) == 0        \
9517           ? 13                         \
9518           : 12                         \
9519       : ((v) & ~0x3fffff) == 0         \
9520         ? ((v) & ~0x1fffff) == 0       \
9521           ? 11                         \
9522           : 10                         \
9523         : ((v) & ~0x7fffff) == 0       \
9524           ? 9                          \
9525           : 8                          \
9526     : ((v) & ~0xfffffff) == 0          \
9527       ? ((v) & ~0x3ffffff) == 0        \
9528         ? ((v) & ~0x1ffffff) == 0      \
9529           ? 7                          \
9530           : 6                          \
9531         : ((v) & ~0x7ffffff) == 0      \
9532           ? 5                          \
9533           : 4                          \
9534       : ((v) & ~0x3fffffff) == 0       \
9535         ? ((v) & ~0x1fffffff) == 0     \
9536           ? 3                          \
9537           : 2                          \
9538         : ((v) & ~0x7fffffff) == 0     \
9539           ? 1                          \
9540           : 0)
9541
9542/*			load_register()
9543 *  This routine generates the least number of instructions necessary to load
9544 *  an absolute expression value into a register.
9545 */
9546static void
9547load_register (int reg, expressionS *ep, int dbl)
9548{
9549  int freg;
9550  expressionS hi32, lo32;
9551
9552  if (ep->X_op != O_big)
9553    {
9554      gas_assert (ep->X_op == O_constant);
9555
9556      /* Sign-extending 32-bit constants makes their handling easier.  */
9557      if (!dbl)
9558	normalize_constant_expr (ep);
9559
9560      if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9561	{
9562	  /* We can handle 16 bit signed values with an addiu to
9563	     $zero.  No need to ever use daddiu here, since $zero and
9564	     the result are always correct in 32 bit mode.  */
9565	  macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9566	  return;
9567	}
9568      else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9569	{
9570	  /* We can handle 16 bit unsigned values with an ori to
9571             $zero.  */
9572	  macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9573	  return;
9574	}
9575      else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9576	{
9577	  /* 32 bit values require an lui.  */
9578	  macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9579	  if ((ep->X_add_number & 0xffff) != 0)
9580	    macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9581	  return;
9582	}
9583    }
9584
9585  /* The value is larger than 32 bits.  */
9586
9587  if (!dbl || GPR_SIZE == 32)
9588    {
9589      char value[32];
9590
9591      sprintf_vma (value, ep->X_add_number);
9592      as_bad (_("number (0x%s) larger than 32 bits"), value);
9593      macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9594      return;
9595    }
9596
9597  if (ep->X_op != O_big)
9598    {
9599      hi32 = *ep;
9600      hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9601      hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9602      hi32.X_add_number &= 0xffffffff;
9603      lo32 = *ep;
9604      lo32.X_add_number &= 0xffffffff;
9605    }
9606  else
9607    {
9608      gas_assert (ep->X_add_number > 2);
9609      if (ep->X_add_number == 3)
9610	generic_bignum[3] = 0;
9611      else if (ep->X_add_number > 4)
9612	as_bad (_("number larger than 64 bits"));
9613      lo32.X_op = O_constant;
9614      lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9615      hi32.X_op = O_constant;
9616      hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9617    }
9618
9619  if (hi32.X_add_number == 0)
9620    freg = 0;
9621  else
9622    {
9623      int shift, bit;
9624      unsigned long hi, lo;
9625
9626      if (hi32.X_add_number == (offsetT) 0xffffffff)
9627	{
9628	  if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9629	    {
9630	      macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9631	      return;
9632	    }
9633	  if (lo32.X_add_number & 0x80000000)
9634	    {
9635	      macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9636	      if (lo32.X_add_number & 0xffff)
9637		macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9638	      return;
9639	    }
9640	}
9641
9642      /* Check for 16bit shifted constant.  We know that hi32 is
9643         non-zero, so start the mask on the first bit of the hi32
9644         value.  */
9645      shift = 17;
9646      do
9647	{
9648	  unsigned long himask, lomask;
9649
9650	  if (shift < 32)
9651	    {
9652	      himask = 0xffff >> (32 - shift);
9653	      lomask = (0xffffU << shift) & 0xffffffff;
9654	    }
9655	  else
9656	    {
9657	      himask = 0xffffU << (shift - 32);
9658	      lomask = 0;
9659	    }
9660	  if ((hi32.X_add_number & ~(offsetT) himask) == 0
9661	      && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9662	    {
9663	      expressionS tmp;
9664
9665	      tmp.X_op = O_constant;
9666	      if (shift < 32)
9667		tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9668				    | (lo32.X_add_number >> shift));
9669	      else
9670		tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9671	      macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9672	      macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9673			   reg, reg, (shift >= 32) ? shift - 32 : shift);
9674	      return;
9675	    }
9676	  ++shift;
9677	}
9678      while (shift <= (64 - 16));
9679
9680      /* Find the bit number of the lowest one bit, and store the
9681         shifted value in hi/lo.  */
9682      hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9683      lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9684      if (lo != 0)
9685	{
9686	  bit = 0;
9687	  while ((lo & 1) == 0)
9688	    {
9689	      lo >>= 1;
9690	      ++bit;
9691	    }
9692	  if (bit != 0)
9693	    {
9694	      lo |= (hi & ((2UL << (bit - 1)) - 1)) << (32 - bit);
9695	      hi >>= bit;
9696	    }
9697	}
9698      else
9699	{
9700	  bit = 32;
9701	  while ((hi & 1) == 0)
9702	    {
9703	      hi >>= 1;
9704	      ++bit;
9705	    }
9706	  lo = hi;
9707	  hi = 0;
9708	}
9709
9710      /* Optimize if the shifted value is a (power of 2) - 1.  */
9711      if ((hi == 0 && ((lo + 1) & lo) == 0)
9712	  || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9713	{
9714	  shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9715	  if (shift != 0)
9716	    {
9717	      expressionS tmp;
9718
9719	      /* This instruction will set the register to be all
9720                 ones.  */
9721	      tmp.X_op = O_constant;
9722	      tmp.X_add_number = (offsetT) -1;
9723	      macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9724	      if (bit != 0)
9725		{
9726		  bit += shift;
9727		  macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9728			       reg, reg, (bit >= 32) ? bit - 32 : bit);
9729		}
9730	      macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9731			   reg, reg, (shift >= 32) ? shift - 32 : shift);
9732	      return;
9733	    }
9734	}
9735
9736      /* Sign extend hi32 before calling load_register, because we can
9737         generally get better code when we load a sign extended value.  */
9738      if ((hi32.X_add_number & 0x80000000) != 0)
9739	hi32.X_add_number |= ~(offsetT) 0xffffffff;
9740      load_register (reg, &hi32, 0);
9741      freg = reg;
9742    }
9743  if ((lo32.X_add_number & 0xffff0000) == 0)
9744    {
9745      if (freg != 0)
9746	{
9747	  macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9748	  freg = reg;
9749	}
9750    }
9751  else
9752    {
9753      expressionS mid16;
9754
9755      if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9756	{
9757	  macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9758	  macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9759	  return;
9760	}
9761
9762      if (freg != 0)
9763	{
9764	  macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9765	  freg = reg;
9766	}
9767      mid16 = lo32;
9768      mid16.X_add_number >>= 16;
9769      macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9770      macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9771      freg = reg;
9772    }
9773  if ((lo32.X_add_number & 0xffff) != 0)
9774    macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9775}
9776
9777static inline void
9778load_delay_nop (void)
9779{
9780  if (!gpr_interlocks)
9781    macro_build (NULL, "nop", "");
9782}
9783
9784/* Load an address into a register.  */
9785
9786static void
9787load_address (int reg, expressionS *ep, int *used_at)
9788{
9789  if (ep->X_op != O_constant
9790      && ep->X_op != O_symbol)
9791    {
9792      as_bad (_("expression too complex"));
9793      ep->X_op = O_constant;
9794    }
9795
9796  if (ep->X_op == O_constant)
9797    {
9798      load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9799      return;
9800    }
9801
9802  if (mips_pic == NO_PIC)
9803    {
9804      /* If this is a reference to a GP relative symbol, we want
9805	   addiu	$reg,$gp,<sym>		(BFD_RELOC_GPREL16)
9806	 Otherwise we want
9807	   lui		$reg,<sym>		(BFD_RELOC_HI16_S)
9808	   addiu	$reg,$reg,<sym>		(BFD_RELOC_LO16)
9809	 If we have an addend, we always use the latter form.
9810
9811	 With 64bit address space and a usable $at we want
9812	   lui		$reg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
9813	   lui		$at,<sym>		(BFD_RELOC_HI16_S)
9814	   daddiu	$reg,<sym>		(BFD_RELOC_MIPS_HIGHER)
9815	   daddiu	$at,<sym>		(BFD_RELOC_LO16)
9816	   dsll32	$reg,0
9817	   daddu	$reg,$reg,$at
9818
9819	 If $at is already in use, we use a path which is suboptimal
9820	 on superscalar processors.
9821	   lui		$reg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
9822	   daddiu	$reg,<sym>		(BFD_RELOC_MIPS_HIGHER)
9823	   dsll		$reg,16
9824	   daddiu	$reg,<sym>		(BFD_RELOC_HI16_S)
9825	   dsll		$reg,16
9826	   daddiu	$reg,<sym>		(BFD_RELOC_LO16)
9827
9828	 For GP relative symbols in 64bit address space we can use
9829	 the same sequence as in 32bit address space.  */
9830      if (HAVE_64BIT_SYMBOLS)
9831	{
9832	  if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9833	      && !nopic_need_relax (ep->X_add_symbol, 1))
9834	    {
9835	      relax_start (ep->X_add_symbol);
9836	      macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9837			   mips_gp_register, BFD_RELOC_GPREL16);
9838	      relax_switch ();
9839	    }
9840
9841	  if (*used_at == 0 && mips_opts.at)
9842	    {
9843	      macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9844	      macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9845	      macro_build (ep, "daddiu", "t,r,j", reg, reg,
9846			   BFD_RELOC_MIPS_HIGHER);
9847	      macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9848	      macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9849	      macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9850	      *used_at = 1;
9851	    }
9852	  else
9853	    {
9854	      macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9855	      macro_build (ep, "daddiu", "t,r,j", reg, reg,
9856			   BFD_RELOC_MIPS_HIGHER);
9857	      macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9858	      macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9859	      macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9860	      macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9861	    }
9862
9863	  if (mips_relax.sequence)
9864	    relax_end ();
9865	}
9866      else
9867	{
9868	  if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9869	      && !nopic_need_relax (ep->X_add_symbol, 1))
9870	    {
9871	      relax_start (ep->X_add_symbol);
9872	      macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9873			   mips_gp_register, BFD_RELOC_GPREL16);
9874	      relax_switch ();
9875	    }
9876	  macro_build_lui (ep, reg);
9877	  macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9878		       reg, reg, BFD_RELOC_LO16);
9879	  if (mips_relax.sequence)
9880	    relax_end ();
9881	}
9882    }
9883  else if (!mips_big_got)
9884    {
9885      expressionS ex;
9886
9887      /* If this is a reference to an external symbol, we want
9888	   lw		$reg,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
9889	 Otherwise we want
9890	   lw		$reg,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
9891	   nop
9892	   addiu	$reg,$reg,<sym>		(BFD_RELOC_LO16)
9893	 If there is a constant, it must be added in after.
9894
9895	 If we have NewABI, we want
9896	   lw		$reg,<sym+cst>($gp)	(BFD_RELOC_MIPS_GOT_DISP)
9897         unless we're referencing a global symbol with a non-zero
9898         offset, in which case cst must be added separately.  */
9899      if (HAVE_NEWABI)
9900	{
9901	  if (ep->X_add_number)
9902	    {
9903	      ex.X_add_number = ep->X_add_number;
9904	      ep->X_add_number = 0;
9905	      relax_start (ep->X_add_symbol);
9906	      macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9907			   BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9908	      if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9909		as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9910	      ex.X_op = O_constant;
9911	      macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9912			   reg, reg, BFD_RELOC_LO16);
9913	      ep->X_add_number = ex.X_add_number;
9914	      relax_switch ();
9915	    }
9916	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9917		       BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9918	  if (mips_relax.sequence)
9919	    relax_end ();
9920	}
9921      else
9922	{
9923	  ex.X_add_number = ep->X_add_number;
9924	  ep->X_add_number = 0;
9925	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9926		       BFD_RELOC_MIPS_GOT16, mips_gp_register);
9927	  load_delay_nop ();
9928	  relax_start (ep->X_add_symbol);
9929	  relax_switch ();
9930	  macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9931		       BFD_RELOC_LO16);
9932	  relax_end ();
9933
9934	  if (ex.X_add_number != 0)
9935	    {
9936	      if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9937		as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9938	      ex.X_op = O_constant;
9939	      macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9940			   reg, reg, BFD_RELOC_LO16);
9941	    }
9942	}
9943    }
9944  else if (mips_big_got)
9945    {
9946      expressionS ex;
9947
9948      /* This is the large GOT case.  If this is a reference to an
9949	 external symbol, we want
9950	   lui		$reg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
9951	   addu		$reg,$reg,$gp
9952	   lw		$reg,<sym>($reg)	(BFD_RELOC_MIPS_GOT_LO16)
9953
9954	 Otherwise, for a reference to a local symbol in old ABI, we want
9955	   lw		$reg,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
9956	   nop
9957	   addiu	$reg,$reg,<sym>		(BFD_RELOC_LO16)
9958	 If there is a constant, it must be added in after.
9959
9960	 In the NewABI, for local symbols, with or without offsets, we want:
9961	   lw		$reg,<sym>($gp)		(BFD_RELOC_MIPS_GOT_PAGE)
9962	   addiu	$reg,$reg,<sym>		(BFD_RELOC_MIPS_GOT_OFST)
9963      */
9964      if (HAVE_NEWABI)
9965	{
9966	  ex.X_add_number = ep->X_add_number;
9967	  ep->X_add_number = 0;
9968	  relax_start (ep->X_add_symbol);
9969	  macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9970	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9971		       reg, reg, mips_gp_register);
9972	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9973		       reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9974	  if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9975	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9976	  else if (ex.X_add_number)
9977	    {
9978	      ex.X_op = O_constant;
9979	      macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9980			   BFD_RELOC_LO16);
9981	    }
9982
9983	  ep->X_add_number = ex.X_add_number;
9984	  relax_switch ();
9985	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9986		       BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9987	  macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9988		       BFD_RELOC_MIPS_GOT_OFST);
9989	  relax_end ();
9990	}
9991      else
9992	{
9993	  ex.X_add_number = ep->X_add_number;
9994	  ep->X_add_number = 0;
9995	  relax_start (ep->X_add_symbol);
9996	  macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9997	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9998		       reg, reg, mips_gp_register);
9999	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
10000		       reg, BFD_RELOC_MIPS_GOT_LO16, reg);
10001	  relax_switch ();
10002	  if (reg_needs_delay (mips_gp_register))
10003	    {
10004	      /* We need a nop before loading from $gp.  This special
10005		 check is required because the lui which starts the main
10006		 instruction stream does not refer to $gp, and so will not
10007		 insert the nop which may be required.  */
10008	      macro_build (NULL, "nop", "");
10009	    }
10010	  macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
10011		       BFD_RELOC_MIPS_GOT16, mips_gp_register);
10012	  load_delay_nop ();
10013	  macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
10014		       BFD_RELOC_LO16);
10015	  relax_end ();
10016
10017	  if (ex.X_add_number != 0)
10018	    {
10019	      if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
10020		as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10021	      ex.X_op = O_constant;
10022	      macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
10023			   BFD_RELOC_LO16);
10024	    }
10025	}
10026    }
10027  else
10028    abort ();
10029
10030  if (!mips_opts.at && *used_at == 1)
10031    as_bad (_("macro used $at after \".set noat\""));
10032}
10033
10034/* Move the contents of register SOURCE into register DEST.  */
10035
10036static void
10037move_register (int dest, int source)
10038{
10039  /* Prefer to use a 16-bit microMIPS instruction unless the previous
10040     instruction specifically requires a 32-bit one.  */
10041  if (mips_opts.micromips
10042      && !mips_opts.insn32
10043      && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10044    macro_build (NULL, "move", "mp,mj", dest, source);
10045  else
10046    macro_build (NULL, "or", "d,v,t", dest, source, 0);
10047}
10048
10049/* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
10050   LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
10051   The two alternatives are:
10052
10053   Global symbol		Local symbol
10054   -------------		------------
10055   lw DEST,%got(SYMBOL)		lw DEST,%got(SYMBOL + OFFSET)
10056   ...				...
10057   addiu DEST,DEST,OFFSET	addiu DEST,DEST,%lo(SYMBOL + OFFSET)
10058
10059   load_got_offset emits the first instruction and add_got_offset
10060   emits the second for a 16-bit offset or add_got_offset_hilo emits
10061   a sequence to add a 32-bit offset using a scratch register.  */
10062
10063static void
10064load_got_offset (int dest, expressionS *local)
10065{
10066  expressionS global;
10067
10068  global = *local;
10069  global.X_add_number = 0;
10070
10071  relax_start (local->X_add_symbol);
10072  macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
10073	       BFD_RELOC_MIPS_GOT16, mips_gp_register);
10074  relax_switch ();
10075  macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
10076	       BFD_RELOC_MIPS_GOT16, mips_gp_register);
10077  relax_end ();
10078}
10079
10080static void
10081add_got_offset (int dest, expressionS *local)
10082{
10083  expressionS global;
10084
10085  global.X_op = O_constant;
10086  global.X_op_symbol = NULL;
10087  global.X_add_symbol = NULL;
10088  global.X_add_number = local->X_add_number;
10089
10090  relax_start (local->X_add_symbol);
10091  macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
10092	       dest, dest, BFD_RELOC_LO16);
10093  relax_switch ();
10094  macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
10095  relax_end ();
10096}
10097
10098static void
10099add_got_offset_hilo (int dest, expressionS *local, int tmp)
10100{
10101  expressionS global;
10102  int hold_mips_optimize;
10103
10104  global.X_op = O_constant;
10105  global.X_op_symbol = NULL;
10106  global.X_add_symbol = NULL;
10107  global.X_add_number = local->X_add_number;
10108
10109  relax_start (local->X_add_symbol);
10110  load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
10111  relax_switch ();
10112  /* Set mips_optimize around the lui instruction to avoid
10113     inserting an unnecessary nop after the lw.  */
10114  hold_mips_optimize = mips_optimize;
10115  mips_optimize = 2;
10116  macro_build_lui (&global, tmp);
10117  mips_optimize = hold_mips_optimize;
10118  macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
10119  relax_end ();
10120
10121  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
10122}
10123
10124/* Emit a sequence of instructions to emulate a branch likely operation.
10125   BR is an ordinary branch corresponding to one to be emulated.  BRNEG
10126   is its complementing branch with the original condition negated.
10127   CALL is set if the original branch specified the link operation.
10128   EP, FMT, SREG and TREG specify the usual macro_build() parameters.
10129
10130   Code like this is produced in the noreorder mode:
10131
10132	BRNEG	<args>, 1f
10133	 nop
10134	b	<sym>
10135	 delay slot (executed only if branch taken)
10136    1:
10137
10138   or, if CALL is set:
10139
10140	BRNEG	<args>, 1f
10141	 nop
10142	bal	<sym>
10143	 delay slot (executed only if branch taken)
10144    1:
10145
10146   In the reorder mode the delay slot would be filled with a nop anyway,
10147   so code produced is simply:
10148
10149	BR	<args>, <sym>
10150	 nop
10151
10152   This function is used when producing code for the microMIPS ASE that
10153   does not implement branch likely instructions in hardware.  */
10154
10155static void
10156macro_build_branch_likely (const char *br, const char *brneg,
10157			   int call, expressionS *ep, const char *fmt,
10158			   unsigned int sreg, unsigned int treg)
10159{
10160  int noreorder = mips_opts.noreorder;
10161  expressionS expr1;
10162
10163  gas_assert (mips_opts.micromips);
10164  start_noreorder ();
10165  if (noreorder)
10166    {
10167      micromips_label_expr (&expr1);
10168      macro_build (&expr1, brneg, fmt, sreg, treg);
10169      macro_build (NULL, "nop", "");
10170      macro_build (ep, call ? "bal" : "b", "p");
10171
10172      /* Set to true so that append_insn adds a label.  */
10173      emit_branch_likely_macro = true;
10174    }
10175  else
10176    {
10177      macro_build (ep, br, fmt, sreg, treg);
10178      macro_build (NULL, "nop", "");
10179    }
10180  end_noreorder ();
10181}
10182
10183/* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
10184   the condition code tested.  EP specifies the branch target.  */
10185
10186static void
10187macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
10188{
10189  const int call = 0;
10190  const char *brneg;
10191  const char *br;
10192
10193  switch (type)
10194    {
10195    case M_BC1FL:
10196      br = "bc1f";
10197      brneg = "bc1t";
10198      break;
10199    case M_BC1TL:
10200      br = "bc1t";
10201      brneg = "bc1f";
10202      break;
10203    case M_BC2FL:
10204      br = "bc2f";
10205      brneg = "bc2t";
10206      break;
10207    case M_BC2TL:
10208      br = "bc2t";
10209      brneg = "bc2f";
10210      break;
10211    default:
10212      abort ();
10213    }
10214  macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
10215}
10216
10217/* Emit a two-argument branch macro specified by TYPE, using SREG as
10218   the register tested.  EP specifies the branch target.  */
10219
10220static void
10221macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
10222{
10223  const char *brneg = NULL;
10224  const char *br;
10225  int call = 0;
10226
10227  switch (type)
10228    {
10229    case M_BGEZ:
10230      br = "bgez";
10231      break;
10232    case M_BGEZL:
10233      br = mips_opts.micromips ? "bgez" : "bgezl";
10234      brneg = "bltz";
10235      break;
10236    case M_BGEZALL:
10237      gas_assert (mips_opts.micromips);
10238      br = mips_opts.insn32 ? "bgezal" : "bgezals";
10239      brneg = "bltz";
10240      call = 1;
10241      break;
10242    case M_BGTZ:
10243      br = "bgtz";
10244      break;
10245    case M_BGTZL:
10246      br = mips_opts.micromips ? "bgtz" : "bgtzl";
10247      brneg = "blez";
10248      break;
10249    case M_BLEZ:
10250      br = "blez";
10251      break;
10252    case M_BLEZL:
10253      br = mips_opts.micromips ? "blez" : "blezl";
10254      brneg = "bgtz";
10255      break;
10256    case M_BLTZ:
10257      br = "bltz";
10258      break;
10259    case M_BLTZL:
10260      br = mips_opts.micromips ? "bltz" : "bltzl";
10261      brneg = "bgez";
10262      break;
10263    case M_BLTZALL:
10264      gas_assert (mips_opts.micromips);
10265      br = mips_opts.insn32 ? "bltzal" : "bltzals";
10266      brneg = "bgez";
10267      call = 1;
10268      break;
10269    default:
10270      abort ();
10271    }
10272  if (mips_opts.micromips && brneg)
10273    macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
10274  else
10275    macro_build (ep, br, "s,p", sreg);
10276}
10277
10278/* Emit a three-argument branch macro specified by TYPE, using SREG and
10279   TREG as the registers tested.  EP specifies the branch target.  */
10280
10281static void
10282macro_build_branch_rsrt (int type, expressionS *ep,
10283			 unsigned int sreg, unsigned int treg)
10284{
10285  const char *brneg = NULL;
10286  const int call = 0;
10287  const char *br;
10288
10289  switch (type)
10290    {
10291    case M_BEQ:
10292    case M_BEQ_I:
10293      br = "beq";
10294      break;
10295    case M_BEQL:
10296    case M_BEQL_I:
10297      br = mips_opts.micromips ? "beq" : "beql";
10298      brneg = "bne";
10299      break;
10300    case M_BNE:
10301    case M_BNE_I:
10302      br = "bne";
10303      break;
10304    case M_BNEL:
10305    case M_BNEL_I:
10306      br = mips_opts.micromips ? "bne" : "bnel";
10307      brneg = "beq";
10308      break;
10309    default:
10310      abort ();
10311    }
10312  if (mips_opts.micromips && brneg)
10313    macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
10314  else
10315    macro_build (ep, br, "s,t,p", sreg, treg);
10316}
10317
10318/* Return the high part that should be loaded in order to make the low
10319   part of VALUE accessible using an offset of OFFBITS bits.  */
10320
10321static offsetT
10322offset_high_part (offsetT value, unsigned int offbits)
10323{
10324  offsetT bias;
10325  addressT low_mask;
10326
10327  if (offbits == 0)
10328    return value;
10329  bias = 1 << (offbits - 1);
10330  low_mask = bias * 2 - 1;
10331  return (value + bias) & ~low_mask;
10332}
10333
10334/* Return true if the value stored in offset_expr and offset_reloc
10335   fits into a signed offset of OFFBITS bits.  RANGE is the maximum
10336   amount that the caller wants to add without inducing overflow
10337   and ALIGN is the known alignment of the value in bytes.  */
10338
10339static bool
10340small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
10341{
10342  if (offbits == 16)
10343    {
10344      /* Accept any relocation operator if overflow isn't a concern.  */
10345      if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
10346	return true;
10347
10348      /* These relocations are guaranteed not to overflow in correct links.  */
10349      if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
10350	  || gprel16_reloc_p (*offset_reloc))
10351	return true;
10352    }
10353  if (offset_expr.X_op == O_constant
10354      && offset_high_part (offset_expr.X_add_number, offbits) == 0
10355      && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
10356    return true;
10357  return false;
10358}
10359
10360/*
10361 *			Build macros
10362 *   This routine implements the seemingly endless macro or synthesized
10363 * instructions and addressing modes in the mips assembly language. Many
10364 * of these macros are simple and are similar to each other. These could
10365 * probably be handled by some kind of table or grammar approach instead of
10366 * this verbose method. Others are not simple macros but are more like
10367 * optimizing code generation.
10368 *   One interesting optimization is when several store macros appear
10369 * consecutively that would load AT with the upper half of the same address.
10370 * The ensuing load upper instructions are omitted. This implies some kind
10371 * of global optimization. We currently only optimize within a single macro.
10372 *   For many of the load and store macros if the address is specified as a
10373 * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
10374 * first load register 'at' with zero and use it as the base register. The
10375 * mips assembler simply uses register $zero. Just one tiny optimization
10376 * we're missing.
10377 */
10378static void
10379macro (struct mips_cl_insn *ip, char *str)
10380{
10381  const struct mips_operand_array *operands;
10382  unsigned int breg, i;
10383  unsigned int tempreg;
10384  int mask;
10385  int used_at = 0;
10386  expressionS label_expr;
10387  expressionS expr1;
10388  expressionS *ep;
10389  const char *s;
10390  const char *s2;
10391  const char *fmt;
10392  int likely = 0;
10393  int coproc = 0;
10394  int offbits = 16;
10395  int call = 0;
10396  int jals = 0;
10397  int dbl = 0;
10398  int imm = 0;
10399  int ust = 0;
10400  int lp = 0;
10401  int ll_sc_paired = 0;
10402  bool large_offset;
10403  int off;
10404  int hold_mips_optimize;
10405  unsigned int align;
10406  unsigned int op[MAX_OPERANDS];
10407
10408  gas_assert (! mips_opts.mips16);
10409
10410  operands = insn_operands (ip);
10411  for (i = 0; i < MAX_OPERANDS; i++)
10412    if (operands->operand[i])
10413      op[i] = insn_extract_operand (ip, operands->operand[i]);
10414    else
10415      op[i] = -1;
10416
10417  mask = ip->insn_mo->mask;
10418
10419  label_expr.X_op = O_constant;
10420  label_expr.X_op_symbol = NULL;
10421  label_expr.X_add_symbol = NULL;
10422  label_expr.X_add_number = 0;
10423
10424  expr1.X_op = O_constant;
10425  expr1.X_op_symbol = NULL;
10426  expr1.X_add_symbol = NULL;
10427  expr1.X_add_number = 1;
10428  align = 1;
10429
10430  switch (mask)
10431    {
10432    case M_DABS:
10433      dbl = 1;
10434      /* Fall through.  */
10435    case M_ABS:
10436      /*    bgez    $a0,1f
10437	    move    v0,$a0
10438	    sub     v0,$zero,$a0
10439	 1:
10440       */
10441
10442      start_noreorder ();
10443
10444      if (mips_opts.micromips)
10445	micromips_label_expr (&label_expr);
10446      else
10447	label_expr.X_add_number = 8;
10448      macro_build (&label_expr, "bgez", "s,p", op[1]);
10449      if (op[0] == op[1])
10450	macro_build (NULL, "nop", "");
10451      else
10452	move_register (op[0], op[1]);
10453      macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
10454      if (mips_opts.micromips)
10455	micromips_add_label ();
10456
10457      end_noreorder ();
10458      break;
10459
10460    case M_ADD_I:
10461      s = "addi";
10462      s2 = "add";
10463      if (ISA_IS_R6 (mips_opts.isa))
10464	goto do_addi_i;
10465      else
10466	goto do_addi;
10467    case M_ADDU_I:
10468      s = "addiu";
10469      s2 = "addu";
10470      goto do_addi;
10471    case M_DADD_I:
10472      dbl = 1;
10473      s = "daddi";
10474      s2 = "dadd";
10475      if (!mips_opts.micromips && !ISA_IS_R6 (mips_opts.isa))
10476	goto do_addi;
10477      if (imm_expr.X_add_number >= -0x200
10478	  && imm_expr.X_add_number < 0x200
10479	  && !ISA_IS_R6 (mips_opts.isa))
10480	{
10481	  macro_build (NULL, s, "t,r,.", op[0], op[1],
10482		       (int) imm_expr.X_add_number);
10483	  break;
10484	}
10485      goto do_addi_i;
10486    case M_DADDU_I:
10487      dbl = 1;
10488      s = "daddiu";
10489      s2 = "daddu";
10490    do_addi:
10491      if (imm_expr.X_add_number >= -0x8000
10492	  && imm_expr.X_add_number < 0x8000)
10493	{
10494	  macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
10495	  break;
10496	}
10497    do_addi_i:
10498      used_at = 1;
10499      load_register (AT, &imm_expr, dbl);
10500      macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10501      break;
10502
10503    case M_AND_I:
10504      s = "andi";
10505      s2 = "and";
10506      goto do_bit;
10507    case M_OR_I:
10508      s = "ori";
10509      s2 = "or";
10510      goto do_bit;
10511    case M_NOR_I:
10512      s = "";
10513      s2 = "nor";
10514      goto do_bit;
10515    case M_XOR_I:
10516      s = "xori";
10517      s2 = "xor";
10518    do_bit:
10519      if (imm_expr.X_add_number >= 0
10520	  && imm_expr.X_add_number < 0x10000)
10521	{
10522	  if (mask != M_NOR_I)
10523	    macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10524	  else
10525	    {
10526	      macro_build (&imm_expr, "ori", "t,r,i",
10527			   op[0], op[1], BFD_RELOC_LO16);
10528	      macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10529	    }
10530	  break;
10531	}
10532
10533      used_at = 1;
10534      load_register (AT, &imm_expr, GPR_SIZE == 64);
10535      macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10536      break;
10537
10538    case M_BALIGN:
10539      switch (imm_expr.X_add_number)
10540	{
10541	case 0:
10542	  macro_build (NULL, "nop", "");
10543	  break;
10544	case 2:
10545	  macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10546	  break;
10547	case 1:
10548	case 3:
10549	  macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10550		       (int) imm_expr.X_add_number);
10551	  break;
10552	default:
10553	  as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10554		  (unsigned long) imm_expr.X_add_number);
10555	  break;
10556	}
10557      break;
10558
10559    case M_BC1FL:
10560    case M_BC1TL:
10561    case M_BC2FL:
10562    case M_BC2TL:
10563      gas_assert (mips_opts.micromips);
10564      macro_build_branch_ccl (mask, &offset_expr,
10565			      EXTRACT_OPERAND (1, BCC, *ip));
10566      break;
10567
10568    case M_BEQ_I:
10569    case M_BEQL_I:
10570    case M_BNE_I:
10571    case M_BNEL_I:
10572      if (imm_expr.X_add_number == 0)
10573	op[1] = 0;
10574      else
10575	{
10576	  op[1] = AT;
10577	  used_at = 1;
10578	  load_register (op[1], &imm_expr, GPR_SIZE == 64);
10579	}
10580      /* Fall through.  */
10581    case M_BEQL:
10582    case M_BNEL:
10583      macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10584      break;
10585
10586    case M_BGEL:
10587      likely = 1;
10588      /* Fall through.  */
10589    case M_BGE:
10590      if (op[1] == 0)
10591	macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10592      else if (op[0] == 0)
10593	macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10594      else
10595	{
10596	  used_at = 1;
10597	  macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10598	  macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10599				   &offset_expr, AT, ZERO);
10600	}
10601      break;
10602
10603    case M_BGEZL:
10604    case M_BGEZALL:
10605    case M_BGTZL:
10606    case M_BLEZL:
10607    case M_BLTZL:
10608    case M_BLTZALL:
10609      macro_build_branch_rs (mask, &offset_expr, op[0]);
10610      break;
10611
10612    case M_BGTL_I:
10613      likely = 1;
10614      /* Fall through.  */
10615    case M_BGT_I:
10616      /* Check for > max integer.  */
10617      if (imm_expr.X_add_number >= GPR_SMAX)
10618	{
10619	do_false:
10620	  /* Result is always false.  */
10621	  if (! likely)
10622	    macro_build (NULL, "nop", "");
10623	  else
10624	    macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10625	  break;
10626	}
10627      ++imm_expr.X_add_number;
10628      /* Fall through.  */
10629    case M_BGE_I:
10630    case M_BGEL_I:
10631      if (mask == M_BGEL_I)
10632	likely = 1;
10633      if (imm_expr.X_add_number == 0)
10634	{
10635	  macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10636				 &offset_expr, op[0]);
10637	  break;
10638	}
10639      if (imm_expr.X_add_number == 1)
10640	{
10641	  macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10642				 &offset_expr, op[0]);
10643	  break;
10644	}
10645      if (imm_expr.X_add_number <= GPR_SMIN)
10646	{
10647	do_true:
10648	  /* Result is always true.  */
10649	  as_warn (_("branch %s is always true"), ip->insn_mo->name);
10650	  macro_build (&offset_expr, "b", "p");
10651	  break;
10652	}
10653      used_at = 1;
10654      set_at (op[0], 0);
10655      macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10656			       &offset_expr, AT, ZERO);
10657      break;
10658
10659    case M_BGEUL:
10660      likely = 1;
10661      /* Fall through.  */
10662    case M_BGEU:
10663      if (op[1] == 0)
10664	goto do_true;
10665      else if (op[0] == 0)
10666	macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10667				 &offset_expr, ZERO, op[1]);
10668      else
10669	{
10670	  used_at = 1;
10671	  macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10672	  macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10673				   &offset_expr, AT, ZERO);
10674	}
10675      break;
10676
10677    case M_BGTUL_I:
10678      likely = 1;
10679      /* Fall through.  */
10680    case M_BGTU_I:
10681      if (op[0] == 0
10682	  || (GPR_SIZE == 32
10683	      && imm_expr.X_add_number == -1))
10684	goto do_false;
10685      ++imm_expr.X_add_number;
10686      /* Fall through.  */
10687    case M_BGEU_I:
10688    case M_BGEUL_I:
10689      if (mask == M_BGEUL_I)
10690	likely = 1;
10691      if (imm_expr.X_add_number == 0)
10692	goto do_true;
10693      else if (imm_expr.X_add_number == 1)
10694	macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10695				 &offset_expr, op[0], ZERO);
10696      else
10697	{
10698	  used_at = 1;
10699	  set_at (op[0], 1);
10700	  macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10701				   &offset_expr, AT, ZERO);
10702	}
10703      break;
10704
10705    case M_BGTL:
10706      likely = 1;
10707      /* Fall through.  */
10708    case M_BGT:
10709      if (op[1] == 0)
10710	macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10711      else if (op[0] == 0)
10712	macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10713      else
10714	{
10715	  used_at = 1;
10716	  macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10717	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10718				   &offset_expr, AT, ZERO);
10719	}
10720      break;
10721
10722    case M_BGTUL:
10723      likely = 1;
10724      /* Fall through.  */
10725    case M_BGTU:
10726      if (op[1] == 0)
10727	macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10728				 &offset_expr, op[0], ZERO);
10729      else if (op[0] == 0)
10730	goto do_false;
10731      else
10732	{
10733	  used_at = 1;
10734	  macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10735	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10736				   &offset_expr, AT, ZERO);
10737	}
10738      break;
10739
10740    case M_BLEL:
10741      likely = 1;
10742      /* Fall through.  */
10743    case M_BLE:
10744      if (op[1] == 0)
10745	macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10746      else if (op[0] == 0)
10747	macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10748      else
10749	{
10750	  used_at = 1;
10751	  macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10752	  macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10753				   &offset_expr, AT, ZERO);
10754	}
10755      break;
10756
10757    case M_BLEL_I:
10758      likely = 1;
10759      /* Fall through.  */
10760    case M_BLE_I:
10761      if (imm_expr.X_add_number >= GPR_SMAX)
10762	goto do_true;
10763      ++imm_expr.X_add_number;
10764      /* Fall through.  */
10765    case M_BLT_I:
10766    case M_BLTL_I:
10767      if (mask == M_BLTL_I)
10768	likely = 1;
10769      if (imm_expr.X_add_number == 0)
10770	macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10771      else if (imm_expr.X_add_number == 1)
10772	macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10773      else
10774	{
10775	  used_at = 1;
10776	  set_at (op[0], 0);
10777	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10778				   &offset_expr, AT, ZERO);
10779	}
10780      break;
10781
10782    case M_BLEUL:
10783      likely = 1;
10784      /* Fall through.  */
10785    case M_BLEU:
10786      if (op[1] == 0)
10787	macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10788				 &offset_expr, op[0], ZERO);
10789      else if (op[0] == 0)
10790	goto do_true;
10791      else
10792	{
10793	  used_at = 1;
10794	  macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10795	  macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10796				   &offset_expr, AT, ZERO);
10797	}
10798      break;
10799
10800    case M_BLEUL_I:
10801      likely = 1;
10802      /* Fall through.  */
10803    case M_BLEU_I:
10804      if (op[0] == 0
10805	  || (GPR_SIZE == 32
10806	      && imm_expr.X_add_number == -1))
10807	goto do_true;
10808      ++imm_expr.X_add_number;
10809      /* Fall through.  */
10810    case M_BLTU_I:
10811    case M_BLTUL_I:
10812      if (mask == M_BLTUL_I)
10813	likely = 1;
10814      if (imm_expr.X_add_number == 0)
10815	goto do_false;
10816      else if (imm_expr.X_add_number == 1)
10817	macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10818				 &offset_expr, op[0], ZERO);
10819      else
10820	{
10821	  used_at = 1;
10822	  set_at (op[0], 1);
10823	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10824				   &offset_expr, AT, ZERO);
10825	}
10826      break;
10827
10828    case M_BLTL:
10829      likely = 1;
10830      /* Fall through.  */
10831    case M_BLT:
10832      if (op[1] == 0)
10833	macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10834      else if (op[0] == 0)
10835	macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10836      else
10837	{
10838	  used_at = 1;
10839	  macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10840	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10841				   &offset_expr, AT, ZERO);
10842	}
10843      break;
10844
10845    case M_BLTUL:
10846      likely = 1;
10847      /* Fall through.  */
10848    case M_BLTU:
10849      if (op[1] == 0)
10850	goto do_false;
10851      else if (op[0] == 0)
10852	macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10853				 &offset_expr, ZERO, op[1]);
10854      else
10855	{
10856	  used_at = 1;
10857	  macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10858	  macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10859				   &offset_expr, AT, ZERO);
10860	}
10861      break;
10862
10863    case M_DDIV_3:
10864      dbl = 1;
10865      /* Fall through.  */
10866    case M_DIV_3:
10867      s = "mflo";
10868      goto do_div3;
10869    case M_DREM_3:
10870      dbl = 1;
10871      /* Fall through.  */
10872    case M_REM_3:
10873      s = "mfhi";
10874    do_div3:
10875      if (op[2] == 0)
10876	{
10877	  as_warn (_("divide by zero"));
10878	  if (mips_trap)
10879	    macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10880	  else
10881	    macro_build (NULL, "break", BRK_FMT, 7);
10882	  break;
10883	}
10884
10885      start_noreorder ();
10886      if (mips_trap)
10887	{
10888	  macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10889	  macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10890	}
10891      else
10892	{
10893	  if (mips_opts.micromips)
10894	    micromips_label_expr (&label_expr);
10895	  else
10896	    label_expr.X_add_number = 8;
10897	  macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10898	  macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10899	  macro_build (NULL, "break", BRK_FMT, 7);
10900	  if (mips_opts.micromips)
10901	    micromips_add_label ();
10902	}
10903      expr1.X_add_number = -1;
10904      used_at = 1;
10905      load_register (AT, &expr1, dbl);
10906      if (mips_opts.micromips)
10907	micromips_label_expr (&label_expr);
10908      else
10909	label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10910      macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10911      if (dbl)
10912	{
10913	  expr1.X_add_number = 1;
10914	  load_register (AT, &expr1, dbl);
10915	  macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10916	}
10917      else
10918	{
10919	  expr1.X_add_number = 0x80000000;
10920	  macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10921	}
10922      if (mips_trap)
10923	{
10924	  macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10925	  /* We want to close the noreorder block as soon as possible, so
10926	     that later insns are available for delay slot filling.  */
10927	  end_noreorder ();
10928	}
10929      else
10930	{
10931	  if (mips_opts.micromips)
10932	    micromips_label_expr (&label_expr);
10933	  else
10934	    label_expr.X_add_number = 8;
10935	  macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10936	  macro_build (NULL, "nop", "");
10937
10938	  /* We want to close the noreorder block as soon as possible, so
10939	     that later insns are available for delay slot filling.  */
10940	  end_noreorder ();
10941
10942	  macro_build (NULL, "break", BRK_FMT, 6);
10943	}
10944      if (mips_opts.micromips)
10945	micromips_add_label ();
10946      macro_build (NULL, s, MFHL_FMT, op[0]);
10947      break;
10948
10949    case M_DIV_3I:
10950      s = "div";
10951      s2 = "mflo";
10952      goto do_divi;
10953    case M_DIVU_3I:
10954      s = "divu";
10955      s2 = "mflo";
10956      goto do_divi;
10957    case M_REM_3I:
10958      s = "div";
10959      s2 = "mfhi";
10960      goto do_divi;
10961    case M_REMU_3I:
10962      s = "divu";
10963      s2 = "mfhi";
10964      goto do_divi;
10965    case M_DDIV_3I:
10966      dbl = 1;
10967      s = "ddiv";
10968      s2 = "mflo";
10969      goto do_divi;
10970    case M_DDIVU_3I:
10971      dbl = 1;
10972      s = "ddivu";
10973      s2 = "mflo";
10974      goto do_divi;
10975    case M_DREM_3I:
10976      dbl = 1;
10977      s = "ddiv";
10978      s2 = "mfhi";
10979      goto do_divi;
10980    case M_DREMU_3I:
10981      dbl = 1;
10982      s = "ddivu";
10983      s2 = "mfhi";
10984    do_divi:
10985      if (imm_expr.X_add_number == 0)
10986	{
10987	  as_warn (_("divide by zero"));
10988	  if (mips_trap)
10989	    macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10990	  else
10991	    macro_build (NULL, "break", BRK_FMT, 7);
10992	  break;
10993	}
10994      if (imm_expr.X_add_number == 1)
10995	{
10996	  if (strcmp (s2, "mflo") == 0)
10997	    move_register (op[0], op[1]);
10998	  else
10999	    move_register (op[0], ZERO);
11000	  break;
11001	}
11002      if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
11003	{
11004	  if (strcmp (s2, "mflo") == 0)
11005	    macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
11006	  else
11007	    move_register (op[0], ZERO);
11008	  break;
11009	}
11010
11011      used_at = 1;
11012      load_register (AT, &imm_expr, dbl);
11013      macro_build (NULL, s, "z,s,t", op[1], AT);
11014      macro_build (NULL, s2, MFHL_FMT, op[0]);
11015      break;
11016
11017    case M_DIVU_3:
11018      s = "divu";
11019      s2 = "mflo";
11020      goto do_divu3;
11021    case M_REMU_3:
11022      s = "divu";
11023      s2 = "mfhi";
11024      goto do_divu3;
11025    case M_DDIVU_3:
11026      s = "ddivu";
11027      s2 = "mflo";
11028      goto do_divu3;
11029    case M_DREMU_3:
11030      s = "ddivu";
11031      s2 = "mfhi";
11032    do_divu3:
11033      start_noreorder ();
11034      if (mips_trap)
11035	{
11036	  macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
11037	  macro_build (NULL, s, "z,s,t", op[1], op[2]);
11038	  /* We want to close the noreorder block as soon as possible, so
11039	     that later insns are available for delay slot filling.  */
11040	  end_noreorder ();
11041	}
11042      else
11043	{
11044	  if (mips_opts.micromips)
11045	    micromips_label_expr (&label_expr);
11046	  else
11047	    label_expr.X_add_number = 8;
11048	  macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
11049	  macro_build (NULL, s, "z,s,t", op[1], op[2]);
11050
11051	  /* We want to close the noreorder block as soon as possible, so
11052	     that later insns are available for delay slot filling.  */
11053	  end_noreorder ();
11054	  macro_build (NULL, "break", BRK_FMT, 7);
11055	  if (mips_opts.micromips)
11056	    micromips_add_label ();
11057	}
11058      macro_build (NULL, s2, MFHL_FMT, op[0]);
11059      break;
11060
11061    case M_DLCA_AB:
11062      dbl = 1;
11063      /* Fall through.  */
11064    case M_LCA_AB:
11065      call = 1;
11066      goto do_la;
11067    case M_DLA_AB:
11068      dbl = 1;
11069      /* Fall through.  */
11070    case M_LA_AB:
11071    do_la:
11072      /* Load the address of a symbol into a register.  If breg is not
11073	 zero, we then add a base register to it.  */
11074
11075      breg = op[2];
11076      if (dbl && GPR_SIZE == 32)
11077	as_warn (_("dla used to load 32-bit register; recommend using la "
11078		   "instead"));
11079
11080      if (!dbl && HAVE_64BIT_OBJECTS)
11081	as_warn (_("la used to load 64-bit address; recommend using dla "
11082		   "instead"));
11083
11084      if (small_offset_p (0, align, 16))
11085	{
11086	  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
11087		       -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11088	  break;
11089	}
11090
11091      if (mips_opts.at && (op[0] == breg))
11092	{
11093	  tempreg = AT;
11094	  used_at = 1;
11095	}
11096      else
11097	tempreg = op[0];
11098
11099      if (offset_expr.X_op != O_symbol
11100	  && offset_expr.X_op != O_constant)
11101	{
11102	  as_bad (_("expression too complex"));
11103	  offset_expr.X_op = O_constant;
11104	}
11105
11106      if (offset_expr.X_op == O_constant)
11107	load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
11108      else if (mips_pic == NO_PIC)
11109	{
11110	  /* If this is a reference to a GP relative symbol, we want
11111	       addiu	$tempreg,$gp,<sym>	(BFD_RELOC_GPREL16)
11112	     Otherwise we want
11113	       lui	$tempreg,<sym>		(BFD_RELOC_HI16_S)
11114	       addiu	$tempreg,$tempreg,<sym>	(BFD_RELOC_LO16)
11115	     If we have a constant, we need two instructions anyhow,
11116	     so we may as well always use the latter form.
11117
11118	     With 64bit address space and a usable $at we want
11119	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
11120	       lui	$at,<sym>		(BFD_RELOC_HI16_S)
11121	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
11122	       daddiu	$at,<sym>		(BFD_RELOC_LO16)
11123	       dsll32	$tempreg,0
11124	       daddu	$tempreg,$tempreg,$at
11125
11126	     If $at is already in use, we use a path which is suboptimal
11127	     on superscalar processors.
11128	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
11129	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
11130	       dsll	$tempreg,16
11131	       daddiu	$tempreg,<sym>		(BFD_RELOC_HI16_S)
11132	       dsll	$tempreg,16
11133	       daddiu	$tempreg,<sym>		(BFD_RELOC_LO16)
11134
11135	     For GP relative symbols in 64bit address space we can use
11136	     the same sequence as in 32bit address space.  */
11137	  if (HAVE_64BIT_SYMBOLS)
11138	    {
11139	      if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11140		  && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11141		{
11142		  relax_start (offset_expr.X_add_symbol);
11143		  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11144			       tempreg, mips_gp_register, BFD_RELOC_GPREL16);
11145		  relax_switch ();
11146		}
11147
11148	      if (used_at == 0 && mips_opts.at)
11149		{
11150		  macro_build (&offset_expr, "lui", LUI_FMT,
11151			       tempreg, BFD_RELOC_MIPS_HIGHEST);
11152		  macro_build (&offset_expr, "lui", LUI_FMT,
11153			       AT, BFD_RELOC_HI16_S);
11154		  macro_build (&offset_expr, "daddiu", "t,r,j",
11155			       tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
11156		  macro_build (&offset_expr, "daddiu", "t,r,j",
11157			       AT, AT, BFD_RELOC_LO16);
11158		  macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11159		  macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11160		  used_at = 1;
11161		}
11162	      else
11163		{
11164		  macro_build (&offset_expr, "lui", LUI_FMT,
11165			       tempreg, BFD_RELOC_MIPS_HIGHEST);
11166		  macro_build (&offset_expr, "daddiu", "t,r,j",
11167			       tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
11168		  macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11169		  macro_build (&offset_expr, "daddiu", "t,r,j",
11170			       tempreg, tempreg, BFD_RELOC_HI16_S);
11171		  macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11172		  macro_build (&offset_expr, "daddiu", "t,r,j",
11173			       tempreg, tempreg, BFD_RELOC_LO16);
11174		}
11175
11176	      if (mips_relax.sequence)
11177		relax_end ();
11178	    }
11179	  else
11180	    {
11181	      if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11182		  && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11183		{
11184		  relax_start (offset_expr.X_add_symbol);
11185		  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11186			       tempreg, mips_gp_register, BFD_RELOC_GPREL16);
11187		  relax_switch ();
11188		}
11189	      if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11190		as_bad (_("offset too large"));
11191	      macro_build_lui (&offset_expr, tempreg);
11192	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11193			   tempreg, tempreg, BFD_RELOC_LO16);
11194	      if (mips_relax.sequence)
11195		relax_end ();
11196	    }
11197	}
11198      else if (!mips_big_got && !HAVE_NEWABI)
11199	{
11200	  int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11201
11202	  /* If this is a reference to an external symbol, and there
11203	     is no constant, we want
11204	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11205	     or for lca or if tempreg is PIC_CALL_REG
11206	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_CALL16)
11207	     For a local symbol, we want
11208	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11209	       nop
11210	       addiu	$tempreg,$tempreg,<sym>	(BFD_RELOC_LO16)
11211
11212	     If we have a small constant, and this is a reference to
11213	     an external symbol, we want
11214	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11215	       nop
11216	       addiu	$tempreg,$tempreg,<constant>
11217	     For a local symbol, we want the same instruction
11218	     sequence, but we output a BFD_RELOC_LO16 reloc on the
11219	     addiu instruction.
11220
11221	     If we have a large constant, and this is a reference to
11222	     an external symbol, we want
11223	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11224	       lui	$at,<hiconstant>
11225	       addiu	$at,$at,<loconstant>
11226	       addu	$tempreg,$tempreg,$at
11227	     For a local symbol, we want the same instruction
11228	     sequence, but we output a BFD_RELOC_LO16 reloc on the
11229	     addiu instruction.
11230	   */
11231
11232	  if (offset_expr.X_add_number == 0)
11233	    {
11234	      if (mips_pic == SVR4_PIC
11235		  && breg == 0
11236		  && (call || tempreg == PIC_CALL_REG))
11237		lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
11238
11239	      relax_start (offset_expr.X_add_symbol);
11240	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11241			   lw_reloc_type, mips_gp_register);
11242	      if (breg != 0)
11243		{
11244		  /* We're going to put in an addu instruction using
11245		     tempreg, so we may as well insert the nop right
11246		     now.  */
11247		  load_delay_nop ();
11248		}
11249	      relax_switch ();
11250	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11251			   tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
11252	      load_delay_nop ();
11253	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11254			   tempreg, tempreg, BFD_RELOC_LO16);
11255	      relax_end ();
11256	      /* FIXME: If breg == 0, and the next instruction uses
11257		 $tempreg, then if this variant case is used an extra
11258		 nop will be generated.  */
11259	    }
11260	  else if (offset_expr.X_add_number >= -0x8000
11261		   && offset_expr.X_add_number < 0x8000)
11262	    {
11263	      load_got_offset (tempreg, &offset_expr);
11264	      load_delay_nop ();
11265	      add_got_offset (tempreg, &offset_expr);
11266	    }
11267	  else
11268	    {
11269	      expr1.X_add_number = offset_expr.X_add_number;
11270	      offset_expr.X_add_number =
11271		SEXT_16BIT (offset_expr.X_add_number);
11272	      load_got_offset (tempreg, &offset_expr);
11273	      offset_expr.X_add_number = expr1.X_add_number;
11274	      /* If we are going to add in a base register, and the
11275		 target register and the base register are the same,
11276		 then we are using AT as a temporary register.  Since
11277		 we want to load the constant into AT, we add our
11278		 current AT (from the global offset table) and the
11279		 register into the register now, and pretend we were
11280		 not using a base register.  */
11281	      if (breg == op[0])
11282		{
11283		  load_delay_nop ();
11284		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11285			       op[0], AT, breg);
11286		  breg = 0;
11287		  tempreg = op[0];
11288		}
11289	      add_got_offset_hilo (tempreg, &offset_expr, AT);
11290	      used_at = 1;
11291	    }
11292	}
11293      else if (!mips_big_got && HAVE_NEWABI)
11294	{
11295	  int add_breg_early = 0;
11296
11297	  /* If this is a reference to an external, and there is no
11298	     constant, or local symbol (*), with or without a
11299	     constant, we want
11300	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT_DISP)
11301	     or for lca or if tempreg is PIC_CALL_REG
11302	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_CALL16)
11303
11304	     If we have a small constant, and this is a reference to
11305	     an external symbol, we want
11306	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT_DISP)
11307	       addiu	$tempreg,$tempreg,<constant>
11308
11309	     If we have a large constant, and this is a reference to
11310	     an external symbol, we want
11311	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT_DISP)
11312	       lui	$at,<hiconstant>
11313	       addiu	$at,$at,<loconstant>
11314	       addu	$tempreg,$tempreg,$at
11315
11316	     (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
11317	     local symbols, even though it introduces an additional
11318	     instruction.  */
11319
11320	  if (offset_expr.X_add_number)
11321	    {
11322	      expr1.X_add_number = offset_expr.X_add_number;
11323	      offset_expr.X_add_number = 0;
11324
11325	      relax_start (offset_expr.X_add_symbol);
11326	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11327			   BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11328
11329	      if (expr1.X_add_number >= -0x8000
11330		  && expr1.X_add_number < 0x8000)
11331		{
11332		  macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11333			       tempreg, tempreg, BFD_RELOC_LO16);
11334		}
11335	      else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11336		{
11337		  unsigned int dreg;
11338
11339		  /* If we are going to add in a base register, and the
11340		     target register and the base register are the same,
11341		     then we are using AT as a temporary register.  Since
11342		     we want to load the constant into AT, we add our
11343		     current AT (from the global offset table) and the
11344		     register into the register now, and pretend we were
11345		     not using a base register.  */
11346		  if (breg != op[0])
11347		    dreg = tempreg;
11348		  else
11349		    {
11350		      gas_assert (tempreg == AT);
11351		      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11352				   op[0], AT, breg);
11353		      dreg = op[0];
11354		      add_breg_early = 1;
11355		    }
11356
11357		  load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11358		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11359			       dreg, dreg, AT);
11360
11361		  used_at = 1;
11362		}
11363	      else
11364		as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11365
11366	      relax_switch ();
11367	      offset_expr.X_add_number = expr1.X_add_number;
11368
11369	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11370			   BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11371	      if (add_breg_early)
11372		{
11373		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11374			       op[0], tempreg, breg);
11375		  breg = 0;
11376		  tempreg = op[0];
11377		}
11378	      relax_end ();
11379	    }
11380	  else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
11381	    {
11382	      relax_start (offset_expr.X_add_symbol);
11383	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11384			   BFD_RELOC_MIPS_CALL16, mips_gp_register);
11385	      relax_switch ();
11386	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11387			   BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11388	      relax_end ();
11389	    }
11390	  else
11391	    {
11392	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11393			   BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11394	    }
11395	}
11396      else if (mips_big_got && !HAVE_NEWABI)
11397	{
11398	  int gpdelay;
11399	  int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11400	  int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11401	  int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11402
11403	  /* This is the large GOT case.  If this is a reference to an
11404	     external symbol, and there is no constant, we want
11405	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11406	       addu	$tempreg,$tempreg,$gp
11407	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11408	     or for lca or if tempreg is PIC_CALL_REG
11409	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_CALL_HI16)
11410	       addu	$tempreg,$tempreg,$gp
11411	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11412	     For a local symbol, we want
11413	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11414	       nop
11415	       addiu	$tempreg,$tempreg,<sym>	(BFD_RELOC_LO16)
11416
11417	     If we have a small constant, and this is a reference to
11418	     an external symbol, we want
11419	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11420	       addu	$tempreg,$tempreg,$gp
11421	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11422	       nop
11423	       addiu	$tempreg,$tempreg,<constant>
11424	     For a local symbol, we want
11425	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11426	       nop
11427	       addiu	$tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
11428
11429	     If we have a large constant, and this is a reference to
11430	     an external symbol, we want
11431	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11432	       addu	$tempreg,$tempreg,$gp
11433	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11434	       lui	$at,<hiconstant>
11435	       addiu	$at,$at,<loconstant>
11436	       addu	$tempreg,$tempreg,$at
11437	     For a local symbol, we want
11438	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
11439	       lui	$at,<hiconstant>
11440	       addiu	$at,$at,<loconstant>	(BFD_RELOC_LO16)
11441	       addu	$tempreg,$tempreg,$at
11442	  */
11443
11444	  expr1.X_add_number = offset_expr.X_add_number;
11445	  offset_expr.X_add_number = 0;
11446	  relax_start (offset_expr.X_add_symbol);
11447	  gpdelay = reg_needs_delay (mips_gp_register);
11448	  if (expr1.X_add_number == 0 && breg == 0
11449	      && (call || tempreg == PIC_CALL_REG))
11450	    {
11451	      lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11452	      lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11453	    }
11454	  macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11455	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11456		       tempreg, tempreg, mips_gp_register);
11457	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11458		       tempreg, lw_reloc_type, tempreg);
11459	  if (expr1.X_add_number == 0)
11460	    {
11461	      if (breg != 0)
11462		{
11463		  /* We're going to put in an addu instruction using
11464		     tempreg, so we may as well insert the nop right
11465		     now.  */
11466		  load_delay_nop ();
11467		}
11468	    }
11469	  else if (expr1.X_add_number >= -0x8000
11470		   && expr1.X_add_number < 0x8000)
11471	    {
11472	      load_delay_nop ();
11473	      macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11474			   tempreg, tempreg, BFD_RELOC_LO16);
11475	    }
11476	  else
11477	    {
11478	      unsigned int dreg;
11479
11480	      /* If we are going to add in a base register, and the
11481		 target register and the base register are the same,
11482		 then we are using AT as a temporary register.  Since
11483		 we want to load the constant into AT, we add our
11484		 current AT (from the global offset table) and the
11485		 register into the register now, and pretend we were
11486		 not using a base register.  */
11487	      if (breg != op[0])
11488		dreg = tempreg;
11489	      else
11490		{
11491		  gas_assert (tempreg == AT);
11492		  load_delay_nop ();
11493		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11494			       op[0], AT, breg);
11495		  dreg = op[0];
11496		}
11497
11498	      load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11499	      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11500
11501	      used_at = 1;
11502	    }
11503	  offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11504	  relax_switch ();
11505
11506	  if (gpdelay)
11507	    {
11508	      /* This is needed because this instruction uses $gp, but
11509		 the first instruction on the main stream does not.  */
11510	      macro_build (NULL, "nop", "");
11511	    }
11512
11513	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11514		       local_reloc_type, mips_gp_register);
11515	  if (expr1.X_add_number >= -0x8000
11516	      && expr1.X_add_number < 0x8000)
11517	    {
11518	      load_delay_nop ();
11519	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11520			   tempreg, tempreg, BFD_RELOC_LO16);
11521	      /* FIXME: If add_number is 0, and there was no base
11522		 register, the external symbol case ended with a load,
11523		 so if the symbol turns out to not be external, and
11524		 the next instruction uses tempreg, an unnecessary nop
11525		 will be inserted.  */
11526	    }
11527	  else
11528	    {
11529	      if (breg == op[0])
11530		{
11531		  /* We must add in the base register now, as in the
11532		     external symbol case.  */
11533		  gas_assert (tempreg == AT);
11534		  load_delay_nop ();
11535		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11536			       op[0], AT, breg);
11537		  tempreg = op[0];
11538		  /* We set breg to 0 because we have arranged to add
11539		     it in in both cases.  */
11540		  breg = 0;
11541		}
11542
11543	      macro_build_lui (&expr1, AT);
11544	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11545			   AT, AT, BFD_RELOC_LO16);
11546	      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11547			   tempreg, tempreg, AT);
11548	      used_at = 1;
11549	    }
11550	  relax_end ();
11551	}
11552      else if (mips_big_got && HAVE_NEWABI)
11553	{
11554	  int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11555	  int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11556	  int add_breg_early = 0;
11557
11558	  /* This is the large GOT case.  If this is a reference to an
11559	     external symbol, and there is no constant, we want
11560	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11561	       add	$tempreg,$tempreg,$gp
11562	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11563	     or for lca or if tempreg is PIC_CALL_REG
11564	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_CALL_HI16)
11565	       add	$tempreg,$tempreg,$gp
11566	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11567
11568	     If we have a small constant, and this is a reference to
11569	     an external symbol, we want
11570	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11571	       add	$tempreg,$tempreg,$gp
11572	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11573	       addi	$tempreg,$tempreg,<constant>
11574
11575	     If we have a large constant, and this is a reference to
11576	     an external symbol, we want
11577	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
11578	       addu	$tempreg,$tempreg,$gp
11579	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11580	       lui	$at,<hiconstant>
11581	       addi	$at,$at,<loconstant>
11582	       add	$tempreg,$tempreg,$at
11583
11584	     If we have NewABI, and we know it's a local symbol, we want
11585	       lw	$reg,<sym>($gp)		(BFD_RELOC_MIPS_GOT_PAGE)
11586	       addiu	$reg,$reg,<sym>		(BFD_RELOC_MIPS_GOT_OFST)
11587	     otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11588
11589	  relax_start (offset_expr.X_add_symbol);
11590
11591	  expr1.X_add_number = offset_expr.X_add_number;
11592	  offset_expr.X_add_number = 0;
11593
11594	  if (expr1.X_add_number == 0 && breg == 0
11595	      && (call || tempreg == PIC_CALL_REG))
11596	    {
11597	      lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11598	      lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11599	    }
11600	  macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11601	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11602		       tempreg, tempreg, mips_gp_register);
11603	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11604		       tempreg, lw_reloc_type, tempreg);
11605
11606	  if (expr1.X_add_number == 0)
11607	    ;
11608	  else if (expr1.X_add_number >= -0x8000
11609		   && expr1.X_add_number < 0x8000)
11610	    {
11611	      macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11612			   tempreg, tempreg, BFD_RELOC_LO16);
11613	    }
11614	  else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11615	    {
11616	      unsigned int dreg;
11617
11618	      /* If we are going to add in a base register, and the
11619		 target register and the base register are the same,
11620		 then we are using AT as a temporary register.  Since
11621		 we want to load the constant into AT, we add our
11622		 current AT (from the global offset table) and the
11623		 register into the register now, and pretend we were
11624		 not using a base register.  */
11625	      if (breg != op[0])
11626		dreg = tempreg;
11627	      else
11628		{
11629		  gas_assert (tempreg == AT);
11630		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11631			       op[0], AT, breg);
11632		  dreg = op[0];
11633		  add_breg_early = 1;
11634		}
11635
11636	      load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11637	      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11638
11639	      used_at = 1;
11640	    }
11641	  else
11642	    as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11643
11644	  relax_switch ();
11645	  offset_expr.X_add_number = expr1.X_add_number;
11646	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11647		       BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11648	  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11649		       tempreg, BFD_RELOC_MIPS_GOT_OFST);
11650	  if (add_breg_early)
11651	    {
11652	      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11653			   op[0], tempreg, breg);
11654	      breg = 0;
11655	      tempreg = op[0];
11656	    }
11657	  relax_end ();
11658	}
11659      else
11660	abort ();
11661
11662      if (breg != 0)
11663	macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11664      break;
11665
11666    case M_JR_S:
11667      macro_build_jrpatch (&expr1, op[2]);
11668      macro_build (NULL, "jr", "s", op[2]);
11669      return;	/* didn't modify $at */
11670
11671    case M_J_S:
11672      macro_build_jrpatch (&expr1, op[2]);
11673      macro_build (NULL, "j", "s", op[2]);
11674      return;	/* didn't modify $at */
11675
11676    case M_JALR_S:
11677      macro_build_jrpatch (&expr1, op[2]);
11678      macro_build (NULL, "jalr", "s", op[2]);
11679      return;	/* didn't modify $at */
11680
11681    case M_JALR_DS:
11682      macro_build_jrpatch (&expr1, op[2]);
11683      macro_build (NULL, "jalr", "d,s", op[0], op[2]);
11684      return;	/* didn't modify $at */
11685
11686    case M_MSGSND:
11687      gas_assert (!mips_opts.micromips);
11688      macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11689      break;
11690
11691    case M_MSGLD:
11692      gas_assert (!mips_opts.micromips);
11693      macro_build (NULL, "c2", "C", 0x02);
11694      break;
11695
11696    case M_MSGLD_T:
11697      gas_assert (!mips_opts.micromips);
11698      macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11699      break;
11700
11701    case M_MSGWAIT:
11702      gas_assert (!mips_opts.micromips);
11703      macro_build (NULL, "c2", "C", 3);
11704      break;
11705
11706    case M_MSGWAIT_T:
11707      gas_assert (!mips_opts.micromips);
11708      macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11709      break;
11710
11711    case M_J_A:
11712      /* The j instruction may not be used in PIC code, since it
11713	 requires an absolute address.  We convert it to a b
11714	 instruction.  */
11715      if (mips_pic == NO_PIC)
11716	macro_build (&offset_expr, "j", "a");
11717      else
11718	macro_build (&offset_expr, "b", "p");
11719      break;
11720
11721      /* The jal instructions must be handled as macros because when
11722	 generating PIC code they expand to multi-instruction
11723	 sequences.  Normally they are simple instructions.  */
11724    case M_JALS_1:
11725      op[1] = op[0];
11726      op[0] = RA;
11727      /* Fall through.  */
11728    case M_JALS_2:
11729      gas_assert (mips_opts.micromips);
11730      if (mips_opts.insn32)
11731	{
11732	  as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11733	  break;
11734	}
11735      jals = 1;
11736      goto jal;
11737    case M_JAL_1:
11738      op[1] = op[0];
11739      op[0] = RA;
11740      /* Fall through.  */
11741    case M_JAL_2:
11742    jal:
11743      if (mips_pic == NO_PIC)
11744	{
11745	  s = jals ? "jalrs" : "jalr";
11746	  if (mips_opts.micromips
11747	      && !mips_opts.insn32
11748	      && op[0] == RA
11749	      && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11750	    macro_build (NULL, s, "mj", op[1]);
11751	  else
11752	    macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11753	}
11754      else
11755	{
11756	  int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11757			   && mips_cprestore_offset >= 0);
11758
11759	  if (op[1] != PIC_CALL_REG)
11760	    as_warn (_("MIPS PIC call to register other than $25"));
11761
11762	  s = ((mips_opts.micromips
11763		&& !mips_opts.insn32
11764		&& (!mips_opts.noreorder || cprestore))
11765	       ? "jalrs" : "jalr");
11766	  if (mips_opts.micromips
11767	      && !mips_opts.insn32
11768	      && op[0] == RA
11769	      && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11770	    macro_build (NULL, s, "mj", op[1]);
11771	  else
11772	    macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11773	  if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11774	    {
11775	      if (mips_cprestore_offset < 0)
11776		as_warn (_("no .cprestore pseudo-op used in PIC code"));
11777	      else
11778		{
11779		  if (!mips_frame_reg_valid)
11780		    {
11781		      as_warn (_("no .frame pseudo-op used in PIC code"));
11782		      /* Quiet this warning.  */
11783		      mips_frame_reg_valid = 1;
11784		    }
11785		  if (!mips_cprestore_valid)
11786		    {
11787		      as_warn (_("no .cprestore pseudo-op used in PIC code"));
11788		      /* Quiet this warning.  */
11789		      mips_cprestore_valid = 1;
11790		    }
11791		  if (mips_opts.noreorder)
11792		    macro_build (NULL, "nop", "");
11793		  expr1.X_add_number = mips_cprestore_offset;
11794		  macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11795						mips_gp_register,
11796						mips_frame_reg,
11797						HAVE_64BIT_ADDRESSES);
11798		}
11799	    }
11800	}
11801
11802      break;
11803
11804    case M_JALS_A:
11805      gas_assert (mips_opts.micromips);
11806      if (mips_opts.insn32)
11807	{
11808	  as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11809	  break;
11810	}
11811      jals = 1;
11812      /* Fall through.  */
11813    case M_JAL_A:
11814      if (mips_pic == NO_PIC)
11815	macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11816      else if (mips_pic == SVR4_PIC)
11817	{
11818	  /* If this is a reference to an external symbol, and we are
11819	     using a small GOT, we want
11820	       lw	$25,<sym>($gp)		(BFD_RELOC_MIPS_CALL16)
11821	       nop
11822	       jalr	$ra,$25
11823	       nop
11824	       lw	$gp,cprestore($sp)
11825	     The cprestore value is set using the .cprestore
11826	     pseudo-op.  If we are using a big GOT, we want
11827	       lui	$25,<sym>		(BFD_RELOC_MIPS_CALL_HI16)
11828	       addu	$25,$25,$gp
11829	       lw	$25,<sym>($25)		(BFD_RELOC_MIPS_CALL_LO16)
11830	       nop
11831	       jalr	$ra,$25
11832	       nop
11833	       lw	$gp,cprestore($sp)
11834	     If the symbol is not external, we want
11835	       lw	$25,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
11836	       nop
11837	       addiu	$25,$25,<sym>		(BFD_RELOC_LO16)
11838	       jalr	$ra,$25
11839	       nop
11840	       lw $gp,cprestore($sp)
11841
11842	     For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11843	     sequences above, minus nops, unless the symbol is local,
11844	     which enables us to use GOT_PAGE/GOT_OFST (big got) or
11845	     GOT_DISP.  */
11846	  if (HAVE_NEWABI)
11847	    {
11848	      if (!mips_big_got)
11849		{
11850		  relax_start (offset_expr.X_add_symbol);
11851		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11852			       PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11853			       mips_gp_register);
11854		  relax_switch ();
11855		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11856			       PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11857			       mips_gp_register);
11858		  relax_end ();
11859		}
11860	      else
11861		{
11862		  relax_start (offset_expr.X_add_symbol);
11863		  macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11864			       BFD_RELOC_MIPS_CALL_HI16);
11865		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11866			       PIC_CALL_REG, mips_gp_register);
11867		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11868			       PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11869			       PIC_CALL_REG);
11870		  relax_switch ();
11871		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11872			       PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11873			       mips_gp_register);
11874		  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11875			       PIC_CALL_REG, PIC_CALL_REG,
11876			       BFD_RELOC_MIPS_GOT_OFST);
11877		  relax_end ();
11878		}
11879
11880	      macro_build_jalr (&offset_expr, 0);
11881	    }
11882	  else
11883	    {
11884	      relax_start (offset_expr.X_add_symbol);
11885	      if (!mips_big_got)
11886		{
11887		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11888			       PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11889			       mips_gp_register);
11890		  load_delay_nop ();
11891		  relax_switch ();
11892		}
11893	      else
11894		{
11895		  int gpdelay;
11896
11897		  gpdelay = reg_needs_delay (mips_gp_register);
11898		  macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11899			       BFD_RELOC_MIPS_CALL_HI16);
11900		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11901			       PIC_CALL_REG, mips_gp_register);
11902		  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11903			       PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11904			       PIC_CALL_REG);
11905		  load_delay_nop ();
11906		  relax_switch ();
11907		  if (gpdelay)
11908		    macro_build (NULL, "nop", "");
11909		}
11910	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11911			   PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11912			   mips_gp_register);
11913	      load_delay_nop ();
11914	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11915			   PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11916	      relax_end ();
11917	      macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11918
11919	      if (mips_cprestore_offset < 0)
11920		as_warn (_("no .cprestore pseudo-op used in PIC code"));
11921	      else
11922		{
11923		  if (!mips_frame_reg_valid)
11924		    {
11925		      as_warn (_("no .frame pseudo-op used in PIC code"));
11926		      /* Quiet this warning.  */
11927		      mips_frame_reg_valid = 1;
11928		    }
11929		  if (!mips_cprestore_valid)
11930		    {
11931		      as_warn (_("no .cprestore pseudo-op used in PIC code"));
11932		      /* Quiet this warning.  */
11933		      mips_cprestore_valid = 1;
11934		    }
11935		  if (mips_opts.noreorder)
11936		    macro_build (NULL, "nop", "");
11937		  expr1.X_add_number = mips_cprestore_offset;
11938		  macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11939						mips_gp_register,
11940						mips_frame_reg,
11941						HAVE_64BIT_ADDRESSES);
11942		}
11943	    }
11944	}
11945      else if (mips_pic == VXWORKS_PIC)
11946	as_bad (_("non-PIC jump used in PIC library"));
11947      else
11948	abort ();
11949
11950      break;
11951
11952    case M_LBUE_AB:
11953      s = "lbue";
11954      fmt = "t,+j(b)";
11955      offbits = 9;
11956      goto ld_st;
11957    case M_LHUE_AB:
11958      s = "lhue";
11959      fmt = "t,+j(b)";
11960      offbits = 9;
11961      goto ld_st;
11962    case M_LBE_AB:
11963      s = "lbe";
11964      fmt = "t,+j(b)";
11965      offbits = 9;
11966      goto ld_st;
11967    case M_LHE_AB:
11968      s = "lhe";
11969      fmt = "t,+j(b)";
11970      offbits = 9;
11971      goto ld_st;
11972    case M_LLE_AB:
11973      s = "lle";
11974      fmt = "t,+j(b)";
11975      offbits = 9;
11976      goto ld_st;
11977    case M_LWE_AB:
11978      s = "lwe";
11979      fmt = "t,+j(b)";
11980      offbits = 9;
11981      goto ld_st;
11982    case M_LWLE_AB:
11983      s = "lwle";
11984      fmt = "t,+j(b)";
11985      offbits = 9;
11986      goto ld_st;
11987    case M_LWRE_AB:
11988      s = "lwre";
11989      fmt = "t,+j(b)";
11990      offbits = 9;
11991      goto ld_st;
11992    case M_SBE_AB:
11993      s = "sbe";
11994      fmt = "t,+j(b)";
11995      offbits = 9;
11996      goto ld_st;
11997    case M_SCE_AB:
11998      s = "sce";
11999      fmt = "t,+j(b)";
12000      offbits = 9;
12001      goto ld_st;
12002    case M_SHE_AB:
12003      s = "she";
12004      fmt = "t,+j(b)";
12005      offbits = 9;
12006      goto ld_st;
12007    case M_SWE_AB:
12008      s = "swe";
12009      fmt = "t,+j(b)";
12010      offbits = 9;
12011      goto ld_st;
12012    case M_SWLE_AB:
12013      s = "swle";
12014      fmt = "t,+j(b)";
12015      offbits = 9;
12016      goto ld_st;
12017    case M_SWRE_AB:
12018      s = "swre";
12019      fmt = "t,+j(b)";
12020      offbits = 9;
12021      goto ld_st;
12022    case M_ACLR_AB:
12023      s = "aclr";
12024      fmt = "\\,~(b)";
12025      offbits = 12;
12026      goto ld_st;
12027    case M_ASET_AB:
12028      s = "aset";
12029      fmt = "\\,~(b)";
12030      offbits = 12;
12031      goto ld_st;
12032    case M_LB_AB:
12033      s = "lb";
12034      fmt = "t,o(b)";
12035      goto ld;
12036    case M_LBU_AB:
12037      s = "lbu";
12038      fmt = "t,o(b)";
12039      goto ld;
12040    case M_LH_AB:
12041      s = "lh";
12042      fmt = "t,o(b)";
12043      goto ld;
12044    case M_LHU_AB:
12045      s = "lhu";
12046      fmt = "t,o(b)";
12047      goto ld;
12048    case M_LW_AB:
12049      s = "lw";
12050      fmt = "t,o(b)";
12051      goto ld;
12052    case M_LWC0_AB:
12053      gas_assert (!mips_opts.micromips);
12054      s = "lwc0";
12055      fmt = "E,o(b)";
12056      /* Itbl support may require additional care here.  */
12057      coproc = 1;
12058      goto ld_st;
12059    case M_LWC1_AB:
12060      s = "lwc1";
12061      fmt = "T,o(b)";
12062      /* Itbl support may require additional care here.  */
12063      coproc = 1;
12064      goto ld_st;
12065    case M_LWC2_AB:
12066      s = "lwc2";
12067      fmt = COP12_FMT;
12068      offbits = (mips_opts.micromips ? 12
12069		 : ISA_IS_R6 (mips_opts.isa) ? 11
12070		 : 16);
12071      /* Itbl support may require additional care here.  */
12072      coproc = 1;
12073      goto ld_st;
12074    case M_LWC3_AB:
12075      gas_assert (!mips_opts.micromips);
12076      s = "lwc3";
12077      fmt = "E,o(b)";
12078      /* Itbl support may require additional care here.  */
12079      coproc = 1;
12080      goto ld_st;
12081    case M_LWL_AB:
12082      s = "lwl";
12083      fmt = MEM12_FMT;
12084      offbits = (mips_opts.micromips ? 12 : 16);
12085      goto ld_st;
12086    case M_LWR_AB:
12087      s = "lwr";
12088      fmt = MEM12_FMT;
12089      offbits = (mips_opts.micromips ? 12 : 16);
12090      goto ld_st;
12091    case M_LDC1_AB:
12092      s = "ldc1";
12093      fmt = "T,o(b)";
12094      /* Itbl support may require additional care here.  */
12095      coproc = 1;
12096      goto ld_st;
12097    case M_LDC2_AB:
12098      s = "ldc2";
12099      fmt = COP12_FMT;
12100      offbits = (mips_opts.micromips ? 12
12101		 : ISA_IS_R6 (mips_opts.isa) ? 11
12102		 : 16);
12103      /* Itbl support may require additional care here.  */
12104      coproc = 1;
12105      goto ld_st;
12106    case M_LQC2_AB:
12107      s = "lqc2";
12108      fmt = "+7,o(b)";
12109      /* Itbl support may require additional care here.  */
12110      coproc = 1;
12111      goto ld_st;
12112    case M_LDC3_AB:
12113      s = "ldc3";
12114      fmt = "E,o(b)";
12115      /* Itbl support may require additional care here.  */
12116      coproc = 1;
12117      goto ld_st;
12118    case M_LDL_AB:
12119      s = "ldl";
12120      fmt = MEM12_FMT;
12121      offbits = (mips_opts.micromips ? 12 : 16);
12122      goto ld_st;
12123    case M_LDR_AB:
12124      s = "ldr";
12125      fmt = MEM12_FMT;
12126      offbits = (mips_opts.micromips ? 12 : 16);
12127      goto ld_st;
12128    case M_LL_AB:
12129      s = "ll";
12130      fmt = LL_SC_FMT;
12131      offbits = (mips_opts.micromips ? 12
12132		 : ISA_IS_R6 (mips_opts.isa) ? 9
12133		 : 16);
12134      goto ld;
12135    case M_LLD_AB:
12136      s = "lld";
12137      fmt = LL_SC_FMT;
12138      offbits = (mips_opts.micromips ? 12
12139		 : ISA_IS_R6 (mips_opts.isa) ? 9
12140		 : 16);
12141      goto ld;
12142    case M_LWU_AB:
12143      s = "lwu";
12144      fmt = MEM12_FMT;
12145      offbits = (mips_opts.micromips ? 12 : 16);
12146      goto ld;
12147    case M_LWP_AB:
12148      gas_assert (mips_opts.micromips);
12149      s = "lwp";
12150      fmt = "t,~(b)";
12151      offbits = 12;
12152      lp = 1;
12153      goto ld;
12154    case M_LDP_AB:
12155      gas_assert (mips_opts.micromips);
12156      s = "ldp";
12157      fmt = "t,~(b)";
12158      offbits = 12;
12159      lp = 1;
12160      goto ld;
12161    case M_LLDP_AB:
12162    case M_LLWP_AB:
12163    case M_LLWPE_AB:
12164      s = ip->insn_mo->name;
12165      fmt = "t,d,s";
12166      ll_sc_paired = 1;
12167      offbits = 0;
12168      goto ld;
12169    case M_LWM_AB:
12170      gas_assert (mips_opts.micromips);
12171      s = "lwm";
12172      fmt = "n,~(b)";
12173      offbits = 12;
12174      goto ld_st;
12175    case M_LDM_AB:
12176      gas_assert (mips_opts.micromips);
12177      s = "ldm";
12178      fmt = "n,~(b)";
12179      offbits = 12;
12180      goto ld_st;
12181
12182    ld:
12183      /* Try to use one the the load registers to compute the base address.
12184	 We don't want to use $0 as tempreg.  */
12185      if (ll_sc_paired)
12186	{
12187	  if ((op[0] == ZERO && op[3] == op[1])
12188	      || (op[1] == ZERO && op[3] == op[0])
12189	      || (op[0] == ZERO && op[1] == ZERO))
12190	    goto ld_st;
12191	  else if (op[0] != op[3] && op[0] != ZERO)
12192	    tempreg = op[0];
12193	  else
12194	    tempreg = op[1];
12195	}
12196      else
12197        {
12198	  if (op[2] == op[0] + lp || op[0] + lp == ZERO)
12199	    goto ld_st;
12200	  else
12201	    tempreg = op[0] + lp;
12202	}
12203      goto ld_noat;
12204
12205    case M_SB_AB:
12206      s = "sb";
12207      fmt = "t,o(b)";
12208      goto ld_st;
12209    case M_SH_AB:
12210      s = "sh";
12211      fmt = "t,o(b)";
12212      goto ld_st;
12213    case M_SW_AB:
12214      s = "sw";
12215      fmt = "t,o(b)";
12216      goto ld_st;
12217    case M_SWC0_AB:
12218      gas_assert (!mips_opts.micromips);
12219      s = "swc0";
12220      fmt = "E,o(b)";
12221      /* Itbl support may require additional care here.  */
12222      coproc = 1;
12223      goto ld_st;
12224    case M_SWC1_AB:
12225      s = "swc1";
12226      fmt = "T,o(b)";
12227      /* Itbl support may require additional care here.  */
12228      coproc = 1;
12229      goto ld_st;
12230    case M_SWC2_AB:
12231      s = "swc2";
12232      fmt = COP12_FMT;
12233      offbits = (mips_opts.micromips ? 12
12234		 : ISA_IS_R6 (mips_opts.isa) ? 11
12235		 : 16);
12236      /* Itbl support may require additional care here.  */
12237      coproc = 1;
12238      goto ld_st;
12239    case M_SWC3_AB:
12240      gas_assert (!mips_opts.micromips);
12241      s = "swc3";
12242      fmt = "E,o(b)";
12243      /* Itbl support may require additional care here.  */
12244      coproc = 1;
12245      goto ld_st;
12246    case M_SWL_AB:
12247      s = "swl";
12248      fmt = MEM12_FMT;
12249      offbits = (mips_opts.micromips ? 12 : 16);
12250      goto ld_st;
12251    case M_SWR_AB:
12252      s = "swr";
12253      fmt = MEM12_FMT;
12254      offbits = (mips_opts.micromips ? 12 : 16);
12255      goto ld_st;
12256    case M_SC_AB:
12257      s = "sc";
12258      fmt = LL_SC_FMT;
12259      offbits = (mips_opts.micromips ? 12
12260		 : ISA_IS_R6 (mips_opts.isa) ? 9
12261		 : 16);
12262      goto ld_st;
12263    case M_SCD_AB:
12264      s = "scd";
12265      fmt = LL_SC_FMT;
12266      offbits = (mips_opts.micromips ? 12
12267		 : ISA_IS_R6 (mips_opts.isa) ? 9
12268		 : 16);
12269      goto ld_st;
12270    case M_SCDP_AB:
12271    case M_SCWP_AB:
12272    case M_SCWPE_AB:
12273      s = ip->insn_mo->name;
12274      fmt = "t,d,s";
12275      ll_sc_paired = 1;
12276      offbits = 0;
12277      goto ld_st;
12278    case M_CACHE_AB:
12279      s = "cache";
12280      fmt = (mips_opts.micromips ? "k,~(b)"
12281	     : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
12282	     : "k,o(b)");
12283      offbits = (mips_opts.micromips ? 12
12284		 : ISA_IS_R6 (mips_opts.isa) ? 9
12285		 : 16);
12286      goto ld_st;
12287    case M_CACHEE_AB:
12288      s = "cachee";
12289      fmt = "k,+j(b)";
12290      offbits = 9;
12291      goto ld_st;
12292    case M_PREF_AB:
12293      s = "pref";
12294      fmt = (mips_opts.micromips ? "k,~(b)"
12295	     : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
12296	     : "k,o(b)");
12297      offbits = (mips_opts.micromips ? 12
12298		 : ISA_IS_R6 (mips_opts.isa) ? 9
12299		 : 16);
12300      goto ld_st;
12301    case M_PREFE_AB:
12302      s = "prefe";
12303      fmt = "k,+j(b)";
12304      offbits = 9;
12305      goto ld_st;
12306    case M_SDC1_AB:
12307      s = "sdc1";
12308      fmt = "T,o(b)";
12309      coproc = 1;
12310      /* Itbl support may require additional care here.  */
12311      goto ld_st;
12312    case M_SDC2_AB:
12313      s = "sdc2";
12314      fmt = COP12_FMT;
12315      offbits = (mips_opts.micromips ? 12
12316		 : ISA_IS_R6 (mips_opts.isa) ? 11
12317		 : 16);
12318      /* Itbl support may require additional care here.  */
12319      coproc = 1;
12320      goto ld_st;
12321    case M_SQC2_AB:
12322      s = "sqc2";
12323      fmt = "+7,o(b)";
12324      /* Itbl support may require additional care here.  */
12325      coproc = 1;
12326      goto ld_st;
12327    case M_SDC3_AB:
12328      gas_assert (!mips_opts.micromips);
12329      s = "sdc3";
12330      fmt = "E,o(b)";
12331      /* Itbl support may require additional care here.  */
12332      coproc = 1;
12333      goto ld_st;
12334    case M_SDL_AB:
12335      s = "sdl";
12336      fmt = MEM12_FMT;
12337      offbits = (mips_opts.micromips ? 12 : 16);
12338      goto ld_st;
12339    case M_SDR_AB:
12340      s = "sdr";
12341      fmt = MEM12_FMT;
12342      offbits = (mips_opts.micromips ? 12 : 16);
12343      goto ld_st;
12344    case M_SWP_AB:
12345      gas_assert (mips_opts.micromips);
12346      s = "swp";
12347      fmt = "t,~(b)";
12348      offbits = 12;
12349      goto ld_st;
12350    case M_SDP_AB:
12351      gas_assert (mips_opts.micromips);
12352      s = "sdp";
12353      fmt = "t,~(b)";
12354      offbits = 12;
12355      goto ld_st;
12356    case M_SWM_AB:
12357      gas_assert (mips_opts.micromips);
12358      s = "swm";
12359      fmt = "n,~(b)";
12360      offbits = 12;
12361      goto ld_st;
12362    case M_SDM_AB:
12363      gas_assert (mips_opts.micromips);
12364      s = "sdm";
12365      fmt = "n,~(b)";
12366      offbits = 12;
12367
12368    ld_st:
12369      tempreg = AT;
12370    ld_noat:
12371      breg = ll_sc_paired ? op[3] : op[2];
12372      if (small_offset_p (0, align, 16))
12373	{
12374	  /* The first case exists for M_LD_AB and M_SD_AB, which are
12375	     macros for o32 but which should act like normal instructions
12376	     otherwise.  */
12377	  if (offbits == 16)
12378	    macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
12379			 offset_reloc[1], offset_reloc[2], breg);
12380	  else if (small_offset_p (0, align, offbits))
12381	    {
12382	      if (offbits == 0)
12383		{
12384		  if (ll_sc_paired)
12385		   macro_build (NULL, s, fmt, op[0], op[1], breg);
12386		  else
12387		   macro_build (NULL, s, fmt, op[0], breg);
12388		}
12389	      else
12390		macro_build (NULL, s, fmt, op[0],
12391			     (int) offset_expr.X_add_number, breg);
12392	    }
12393	  else
12394	    {
12395	      if (tempreg == AT)
12396		used_at = 1;
12397	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
12398			   tempreg, breg, -1, offset_reloc[0],
12399			   offset_reloc[1], offset_reloc[2]);
12400	      if (offbits == 0)
12401		{
12402		  if (ll_sc_paired)
12403		    macro_build (NULL, s, fmt, op[0], op[1], tempreg);
12404		  else
12405		    macro_build (NULL, s, fmt, op[0], tempreg);
12406		}
12407	      else
12408		macro_build (NULL, s, fmt, op[0], 0, tempreg);
12409	    }
12410	  break;
12411	}
12412
12413      if (tempreg == AT)
12414	used_at = 1;
12415
12416      if (offset_expr.X_op != O_constant
12417	  && offset_expr.X_op != O_symbol)
12418	{
12419	  as_bad (_("expression too complex"));
12420	  offset_expr.X_op = O_constant;
12421	}
12422
12423      if (HAVE_32BIT_ADDRESSES
12424	  && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12425	{
12426	  char value [32];
12427
12428	  sprintf_vma (value, offset_expr.X_add_number);
12429	  as_bad (_("number (0x%s) larger than 32 bits"), value);
12430	}
12431
12432      /* A constant expression in PIC code can be handled just as it
12433	 is in non PIC code.  */
12434      if (offset_expr.X_op == O_constant)
12435	{
12436	  expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
12437						 offbits == 0 ? 16 : offbits);
12438	  offset_expr.X_add_number -= expr1.X_add_number;
12439
12440	  load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
12441	  if (breg != 0)
12442	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12443			 tempreg, tempreg, breg);
12444	  if (offbits == 0)
12445	    {
12446	      if (offset_expr.X_add_number != 0)
12447		macro_build (&offset_expr, ADDRESS_ADDI_INSN,
12448			     "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
12449	      if (ll_sc_paired)
12450		macro_build (NULL, s, fmt, op[0], op[1], tempreg);
12451	      else
12452		macro_build (NULL, s, fmt, op[0], tempreg);
12453	    }
12454	  else if (offbits == 16)
12455	    macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12456	  else
12457	    macro_build (NULL, s, fmt, op[0],
12458			 (int) offset_expr.X_add_number, tempreg);
12459	}
12460      else if (offbits != 16)
12461	{
12462	  /* The offset field is too narrow to be used for a low-part
12463	     relocation, so load the whole address into the auxiliary
12464	     register.  */
12465	  load_address (tempreg, &offset_expr, &used_at);
12466	  if (breg != 0)
12467	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12468			 tempreg, tempreg, breg);
12469	  if (offbits == 0)
12470	    {
12471	      if (ll_sc_paired)
12472		macro_build (NULL, s, fmt, op[0], op[1], tempreg);
12473	      else
12474		macro_build (NULL, s, fmt, op[0], tempreg);
12475	    }
12476	  else
12477	    macro_build (NULL, s, fmt, op[0], 0, tempreg);
12478	}
12479      else if (mips_pic == NO_PIC)
12480	{
12481	  /* If this is a reference to a GP relative symbol, and there
12482	     is no base register, we want
12483	       <op>	op[0],<sym>($gp)	(BFD_RELOC_GPREL16)
12484	     Otherwise, if there is no base register, we want
12485	       lui	$tempreg,<sym>		(BFD_RELOC_HI16_S)
12486	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12487	     If we have a constant, we need two instructions anyhow,
12488	     so we always use the latter form.
12489
12490	     If we have a base register, and this is a reference to a
12491	     GP relative symbol, we want
12492	       addu	$tempreg,$breg,$gp
12493	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_GPREL16)
12494	     Otherwise we want
12495	       lui	$tempreg,<sym>		(BFD_RELOC_HI16_S)
12496	       addu	$tempreg,$tempreg,$breg
12497	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12498	     With a constant we always use the latter case.
12499
12500	     With 64bit address space and no base register and $at usable,
12501	     we want
12502	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
12503	       lui	$at,<sym>		(BFD_RELOC_HI16_S)
12504	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
12505	       dsll32	$tempreg,0
12506	       daddu	$tempreg,$at
12507	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12508	     If we have a base register, we want
12509	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
12510	       lui	$at,<sym>		(BFD_RELOC_HI16_S)
12511	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
12512	       daddu	$at,$breg
12513	       dsll32	$tempreg,0
12514	       daddu	$tempreg,$at
12515	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12516
12517	     Without $at we can't generate the optimal path for superscalar
12518	     processors here since this would require two temporary registers.
12519	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
12520	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
12521	       dsll	$tempreg,16
12522	       daddiu	$tempreg,<sym>		(BFD_RELOC_HI16_S)
12523	       dsll	$tempreg,16
12524	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12525	     If we have a base register, we want
12526	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHEST)
12527	       daddiu	$tempreg,<sym>		(BFD_RELOC_MIPS_HIGHER)
12528	       dsll	$tempreg,16
12529	       daddiu	$tempreg,<sym>		(BFD_RELOC_HI16_S)
12530	       dsll	$tempreg,16
12531	       daddu	$tempreg,$tempreg,$breg
12532	       <op>	op[0],<sym>($tempreg)	(BFD_RELOC_LO16)
12533
12534	     For GP relative symbols in 64bit address space we can use
12535	     the same sequence as in 32bit address space.  */
12536	  if (HAVE_64BIT_SYMBOLS)
12537	    {
12538	      if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12539		  && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12540		{
12541		  relax_start (offset_expr.X_add_symbol);
12542		  if (breg == 0)
12543		    {
12544		      macro_build (&offset_expr, s, fmt, op[0],
12545				   BFD_RELOC_GPREL16, mips_gp_register);
12546		    }
12547		  else
12548		    {
12549		      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12550				   tempreg, breg, mips_gp_register);
12551		      macro_build (&offset_expr, s, fmt, op[0],
12552				   BFD_RELOC_GPREL16, tempreg);
12553		    }
12554		  relax_switch ();
12555		}
12556
12557	      if (used_at == 0 && mips_opts.at)
12558		{
12559		  macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12560			       BFD_RELOC_MIPS_HIGHEST);
12561		  macro_build (&offset_expr, "lui", LUI_FMT, AT,
12562			       BFD_RELOC_HI16_S);
12563		  macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12564			       tempreg, BFD_RELOC_MIPS_HIGHER);
12565		  if (breg != 0)
12566		    macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12567		  macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12568		  macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12569		  macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12570			       tempreg);
12571		  used_at = 1;
12572		}
12573	      else
12574		{
12575		  macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12576			       BFD_RELOC_MIPS_HIGHEST);
12577		  macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12578			       tempreg, BFD_RELOC_MIPS_HIGHER);
12579		  macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12580		  macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12581			       tempreg, BFD_RELOC_HI16_S);
12582		  macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12583		  if (breg != 0)
12584		    macro_build (NULL, "daddu", "d,v,t",
12585				 tempreg, tempreg, breg);
12586		  macro_build (&offset_expr, s, fmt, op[0],
12587			       BFD_RELOC_LO16, tempreg);
12588		}
12589
12590	      if (mips_relax.sequence)
12591		relax_end ();
12592	      break;
12593	    }
12594
12595	  if (breg == 0)
12596	    {
12597	      if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12598		  && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12599		{
12600		  relax_start (offset_expr.X_add_symbol);
12601		  macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12602			       mips_gp_register);
12603		  relax_switch ();
12604		}
12605	      macro_build_lui (&offset_expr, tempreg);
12606	      macro_build (&offset_expr, s, fmt, op[0],
12607			   BFD_RELOC_LO16, tempreg);
12608	      if (mips_relax.sequence)
12609		relax_end ();
12610	    }
12611	  else
12612	    {
12613	      if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12614		  && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12615		{
12616		  relax_start (offset_expr.X_add_symbol);
12617		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12618			       tempreg, breg, mips_gp_register);
12619		  macro_build (&offset_expr, s, fmt, op[0],
12620			       BFD_RELOC_GPREL16, tempreg);
12621		  relax_switch ();
12622		}
12623	      macro_build_lui (&offset_expr, tempreg);
12624	      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12625			   tempreg, tempreg, breg);
12626	      macro_build (&offset_expr, s, fmt, op[0],
12627			   BFD_RELOC_LO16, tempreg);
12628	      if (mips_relax.sequence)
12629		relax_end ();
12630	    }
12631	}
12632      else if (!mips_big_got)
12633	{
12634	  int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12635
12636	  /* If this is a reference to an external symbol, we want
12637	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
12638	       nop
12639	       <op>	op[0],0($tempreg)
12640	     Otherwise we want
12641	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
12642	       nop
12643	       addiu	$tempreg,$tempreg,<sym>	(BFD_RELOC_LO16)
12644	       <op>	op[0],0($tempreg)
12645
12646	     For NewABI, we want
12647	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT_PAGE)
12648	       <op>	op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12649
12650	     If there is a base register, we add it to $tempreg before
12651	     the <op>.  If there is a constant, we stick it in the
12652	     <op> instruction.  We don't handle constants larger than
12653	     16 bits, because we have no way to load the upper 16 bits
12654	     (actually, we could handle them for the subset of cases
12655	     in which we are not using $at).  */
12656	  gas_assert (offset_expr.X_op == O_symbol);
12657	  if (HAVE_NEWABI)
12658	    {
12659	      macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12660			   BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12661	      if (breg != 0)
12662		macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12663			     tempreg, tempreg, breg);
12664	      macro_build (&offset_expr, s, fmt, op[0],
12665			   BFD_RELOC_MIPS_GOT_OFST, tempreg);
12666	      break;
12667	    }
12668	  expr1.X_add_number = offset_expr.X_add_number;
12669	  offset_expr.X_add_number = 0;
12670	  if (expr1.X_add_number < -0x8000
12671	      || expr1.X_add_number >= 0x8000)
12672	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12673	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12674		       lw_reloc_type, mips_gp_register);
12675	  load_delay_nop ();
12676	  relax_start (offset_expr.X_add_symbol);
12677	  relax_switch ();
12678	  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12679		       tempreg, BFD_RELOC_LO16);
12680	  relax_end ();
12681	  if (breg != 0)
12682	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12683			 tempreg, tempreg, breg);
12684	  macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12685	}
12686      else if (mips_big_got && !HAVE_NEWABI)
12687	{
12688	  int gpdelay;
12689
12690	  /* If this is a reference to an external symbol, we want
12691	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
12692	       addu	$tempreg,$tempreg,$gp
12693	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12694	       <op>	op[0],0($tempreg)
12695	     Otherwise we want
12696	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT16)
12697	       nop
12698	       addiu	$tempreg,$tempreg,<sym>	(BFD_RELOC_LO16)
12699	       <op>	op[0],0($tempreg)
12700	     If there is a base register, we add it to $tempreg before
12701	     the <op>.  If there is a constant, we stick it in the
12702	     <op> instruction.  We don't handle constants larger than
12703	     16 bits, because we have no way to load the upper 16 bits
12704	     (actually, we could handle them for the subset of cases
12705	     in which we are not using $at).  */
12706	  gas_assert (offset_expr.X_op == O_symbol);
12707	  expr1.X_add_number = offset_expr.X_add_number;
12708	  offset_expr.X_add_number = 0;
12709	  if (expr1.X_add_number < -0x8000
12710	      || expr1.X_add_number >= 0x8000)
12711	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12712	  gpdelay = reg_needs_delay (mips_gp_register);
12713	  relax_start (offset_expr.X_add_symbol);
12714	  macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12715		       BFD_RELOC_MIPS_GOT_HI16);
12716	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12717		       mips_gp_register);
12718	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12719		       BFD_RELOC_MIPS_GOT_LO16, tempreg);
12720	  relax_switch ();
12721	  if (gpdelay)
12722	    macro_build (NULL, "nop", "");
12723	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12724		       BFD_RELOC_MIPS_GOT16, mips_gp_register);
12725	  load_delay_nop ();
12726	  macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12727		       tempreg, BFD_RELOC_LO16);
12728	  relax_end ();
12729
12730	  if (breg != 0)
12731	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12732			 tempreg, tempreg, breg);
12733	  macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12734	}
12735      else if (mips_big_got && HAVE_NEWABI)
12736	{
12737	  /* If this is a reference to an external symbol, we want
12738	       lui	$tempreg,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
12739	       add	$tempreg,$tempreg,$gp
12740	       lw	$tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12741	       <op>	op[0],<ofst>($tempreg)
12742	     Otherwise, for local symbols, we want:
12743	       lw	$tempreg,<sym>($gp)	(BFD_RELOC_MIPS_GOT_PAGE)
12744	       <op>	op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12745	  gas_assert (offset_expr.X_op == O_symbol);
12746	  expr1.X_add_number = offset_expr.X_add_number;
12747	  offset_expr.X_add_number = 0;
12748	  if (expr1.X_add_number < -0x8000
12749	      || expr1.X_add_number >= 0x8000)
12750	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12751	  relax_start (offset_expr.X_add_symbol);
12752	  macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12753		       BFD_RELOC_MIPS_GOT_HI16);
12754	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12755		       mips_gp_register);
12756	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12757		       BFD_RELOC_MIPS_GOT_LO16, tempreg);
12758	  if (breg != 0)
12759	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12760			 tempreg, tempreg, breg);
12761	  macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12762
12763	  relax_switch ();
12764	  offset_expr.X_add_number = expr1.X_add_number;
12765	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12766		       BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12767	  if (breg != 0)
12768	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12769			 tempreg, tempreg, breg);
12770	  macro_build (&offset_expr, s, fmt, op[0],
12771		       BFD_RELOC_MIPS_GOT_OFST, tempreg);
12772	  relax_end ();
12773	}
12774      else
12775	abort ();
12776
12777      break;
12778
12779    case M_JRADDIUSP:
12780      gas_assert (mips_opts.micromips);
12781      gas_assert (mips_opts.insn32);
12782      start_noreorder ();
12783      macro_build (NULL, "jr", "s", RA);
12784      expr1.X_add_number = op[0] << 2;
12785      macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12786      end_noreorder ();
12787      break;
12788
12789    case M_JRC:
12790      gas_assert (mips_opts.micromips);
12791      gas_assert (mips_opts.insn32);
12792      macro_build (NULL, "jr", "s", op[0]);
12793      if (mips_opts.noreorder)
12794	macro_build (NULL, "nop", "");
12795      break;
12796
12797    case M_LI:
12798    case M_LI_S:
12799      load_register (op[0], &imm_expr, 0);
12800      break;
12801
12802    case M_DLI:
12803      load_register (op[0], &imm_expr, 1);
12804      break;
12805
12806    case M_LI_SS:
12807      if (imm_expr.X_op == O_constant)
12808	{
12809	  used_at = 1;
12810	  load_register (AT, &imm_expr, 0);
12811	  macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12812	  break;
12813	}
12814      else
12815	{
12816	  gas_assert (imm_expr.X_op == O_absent
12817		      && offset_expr.X_op == O_symbol
12818		      && strcmp (segment_name (S_GET_SEGMENT
12819					       (offset_expr.X_add_symbol)),
12820				 ".lit4") == 0
12821		      && offset_expr.X_add_number == 0);
12822	  macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12823		       BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12824	  break;
12825	}
12826
12827    case M_LI_D:
12828      /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12829         wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12830         order 32 bits of the value and the low order 32 bits are either
12831         zero or in OFFSET_EXPR.  */
12832      if (imm_expr.X_op == O_constant)
12833	{
12834	  if (GPR_SIZE == 64)
12835	    load_register (op[0], &imm_expr, 1);
12836	  else
12837	    {
12838	      int hreg, lreg;
12839
12840	      if (target_big_endian)
12841		{
12842		  hreg = op[0];
12843		  lreg = op[0] + 1;
12844		}
12845	      else
12846		{
12847		  hreg = op[0] + 1;
12848		  lreg = op[0];
12849		}
12850
12851	      if (hreg <= 31)
12852		load_register (hreg, &imm_expr, 0);
12853	      if (lreg <= 31)
12854		{
12855		  if (offset_expr.X_op == O_absent)
12856		    move_register (lreg, 0);
12857		  else
12858		    {
12859		      gas_assert (offset_expr.X_op == O_constant);
12860		      load_register (lreg, &offset_expr, 0);
12861		    }
12862		}
12863	    }
12864	  break;
12865	}
12866      gas_assert (imm_expr.X_op == O_absent);
12867
12868      /* We know that sym is in the .rdata section.  First we get the
12869	 upper 16 bits of the address.  */
12870      if (mips_pic == NO_PIC)
12871	{
12872	  macro_build_lui (&offset_expr, AT);
12873	  used_at = 1;
12874	}
12875      else
12876	{
12877	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12878		       BFD_RELOC_MIPS_GOT16, mips_gp_register);
12879	  used_at = 1;
12880	}
12881
12882      /* Now we load the register(s).  */
12883      if (GPR_SIZE == 64)
12884	{
12885	  used_at = 1;
12886	  macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12887		       BFD_RELOC_LO16, AT);
12888	}
12889      else
12890	{
12891	  used_at = 1;
12892	  macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12893		       BFD_RELOC_LO16, AT);
12894	  if (op[0] != RA)
12895	    {
12896	      /* FIXME: How in the world do we deal with the possible
12897		 overflow here?  */
12898	      offset_expr.X_add_number += 4;
12899	      macro_build (&offset_expr, "lw", "t,o(b)",
12900			   op[0] + 1, BFD_RELOC_LO16, AT);
12901	    }
12902	}
12903      break;
12904
12905    case M_LI_DD:
12906      /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12907         wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12908         bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12909         the value and the low order 32 bits are either zero or in
12910         OFFSET_EXPR.  */
12911      if (imm_expr.X_op == O_constant)
12912	{
12913	  tempreg = ZERO;
12914	  if (((FPR_SIZE == 64 && GPR_SIZE == 64)
12915	       || !ISA_HAS_MXHC1 (mips_opts.isa))
12916	      && imm_expr.X_add_number != 0)
12917	    {
12918	      used_at = 1;
12919	      tempreg = AT;
12920	      load_register (AT, &imm_expr, FPR_SIZE == 64);
12921	    }
12922	  if (FPR_SIZE == 64 && GPR_SIZE == 64)
12923	    macro_build (NULL, "dmtc1", "t,S", tempreg, op[0]);
12924	  else
12925	    {
12926	      if (!ISA_HAS_MXHC1 (mips_opts.isa))
12927		{
12928		  if (FPR_SIZE != 32)
12929		    as_bad (_("Unable to generate `%s' compliant code "
12930			      "without mthc1"),
12931			    (FPR_SIZE == 64) ? "fp64" : "fpxx");
12932		  else
12933		    macro_build (NULL, "mtc1", "t,G", tempreg, op[0] + 1);
12934		}
12935	      if (offset_expr.X_op == O_absent)
12936		macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12937	      else
12938		{
12939		  gas_assert (offset_expr.X_op == O_constant);
12940		  load_register (AT, &offset_expr, 0);
12941		  macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12942		}
12943	      if (ISA_HAS_MXHC1 (mips_opts.isa))
12944		{
12945		  if (imm_expr.X_add_number != 0)
12946		    {
12947		      used_at = 1;
12948		      tempreg = AT;
12949		      load_register (AT, &imm_expr, 0);
12950		    }
12951		  macro_build (NULL, "mthc1", "t,G", tempreg, op[0]);
12952		}
12953	    }
12954	  break;
12955	}
12956
12957      gas_assert (imm_expr.X_op == O_absent
12958		  && offset_expr.X_op == O_symbol
12959		  && offset_expr.X_add_number == 0);
12960      s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12961      if (strcmp (s, ".lit8") == 0)
12962	{
12963	  op[2] = mips_gp_register;
12964	  offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12965	  offset_reloc[1] = BFD_RELOC_UNUSED;
12966	  offset_reloc[2] = BFD_RELOC_UNUSED;
12967	}
12968      else
12969	{
12970	  gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12971	  used_at = 1;
12972	  if (mips_pic != NO_PIC)
12973	    macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12974			 BFD_RELOC_MIPS_GOT16, mips_gp_register);
12975	  else
12976	    {
12977	      /* FIXME: This won't work for a 64 bit address.  */
12978	      macro_build_lui (&offset_expr, AT);
12979	    }
12980
12981	  op[2] = AT;
12982	  offset_reloc[0] = BFD_RELOC_LO16;
12983	  offset_reloc[1] = BFD_RELOC_UNUSED;
12984	  offset_reloc[2] = BFD_RELOC_UNUSED;
12985	}
12986      align = 8;
12987      /* Fall through.  */
12988
12989    case M_L_DAB:
12990      /* The MIPS assembler seems to check for X_add_number not
12991         being double aligned and generating:
12992        	lui	at,%hi(foo+1)
12993        	addu	at,at,v1
12994        	addiu	at,at,%lo(foo+1)
12995        	lwc1	f2,0(at)
12996        	lwc1	f3,4(at)
12997         But, the resulting address is the same after relocation so why
12998         generate the extra instruction?  */
12999      /* Itbl support may require additional care here.  */
13000      coproc = 1;
13001      fmt = "T,o(b)";
13002      if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
13003	{
13004	  s = "ldc1";
13005	  goto ld_st;
13006	}
13007      s = "lwc1";
13008      goto ldd_std;
13009
13010    case M_S_DAB:
13011      gas_assert (!mips_opts.micromips);
13012      /* Itbl support may require additional care here.  */
13013      coproc = 1;
13014      fmt = "T,o(b)";
13015      if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
13016	{
13017	  s = "sdc1";
13018	  goto ld_st;
13019	}
13020      s = "swc1";
13021      goto ldd_std;
13022
13023    case M_LQ_AB:
13024      fmt = "t,o(b)";
13025      s = "lq";
13026      goto ld;
13027
13028    case M_SQ_AB:
13029      fmt = "t,o(b)";
13030      s = "sq";
13031      goto ld_st;
13032
13033    case M_LD_AB:
13034      fmt = "t,o(b)";
13035      if (GPR_SIZE == 64)
13036	{
13037	  s = "ld";
13038	  goto ld;
13039	}
13040      s = "lw";
13041      goto ldd_std;
13042
13043    case M_SD_AB:
13044      fmt = "t,o(b)";
13045      if (GPR_SIZE == 64)
13046	{
13047	  s = "sd";
13048	  goto ld_st;
13049	}
13050      s = "sw";
13051
13052    ldd_std:
13053      /* Even on a big endian machine $fn comes before $fn+1.  We have
13054	 to adjust when loading from memory.  We set coproc if we must
13055	 load $fn+1 first.  */
13056      /* Itbl support may require additional care here.  */
13057      if (!target_big_endian)
13058	coproc = 0;
13059
13060      breg = op[2];
13061      if (small_offset_p (0, align, 16))
13062	{
13063	  ep = &offset_expr;
13064	  if (!small_offset_p (4, align, 16))
13065	    {
13066	      macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
13067			   -1, offset_reloc[0], offset_reloc[1],
13068			   offset_reloc[2]);
13069	      expr1.X_add_number = 0;
13070	      ep = &expr1;
13071	      breg = AT;
13072	      used_at = 1;
13073	      offset_reloc[0] = BFD_RELOC_LO16;
13074	      offset_reloc[1] = BFD_RELOC_UNUSED;
13075	      offset_reloc[2] = BFD_RELOC_UNUSED;
13076	    }
13077	  if (strcmp (s, "lw") == 0 && op[0] == breg)
13078	    {
13079	      ep->X_add_number += 4;
13080	      macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
13081			   offset_reloc[1], offset_reloc[2], breg);
13082	      ep->X_add_number -= 4;
13083	      macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
13084			   offset_reloc[1], offset_reloc[2], breg);
13085	    }
13086	  else
13087	    {
13088	      macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
13089			   offset_reloc[0], offset_reloc[1], offset_reloc[2],
13090			   breg);
13091	      ep->X_add_number += 4;
13092	      macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
13093			   offset_reloc[0], offset_reloc[1], offset_reloc[2],
13094			   breg);
13095	    }
13096	  break;
13097	}
13098
13099      if (offset_expr.X_op != O_symbol
13100	  && offset_expr.X_op != O_constant)
13101	{
13102	  as_bad (_("expression too complex"));
13103	  offset_expr.X_op = O_constant;
13104	}
13105
13106      if (HAVE_32BIT_ADDRESSES
13107	  && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
13108	{
13109	  char value [32];
13110
13111	  sprintf_vma (value, offset_expr.X_add_number);
13112	  as_bad (_("number (0x%s) larger than 32 bits"), value);
13113	}
13114
13115      if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
13116	{
13117	  /* If this is a reference to a GP relative symbol, we want
13118	       <op>	op[0],<sym>($gp)	(BFD_RELOC_GPREL16)
13119	       <op>	op[0]+1,<sym>+4($gp)	(BFD_RELOC_GPREL16)
13120	     If we have a base register, we use this
13121	       addu	$at,$breg,$gp
13122	       <op>	op[0],<sym>($at)	(BFD_RELOC_GPREL16)
13123	       <op>	op[0]+1,<sym>+4($at)	(BFD_RELOC_GPREL16)
13124	     If this is not a GP relative symbol, we want
13125	       lui	$at,<sym>		(BFD_RELOC_HI16_S)
13126	       <op>	op[0],<sym>($at)	(BFD_RELOC_LO16)
13127	       <op>	op[0]+1,<sym>+4($at)	(BFD_RELOC_LO16)
13128	     If there is a base register, we add it to $at after the
13129	     lui instruction.  If there is a constant, we always use
13130	     the last case.  */
13131	  if (offset_expr.X_op == O_symbol
13132	      && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
13133	      && !nopic_need_relax (offset_expr.X_add_symbol, 1))
13134	    {
13135	      relax_start (offset_expr.X_add_symbol);
13136	      if (breg == 0)
13137		{
13138		  tempreg = mips_gp_register;
13139		}
13140	      else
13141		{
13142		  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13143			       AT, breg, mips_gp_register);
13144		  tempreg = AT;
13145		  used_at = 1;
13146		}
13147
13148	      /* Itbl support may require additional care here.  */
13149	      macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
13150			   BFD_RELOC_GPREL16, tempreg);
13151	      offset_expr.X_add_number += 4;
13152
13153	      /* Set mips_optimize to 2 to avoid inserting an
13154                 undesired nop.  */
13155	      hold_mips_optimize = mips_optimize;
13156	      mips_optimize = 2;
13157	      /* Itbl support may require additional care here.  */
13158	      macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
13159			   BFD_RELOC_GPREL16, tempreg);
13160	      mips_optimize = hold_mips_optimize;
13161
13162	      relax_switch ();
13163
13164	      offset_expr.X_add_number -= 4;
13165	    }
13166	  used_at = 1;
13167	  if (offset_high_part (offset_expr.X_add_number, 16)
13168	      != offset_high_part (offset_expr.X_add_number + 4, 16))
13169	    {
13170	      load_address (AT, &offset_expr, &used_at);
13171	      offset_expr.X_op = O_constant;
13172	      offset_expr.X_add_number = 0;
13173	    }
13174	  else
13175	    macro_build_lui (&offset_expr, AT);
13176	  if (breg != 0)
13177	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
13178	  /* Itbl support may require additional care here.  */
13179	  macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
13180		       BFD_RELOC_LO16, AT);
13181	  /* FIXME: How do we handle overflow here?  */
13182	  offset_expr.X_add_number += 4;
13183	  /* Itbl support may require additional care here.  */
13184	  macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
13185		       BFD_RELOC_LO16, AT);
13186	  if (mips_relax.sequence)
13187	    relax_end ();
13188	}
13189      else if (!mips_big_got)
13190	{
13191	  /* If this is a reference to an external symbol, we want
13192	       lw	$at,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
13193	       nop
13194	       <op>	op[0],0($at)
13195	       <op>	op[0]+1,4($at)
13196	     Otherwise we want
13197	       lw	$at,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
13198	       nop
13199	       <op>	op[0],<sym>($at)	(BFD_RELOC_LO16)
13200	       <op>	op[0]+1,<sym>+4($at)	(BFD_RELOC_LO16)
13201	     If there is a base register we add it to $at before the
13202	     lwc1 instructions.  If there is a constant we include it
13203	     in the lwc1 instructions.  */
13204	  used_at = 1;
13205	  expr1.X_add_number = offset_expr.X_add_number;
13206	  if (expr1.X_add_number < -0x8000
13207	      || expr1.X_add_number >= 0x8000 - 4)
13208	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
13209	  load_got_offset (AT, &offset_expr);
13210	  load_delay_nop ();
13211	  if (breg != 0)
13212	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
13213
13214	  /* Set mips_optimize to 2 to avoid inserting an undesired
13215             nop.  */
13216	  hold_mips_optimize = mips_optimize;
13217	  mips_optimize = 2;
13218
13219	  /* Itbl support may require additional care here.  */
13220	  relax_start (offset_expr.X_add_symbol);
13221	  macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
13222		       BFD_RELOC_LO16, AT);
13223	  expr1.X_add_number += 4;
13224	  macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
13225		       BFD_RELOC_LO16, AT);
13226	  relax_switch ();
13227	  macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
13228		       BFD_RELOC_LO16, AT);
13229	  offset_expr.X_add_number += 4;
13230	  macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
13231		       BFD_RELOC_LO16, AT);
13232	  relax_end ();
13233
13234	  mips_optimize = hold_mips_optimize;
13235	}
13236      else if (mips_big_got)
13237	{
13238	  int gpdelay;
13239
13240	  /* If this is a reference to an external symbol, we want
13241	       lui	$at,<sym>		(BFD_RELOC_MIPS_GOT_HI16)
13242	       addu	$at,$at,$gp
13243	       lw	$at,<sym>($at)		(BFD_RELOC_MIPS_GOT_LO16)
13244	       nop
13245	       <op>	op[0],0($at)
13246	       <op>	op[0]+1,4($at)
13247	     Otherwise we want
13248	       lw	$at,<sym>($gp)		(BFD_RELOC_MIPS_GOT16)
13249	       nop
13250	       <op>	op[0],<sym>($at)	(BFD_RELOC_LO16)
13251	       <op>	op[0]+1,<sym>+4($at)	(BFD_RELOC_LO16)
13252	     If there is a base register we add it to $at before the
13253	     lwc1 instructions.  If there is a constant we include it
13254	     in the lwc1 instructions.  */
13255	  used_at = 1;
13256	  expr1.X_add_number = offset_expr.X_add_number;
13257	  offset_expr.X_add_number = 0;
13258	  if (expr1.X_add_number < -0x8000
13259	      || expr1.X_add_number >= 0x8000 - 4)
13260	    as_bad (_("PIC code offset overflow (max 16 signed bits)"));
13261	  gpdelay = reg_needs_delay (mips_gp_register);
13262	  relax_start (offset_expr.X_add_symbol);
13263	  macro_build (&offset_expr, "lui", LUI_FMT,
13264		       AT, BFD_RELOC_MIPS_GOT_HI16);
13265	  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13266		       AT, AT, mips_gp_register);
13267	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
13268		       AT, BFD_RELOC_MIPS_GOT_LO16, AT);
13269	  load_delay_nop ();
13270	  if (breg != 0)
13271	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
13272	  /* Itbl support may require additional care here.  */
13273	  macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
13274		       BFD_RELOC_LO16, AT);
13275	  expr1.X_add_number += 4;
13276
13277	  /* Set mips_optimize to 2 to avoid inserting an undesired
13278             nop.  */
13279	  hold_mips_optimize = mips_optimize;
13280	  mips_optimize = 2;
13281	  /* Itbl support may require additional care here.  */
13282	  macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
13283		       BFD_RELOC_LO16, AT);
13284	  mips_optimize = hold_mips_optimize;
13285	  expr1.X_add_number -= 4;
13286
13287	  relax_switch ();
13288	  offset_expr.X_add_number = expr1.X_add_number;
13289	  if (gpdelay)
13290	    macro_build (NULL, "nop", "");
13291	  macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
13292		       BFD_RELOC_MIPS_GOT16, mips_gp_register);
13293	  load_delay_nop ();
13294	  if (breg != 0)
13295	    macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
13296	  /* Itbl support may require additional care here.  */
13297	  macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
13298		       BFD_RELOC_LO16, AT);
13299	  offset_expr.X_add_number += 4;
13300
13301	  /* Set mips_optimize to 2 to avoid inserting an undesired
13302             nop.  */
13303	  hold_mips_optimize = mips_optimize;
13304	  mips_optimize = 2;
13305	  /* Itbl support may require additional care here.  */
13306	  macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
13307		       BFD_RELOC_LO16, AT);
13308	  mips_optimize = hold_mips_optimize;
13309	  relax_end ();
13310	}
13311      else
13312	abort ();
13313
13314      break;
13315
13316    case M_SAA_AB:
13317      s = "saa";
13318      goto saa_saad;
13319    case M_SAAD_AB:
13320      s = "saad";
13321    saa_saad:
13322      gas_assert (!mips_opts.micromips);
13323      offbits = 0;
13324      fmt = "t,(b)";
13325      goto ld_st;
13326
13327   /* New code added to support COPZ instructions.
13328      This code builds table entries out of the macros in mip_opcodes.
13329      R4000 uses interlocks to handle coproc delays.
13330      Other chips (like the R3000) require nops to be inserted for delays.
13331
13332      FIXME: Currently, we require that the user handle delays.
13333      In order to fill delay slots for non-interlocked chips,
13334      we must have a way to specify delays based on the coprocessor.
13335      Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
13336      What are the side-effects of the cop instruction?
13337      What cache support might we have and what are its effects?
13338      Both coprocessor & memory require delays. how long???
13339      What registers are read/set/modified?
13340
13341      If an itbl is provided to interpret cop instructions,
13342      this knowledge can be encoded in the itbl spec.  */
13343
13344    case M_COP0:
13345      s = "c0";
13346      goto copz;
13347    case M_COP1:
13348      s = "c1";
13349      goto copz;
13350    case M_COP2:
13351      s = "c2";
13352      goto copz;
13353    case M_COP3:
13354      s = "c3";
13355    copz:
13356      gas_assert (!mips_opts.micromips);
13357      /* For now we just do C (same as Cz).  The parameter will be
13358         stored in insn_opcode by mips_ip.  */
13359      macro_build (NULL, s, "C", (int) ip->insn_opcode);
13360      break;
13361
13362    case M_MOVE:
13363      move_register (op[0], op[1]);
13364      break;
13365
13366    case M_MOVEP:
13367      gas_assert (mips_opts.micromips);
13368      gas_assert (mips_opts.insn32);
13369      move_register (micromips_to_32_reg_h_map1[op[0]],
13370		     micromips_to_32_reg_m_map[op[1]]);
13371      move_register (micromips_to_32_reg_h_map2[op[0]],
13372		     micromips_to_32_reg_n_map[op[2]]);
13373      break;
13374
13375    case M_DMUL:
13376      dbl = 1;
13377      /* Fall through.  */
13378    case M_MUL:
13379      if (mips_opts.arch == CPU_R5900)
13380	macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
13381		     op[2]);
13382      else
13383        {
13384	  macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
13385	  macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13386        }
13387      break;
13388
13389    case M_DMUL_I:
13390      dbl = 1;
13391      /* Fall through.  */
13392    case M_MUL_I:
13393      /* The MIPS assembler some times generates shifts and adds.  I'm
13394	 not trying to be that fancy. GCC should do this for us
13395	 anyway.  */
13396      used_at = 1;
13397      load_register (AT, &imm_expr, dbl);
13398      macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
13399      macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13400      break;
13401
13402    case M_DMULO_I:
13403      dbl = 1;
13404      /* Fall through.  */
13405    case M_MULO_I:
13406      imm = 1;
13407      goto do_mulo;
13408
13409    case M_DMULO:
13410      dbl = 1;
13411      /* Fall through.  */
13412    case M_MULO:
13413    do_mulo:
13414      start_noreorder ();
13415      used_at = 1;
13416      if (imm)
13417	load_register (AT, &imm_expr, dbl);
13418      macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
13419		   op[1], imm ? AT : op[2]);
13420      macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13421      macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
13422      macro_build (NULL, "mfhi", MFHL_FMT, AT);
13423      if (mips_trap)
13424	macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
13425      else
13426	{
13427	  if (mips_opts.micromips)
13428	    micromips_label_expr (&label_expr);
13429	  else
13430	    label_expr.X_add_number = 8;
13431	  macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
13432	  macro_build (NULL, "nop", "");
13433	  macro_build (NULL, "break", BRK_FMT, 6);
13434	  if (mips_opts.micromips)
13435	    micromips_add_label ();
13436	}
13437      end_noreorder ();
13438      macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13439      break;
13440
13441    case M_DMULOU_I:
13442      dbl = 1;
13443      /* Fall through.  */
13444    case M_MULOU_I:
13445      imm = 1;
13446      goto do_mulou;
13447
13448    case M_DMULOU:
13449      dbl = 1;
13450      /* Fall through.  */
13451    case M_MULOU:
13452    do_mulou:
13453      start_noreorder ();
13454      used_at = 1;
13455      if (imm)
13456	load_register (AT, &imm_expr, dbl);
13457      macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
13458		   op[1], imm ? AT : op[2]);
13459      macro_build (NULL, "mfhi", MFHL_FMT, AT);
13460      macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13461      if (mips_trap)
13462	macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
13463      else
13464	{
13465	  if (mips_opts.micromips)
13466	    micromips_label_expr (&label_expr);
13467	  else
13468	    label_expr.X_add_number = 8;
13469	  macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
13470	  macro_build (NULL, "nop", "");
13471	  macro_build (NULL, "break", BRK_FMT, 6);
13472	  if (mips_opts.micromips)
13473	    micromips_add_label ();
13474	}
13475      end_noreorder ();
13476      break;
13477
13478    case M_DROL:
13479      if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13480	{
13481	  if (op[0] == op[1])
13482	    {
13483	      tempreg = AT;
13484	      used_at = 1;
13485	    }
13486	  else
13487	    tempreg = op[0];
13488	  macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
13489	  macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
13490	  break;
13491	}
13492      used_at = 1;
13493      macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13494      macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
13495      macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
13496      macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13497      break;
13498
13499    case M_ROL:
13500      if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13501	{
13502	  if (op[0] == op[1])
13503	    {
13504	      tempreg = AT;
13505	      used_at = 1;
13506	    }
13507	  else
13508	    tempreg = op[0];
13509	  macro_build (NULL, "negu", "d,w", tempreg, op[2]);
13510	  macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
13511	  break;
13512	}
13513      used_at = 1;
13514      macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13515      macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
13516      macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
13517      macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13518      break;
13519
13520    case M_DROL_I:
13521      {
13522	unsigned int rot;
13523	const char *l;
13524	const char *rr;
13525
13526	rot = imm_expr.X_add_number & 0x3f;
13527	if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13528	  {
13529	    rot = (64 - rot) & 0x3f;
13530	    if (rot >= 32)
13531	      macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13532	    else
13533	      macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13534	    break;
13535	  }
13536	if (rot == 0)
13537	  {
13538	    macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13539	    break;
13540	  }
13541	l = (rot < 0x20) ? "dsll" : "dsll32";
13542	rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
13543	rot &= 0x1f;
13544	used_at = 1;
13545	macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
13546	macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13547	macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13548      }
13549      break;
13550
13551    case M_ROL_I:
13552      {
13553	unsigned int rot;
13554
13555	rot = imm_expr.X_add_number & 0x1f;
13556	if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13557	  {
13558	    macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
13559			 (32 - rot) & 0x1f);
13560	    break;
13561	  }
13562	if (rot == 0)
13563	  {
13564	    macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13565	    break;
13566	  }
13567	used_at = 1;
13568	macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
13569	macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13570	macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13571      }
13572      break;
13573
13574    case M_DROR:
13575      if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13576	{
13577	  macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
13578	  break;
13579	}
13580      used_at = 1;
13581      macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13582      macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13583      macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13584      macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13585      break;
13586
13587    case M_ROR:
13588      if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13589	{
13590	  macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13591	  break;
13592	}
13593      used_at = 1;
13594      macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13595      macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13596      macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13597      macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13598      break;
13599
13600    case M_DROR_I:
13601      {
13602	unsigned int rot;
13603	const char *l;
13604	const char *rr;
13605
13606	rot = imm_expr.X_add_number & 0x3f;
13607	if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13608	  {
13609	    if (rot >= 32)
13610	      macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13611	    else
13612	      macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13613	    break;
13614	  }
13615	if (rot == 0)
13616	  {
13617	    macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13618	    break;
13619	  }
13620	rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13621	l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13622	rot &= 0x1f;
13623	used_at = 1;
13624	macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13625	macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13626	macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13627      }
13628      break;
13629
13630    case M_ROR_I:
13631      {
13632	unsigned int rot;
13633
13634	rot = imm_expr.X_add_number & 0x1f;
13635	if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13636	  {
13637	    macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13638	    break;
13639	  }
13640	if (rot == 0)
13641	  {
13642	    macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13643	    break;
13644	  }
13645	used_at = 1;
13646	macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13647	macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13648	macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13649      }
13650      break;
13651
13652    case M_SEQ:
13653      if (op[1] == 0)
13654	macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13655      else if (op[2] == 0)
13656	macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13657      else
13658	{
13659	  macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13660	  macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13661	}
13662      break;
13663
13664    case M_SEQ_I:
13665      if (imm_expr.X_add_number == 0)
13666	{
13667	  macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13668	  break;
13669	}
13670      if (op[1] == 0)
13671	{
13672	  as_warn (_("instruction %s: result is always false"),
13673		   ip->insn_mo->name);
13674	  move_register (op[0], 0);
13675	  break;
13676	}
13677      if (CPU_HAS_SEQ (mips_opts.arch)
13678	  && -512 <= imm_expr.X_add_number
13679	  && imm_expr.X_add_number < 512)
13680	{
13681	  macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13682		       (int) imm_expr.X_add_number);
13683	  break;
13684	}
13685      if (imm_expr.X_add_number >= 0
13686	  && imm_expr.X_add_number < 0x10000)
13687	macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13688      else if (imm_expr.X_add_number > -0x8000
13689	       && imm_expr.X_add_number < 0)
13690	{
13691	  imm_expr.X_add_number = -imm_expr.X_add_number;
13692	  macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13693		       "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13694	}
13695      else if (CPU_HAS_SEQ (mips_opts.arch))
13696	{
13697	  used_at = 1;
13698	  load_register (AT, &imm_expr, GPR_SIZE == 64);
13699	  macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13700	  break;
13701	}
13702      else
13703	{
13704	  load_register (AT, &imm_expr, GPR_SIZE == 64);
13705	  macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13706	  used_at = 1;
13707	}
13708      macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13709      break;
13710
13711    case M_SGE:		/* X >= Y  <==>  not (X < Y) */
13712      s = "slt";
13713      goto sge;
13714    case M_SGEU:
13715      s = "sltu";
13716    sge:
13717      macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13718      macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13719      break;
13720
13721    case M_SGE_I:	/* X >= I  <==>  not (X < I).  */
13722    case M_SGEU_I:
13723      if (imm_expr.X_add_number >= -0x8000
13724	  && imm_expr.X_add_number < 0x8000)
13725	macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13726		     op[0], op[1], BFD_RELOC_LO16);
13727      else
13728	{
13729	  load_register (AT, &imm_expr, GPR_SIZE == 64);
13730	  macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13731		       op[0], op[1], AT);
13732	  used_at = 1;
13733	}
13734      macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13735      break;
13736
13737    case M_SGT:		/* X > Y  <==>  Y < X.  */
13738      s = "slt";
13739      goto sgt;
13740    case M_SGTU:
13741      s = "sltu";
13742    sgt:
13743      macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13744      break;
13745
13746    case M_SGT_I:	/* X > I  <==>  I < X.  */
13747      s = "slt";
13748      goto sgti;
13749    case M_SGTU_I:
13750      s = "sltu";
13751    sgti:
13752      used_at = 1;
13753      load_register (AT, &imm_expr, GPR_SIZE == 64);
13754      macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13755      break;
13756
13757    case M_SLE:		/* X <= Y  <==>  Y >= X  <==>  not (Y < X).  */
13758      s = "slt";
13759      goto sle;
13760    case M_SLEU:
13761      s = "sltu";
13762    sle:
13763      macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13764      macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13765      break;
13766
13767    case M_SLE_I:	/* X <= I  <==>  I >= X  <==>  not (I < X) */
13768      s = "slt";
13769      goto slei;
13770    case M_SLEU_I:
13771      s = "sltu";
13772    slei:
13773      used_at = 1;
13774      load_register (AT, &imm_expr, GPR_SIZE == 64);
13775      macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13776      macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13777      break;
13778
13779    case M_SLT_I:
13780      if (imm_expr.X_add_number >= -0x8000
13781	  && imm_expr.X_add_number < 0x8000)
13782	{
13783	  macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13784		       BFD_RELOC_LO16);
13785	  break;
13786	}
13787      used_at = 1;
13788      load_register (AT, &imm_expr, GPR_SIZE == 64);
13789      macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13790      break;
13791
13792    case M_SLTU_I:
13793      if (imm_expr.X_add_number >= -0x8000
13794	  && imm_expr.X_add_number < 0x8000)
13795	{
13796	  macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13797		       BFD_RELOC_LO16);
13798	  break;
13799	}
13800      used_at = 1;
13801      load_register (AT, &imm_expr, GPR_SIZE == 64);
13802      macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13803      break;
13804
13805    case M_SNE:
13806      if (op[1] == 0)
13807	macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13808      else if (op[2] == 0)
13809	macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13810      else
13811	{
13812	  macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13813	  macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13814	}
13815      break;
13816
13817    case M_SNE_I:
13818      if (imm_expr.X_add_number == 0)
13819	{
13820	  macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13821	  break;
13822	}
13823      if (op[1] == 0)
13824	{
13825	  as_warn (_("instruction %s: result is always true"),
13826		   ip->insn_mo->name);
13827	  macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13828		       op[0], 0, BFD_RELOC_LO16);
13829	  break;
13830	}
13831      if (CPU_HAS_SEQ (mips_opts.arch)
13832	  && -512 <= imm_expr.X_add_number
13833	  && imm_expr.X_add_number < 512)
13834	{
13835	  macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13836		       (int) imm_expr.X_add_number);
13837	  break;
13838	}
13839      if (imm_expr.X_add_number >= 0
13840	  && imm_expr.X_add_number < 0x10000)
13841	{
13842	  macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13843		       BFD_RELOC_LO16);
13844	}
13845      else if (imm_expr.X_add_number > -0x8000
13846	       && imm_expr.X_add_number < 0)
13847	{
13848	  imm_expr.X_add_number = -imm_expr.X_add_number;
13849	  macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13850		       "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13851	}
13852      else if (CPU_HAS_SEQ (mips_opts.arch))
13853	{
13854	  used_at = 1;
13855	  load_register (AT, &imm_expr, GPR_SIZE == 64);
13856	  macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13857	  break;
13858	}
13859      else
13860	{
13861	  load_register (AT, &imm_expr, GPR_SIZE == 64);
13862	  macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13863	  used_at = 1;
13864	}
13865      macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13866      break;
13867
13868    case M_SUB_I:
13869      s = "addi";
13870      s2 = "sub";
13871      if (ISA_IS_R6 (mips_opts.isa))
13872	goto do_subi_i;
13873      else
13874	goto do_subi;
13875    case M_SUBU_I:
13876      s = "addiu";
13877      s2 = "subu";
13878      goto do_subi;
13879    case M_DSUB_I:
13880      dbl = 1;
13881      s = "daddi";
13882      s2 = "dsub";
13883      if (!mips_opts.micromips && !ISA_IS_R6 (mips_opts.isa))
13884	goto do_subi;
13885      if (imm_expr.X_add_number > -0x200
13886	  && imm_expr.X_add_number <= 0x200
13887	  && !ISA_IS_R6 (mips_opts.isa))
13888	{
13889	  macro_build (NULL, s, "t,r,.", op[0], op[1],
13890		       (int) -imm_expr.X_add_number);
13891	  break;
13892	}
13893      goto do_subi_i;
13894    case M_DSUBU_I:
13895      dbl = 1;
13896      s = "daddiu";
13897      s2 = "dsubu";
13898    do_subi:
13899      if (imm_expr.X_add_number > -0x8000
13900	  && imm_expr.X_add_number <= 0x8000)
13901	{
13902	  imm_expr.X_add_number = -imm_expr.X_add_number;
13903	  macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13904	  break;
13905	}
13906    do_subi_i:
13907      used_at = 1;
13908      load_register (AT, &imm_expr, dbl);
13909      macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13910      break;
13911
13912    case M_TEQ_I:
13913      s = "teq";
13914      goto trap;
13915    case M_TGE_I:
13916      s = "tge";
13917      goto trap;
13918    case M_TGEU_I:
13919      s = "tgeu";
13920      goto trap;
13921    case M_TLT_I:
13922      s = "tlt";
13923      goto trap;
13924    case M_TLTU_I:
13925      s = "tltu";
13926      goto trap;
13927    case M_TNE_I:
13928      s = "tne";
13929    trap:
13930      used_at = 1;
13931      load_register (AT, &imm_expr, GPR_SIZE == 64);
13932      macro_build (NULL, s, "s,t", op[0], AT);
13933      break;
13934
13935    case M_TRUNCWS:
13936    case M_TRUNCWD:
13937      gas_assert (!mips_opts.micromips);
13938      gas_assert (mips_opts.isa == ISA_MIPS1);
13939      used_at = 1;
13940
13941      /*
13942       * Is the double cfc1 instruction a bug in the mips assembler;
13943       * or is there a reason for it?
13944       */
13945      start_noreorder ();
13946      macro_build (NULL, "cfc1", "t,g", op[2], FCSR);
13947      macro_build (NULL, "cfc1", "t,g", op[2], FCSR);
13948      macro_build (NULL, "nop", "");
13949      expr1.X_add_number = 3;
13950      macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13951      expr1.X_add_number = 2;
13952      macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13953      macro_build (NULL, "ctc1", "t,g", AT, FCSR);
13954      macro_build (NULL, "nop", "");
13955      macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13956		   op[0], op[1]);
13957      macro_build (NULL, "ctc1", "t,g", op[2], FCSR);
13958      macro_build (NULL, "nop", "");
13959      end_noreorder ();
13960      break;
13961
13962    case M_ULH_AB:
13963      s = "lb";
13964      s2 = "lbu";
13965      off = 1;
13966      goto uld_st;
13967    case M_ULHU_AB:
13968      s = "lbu";
13969      s2 = "lbu";
13970      off = 1;
13971      goto uld_st;
13972    case M_ULW_AB:
13973      s = "lwl";
13974      s2 = "lwr";
13975      offbits = (mips_opts.micromips ? 12 : 16);
13976      off = 3;
13977      goto uld_st;
13978    case M_ULD_AB:
13979      s = "ldl";
13980      s2 = "ldr";
13981      offbits = (mips_opts.micromips ? 12 : 16);
13982      off = 7;
13983      goto uld_st;
13984    case M_USH_AB:
13985      s = "sb";
13986      s2 = "sb";
13987      off = 1;
13988      ust = 1;
13989      goto uld_st;
13990    case M_USW_AB:
13991      s = "swl";
13992      s2 = "swr";
13993      offbits = (mips_opts.micromips ? 12 : 16);
13994      off = 3;
13995      ust = 1;
13996      goto uld_st;
13997    case M_USD_AB:
13998      s = "sdl";
13999      s2 = "sdr";
14000      offbits = (mips_opts.micromips ? 12 : 16);
14001      off = 7;
14002      ust = 1;
14003
14004    uld_st:
14005      breg = op[2];
14006      large_offset = !small_offset_p (off, align, offbits);
14007      ep = &offset_expr;
14008      expr1.X_add_number = 0;
14009      if (large_offset)
14010	{
14011	  used_at = 1;
14012	  tempreg = AT;
14013	  if (small_offset_p (0, align, 16))
14014	    macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
14015			 offset_reloc[0], offset_reloc[1], offset_reloc[2]);
14016	  else
14017	    {
14018	      load_address (tempreg, ep, &used_at);
14019	      if (breg != 0)
14020		macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
14021			     tempreg, tempreg, breg);
14022	    }
14023	  offset_reloc[0] = BFD_RELOC_LO16;
14024	  offset_reloc[1] = BFD_RELOC_UNUSED;
14025	  offset_reloc[2] = BFD_RELOC_UNUSED;
14026	  breg = tempreg;
14027	  tempreg = op[0];
14028	  ep = &expr1;
14029	}
14030      else if (!ust && op[0] == breg)
14031	{
14032	  used_at = 1;
14033	  tempreg = AT;
14034	}
14035      else
14036	tempreg = op[0];
14037
14038      if (off == 1)
14039	goto ulh_sh;
14040
14041      if (!target_big_endian)
14042	ep->X_add_number += off;
14043      if (offbits == 12)
14044	macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
14045      else
14046	macro_build (ep, s, "t,o(b)", tempreg, -1,
14047		     offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
14048
14049      if (!target_big_endian)
14050	ep->X_add_number -= off;
14051      else
14052	ep->X_add_number += off;
14053      if (offbits == 12)
14054	macro_build (NULL, s2, "t,~(b)",
14055		     tempreg, (int) ep->X_add_number, breg);
14056      else
14057	macro_build (ep, s2, "t,o(b)", tempreg, -1,
14058		     offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
14059
14060      /* If necessary, move the result in tempreg to the final destination.  */
14061      if (!ust && op[0] != tempreg)
14062        {
14063	  /* Protect second load's delay slot.  */
14064	  load_delay_nop ();
14065	  move_register (op[0], tempreg);
14066	}
14067      break;
14068
14069    ulh_sh:
14070      used_at = 1;
14071      if (target_big_endian == ust)
14072	ep->X_add_number += off;
14073      tempreg = ust || large_offset ? op[0] : AT;
14074      macro_build (ep, s, "t,o(b)", tempreg, -1,
14075		   offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
14076
14077      /* For halfword transfers we need a temporary register to shuffle
14078         bytes.  Unfortunately for M_USH_A we have none available before
14079         the next store as AT holds the base address.  We deal with this
14080         case by clobbering TREG and then restoring it as with ULH.  */
14081      tempreg = ust == large_offset ? op[0] : AT;
14082      if (ust)
14083	macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
14084
14085      if (target_big_endian == ust)
14086	ep->X_add_number -= off;
14087      else
14088	ep->X_add_number += off;
14089      macro_build (ep, s2, "t,o(b)", tempreg, -1,
14090		   offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
14091
14092      /* For M_USH_A re-retrieve the LSB.  */
14093      if (ust && large_offset)
14094	{
14095	  if (target_big_endian)
14096	    ep->X_add_number += off;
14097	  else
14098	    ep->X_add_number -= off;
14099	  macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
14100		       offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
14101	}
14102      /* For ULH and M_USH_A OR the LSB in.  */
14103      if (!ust || large_offset)
14104	{
14105	  tempreg = !large_offset ? AT : op[0];
14106	  macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
14107	  macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
14108	}
14109      break;
14110
14111    default:
14112      /* FIXME: Check if this is one of the itbl macros, since they
14113	 are added dynamically.  */
14114      as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
14115      break;
14116    }
14117  if (!mips_opts.at && used_at)
14118    as_bad (_("macro used $at after \".set noat\""));
14119}
14120
14121/* Implement macros in mips16 mode.  */
14122
14123static void
14124mips16_macro (struct mips_cl_insn *ip)
14125{
14126  const struct mips_operand_array *operands;
14127  int mask;
14128  int tmp;
14129  expressionS expr1;
14130  int dbl;
14131  const char *s, *s2, *s3;
14132  unsigned int op[MAX_OPERANDS];
14133  unsigned int i;
14134
14135  mask = ip->insn_mo->mask;
14136
14137  operands = insn_operands (ip);
14138  for (i = 0; i < MAX_OPERANDS; i++)
14139    if (operands->operand[i])
14140      op[i] = insn_extract_operand (ip, operands->operand[i]);
14141    else
14142      op[i] = -1;
14143
14144  expr1.X_op = O_constant;
14145  expr1.X_op_symbol = NULL;
14146  expr1.X_add_symbol = NULL;
14147  expr1.X_add_number = 1;
14148
14149  dbl = 0;
14150
14151  switch (mask)
14152    {
14153    default:
14154      abort ();
14155
14156    case M_DDIV_3:
14157      dbl = 1;
14158      /* Fall through.  */
14159    case M_DIV_3:
14160      s = "mflo";
14161      goto do_div3;
14162    case M_DREM_3:
14163      dbl = 1;
14164      /* Fall through.  */
14165    case M_REM_3:
14166      s = "mfhi";
14167    do_div3:
14168      start_noreorder ();
14169      macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
14170      expr1.X_add_number = 2;
14171      macro_build (&expr1, "bnez", "x,p", op[2]);
14172      macro_build (NULL, "break", "6", 7);
14173
14174      /* FIXME: The normal code checks for of -1 / -0x80000000 here,
14175         since that causes an overflow.  We should do that as well,
14176         but I don't see how to do the comparisons without a temporary
14177         register.  */
14178      end_noreorder ();
14179      macro_build (NULL, s, "x", op[0]);
14180      break;
14181
14182    case M_DIVU_3:
14183      s = "divu";
14184      s2 = "mflo";
14185      goto do_divu3;
14186    case M_REMU_3:
14187      s = "divu";
14188      s2 = "mfhi";
14189      goto do_divu3;
14190    case M_DDIVU_3:
14191      s = "ddivu";
14192      s2 = "mflo";
14193      goto do_divu3;
14194    case M_DREMU_3:
14195      s = "ddivu";
14196      s2 = "mfhi";
14197    do_divu3:
14198      start_noreorder ();
14199      macro_build (NULL, s, ".,x,y", op[1], op[2]);
14200      expr1.X_add_number = 2;
14201      macro_build (&expr1, "bnez", "x,p", op[2]);
14202      macro_build (NULL, "break", "6", 7);
14203      end_noreorder ();
14204      macro_build (NULL, s2, "x", op[0]);
14205      break;
14206
14207    case M_DMUL:
14208      dbl = 1;
14209      /* Fall through.  */
14210    case M_MUL:
14211      macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
14212      macro_build (NULL, "mflo", "x", op[0]);
14213      break;
14214
14215    case M_DSUBU_I:
14216      dbl = 1;
14217      goto do_subu;
14218    case M_SUBU_I:
14219    do_subu:
14220      imm_expr.X_add_number = -imm_expr.X_add_number;
14221      macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
14222      break;
14223
14224    case M_SUBU_I_2:
14225      imm_expr.X_add_number = -imm_expr.X_add_number;
14226      macro_build (&imm_expr, "addiu", "x,k", op[0]);
14227      break;
14228
14229    case M_DSUBU_I_2:
14230      imm_expr.X_add_number = -imm_expr.X_add_number;
14231      macro_build (&imm_expr, "daddiu", "y,j", op[0]);
14232      break;
14233
14234    case M_BEQ:
14235      s = "cmp";
14236      s2 = "bteqz";
14237      goto do_branch;
14238    case M_BNE:
14239      s = "cmp";
14240      s2 = "btnez";
14241      goto do_branch;
14242    case M_BLT:
14243      s = "slt";
14244      s2 = "btnez";
14245      goto do_branch;
14246    case M_BLTU:
14247      s = "sltu";
14248      s2 = "btnez";
14249      goto do_branch;
14250    case M_BLE:
14251      s = "slt";
14252      s2 = "bteqz";
14253      goto do_reverse_branch;
14254    case M_BLEU:
14255      s = "sltu";
14256      s2 = "bteqz";
14257      goto do_reverse_branch;
14258    case M_BGE:
14259      s = "slt";
14260      s2 = "bteqz";
14261      goto do_branch;
14262    case M_BGEU:
14263      s = "sltu";
14264      s2 = "bteqz";
14265      goto do_branch;
14266    case M_BGT:
14267      s = "slt";
14268      s2 = "btnez";
14269      goto do_reverse_branch;
14270    case M_BGTU:
14271      s = "sltu";
14272      s2 = "btnez";
14273
14274    do_reverse_branch:
14275      tmp = op[1];
14276      op[1] = op[0];
14277      op[0] = tmp;
14278
14279    do_branch:
14280      macro_build (NULL, s, "x,y", op[0], op[1]);
14281      macro_build (&offset_expr, s2, "p");
14282      break;
14283
14284    case M_BEQ_I:
14285      s = "cmpi";
14286      s2 = "bteqz";
14287      s3 = "x,U";
14288      goto do_branch_i;
14289    case M_BNE_I:
14290      s = "cmpi";
14291      s2 = "btnez";
14292      s3 = "x,U";
14293      goto do_branch_i;
14294    case M_BLT_I:
14295      s = "slti";
14296      s2 = "btnez";
14297      s3 = "x,8";
14298      goto do_branch_i;
14299    case M_BLTU_I:
14300      s = "sltiu";
14301      s2 = "btnez";
14302      s3 = "x,8";
14303      goto do_branch_i;
14304    case M_BLE_I:
14305      s = "slti";
14306      s2 = "btnez";
14307      s3 = "x,8";
14308      goto do_addone_branch_i;
14309    case M_BLEU_I:
14310      s = "sltiu";
14311      s2 = "btnez";
14312      s3 = "x,8";
14313      goto do_addone_branch_i;
14314    case M_BGE_I:
14315      s = "slti";
14316      s2 = "bteqz";
14317      s3 = "x,8";
14318      goto do_branch_i;
14319    case M_BGEU_I:
14320      s = "sltiu";
14321      s2 = "bteqz";
14322      s3 = "x,8";
14323      goto do_branch_i;
14324    case M_BGT_I:
14325      s = "slti";
14326      s2 = "bteqz";
14327      s3 = "x,8";
14328      goto do_addone_branch_i;
14329    case M_BGTU_I:
14330      s = "sltiu";
14331      s2 = "bteqz";
14332      s3 = "x,8";
14333
14334    do_addone_branch_i:
14335      ++imm_expr.X_add_number;
14336
14337    do_branch_i:
14338      macro_build (&imm_expr, s, s3, op[0]);
14339      macro_build (&offset_expr, s2, "p");
14340      break;
14341
14342    case M_ABS:
14343      expr1.X_add_number = 0;
14344      macro_build (&expr1, "slti", "x,8", op[1]);
14345      if (op[0] != op[1])
14346	macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
14347      expr1.X_add_number = 2;
14348      macro_build (&expr1, "bteqz", "p");
14349      macro_build (NULL, "neg", "x,w", op[0], op[0]);
14350      break;
14351    }
14352}
14353
14354/* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
14355   opcode bits in *OPCODE_EXTRA.  */
14356
14357static struct mips_opcode *
14358mips_lookup_insn (htab_t hash, const char *start,
14359		  ssize_t length, unsigned int *opcode_extra)
14360{
14361  char *name, *dot, *p;
14362  unsigned int mask, suffix;
14363  ssize_t opend;
14364  struct mips_opcode *insn;
14365
14366  /* Make a copy of the instruction so that we can fiddle with it.  */
14367  name = xstrndup (start, length);
14368
14369  /* Look up the instruction as-is.  */
14370  insn = (struct mips_opcode *) str_hash_find (hash, name);
14371  if (insn)
14372    goto end;
14373
14374  dot = strchr (name, '.');
14375  if (dot && dot[1])
14376    {
14377      /* Try to interpret the text after the dot as a VU0 channel suffix.  */
14378      p = mips_parse_vu0_channels (dot + 1, &mask);
14379      if (*p == 0 && mask != 0)
14380	{
14381	  *dot = 0;
14382	  insn = (struct mips_opcode *) str_hash_find (hash, name);
14383	  *dot = '.';
14384	  if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
14385	    {
14386	      *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
14387	      goto end;
14388	    }
14389	}
14390    }
14391
14392  if (mips_opts.micromips)
14393    {
14394      /* See if there's an instruction size override suffix,
14395	 either `16' or `32', at the end of the mnemonic proper,
14396	 that defines the operation, i.e. before the first `.'
14397	 character if any.  Strip it and retry.  */
14398      opend = dot != NULL ? dot - name : length;
14399      if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
14400	suffix = 2;
14401      else if (opend >= 2 && name[opend - 2] == '3' && name[opend - 1] == '2')
14402	suffix = 4;
14403      else
14404	suffix = 0;
14405      if (suffix)
14406	{
14407	  memmove (name + opend - 2, name + opend, length - opend + 1);
14408	  insn = (struct mips_opcode *) str_hash_find (hash, name);
14409	  if (insn)
14410	    {
14411	      forced_insn_length = suffix;
14412	      goto end;
14413	    }
14414	}
14415    }
14416
14417  insn = NULL;
14418 end:
14419  free (name);
14420  return insn;
14421}
14422
14423/* Assemble an instruction into its binary format.  If the instruction
14424   is a macro, set imm_expr and offset_expr to the values associated
14425   with "I" and "A" operands respectively.  Otherwise store the value
14426   of the relocatable field (if any) in offset_expr.  In both cases
14427   set offset_reloc to the relocation operators applied to offset_expr.  */
14428
14429static void
14430mips_ip (char *str, struct mips_cl_insn *insn)
14431{
14432  const struct mips_opcode *first, *past;
14433  htab_t hash;
14434  char format;
14435  size_t end;
14436  struct mips_operand_token *tokens;
14437  unsigned int opcode_extra;
14438
14439  if (mips_opts.micromips)
14440    {
14441      hash = micromips_op_hash;
14442      past = &micromips_opcodes[bfd_micromips_num_opcodes];
14443    }
14444  else
14445    {
14446      hash = op_hash;
14447      past = &mips_opcodes[NUMOPCODES];
14448    }
14449  forced_insn_length = 0;
14450  opcode_extra = 0;
14451
14452  /* We first try to match an instruction up to a space or to the end.  */
14453  for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
14454    continue;
14455
14456  first = mips_lookup_insn (hash, str, end, &opcode_extra);
14457  if (first == NULL)
14458    {
14459      set_insn_error (0, _("unrecognized opcode"));
14460      return;
14461    }
14462
14463  if (strcmp (first->name, "li.s") == 0)
14464    format = 'f';
14465  else if (strcmp (first->name, "li.d") == 0)
14466    format = 'd';
14467  else
14468    format = 0;
14469  tokens = mips_parse_arguments (str + end, format);
14470  if (!tokens)
14471    return;
14472
14473  if (!match_insns (insn, first, past, tokens, opcode_extra, false)
14474      && !match_insns (insn, first, past, tokens, opcode_extra, true))
14475    set_insn_error (0, _("invalid operands"));
14476
14477  obstack_free (&mips_operand_tokens, tokens);
14478}
14479
14480/* As for mips_ip, but used when assembling MIPS16 code.
14481   Also set forced_insn_length to the resulting instruction size in
14482   bytes if the user explicitly requested a small or extended instruction.  */
14483
14484static void
14485mips16_ip (char *str, struct mips_cl_insn *insn)
14486{
14487  char *end, *s, c;
14488  struct mips_opcode *first;
14489  struct mips_operand_token *tokens;
14490  unsigned int l;
14491
14492  for (s = str; *s != '\0' && *s != '.' && *s != ' '; ++s)
14493    ;
14494  end = s;
14495  c = *end;
14496
14497  l = 0;
14498  switch (c)
14499    {
14500    case '\0':
14501      break;
14502
14503    case ' ':
14504      s++;
14505      break;
14506
14507    case '.':
14508      s++;
14509      if (*s == 't')
14510	{
14511	  l = 2;
14512	  s++;
14513	}
14514      else if (*s == 'e')
14515	{
14516	  l = 4;
14517	  s++;
14518	}
14519      if (*s == '\0')
14520	break;
14521      else if (*s++ == ' ')
14522	break;
14523      set_insn_error (0, _("unrecognized opcode"));
14524      return;
14525    }
14526  forced_insn_length = l;
14527
14528  *end = 0;
14529  first = (struct mips_opcode *) str_hash_find (mips16_op_hash, str);
14530  *end = c;
14531
14532  if (!first)
14533    {
14534      set_insn_error (0, _("unrecognized opcode"));
14535      return;
14536    }
14537
14538  tokens = mips_parse_arguments (s, 0);
14539  if (!tokens)
14540    return;
14541
14542  if (!match_mips16_insns (insn, first, tokens))
14543    set_insn_error (0, _("invalid operands"));
14544
14545  obstack_free (&mips_operand_tokens, tokens);
14546}
14547
14548/* Marshal immediate value VAL for an extended MIPS16 instruction.
14549   NBITS is the number of significant bits in VAL.  */
14550
14551static unsigned long
14552mips16_immed_extend (offsetT val, unsigned int nbits)
14553{
14554  int extval;
14555
14556  extval = 0;
14557  val &= (1U << nbits) - 1;
14558  if (nbits == 16 || nbits == 9)
14559    {
14560      extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14561      val &= 0x1f;
14562    }
14563  else if (nbits == 15)
14564    {
14565      extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14566      val &= 0xf;
14567    }
14568  else if (nbits == 6)
14569    {
14570      extval = ((val & 0x1f) << 6) | (val & 0x20);
14571      val = 0;
14572    }
14573  return (extval << 16) | val;
14574}
14575
14576/* Like decode_mips16_operand, but require the operand to be defined and
14577   require it to be an integer.  */
14578
14579static const struct mips_int_operand *
14580mips16_immed_operand (int type, bool extended_p)
14581{
14582  const struct mips_operand *operand;
14583
14584  operand = decode_mips16_operand (type, extended_p);
14585  if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
14586    abort ();
14587  return (const struct mips_int_operand *) operand;
14588}
14589
14590/* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14591
14592static bool
14593mips16_immed_in_range_p (const struct mips_int_operand *operand,
14594			 bfd_reloc_code_real_type reloc, offsetT sval)
14595{
14596  int min_val, max_val;
14597
14598  min_val = mips_int_operand_min (operand);
14599  max_val = mips_int_operand_max (operand);
14600  if (reloc != BFD_RELOC_UNUSED)
14601    {
14602      if (min_val < 0)
14603	sval = SEXT_16BIT (sval);
14604      else
14605	sval &= 0xffff;
14606    }
14607
14608  return (sval >= min_val
14609	  && sval <= max_val
14610	  && (sval & ((1 << operand->shift) - 1)) == 0);
14611}
14612
14613/* Install immediate value VAL into MIPS16 instruction *INSN,
14614   extending it if necessary.  The instruction in *INSN may
14615   already be extended.
14616
14617   RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14618   if none.  In the former case, VAL is a 16-bit number with no
14619   defined signedness.
14620
14621   TYPE is the type of the immediate field.  USER_INSN_LENGTH
14622   is the length that the user requested, or 0 if none.  */
14623
14624static void
14625mips16_immed (const char *file, unsigned int line, int type,
14626	      bfd_reloc_code_real_type reloc, offsetT val,
14627	      unsigned int user_insn_length, unsigned long *insn)
14628{
14629  const struct mips_int_operand *operand;
14630  unsigned int uval, length;
14631
14632  operand = mips16_immed_operand (type, false);
14633  if (!mips16_immed_in_range_p (operand, reloc, val))
14634    {
14635      /* We need an extended instruction.  */
14636      if (user_insn_length == 2)
14637	as_bad_where (file, line, _("invalid unextended operand value"));
14638      else
14639	*insn |= MIPS16_EXTEND;
14640    }
14641  else if (user_insn_length == 4)
14642    {
14643      /* The operand doesn't force an unextended instruction to be extended.
14644	 Warn if the user wanted an extended instruction anyway.  */
14645      *insn |= MIPS16_EXTEND;
14646      as_warn_where (file, line,
14647		     _("extended operand requested but not required"));
14648    }
14649
14650  length = mips16_opcode_length (*insn);
14651  if (length == 4)
14652    {
14653      operand = mips16_immed_operand (type, true);
14654      if (!mips16_immed_in_range_p (operand, reloc, val))
14655	as_bad_where (file, line,
14656		      _("operand value out of range for instruction"));
14657    }
14658  uval = ((unsigned int) val >> operand->shift) - operand->bias;
14659  if (length == 2 || operand->root.lsb != 0)
14660    *insn = mips_insert_operand (&operand->root, *insn, uval);
14661  else
14662    *insn |= mips16_immed_extend (uval, operand->root.size);
14663}
14664
14665struct percent_op_match
14666{
14667  const char *str;
14668  bfd_reloc_code_real_type reloc;
14669};
14670
14671static const struct percent_op_match mips_percent_op[] =
14672{
14673  {"%lo", BFD_RELOC_LO16},
14674  {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14675  {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14676  {"%call16", BFD_RELOC_MIPS_CALL16},
14677  {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14678  {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14679  {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14680  {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14681  {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14682  {"%got", BFD_RELOC_MIPS_GOT16},
14683  {"%gp_rel", BFD_RELOC_GPREL16},
14684  {"%gprel", BFD_RELOC_GPREL16},
14685  {"%half", BFD_RELOC_MIPS_16},
14686  {"%highest", BFD_RELOC_MIPS_HIGHEST},
14687  {"%higher", BFD_RELOC_MIPS_HIGHER},
14688  {"%neg", BFD_RELOC_MIPS_SUB},
14689  {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14690  {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14691  {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14692  {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14693  {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14694  {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14695  {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14696  {"%hi", BFD_RELOC_HI16_S},
14697  {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14698  {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14699};
14700
14701static const struct percent_op_match mips16_percent_op[] =
14702{
14703  {"%lo", BFD_RELOC_MIPS16_LO16},
14704  {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14705  {"%gprel", BFD_RELOC_MIPS16_GPREL},
14706  {"%got", BFD_RELOC_MIPS16_GOT16},
14707  {"%call16", BFD_RELOC_MIPS16_CALL16},
14708  {"%hi", BFD_RELOC_MIPS16_HI16_S},
14709  {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14710  {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14711  {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14712  {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14713  {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14714  {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14715  {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14716};
14717
14718
14719/* Return true if *STR points to a relocation operator.  When returning true,
14720   move *STR over the operator and store its relocation code in *RELOC.
14721   Leave both *STR and *RELOC alone when returning false.  */
14722
14723static bool
14724parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14725{
14726  const struct percent_op_match *percent_op;
14727  size_t limit, i;
14728
14729  if (mips_opts.mips16)
14730    {
14731      percent_op = mips16_percent_op;
14732      limit = ARRAY_SIZE (mips16_percent_op);
14733    }
14734  else
14735    {
14736      percent_op = mips_percent_op;
14737      limit = ARRAY_SIZE (mips_percent_op);
14738    }
14739
14740  for (i = 0; i < limit; i++)
14741    if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14742      {
14743	int len = strlen (percent_op[i].str);
14744
14745	if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14746	  continue;
14747
14748	*str += strlen (percent_op[i].str);
14749	*reloc = percent_op[i].reloc;
14750
14751	/* Check whether the output BFD supports this relocation.
14752	   If not, issue an error and fall back on something safe.  */
14753	if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14754	  {
14755	    as_bad (_("relocation %s isn't supported by the current ABI"),
14756		    percent_op[i].str);
14757	    *reloc = BFD_RELOC_UNUSED;
14758	  }
14759	return true;
14760      }
14761  return false;
14762}
14763
14764
14765/* Parse string STR as a 16-bit relocatable operand.  Store the
14766   expression in *EP and the relocations in the array starting
14767   at RELOC.  Return the number of relocation operators used.
14768
14769   On exit, EXPR_END points to the first character after the expression.  */
14770
14771static size_t
14772my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14773		       char *str)
14774{
14775  bfd_reloc_code_real_type reversed_reloc[3];
14776  size_t reloc_index, i;
14777  int crux_depth, str_depth;
14778  char *crux;
14779
14780  /* Search for the start of the main expression, recoding relocations
14781     in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14782     of the main expression and with CRUX_DEPTH containing the number
14783     of open brackets at that point.  */
14784  reloc_index = -1;
14785  str_depth = 0;
14786  do
14787    {
14788      reloc_index++;
14789      crux = str;
14790      crux_depth = str_depth;
14791
14792      /* Skip over whitespace and brackets, keeping count of the number
14793	 of brackets.  */
14794      while (*str == ' ' || *str == '\t' || *str == '(')
14795	if (*str++ == '(')
14796	  str_depth++;
14797    }
14798  while (*str == '%'
14799	 && reloc_index < (HAVE_NEWABI ? 3 : 1)
14800	 && parse_relocation (&str, &reversed_reloc[reloc_index]));
14801
14802  my_getExpression (ep, crux);
14803  str = expr_end;
14804
14805  /* Match every open bracket.  */
14806  while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14807    if (*str++ == ')')
14808      crux_depth--;
14809
14810  if (crux_depth > 0)
14811    as_bad (_("unclosed '('"));
14812
14813  expr_end = str;
14814
14815  for (i = 0; i < reloc_index; i++)
14816    reloc[i] = reversed_reloc[reloc_index - 1 - i];
14817
14818  return reloc_index;
14819}
14820
14821static void
14822my_getExpression (expressionS *ep, char *str)
14823{
14824  char *save_in;
14825
14826  save_in = input_line_pointer;
14827  input_line_pointer = str;
14828  expression (ep);
14829  expr_end = input_line_pointer;
14830  input_line_pointer = save_in;
14831}
14832
14833const char *
14834md_atof (int type, char *litP, int *sizeP)
14835{
14836  return ieee_md_atof (type, litP, sizeP, target_big_endian);
14837}
14838
14839void
14840md_number_to_chars (char *buf, valueT val, int n)
14841{
14842  if (target_big_endian)
14843    number_to_chars_bigendian (buf, val, n);
14844  else
14845    number_to_chars_littleendian (buf, val, n);
14846}
14847
14848static int support_64bit_objects(void)
14849{
14850  const char **list, **l;
14851  int yes;
14852
14853  list = bfd_target_list ();
14854  for (l = list; *l != NULL; l++)
14855    if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14856	|| strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14857      break;
14858  yes = (*l != NULL);
14859  free (list);
14860  return yes;
14861}
14862
14863/* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14864   NEW_VALUE.  Warn if another value was already specified.  Note:
14865   we have to defer parsing the -march and -mtune arguments in order
14866   to handle 'from-abi' correctly, since the ABI might be specified
14867   in a later argument.  */
14868
14869static void
14870mips_set_option_string (const char **string_ptr, const char *new_value)
14871{
14872  if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14873    as_warn (_("a different %s was already specified, is now %s"),
14874	     string_ptr == &mips_arch_string ? "-march" : "-mtune",
14875	     new_value);
14876
14877  *string_ptr = new_value;
14878}
14879
14880int
14881md_parse_option (int c, const char *arg)
14882{
14883  unsigned int i;
14884
14885  for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14886    if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14887      {
14888	file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14889					   c == mips_ases[i].option_on);
14890	return 1;
14891      }
14892
14893  switch (c)
14894    {
14895    case OPTION_CONSTRUCT_FLOATS:
14896      mips_disable_float_construction = 0;
14897      break;
14898
14899    case OPTION_NO_CONSTRUCT_FLOATS:
14900      mips_disable_float_construction = 1;
14901      break;
14902
14903    case OPTION_TRAP:
14904      mips_trap = 1;
14905      break;
14906
14907    case OPTION_BREAK:
14908      mips_trap = 0;
14909      break;
14910
14911    case OPTION_EB:
14912      target_big_endian = 1;
14913      break;
14914
14915    case OPTION_EL:
14916      target_big_endian = 0;
14917      break;
14918
14919    case 'O':
14920      if (arg == NULL)
14921	mips_optimize = 1;
14922      else if (arg[0] == '0')
14923	mips_optimize = 0;
14924      else if (arg[0] == '1')
14925	mips_optimize = 1;
14926      else
14927	mips_optimize = 2;
14928      break;
14929
14930    case 'g':
14931      if (arg == NULL)
14932	mips_debug = 2;
14933      else
14934	mips_debug = atoi (arg);
14935      break;
14936
14937    case OPTION_MIPS1:
14938      file_mips_opts.isa = ISA_MIPS1;
14939      break;
14940
14941    case OPTION_MIPS2:
14942      file_mips_opts.isa = ISA_MIPS2;
14943      break;
14944
14945    case OPTION_MIPS3:
14946      file_mips_opts.isa = ISA_MIPS3;
14947      break;
14948
14949    case OPTION_MIPS4:
14950      file_mips_opts.isa = ISA_MIPS4;
14951      break;
14952
14953    case OPTION_MIPS5:
14954      file_mips_opts.isa = ISA_MIPS5;
14955      break;
14956
14957    case OPTION_MIPS32:
14958      file_mips_opts.isa = ISA_MIPS32;
14959      break;
14960
14961    case OPTION_MIPS32R2:
14962      file_mips_opts.isa = ISA_MIPS32R2;
14963      break;
14964
14965    case OPTION_MIPS32R3:
14966      file_mips_opts.isa = ISA_MIPS32R3;
14967      break;
14968
14969    case OPTION_MIPS32R5:
14970      file_mips_opts.isa = ISA_MIPS32R5;
14971      break;
14972
14973    case OPTION_MIPS32R6:
14974      file_mips_opts.isa = ISA_MIPS32R6;
14975      break;
14976
14977    case OPTION_MIPS64R2:
14978      file_mips_opts.isa = ISA_MIPS64R2;
14979      break;
14980
14981    case OPTION_MIPS64R3:
14982      file_mips_opts.isa = ISA_MIPS64R3;
14983      break;
14984
14985    case OPTION_MIPS64R5:
14986      file_mips_opts.isa = ISA_MIPS64R5;
14987      break;
14988
14989    case OPTION_MIPS64R6:
14990      file_mips_opts.isa = ISA_MIPS64R6;
14991      break;
14992
14993    case OPTION_MIPS64:
14994      file_mips_opts.isa = ISA_MIPS64;
14995      break;
14996
14997    case OPTION_MTUNE:
14998      mips_set_option_string (&mips_tune_string, arg);
14999      break;
15000
15001    case OPTION_MARCH:
15002      mips_set_option_string (&mips_arch_string, arg);
15003      break;
15004
15005    case OPTION_M4650:
15006      mips_set_option_string (&mips_arch_string, "4650");
15007      mips_set_option_string (&mips_tune_string, "4650");
15008      break;
15009
15010    case OPTION_NO_M4650:
15011      break;
15012
15013    case OPTION_M4010:
15014      mips_set_option_string (&mips_arch_string, "4010");
15015      mips_set_option_string (&mips_tune_string, "4010");
15016      break;
15017
15018    case OPTION_NO_M4010:
15019      break;
15020
15021    case OPTION_M4100:
15022      mips_set_option_string (&mips_arch_string, "4100");
15023      mips_set_option_string (&mips_tune_string, "4100");
15024      break;
15025
15026    case OPTION_NO_M4100:
15027      break;
15028
15029    case OPTION_M3900:
15030      mips_set_option_string (&mips_arch_string, "3900");
15031      mips_set_option_string (&mips_tune_string, "3900");
15032      break;
15033
15034    case OPTION_NO_M3900:
15035      break;
15036
15037    case OPTION_MICROMIPS:
15038      if (file_mips_opts.mips16 == 1)
15039	{
15040	  as_bad (_("-mmicromips cannot be used with -mips16"));
15041	  return 0;
15042	}
15043      file_mips_opts.micromips = 1;
15044      mips_no_prev_insn ();
15045      break;
15046
15047    case OPTION_NO_MICROMIPS:
15048      file_mips_opts.micromips = 0;
15049      mips_no_prev_insn ();
15050      break;
15051
15052    case OPTION_MIPS16:
15053      if (file_mips_opts.micromips == 1)
15054	{
15055	  as_bad (_("-mips16 cannot be used with -micromips"));
15056	  return 0;
15057	}
15058      file_mips_opts.mips16 = 1;
15059      mips_no_prev_insn ();
15060      break;
15061
15062    case OPTION_NO_MIPS16:
15063      file_mips_opts.mips16 = 0;
15064      mips_no_prev_insn ();
15065      break;
15066
15067    case OPTION_FIX_24K:
15068      mips_fix_24k = 1;
15069      break;
15070
15071    case OPTION_NO_FIX_24K:
15072      mips_fix_24k = 0;
15073      break;
15074
15075    case OPTION_FIX_RM7000:
15076      mips_fix_rm7000 = 1;
15077      break;
15078
15079    case OPTION_NO_FIX_RM7000:
15080      mips_fix_rm7000 = 0;
15081      break;
15082
15083    case OPTION_FIX_LOONGSON3_LLSC:
15084      mips_fix_loongson3_llsc = true;
15085      break;
15086
15087    case OPTION_NO_FIX_LOONGSON3_LLSC:
15088      mips_fix_loongson3_llsc = false;
15089      break;
15090
15091    case OPTION_FIX_LOONGSON2F_JUMP:
15092      mips_fix_loongson2f_jump = true;
15093      break;
15094
15095    case OPTION_NO_FIX_LOONGSON2F_JUMP:
15096      mips_fix_loongson2f_jump = false;
15097      break;
15098
15099    case OPTION_FIX_LOONGSON2F_NOP:
15100      mips_fix_loongson2f_nop = true;
15101      break;
15102
15103    case OPTION_NO_FIX_LOONGSON2F_NOP:
15104      mips_fix_loongson2f_nop = false;
15105      break;
15106
15107    case OPTION_FIX_VR4120:
15108      mips_fix_vr4120 = 1;
15109      break;
15110
15111    case OPTION_NO_FIX_VR4120:
15112      mips_fix_vr4120 = 0;
15113      break;
15114
15115    case OPTION_FIX_VR4130:
15116      mips_fix_vr4130 = 1;
15117      break;
15118
15119    case OPTION_NO_FIX_VR4130:
15120      mips_fix_vr4130 = 0;
15121      break;
15122
15123    case OPTION_FIX_LOONGSON2F_BTB:
15124      mips_fix_loongson2f_btb = 1;
15125      break;
15126
15127    case OPTION_NO_FIX_LOONGSON2F_BTB:
15128      mips_fix_loongson2f_btb = 0;
15129      break;
15130
15131    case OPTION_FIX_CN63XXP1:
15132      mips_fix_cn63xxp1 = true;
15133      break;
15134
15135    case OPTION_NO_FIX_CN63XXP1:
15136      mips_fix_cn63xxp1 = false;
15137      break;
15138
15139    case OPTION_FIX_R5900:
15140      mips_fix_r5900 = true;
15141      mips_fix_r5900_explicit = true;
15142      break;
15143
15144    case OPTION_NO_FIX_R5900:
15145      mips_fix_r5900 = false;
15146      mips_fix_r5900_explicit = true;
15147      break;
15148
15149    case OPTION_RELAX_BRANCH:
15150      mips_relax_branch = 1;
15151      break;
15152
15153    case OPTION_NO_RELAX_BRANCH:
15154      mips_relax_branch = 0;
15155      break;
15156
15157    case OPTION_IGNORE_BRANCH_ISA:
15158      mips_ignore_branch_isa = true;
15159      break;
15160
15161    case OPTION_NO_IGNORE_BRANCH_ISA:
15162      mips_ignore_branch_isa = false;
15163      break;
15164
15165    case OPTION_INSN32:
15166      file_mips_opts.insn32 = true;
15167      break;
15168
15169    case OPTION_NO_INSN32:
15170      file_mips_opts.insn32 = false;
15171      break;
15172
15173    case OPTION_MSHARED:
15174      mips_in_shared = true;
15175      break;
15176
15177    case OPTION_MNO_SHARED:
15178      mips_in_shared = false;
15179      break;
15180
15181    case OPTION_MSYM32:
15182      file_mips_opts.sym32 = true;
15183      break;
15184
15185    case OPTION_MNO_SYM32:
15186      file_mips_opts.sym32 = false;
15187      break;
15188
15189      /* When generating ELF code, we permit -KPIC and -call_shared to
15190	 select SVR4_PIC, and -non_shared to select no PIC.  This is
15191	 intended to be compatible with Irix 5.  */
15192    case OPTION_CALL_SHARED:
15193      mips_pic = SVR4_PIC;
15194      mips_abicalls = true;
15195      break;
15196
15197    case OPTION_CALL_NONPIC:
15198      mips_pic = NO_PIC;
15199      mips_abicalls = true;
15200      break;
15201
15202    case OPTION_NON_SHARED:
15203      mips_pic = NO_PIC;
15204      mips_abicalls = false;
15205      break;
15206
15207      /* The -xgot option tells the assembler to use 32 bit offsets
15208         when accessing the got in SVR4_PIC mode.  It is for Irix
15209         compatibility.  */
15210    case OPTION_XGOT:
15211      mips_big_got = 1;
15212      break;
15213
15214    case 'G':
15215      g_switch_value = atoi (arg);
15216      g_switch_seen = 1;
15217      break;
15218
15219      /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
15220	 and -mabi=64.  */
15221    case OPTION_32:
15222      mips_abi = O32_ABI;
15223      break;
15224
15225    case OPTION_N32:
15226      mips_abi = N32_ABI;
15227      break;
15228
15229    case OPTION_64:
15230      mips_abi = N64_ABI;
15231      if (!support_64bit_objects())
15232	as_fatal (_("no compiled in support for 64 bit object file format"));
15233      break;
15234
15235    case OPTION_GP32:
15236      file_mips_opts.gp = 32;
15237      break;
15238
15239    case OPTION_GP64:
15240      file_mips_opts.gp = 64;
15241      break;
15242
15243    case OPTION_FP32:
15244      file_mips_opts.fp = 32;
15245      break;
15246
15247    case OPTION_FPXX:
15248      file_mips_opts.fp = 0;
15249      break;
15250
15251    case OPTION_FP64:
15252      file_mips_opts.fp = 64;
15253      break;
15254
15255    case OPTION_ODD_SPREG:
15256      file_mips_opts.oddspreg = 1;
15257      break;
15258
15259    case OPTION_NO_ODD_SPREG:
15260      file_mips_opts.oddspreg = 0;
15261      break;
15262
15263    case OPTION_SINGLE_FLOAT:
15264      file_mips_opts.single_float = 1;
15265      break;
15266
15267    case OPTION_DOUBLE_FLOAT:
15268      file_mips_opts.single_float = 0;
15269      break;
15270
15271    case OPTION_SOFT_FLOAT:
15272      file_mips_opts.soft_float = 1;
15273      break;
15274
15275    case OPTION_HARD_FLOAT:
15276      file_mips_opts.soft_float = 0;
15277      break;
15278
15279    case OPTION_MABI:
15280      if (strcmp (arg, "32") == 0)
15281	mips_abi = O32_ABI;
15282      else if (strcmp (arg, "o64") == 0)
15283	mips_abi = O64_ABI;
15284      else if (strcmp (arg, "n32") == 0)
15285	mips_abi = N32_ABI;
15286      else if (strcmp (arg, "64") == 0)
15287	{
15288	  mips_abi = N64_ABI;
15289	  if (! support_64bit_objects())
15290	    as_fatal (_("no compiled in support for 64 bit object file "
15291			"format"));
15292	}
15293      else if (strcmp (arg, "eabi") == 0)
15294	mips_abi = EABI_ABI;
15295      else
15296	{
15297	  as_fatal (_("invalid abi -mabi=%s"), arg);
15298	  return 0;
15299	}
15300      break;
15301
15302    case OPTION_M7000_HILO_FIX:
15303      mips_7000_hilo_fix = true;
15304      break;
15305
15306    case OPTION_MNO_7000_HILO_FIX:
15307      mips_7000_hilo_fix = false;
15308      break;
15309
15310    case OPTION_MDEBUG:
15311      mips_flag_mdebug = true;
15312      break;
15313
15314    case OPTION_NO_MDEBUG:
15315      mips_flag_mdebug = false;
15316      break;
15317
15318    case OPTION_PDR:
15319      mips_flag_pdr = true;
15320      break;
15321
15322    case OPTION_NO_PDR:
15323      mips_flag_pdr = false;
15324      break;
15325
15326    case OPTION_MVXWORKS_PIC:
15327      mips_pic = VXWORKS_PIC;
15328      break;
15329
15330    case OPTION_NAN:
15331      if (strcmp (arg, "2008") == 0)
15332	mips_nan2008 = 1;
15333      else if (strcmp (arg, "legacy") == 0)
15334	mips_nan2008 = 0;
15335      else
15336	{
15337	  as_fatal (_("invalid NaN setting -mnan=%s"), arg);
15338	  return 0;
15339	}
15340      break;
15341
15342    default:
15343      return 0;
15344    }
15345
15346    mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
15347
15348  return 1;
15349}
15350
15351/* Set up globals to tune for the ISA or processor described by INFO.  */
15352
15353static void
15354mips_set_tune (const struct mips_cpu_info *info)
15355{
15356  if (info != 0)
15357    mips_tune = info->cpu;
15358}
15359
15360
15361void
15362mips_after_parse_args (void)
15363{
15364  const struct mips_cpu_info *arch_info = 0;
15365  const struct mips_cpu_info *tune_info = 0;
15366
15367  /* GP relative stuff not working for PE.  */
15368  if (startswith (TARGET_OS, "pe"))
15369    {
15370      if (g_switch_seen && g_switch_value != 0)
15371	as_bad (_("-G not supported in this configuration"));
15372      g_switch_value = 0;
15373    }
15374
15375  if (mips_abi == NO_ABI)
15376    mips_abi = MIPS_DEFAULT_ABI;
15377
15378  /* The following code determines the architecture.
15379     Similar code was added to GCC 3.3 (see override_options() in
15380     config/mips/mips.c).  The GAS and GCC code should be kept in sync
15381     as much as possible.  */
15382
15383  if (mips_arch_string != 0)
15384    arch_info = mips_parse_cpu ("-march", mips_arch_string);
15385
15386  if (file_mips_opts.isa != ISA_UNKNOWN)
15387    {
15388      /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
15389	 ISA level specified by -mipsN, while arch_info->isa contains
15390	 the -march selection (if any).  */
15391      if (arch_info != 0)
15392	{
15393	  /* -march takes precedence over -mipsN, since it is more descriptive.
15394	     There's no harm in specifying both as long as the ISA levels
15395	     are the same.  */
15396	  if (file_mips_opts.isa != arch_info->isa)
15397	    as_bad (_("-%s conflicts with the other architecture options,"
15398		      " which imply -%s"),
15399		    mips_cpu_info_from_isa (file_mips_opts.isa)->name,
15400		    mips_cpu_info_from_isa (arch_info->isa)->name);
15401	}
15402      else
15403	arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
15404    }
15405
15406  if (arch_info == 0)
15407    {
15408      arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15409      gas_assert (arch_info);
15410    }
15411
15412  if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15413    as_bad (_("-march=%s is not compatible with the selected ABI"),
15414	    arch_info->name);
15415
15416  file_mips_opts.arch = arch_info->cpu;
15417  file_mips_opts.isa = arch_info->isa;
15418  file_mips_opts.init_ase = arch_info->ase;
15419
15420  /* The EVA Extension has instructions which are only valid when the R6 ISA
15421     is enabled.  This sets the ASE_EVA_R6 flag when both EVA and R6 ISA are
15422     present.  */
15423  if (((file_mips_opts.ase & ASE_EVA) != 0) && ISA_IS_R6 (file_mips_opts.isa))
15424    file_mips_opts.ase |= ASE_EVA_R6;
15425
15426  /* Set up initial mips_opts state.  */
15427  mips_opts = file_mips_opts;
15428
15429  /* For the R5900 default to `-mfix-r5900' unless the user told otherwise.  */
15430  if (!mips_fix_r5900_explicit)
15431    mips_fix_r5900 = file_mips_opts.arch == CPU_R5900;
15432
15433  /* The register size inference code is now placed in
15434     file_mips_check_options.  */
15435
15436  /* Optimize for file_mips_opts.arch, unless -mtune selects a different
15437     processor.  */
15438  if (mips_tune_string != 0)
15439    tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15440
15441  if (tune_info == 0)
15442    mips_set_tune (arch_info);
15443  else
15444    mips_set_tune (tune_info);
15445
15446  if (mips_flag_mdebug < 0)
15447    mips_flag_mdebug = 0;
15448}
15449
15450void
15451mips_init_after_args (void)
15452{
15453  /* Initialize opcodes.  */
15454  bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15455  mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15456}
15457
15458long
15459md_pcrel_from (fixS *fixP)
15460{
15461  valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15462
15463  switch (fixP->fx_r_type)
15464    {
15465    case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15466    case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15467      /* Return the address of the delay slot.  */
15468      return addr + 2;
15469
15470    case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15471    case BFD_RELOC_MICROMIPS_JMP:
15472    case BFD_RELOC_MIPS16_16_PCREL_S1:
15473    case BFD_RELOC_16_PCREL_S2:
15474    case BFD_RELOC_MIPS_21_PCREL_S2:
15475    case BFD_RELOC_MIPS_26_PCREL_S2:
15476    case BFD_RELOC_MIPS_JMP:
15477      /* Return the address of the delay slot.  */
15478      return addr + 4;
15479
15480    case BFD_RELOC_MIPS_18_PCREL_S3:
15481      /* Return the aligned address of the doubleword containing
15482         the instruction.  */
15483      return addr & ~7;
15484
15485    default:
15486      return addr;
15487    }
15488}
15489
15490/* This is called before the symbol table is processed.  In order to
15491   work with gcc when using mips-tfile, we must keep all local labels.
15492   However, in other cases, we want to discard them.  If we were
15493   called with -g, but we didn't see any debugging information, it may
15494   mean that gcc is smuggling debugging information through to
15495   mips-tfile, in which case we must generate all local labels.  */
15496
15497void
15498mips_frob_file_before_adjust (void)
15499{
15500#ifndef NO_ECOFF_DEBUGGING
15501  if (ECOFF_DEBUGGING
15502      && mips_debug != 0
15503      && ! ecoff_debugging_seen)
15504    flag_keep_locals = 1;
15505#endif
15506}
15507
15508/* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15509   the corresponding LO16 reloc.  This is called before md_apply_fix and
15510   tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15511   relocation operators.
15512
15513   For our purposes, a %lo() expression matches a %got() or %hi()
15514   expression if:
15515
15516      (a) it refers to the same symbol; and
15517      (b) the offset applied in the %lo() expression is no lower than
15518	  the offset applied in the %got() or %hi().
15519
15520   (b) allows us to cope with code like:
15521
15522	lui	$4,%hi(foo)
15523	lh	$4,%lo(foo+2)($4)
15524
15525   ...which is legal on RELA targets, and has a well-defined behaviour
15526   if the user knows that adding 2 to "foo" will not induce a carry to
15527   the high 16 bits.
15528
15529   When several %lo()s match a particular %got() or %hi(), we use the
15530   following rules to distinguish them:
15531
15532     (1) %lo()s with smaller offsets are a better match than %lo()s with
15533         higher offsets.
15534
15535     (2) %lo()s with no matching %got() or %hi() are better than those
15536         that already have a matching %got() or %hi().
15537
15538     (3) later %lo()s are better than earlier %lo()s.
15539
15540   These rules are applied in order.
15541
15542   (1) means, among other things, that %lo()s with identical offsets are
15543   chosen if they exist.
15544
15545   (2) means that we won't associate several high-part relocations with
15546   the same low-part relocation unless there's no alternative.  Having
15547   several high parts for the same low part is a GNU extension; this rule
15548   allows careful users to avoid it.
15549
15550   (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15551   with the last high-part relocation being at the front of the list.
15552   It therefore makes sense to choose the last matching low-part
15553   relocation, all other things being equal.  It's also easier
15554   to code that way.  */
15555
15556void
15557mips_frob_file (void)
15558{
15559  struct mips_hi_fixup *l;
15560  bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15561
15562  for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15563    {
15564      segment_info_type *seginfo;
15565      bool matched_lo_p;
15566      fixS **hi_pos, **lo_pos, **pos;
15567
15568      gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15569
15570      /* If a GOT16 relocation turns out to be against a global symbol,
15571	 there isn't supposed to be a matching LO.  Ignore %gots against
15572	 constants; we'll report an error for those later.  */
15573      if (got16_reloc_p (l->fixp->fx_r_type)
15574	  && !(l->fixp->fx_addsy
15575	       && pic_need_relax (l->fixp->fx_addsy)))
15576	continue;
15577
15578      /* Check quickly whether the next fixup happens to be a matching %lo.  */
15579      if (fixup_has_matching_lo_p (l->fixp))
15580	continue;
15581
15582      seginfo = seg_info (l->seg);
15583
15584      /* Set HI_POS to the position of this relocation in the chain.
15585	 Set LO_POS to the position of the chosen low-part relocation.
15586	 MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15587	 relocation that matches an immediately-preceding high-part
15588	 relocation.  */
15589      hi_pos = NULL;
15590      lo_pos = NULL;
15591      matched_lo_p = false;
15592      looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15593
15594      for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15595	{
15596	  if (*pos == l->fixp)
15597	    hi_pos = pos;
15598
15599	  if ((*pos)->fx_r_type == looking_for_rtype
15600	      && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15601	      && (*pos)->fx_offset >= l->fixp->fx_offset
15602	      && (lo_pos == NULL
15603		  || (*pos)->fx_offset < (*lo_pos)->fx_offset
15604		  || (!matched_lo_p
15605		      && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15606	    lo_pos = pos;
15607
15608	  matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15609			  && fixup_has_matching_lo_p (*pos));
15610	}
15611
15612      /* If we found a match, remove the high-part relocation from its
15613	 current position and insert it before the low-part relocation.
15614	 Make the offsets match so that fixup_has_matching_lo_p()
15615	 will return true.
15616
15617	 We don't warn about unmatched high-part relocations since some
15618	 versions of gcc have been known to emit dead "lui ...%hi(...)"
15619	 instructions.  */
15620      if (lo_pos != NULL)
15621	{
15622	  l->fixp->fx_offset = (*lo_pos)->fx_offset;
15623	  if (l->fixp->fx_next != *lo_pos)
15624	    {
15625	      *hi_pos = l->fixp->fx_next;
15626	      l->fixp->fx_next = *lo_pos;
15627	      *lo_pos = l->fixp;
15628	    }
15629	}
15630    }
15631}
15632
15633int
15634mips_force_relocation (fixS *fixp)
15635{
15636  if (generic_force_reloc (fixp))
15637    return 1;
15638
15639  /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15640     so that the linker relaxation can update targets.  */
15641  if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15642      || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15643      || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15644    return 1;
15645
15646  /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15647     and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15648     microMIPS symbols so that we can do cross-mode branch diagnostics
15649     and BAL to JALX conversion by the linker.  */
15650  if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15651       || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15652       || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15653      && fixp->fx_addsy
15654      && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15655    return 1;
15656
15657  /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15658  if (ISA_IS_R6 (file_mips_opts.isa)
15659      && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15660	  || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15661	  || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15662	  || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15663	  || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15664	  || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15665	  || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15666    return 1;
15667
15668  return 0;
15669}
15670
15671/* Implement TC_FORCE_RELOCATION_ABS.  */
15672
15673bool
15674mips_force_relocation_abs (fixS *fixp)
15675{
15676  if (generic_force_reloc (fixp))
15677    return true;
15678
15679  /* These relocations do not have enough bits in the in-place addend
15680     to hold an arbitrary absolute section's offset.  */
15681  if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15682    return true;
15683
15684  return false;
15685}
15686
15687/* Read the instruction associated with RELOC from BUF.  */
15688
15689static unsigned int
15690read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15691{
15692  if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15693    return read_compressed_insn (buf, 4);
15694  else
15695    return read_insn (buf);
15696}
15697
15698/* Write instruction INSN to BUF, given that it has been relocated
15699   by RELOC.  */
15700
15701static void
15702write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15703		  unsigned long insn)
15704{
15705  if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15706    write_compressed_insn (buf, insn, 4);
15707  else
15708    write_insn (buf, insn);
15709}
15710
15711/* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15712   to a symbol in another ISA mode, which cannot be converted to JALX.  */
15713
15714static bool
15715fix_bad_cross_mode_jump_p (fixS *fixP)
15716{
15717  unsigned long opcode;
15718  int other;
15719  char *buf;
15720
15721  if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, true))
15722    return false;
15723
15724  other = S_GET_OTHER (fixP->fx_addsy);
15725  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15726  opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15727  switch (fixP->fx_r_type)
15728    {
15729    case BFD_RELOC_MIPS_JMP:
15730      return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15731    case BFD_RELOC_MICROMIPS_JMP:
15732      return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15733    default:
15734      return false;
15735    }
15736}
15737
15738/* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15739   jump to a symbol in the same ISA mode.  */
15740
15741static bool
15742fix_bad_same_mode_jalx_p (fixS *fixP)
15743{
15744  unsigned long opcode;
15745  int other;
15746  char *buf;
15747
15748  if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, true))
15749    return false;
15750
15751  other = S_GET_OTHER (fixP->fx_addsy);
15752  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15753  opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15754  switch (fixP->fx_r_type)
15755    {
15756    case BFD_RELOC_MIPS_JMP:
15757      return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15758    case BFD_RELOC_MIPS16_JMP:
15759      return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15760    case BFD_RELOC_MICROMIPS_JMP:
15761      return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15762    default:
15763      return false;
15764    }
15765}
15766
15767/* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15768   to a symbol whose value plus addend is not aligned according to the
15769   ultimate (after linker relaxation) jump instruction's immediate field
15770   requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15771   regular MIPS code, to (1 << 2).  */
15772
15773static bool
15774fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15775{
15776  bool micro_to_mips_p;
15777  valueT val;
15778  int other;
15779
15780  if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, true))
15781    return false;
15782
15783  other = S_GET_OTHER (fixP->fx_addsy);
15784  val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15785  val += fixP->fx_offset;
15786  micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15787		     && !ELF_ST_IS_MICROMIPS (other));
15788  return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15789	  != ELF_ST_IS_COMPRESSED (other));
15790}
15791
15792/* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15793   to a symbol whose annotation indicates another ISA mode.  For absolute
15794   symbols check the ISA bit instead.
15795
15796   We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15797   symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15798   MIPS symbols and associated with BAL instructions as these instructions
15799   may be converted to JALX by the linker.  */
15800
15801static bool
15802fix_bad_cross_mode_branch_p (fixS *fixP)
15803{
15804  bool absolute_p;
15805  unsigned long opcode;
15806  asection *symsec;
15807  valueT val;
15808  int other;
15809  char *buf;
15810
15811  if (mips_ignore_branch_isa)
15812    return false;
15813
15814  if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, true))
15815    return false;
15816
15817  symsec = S_GET_SEGMENT (fixP->fx_addsy);
15818  absolute_p = bfd_is_abs_section (symsec);
15819
15820  val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15821  other = S_GET_OTHER (fixP->fx_addsy);
15822
15823  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15824  opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15825  switch (fixP->fx_r_type)
15826    {
15827    case BFD_RELOC_16_PCREL_S2:
15828      return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15829	      && opcode != 0x0411);
15830    case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15831      return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15832	      && opcode != 0x4060);
15833    case BFD_RELOC_MIPS_21_PCREL_S2:
15834    case BFD_RELOC_MIPS_26_PCREL_S2:
15835      return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15836    case BFD_RELOC_MIPS16_16_PCREL_S1:
15837      return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15838    case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15839    case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15840      return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15841    default:
15842      abort ();
15843    }
15844}
15845
15846/* Return TRUE if the symbol plus addend associated with a regular MIPS
15847   branch instruction pointed to by FIXP is not aligned according to the
15848   branch instruction's immediate field requirement.  We need the addend
15849   to preserve the ISA bit and also the sum must not have bit 2 set.  We
15850   must explicitly OR in the ISA bit from symbol annotation as the bit
15851   won't be set in the symbol's value then.  */
15852
15853static bool
15854fix_bad_misaligned_branch_p (fixS *fixP)
15855{
15856  bool absolute_p;
15857  asection *symsec;
15858  valueT isa_bit;
15859  valueT val;
15860  valueT off;
15861  int other;
15862
15863  if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, true))
15864    return false;
15865
15866  symsec = S_GET_SEGMENT (fixP->fx_addsy);
15867  absolute_p = bfd_is_abs_section (symsec);
15868
15869  val = S_GET_VALUE (fixP->fx_addsy);
15870  other = S_GET_OTHER (fixP->fx_addsy);
15871  off = fixP->fx_offset;
15872
15873  isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15874  val |= ELF_ST_IS_COMPRESSED (other);
15875  val += off;
15876  return (val & 0x3) != isa_bit;
15877}
15878
15879/* Calculate the relocation target by masking off ISA mode bit before
15880   combining symbol and addend.  */
15881
15882static valueT
15883fix_bad_misaligned_address (fixS *fixP)
15884{
15885  valueT val;
15886  valueT off;
15887  unsigned isa_mode;
15888  gas_assert (fixP != NULL && fixP->fx_addsy != NULL);
15889  val = S_GET_VALUE (fixP->fx_addsy);
15890  off = fixP->fx_offset;
15891  isa_mode = (ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixP->fx_addsy))
15892	      ? 1 : 0);
15893
15894  return ((val & ~isa_mode) + off);
15895}
15896
15897/* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15898   and its calculated value VAL.  */
15899
15900static void
15901fix_validate_branch (fixS *fixP, valueT val)
15902{
15903  if (fixP->fx_done && (val & 0x3) != 0)
15904    as_bad_where (fixP->fx_file, fixP->fx_line,
15905		  _("branch to misaligned address (0x%lx)"),
15906		  (long) (val + md_pcrel_from (fixP)));
15907  else if (fix_bad_cross_mode_branch_p (fixP))
15908    as_bad_where (fixP->fx_file, fixP->fx_line,
15909		  _("branch to a symbol in another ISA mode"));
15910  else if (fix_bad_misaligned_branch_p (fixP))
15911    as_bad_where (fixP->fx_file, fixP->fx_line,
15912		  _("branch to misaligned address (0x%lx)"),
15913		  (long) fix_bad_misaligned_address (fixP));
15914  else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15915    as_bad_where (fixP->fx_file, fixP->fx_line,
15916		  _("cannot encode misaligned addend "
15917		    "in the relocatable field (0x%lx)"),
15918		  (long) fixP->fx_offset);
15919}
15920
15921/* Apply a fixup to the object file.  */
15922
15923void
15924md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15925{
15926  char *buf;
15927  unsigned long insn;
15928  reloc_howto_type *howto;
15929
15930  if (fixP->fx_pcrel)
15931    switch (fixP->fx_r_type)
15932      {
15933      case BFD_RELOC_16_PCREL_S2:
15934      case BFD_RELOC_MIPS16_16_PCREL_S1:
15935      case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15936      case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15937      case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15938      case BFD_RELOC_32_PCREL:
15939      case BFD_RELOC_MIPS_21_PCREL_S2:
15940      case BFD_RELOC_MIPS_26_PCREL_S2:
15941      case BFD_RELOC_MIPS_18_PCREL_S3:
15942      case BFD_RELOC_MIPS_19_PCREL_S2:
15943      case BFD_RELOC_HI16_S_PCREL:
15944      case BFD_RELOC_LO16_PCREL:
15945	break;
15946
15947      case BFD_RELOC_32:
15948	fixP->fx_r_type = BFD_RELOC_32_PCREL;
15949	break;
15950
15951      default:
15952	as_bad_where (fixP->fx_file, fixP->fx_line,
15953		      _("PC-relative reference to a different section"));
15954	break;
15955      }
15956
15957  /* Handle BFD_RELOC_8 and BFD_RELOC_16.  Punt on other bfd
15958     relocations that have no MIPS ELF equivalent.  */
15959  if (fixP->fx_r_type != BFD_RELOC_8
15960      && fixP->fx_r_type != BFD_RELOC_16)
15961    {
15962      howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15963      if (!howto)
15964	return;
15965    }
15966
15967  gas_assert (fixP->fx_size == 2
15968	      || fixP->fx_size == 4
15969	      || fixP->fx_r_type == BFD_RELOC_8
15970	      || fixP->fx_r_type == BFD_RELOC_64
15971	      || fixP->fx_r_type == BFD_RELOC_CTOR
15972	      || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15973	      || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15974	      || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15975	      || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15976	      || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15977	      || fixP->fx_r_type == BFD_RELOC_NONE);
15978
15979  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15980
15981  /* Don't treat parts of a composite relocation as done.  There are two
15982     reasons for this:
15983
15984     (1) The second and third parts will be against 0 (RSS_UNDEF) but
15985	 should nevertheless be emitted if the first part is.
15986
15987     (2) In normal usage, composite relocations are never assembly-time
15988	 constants.  The easiest way of dealing with the pathological
15989	 exceptions is to generate a relocation against STN_UNDEF and
15990	 leave everything up to the linker.  */
15991  if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15992    fixP->fx_done = 1;
15993
15994  switch (fixP->fx_r_type)
15995    {
15996    case BFD_RELOC_MIPS_TLS_GD:
15997    case BFD_RELOC_MIPS_TLS_LDM:
15998    case BFD_RELOC_MIPS_TLS_DTPREL32:
15999    case BFD_RELOC_MIPS_TLS_DTPREL64:
16000    case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
16001    case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
16002    case BFD_RELOC_MIPS_TLS_GOTTPREL:
16003    case BFD_RELOC_MIPS_TLS_TPREL32:
16004    case BFD_RELOC_MIPS_TLS_TPREL64:
16005    case BFD_RELOC_MIPS_TLS_TPREL_HI16:
16006    case BFD_RELOC_MIPS_TLS_TPREL_LO16:
16007    case BFD_RELOC_MICROMIPS_TLS_GD:
16008    case BFD_RELOC_MICROMIPS_TLS_LDM:
16009    case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
16010    case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
16011    case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
16012    case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
16013    case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
16014    case BFD_RELOC_MIPS16_TLS_GD:
16015    case BFD_RELOC_MIPS16_TLS_LDM:
16016    case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
16017    case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
16018    case BFD_RELOC_MIPS16_TLS_GOTTPREL:
16019    case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
16020    case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
16021      if (fixP->fx_addsy)
16022	S_SET_THREAD_LOCAL (fixP->fx_addsy);
16023      else
16024	as_bad_where (fixP->fx_file, fixP->fx_line,
16025		      _("TLS relocation against a constant"));
16026      break;
16027
16028    case BFD_RELOC_MIPS_JMP:
16029    case BFD_RELOC_MIPS16_JMP:
16030    case BFD_RELOC_MICROMIPS_JMP:
16031      {
16032	int shift;
16033
16034	gas_assert (!fixP->fx_done);
16035
16036	/* Shift is 2, unusually, for microMIPS JALX.  */
16037	if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
16038	    && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
16039	  shift = 1;
16040	else
16041	  shift = 2;
16042
16043	if (fix_bad_cross_mode_jump_p (fixP))
16044	  as_bad_where (fixP->fx_file, fixP->fx_line,
16045			_("jump to a symbol in another ISA mode"));
16046	else if (fix_bad_same_mode_jalx_p (fixP))
16047	  as_bad_where (fixP->fx_file, fixP->fx_line,
16048			_("JALX to a symbol in the same ISA mode"));
16049	else if (fix_bad_misaligned_jump_p (fixP, shift))
16050	  as_bad_where (fixP->fx_file, fixP->fx_line,
16051			_("jump to misaligned address (0x%lx)"),
16052			(long) fix_bad_misaligned_address (fixP));
16053	else if (HAVE_IN_PLACE_ADDENDS
16054		 && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
16055	  as_bad_where (fixP->fx_file, fixP->fx_line,
16056			_("cannot encode misaligned addend "
16057			  "in the relocatable field (0x%lx)"),
16058			(long) fixP->fx_offset);
16059      }
16060      /* Fall through.  */
16061
16062    case BFD_RELOC_MIPS_SHIFT5:
16063    case BFD_RELOC_MIPS_SHIFT6:
16064    case BFD_RELOC_MIPS_GOT_DISP:
16065    case BFD_RELOC_MIPS_GOT_PAGE:
16066    case BFD_RELOC_MIPS_GOT_OFST:
16067    case BFD_RELOC_MIPS_SUB:
16068    case BFD_RELOC_MIPS_INSERT_A:
16069    case BFD_RELOC_MIPS_INSERT_B:
16070    case BFD_RELOC_MIPS_DELETE:
16071    case BFD_RELOC_MIPS_HIGHEST:
16072    case BFD_RELOC_MIPS_HIGHER:
16073    case BFD_RELOC_MIPS_SCN_DISP:
16074    case BFD_RELOC_MIPS_RELGOT:
16075    case BFD_RELOC_MIPS_JALR:
16076    case BFD_RELOC_HI16:
16077    case BFD_RELOC_HI16_S:
16078    case BFD_RELOC_LO16:
16079    case BFD_RELOC_GPREL16:
16080    case BFD_RELOC_MIPS_LITERAL:
16081    case BFD_RELOC_MIPS_CALL16:
16082    case BFD_RELOC_MIPS_GOT16:
16083    case BFD_RELOC_GPREL32:
16084    case BFD_RELOC_MIPS_GOT_HI16:
16085    case BFD_RELOC_MIPS_GOT_LO16:
16086    case BFD_RELOC_MIPS_CALL_HI16:
16087    case BFD_RELOC_MIPS_CALL_LO16:
16088    case BFD_RELOC_HI16_S_PCREL:
16089    case BFD_RELOC_LO16_PCREL:
16090    case BFD_RELOC_MIPS16_GPREL:
16091    case BFD_RELOC_MIPS16_GOT16:
16092    case BFD_RELOC_MIPS16_CALL16:
16093    case BFD_RELOC_MIPS16_HI16:
16094    case BFD_RELOC_MIPS16_HI16_S:
16095    case BFD_RELOC_MIPS16_LO16:
16096    case BFD_RELOC_MICROMIPS_GOT_DISP:
16097    case BFD_RELOC_MICROMIPS_GOT_PAGE:
16098    case BFD_RELOC_MICROMIPS_GOT_OFST:
16099    case BFD_RELOC_MICROMIPS_SUB:
16100    case BFD_RELOC_MICROMIPS_HIGHEST:
16101    case BFD_RELOC_MICROMIPS_HIGHER:
16102    case BFD_RELOC_MICROMIPS_SCN_DISP:
16103    case BFD_RELOC_MICROMIPS_JALR:
16104    case BFD_RELOC_MICROMIPS_HI16:
16105    case BFD_RELOC_MICROMIPS_HI16_S:
16106    case BFD_RELOC_MICROMIPS_LO16:
16107    case BFD_RELOC_MICROMIPS_GPREL16:
16108    case BFD_RELOC_MICROMIPS_LITERAL:
16109    case BFD_RELOC_MICROMIPS_CALL16:
16110    case BFD_RELOC_MICROMIPS_GOT16:
16111    case BFD_RELOC_MICROMIPS_GOT_HI16:
16112    case BFD_RELOC_MICROMIPS_GOT_LO16:
16113    case BFD_RELOC_MICROMIPS_CALL_HI16:
16114    case BFD_RELOC_MICROMIPS_CALL_LO16:
16115    case BFD_RELOC_MIPS_EH:
16116      if (fixP->fx_done)
16117	{
16118	  offsetT value;
16119
16120	  if (calculate_reloc (fixP->fx_r_type, *valP, &value))
16121	    {
16122	      insn = read_reloc_insn (buf, fixP->fx_r_type);
16123	      if (mips16_reloc_p (fixP->fx_r_type))
16124		insn |= mips16_immed_extend (value, 16);
16125	      else
16126		insn |= (value & 0xffff);
16127	      write_reloc_insn (buf, fixP->fx_r_type, insn);
16128	    }
16129	  else
16130	    as_bad_where (fixP->fx_file, fixP->fx_line,
16131			  _("unsupported constant in relocation"));
16132	}
16133      break;
16134
16135    case BFD_RELOC_64:
16136      /* This is handled like BFD_RELOC_32, but we output a sign
16137         extended value if we are only 32 bits.  */
16138      if (fixP->fx_done)
16139	{
16140	  if (8 <= sizeof (valueT))
16141	    md_number_to_chars (buf, *valP, 8);
16142	  else
16143	    {
16144	      valueT hiv;
16145
16146	      if ((*valP & 0x80000000) != 0)
16147		hiv = 0xffffffff;
16148	      else
16149		hiv = 0;
16150	      md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
16151	      md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
16152	    }
16153	}
16154      break;
16155
16156    case BFD_RELOC_RVA:
16157    case BFD_RELOC_32:
16158    case BFD_RELOC_32_PCREL:
16159    case BFD_RELOC_MIPS_16:
16160    case BFD_RELOC_16:
16161    case BFD_RELOC_8:
16162      /* If we are deleting this reloc entry, we must fill in the
16163	 value now.  This can happen if we have a .word which is not
16164	 resolved when it appears but is later defined.  */
16165      if (fixP->fx_done)
16166	md_number_to_chars (buf, *valP, fixP->fx_size);
16167      break;
16168
16169    case BFD_RELOC_MIPS_21_PCREL_S2:
16170      fix_validate_branch (fixP, *valP);
16171      if (!fixP->fx_done)
16172	break;
16173
16174      if (*valP + 0x400000 <= 0x7fffff)
16175	{
16176	  insn = read_insn (buf);
16177	  insn |= (*valP >> 2) & 0x1fffff;
16178	  write_insn (buf, insn);
16179	}
16180      else
16181	as_bad_where (fixP->fx_file, fixP->fx_line,
16182		      _("branch out of range"));
16183      break;
16184
16185    case BFD_RELOC_MIPS_26_PCREL_S2:
16186      fix_validate_branch (fixP, *valP);
16187      if (!fixP->fx_done)
16188	break;
16189
16190      if (*valP + 0x8000000 <= 0xfffffff)
16191	{
16192	  insn = read_insn (buf);
16193	  insn |= (*valP >> 2) & 0x3ffffff;
16194	  write_insn (buf, insn);
16195	}
16196      else
16197	as_bad_where (fixP->fx_file, fixP->fx_line,
16198		      _("branch out of range"));
16199      break;
16200
16201    case BFD_RELOC_MIPS_18_PCREL_S3:
16202      if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
16203	as_bad_where (fixP->fx_file, fixP->fx_line,
16204		      _("PC-relative access using misaligned symbol (%lx)"),
16205		      (long) S_GET_VALUE (fixP->fx_addsy));
16206      if ((fixP->fx_offset & 0x7) != 0)
16207	as_bad_where (fixP->fx_file, fixP->fx_line,
16208		      _("PC-relative access using misaligned offset (%lx)"),
16209		      (long) fixP->fx_offset);
16210      if (!fixP->fx_done)
16211	break;
16212
16213      if (*valP + 0x100000 <= 0x1fffff)
16214	{
16215	  insn = read_insn (buf);
16216	  insn |= (*valP >> 3) & 0x3ffff;
16217	  write_insn (buf, insn);
16218	}
16219      else
16220	as_bad_where (fixP->fx_file, fixP->fx_line,
16221		      _("PC-relative access out of range"));
16222      break;
16223
16224    case BFD_RELOC_MIPS_19_PCREL_S2:
16225      if ((*valP & 0x3) != 0)
16226	as_bad_where (fixP->fx_file, fixP->fx_line,
16227		      _("PC-relative access to misaligned address (%lx)"),
16228		      (long) *valP);
16229      if (!fixP->fx_done)
16230	break;
16231
16232      if (*valP + 0x100000 <= 0x1fffff)
16233	{
16234	  insn = read_insn (buf);
16235	  insn |= (*valP >> 2) & 0x7ffff;
16236	  write_insn (buf, insn);
16237	}
16238      else
16239	as_bad_where (fixP->fx_file, fixP->fx_line,
16240		      _("PC-relative access out of range"));
16241      break;
16242
16243    case BFD_RELOC_16_PCREL_S2:
16244      fix_validate_branch (fixP, *valP);
16245
16246      /* We need to save the bits in the instruction since fixup_segment()
16247	 might be deleting the relocation entry (i.e., a branch within
16248	 the current segment).  */
16249      if (! fixP->fx_done)
16250	break;
16251
16252      /* Update old instruction data.  */
16253      insn = read_insn (buf);
16254
16255      if (*valP + 0x20000 <= 0x3ffff)
16256	{
16257	  insn |= (*valP >> 2) & 0xffff;
16258	  write_insn (buf, insn);
16259	}
16260      else if (fixP->fx_tcbit2
16261	       && fixP->fx_done
16262	       && fixP->fx_frag->fr_address >= text_section->vma
16263	       && (fixP->fx_frag->fr_address
16264		   < text_section->vma + bfd_section_size (text_section))
16265	       && ((insn & 0xffff0000) == 0x10000000	 /* beq $0,$0 */
16266		   || (insn & 0xffff0000) == 0x04010000	 /* bgez $0 */
16267		   || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
16268	{
16269	  /* The branch offset is too large.  If this is an
16270             unconditional branch, and we are not generating PIC code,
16271             we can convert it to an absolute jump instruction.  */
16272	  if ((insn & 0xffff0000) == 0x04110000)	 /* bgezal $0 */
16273	    insn = 0x0c000000;	/* jal */
16274	  else
16275	    insn = 0x08000000;	/* j */
16276	  fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
16277	  fixP->fx_done = 0;
16278	  fixP->fx_addsy = section_symbol (text_section);
16279	  *valP += md_pcrel_from (fixP);
16280	  write_insn (buf, insn);
16281	}
16282      else
16283	{
16284	  /* If we got here, we have branch-relaxation disabled,
16285	     and there's nothing we can do to fix this instruction
16286	     without turning it into a longer sequence.  */
16287	  as_bad_where (fixP->fx_file, fixP->fx_line,
16288			_("branch out of range"));
16289	}
16290      break;
16291
16292    case BFD_RELOC_MIPS16_16_PCREL_S1:
16293    case BFD_RELOC_MICROMIPS_7_PCREL_S1:
16294    case BFD_RELOC_MICROMIPS_10_PCREL_S1:
16295    case BFD_RELOC_MICROMIPS_16_PCREL_S1:
16296      gas_assert (!fixP->fx_done);
16297      if (fix_bad_cross_mode_branch_p (fixP))
16298	as_bad_where (fixP->fx_file, fixP->fx_line,
16299		      _("branch to a symbol in another ISA mode"));
16300      else if (fixP->fx_addsy
16301	       && !S_FORCE_RELOC (fixP->fx_addsy, true)
16302	       && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
16303	       && (fixP->fx_offset & 0x1) != 0)
16304	as_bad_where (fixP->fx_file, fixP->fx_line,
16305		      _("branch to misaligned address (0x%lx)"),
16306		      (long) fix_bad_misaligned_address (fixP));
16307      else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
16308	as_bad_where (fixP->fx_file, fixP->fx_line,
16309		      _("cannot encode misaligned addend "
16310			"in the relocatable field (0x%lx)"),
16311		      (long) fixP->fx_offset);
16312      break;
16313
16314    case BFD_RELOC_VTABLE_INHERIT:
16315      fixP->fx_done = 0;
16316      if (fixP->fx_addsy
16317          && !S_IS_DEFINED (fixP->fx_addsy)
16318          && !S_IS_WEAK (fixP->fx_addsy))
16319        S_SET_WEAK (fixP->fx_addsy);
16320      break;
16321
16322    case BFD_RELOC_NONE:
16323    case BFD_RELOC_VTABLE_ENTRY:
16324      fixP->fx_done = 0;
16325      break;
16326
16327    default:
16328      abort ();
16329    }
16330
16331  /* Remember value for tc_gen_reloc.  */
16332  fixP->fx_addnumber = *valP;
16333}
16334
16335static symbolS *
16336get_symbol (void)
16337{
16338  int c;
16339  char *name;
16340  symbolS *p;
16341
16342  c = get_symbol_name (&name);
16343  p = (symbolS *) symbol_find_or_make (name);
16344  (void) restore_line_pointer (c);
16345  return p;
16346}
16347
16348/* Align the current frag to a given power of two.  If a particular
16349   fill byte should be used, FILL points to an integer that contains
16350   that byte, otherwise FILL is null.
16351
16352   This function used to have the comment:
16353
16354      The MIPS assembler also automatically adjusts any preceding label.
16355
16356   The implementation therefore applied the adjustment to a maximum of
16357   one label.  However, other label adjustments are applied to batches
16358   of labels, and adjusting just one caused problems when new labels
16359   were added for the sake of debugging or unwind information.
16360   We therefore adjust all preceding labels (given as LABELS) instead.  */
16361
16362static void
16363mips_align (int to, int *fill, struct insn_label_list *labels)
16364{
16365  mips_emit_delays ();
16366  mips_record_compressed_mode ();
16367  if (fill == NULL && subseg_text_p (now_seg))
16368    frag_align_code (to, 0);
16369  else
16370    frag_align (to, fill ? *fill : 0, 0);
16371  record_alignment (now_seg, to);
16372  mips_move_labels (labels, subseg_text_p (now_seg));
16373}
16374
16375/* Align to a given power of two.  .align 0 turns off the automatic
16376   alignment used by the data creating pseudo-ops.  */
16377
16378static void
16379s_align (int x ATTRIBUTE_UNUSED)
16380{
16381  int temp, fill_value, *fill_ptr;
16382  long max_alignment = 28;
16383
16384  /* o Note that the assembler pulls down any immediately preceding label
16385       to the aligned address.
16386     o It's not documented but auto alignment is reinstated by
16387       a .align pseudo instruction.
16388     o Note also that after auto alignment is turned off the mips assembler
16389       issues an error on attempt to assemble an improperly aligned data item.
16390       We don't.  */
16391
16392  temp = get_absolute_expression ();
16393  if (temp > max_alignment)
16394    as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
16395  else if (temp < 0)
16396    {
16397      as_warn (_("alignment negative, 0 assumed"));
16398      temp = 0;
16399    }
16400  if (*input_line_pointer == ',')
16401    {
16402      ++input_line_pointer;
16403      fill_value = get_absolute_expression ();
16404      fill_ptr = &fill_value;
16405    }
16406  else
16407    fill_ptr = 0;
16408  if (temp)
16409    {
16410      segment_info_type *si = seg_info (now_seg);
16411      struct insn_label_list *l = si->label_list;
16412      /* Auto alignment should be switched on by next section change.  */
16413      auto_align = 1;
16414      mips_align (temp, fill_ptr, l);
16415    }
16416  else
16417    {
16418      auto_align = 0;
16419    }
16420
16421  demand_empty_rest_of_line ();
16422}
16423
16424static void
16425s_change_sec (int sec)
16426{
16427  segT seg;
16428
16429  /* The ELF backend needs to know that we are changing sections, so
16430     that .previous works correctly.  We could do something like check
16431     for an obj_section_change_hook macro, but that might be confusing
16432     as it would not be appropriate to use it in the section changing
16433     functions in read.c, since obj-elf.c intercepts those.  FIXME:
16434     This should be cleaner, somehow.  */
16435  obj_elf_section_change_hook ();
16436
16437  mips_emit_delays ();
16438
16439  switch (sec)
16440    {
16441    case 't':
16442      s_text (0);
16443      break;
16444    case 'd':
16445      s_data (0);
16446      break;
16447    case 'b':
16448      subseg_set (bss_section, (subsegT) get_absolute_expression ());
16449      demand_empty_rest_of_line ();
16450      break;
16451
16452    case 'r':
16453      seg = subseg_new (RDATA_SECTION_NAME,
16454			(subsegT) get_absolute_expression ());
16455      bfd_set_section_flags (seg, (SEC_ALLOC | SEC_LOAD | SEC_READONLY
16456				   | SEC_RELOC | SEC_DATA));
16457      if (!startswith (TARGET_OS, "elf"))
16458	record_alignment (seg, 4);
16459      demand_empty_rest_of_line ();
16460      break;
16461
16462    case 's':
16463      seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
16464      bfd_set_section_flags (seg, (SEC_ALLOC | SEC_LOAD | SEC_RELOC
16465				   | SEC_DATA | SEC_SMALL_DATA));
16466      if (!startswith (TARGET_OS, "elf"))
16467	record_alignment (seg, 4);
16468      demand_empty_rest_of_line ();
16469      break;
16470
16471    case 'B':
16472      seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
16473      bfd_set_section_flags (seg, SEC_ALLOC | SEC_SMALL_DATA);
16474      if (!startswith (TARGET_OS, "elf"))
16475	record_alignment (seg, 4);
16476      demand_empty_rest_of_line ();
16477      break;
16478    }
16479
16480  auto_align = 1;
16481}
16482
16483void
16484s_change_section (int ignore ATTRIBUTE_UNUSED)
16485{
16486  char *saved_ilp;
16487  const char *section_name;
16488  char c, next_c = 0;
16489  int section_type;
16490  int section_flag;
16491  int section_entry_size;
16492  int section_alignment;
16493
16494  saved_ilp = input_line_pointer;
16495  section_name = obj_elf_section_name ();
16496  if (section_name == NULL)
16497    return;
16498  c = input_line_pointer[0];
16499  if (c)
16500    next_c = input_line_pointer[1];
16501
16502  /* Do we have .section Name<,"flags">?  */
16503  if (c != ',' || (c == ',' && next_c == '"'))
16504    {
16505      input_line_pointer = saved_ilp;
16506      obj_elf_section (ignore);
16507      return;
16508    }
16509
16510  input_line_pointer++;
16511
16512  /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16513  if (c == ',')
16514    section_type = get_absolute_expression ();
16515  else
16516    section_type = 0;
16517
16518  if (*input_line_pointer++ == ',')
16519    section_flag = get_absolute_expression ();
16520  else
16521    section_flag = 0;
16522
16523  if (*input_line_pointer++ == ',')
16524    section_entry_size = get_absolute_expression ();
16525  else
16526    section_entry_size = 0;
16527
16528  if (*input_line_pointer++ == ',')
16529    section_alignment = get_absolute_expression ();
16530  else
16531    section_alignment = 0;
16532
16533  /* FIXME: really ignore?  */
16534  (void) section_alignment;
16535
16536  /* When using the generic form of .section (as implemented by obj-elf.c),
16537     there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16538     traditionally had to fall back on the more common @progbits instead.
16539
16540     There's nothing really harmful in this, since bfd will correct
16541     SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16542     means that, for backwards compatibility, the special_section entries
16543     for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16544
16545     Even so, we shouldn't force users of the MIPS .section syntax to
16546     incorrectly label the sections as SHT_PROGBITS.  The best compromise
16547     seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16548     generic type-checking code.  */
16549  if (section_type == SHT_MIPS_DWARF)
16550    section_type = SHT_PROGBITS;
16551
16552  obj_elf_change_section (section_name, section_type, section_flag,
16553			  section_entry_size, 0, 0, 0);
16554}
16555
16556void
16557mips_enable_auto_align (void)
16558{
16559  auto_align = 1;
16560}
16561
16562static void
16563s_cons (int log_size)
16564{
16565  segment_info_type *si = seg_info (now_seg);
16566  struct insn_label_list *l = si->label_list;
16567
16568  mips_emit_delays ();
16569  if (log_size > 0 && auto_align)
16570    mips_align (log_size, 0, l);
16571  cons (1 << log_size);
16572  mips_clear_insn_labels ();
16573}
16574
16575static void
16576s_float_cons (int type)
16577{
16578  segment_info_type *si = seg_info (now_seg);
16579  struct insn_label_list *l = si->label_list;
16580
16581  mips_emit_delays ();
16582
16583  if (auto_align)
16584    {
16585      if (type == 'd')
16586	mips_align (3, 0, l);
16587      else
16588	mips_align (2, 0, l);
16589    }
16590
16591  float_cons (type);
16592  mips_clear_insn_labels ();
16593}
16594
16595/* Handle .globl.  We need to override it because on Irix 5 you are
16596   permitted to say
16597       .globl foo .text
16598   where foo is an undefined symbol, to mean that foo should be
16599   considered to be the address of a function.  */
16600
16601static void
16602s_mips_globl (int x ATTRIBUTE_UNUSED)
16603{
16604  char *name;
16605  int c;
16606  symbolS *symbolP;
16607
16608  do
16609    {
16610      c = get_symbol_name (&name);
16611      symbolP = symbol_find_or_make (name);
16612      S_SET_EXTERNAL (symbolP);
16613
16614      *input_line_pointer = c;
16615      SKIP_WHITESPACE_AFTER_NAME ();
16616
16617      if (!is_end_of_line[(unsigned char) *input_line_pointer]
16618	  && (*input_line_pointer != ','))
16619	{
16620	  char *secname;
16621	  asection *sec;
16622
16623	  c = get_symbol_name (&secname);
16624	  sec = bfd_get_section_by_name (stdoutput, secname);
16625	  if (sec == NULL)
16626	    as_bad (_("%s: no such section"), secname);
16627	  (void) restore_line_pointer (c);
16628
16629	  if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16630	    symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
16631	}
16632
16633      c = *input_line_pointer;
16634      if (c == ',')
16635	{
16636	  input_line_pointer++;
16637	  SKIP_WHITESPACE ();
16638	  if (is_end_of_line[(unsigned char) *input_line_pointer])
16639	    c = '\n';
16640	}
16641    }
16642  while (c == ',');
16643
16644  demand_empty_rest_of_line ();
16645}
16646
16647#ifdef TE_IRIX
16648/* The Irix 5 and 6 assemblers set the type of any common symbol and
16649   any undefined non-function symbol to STT_OBJECT.  We try to be
16650   compatible, since newer Irix 5 and 6 linkers care.  */
16651
16652void
16653mips_frob_symbol (symbolS *symp ATTRIBUTE_UNUSED)
16654{
16655  /* This late in assembly we can set BSF_OBJECT indiscriminately
16656     and let elf.c:swap_out_syms sort out the symbol type.  */
16657  flagword *flags = &symbol_get_bfdsym (symp)->flags;
16658  if ((*flags & (BSF_GLOBAL | BSF_WEAK)) != 0
16659      || !S_IS_DEFINED (symp))
16660    *flags |= BSF_OBJECT;
16661}
16662#endif
16663
16664static void
16665s_option (int x ATTRIBUTE_UNUSED)
16666{
16667  char *opt;
16668  char c;
16669
16670  c = get_symbol_name (&opt);
16671
16672  if (*opt == 'O')
16673    {
16674      /* FIXME: What does this mean?  */
16675    }
16676  else if (startswith (opt, "pic") && ISDIGIT (opt[3]) && opt[4] == '\0')
16677    {
16678      int i;
16679
16680      i = atoi (opt + 3);
16681      if (i != 0 && i != 2)
16682	as_bad (_(".option pic%d not supported"), i);
16683      else if (mips_pic == VXWORKS_PIC)
16684	as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16685      else if (i == 0)
16686	mips_pic = NO_PIC;
16687      else if (i == 2)
16688	{
16689	  mips_pic = SVR4_PIC;
16690	  mips_abicalls = true;
16691	}
16692
16693      if (mips_pic == SVR4_PIC)
16694	{
16695	  if (g_switch_seen && g_switch_value != 0)
16696	    as_warn (_("-G may not be used with SVR4 PIC code"));
16697	  g_switch_value = 0;
16698	  bfd_set_gp_size (stdoutput, 0);
16699	}
16700    }
16701  else
16702    as_warn (_("unrecognized option \"%s\""), opt);
16703
16704  (void) restore_line_pointer (c);
16705  demand_empty_rest_of_line ();
16706}
16707
16708/* This structure is used to hold a stack of .set values.  */
16709
16710struct mips_option_stack
16711{
16712  struct mips_option_stack *next;
16713  struct mips_set_options options;
16714};
16715
16716static struct mips_option_stack *mips_opts_stack;
16717
16718/* Return status for .set/.module option handling.  */
16719
16720enum code_option_type
16721{
16722  /* Unrecognized option.  */
16723  OPTION_TYPE_BAD = -1,
16724
16725  /* Ordinary option.  */
16726  OPTION_TYPE_NORMAL,
16727
16728  /* ISA changing option.  */
16729  OPTION_TYPE_ISA
16730};
16731
16732/* Handle common .set/.module options.  Return status indicating option
16733   type.  */
16734
16735static enum code_option_type
16736parse_code_option (char * name)
16737{
16738  bool isa_set = false;
16739  const struct mips_ase *ase;
16740
16741  if (startswith (name, "at="))
16742    {
16743      char *s = name + 3;
16744
16745      if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16746	as_bad (_("unrecognized register name `%s'"), s);
16747    }
16748  else if (strcmp (name, "at") == 0)
16749    mips_opts.at = ATREG;
16750  else if (strcmp (name, "noat") == 0)
16751    mips_opts.at = ZERO;
16752  else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16753    mips_opts.nomove = 0;
16754  else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16755    mips_opts.nomove = 1;
16756  else if (strcmp (name, "bopt") == 0)
16757    mips_opts.nobopt = 0;
16758  else if (strcmp (name, "nobopt") == 0)
16759    mips_opts.nobopt = 1;
16760  else if (strcmp (name, "gp=32") == 0)
16761    mips_opts.gp = 32;
16762  else if (strcmp (name, "gp=64") == 0)
16763    mips_opts.gp = 64;
16764  else if (strcmp (name, "fp=32") == 0)
16765    mips_opts.fp = 32;
16766  else if (strcmp (name, "fp=xx") == 0)
16767    mips_opts.fp = 0;
16768  else if (strcmp (name, "fp=64") == 0)
16769    mips_opts.fp = 64;
16770  else if (strcmp (name, "softfloat") == 0)
16771    mips_opts.soft_float = 1;
16772  else if (strcmp (name, "hardfloat") == 0)
16773    mips_opts.soft_float = 0;
16774  else if (strcmp (name, "singlefloat") == 0)
16775    mips_opts.single_float = 1;
16776  else if (strcmp (name, "doublefloat") == 0)
16777    mips_opts.single_float = 0;
16778  else if (strcmp (name, "nooddspreg") == 0)
16779    mips_opts.oddspreg = 0;
16780  else if (strcmp (name, "oddspreg") == 0)
16781    mips_opts.oddspreg = 1;
16782  else if (strcmp (name, "mips16") == 0
16783	   || strcmp (name, "MIPS-16") == 0)
16784    mips_opts.mips16 = 1;
16785  else if (strcmp (name, "nomips16") == 0
16786	   || strcmp (name, "noMIPS-16") == 0)
16787    mips_opts.mips16 = 0;
16788  else if (strcmp (name, "micromips") == 0)
16789    mips_opts.micromips = 1;
16790  else if (strcmp (name, "nomicromips") == 0)
16791    mips_opts.micromips = 0;
16792  else if (name[0] == 'n'
16793	   && name[1] == 'o'
16794	   && (ase = mips_lookup_ase (name + 2)))
16795    mips_set_ase (ase, &mips_opts, false);
16796  else if ((ase = mips_lookup_ase (name)))
16797    mips_set_ase (ase, &mips_opts, true);
16798  else if (startswith (name, "mips") || startswith (name, "arch="))
16799    {
16800      /* Permit the user to change the ISA and architecture on the fly.
16801	 Needless to say, misuse can cause serious problems.  */
16802      if (startswith (name, "arch="))
16803	{
16804	  const struct mips_cpu_info *p;
16805
16806	  p = mips_parse_cpu ("internal use", name + 5);
16807	  if (!p)
16808	    as_bad (_("unknown architecture %s"), name + 5);
16809	  else
16810	    {
16811	      mips_opts.arch = p->cpu;
16812	      mips_opts.isa = p->isa;
16813	      isa_set = true;
16814	      mips_opts.init_ase = p->ase;
16815	    }
16816	}
16817      else if (startswith (name, "mips"))
16818	{
16819	  const struct mips_cpu_info *p;
16820
16821	  p = mips_parse_cpu ("internal use", name);
16822	  if (!p)
16823	    as_bad (_("unknown ISA level %s"), name + 4);
16824	  else
16825	    {
16826	      mips_opts.arch = p->cpu;
16827	      mips_opts.isa = p->isa;
16828	      isa_set = true;
16829	      mips_opts.init_ase = p->ase;
16830	    }
16831	}
16832      else
16833	as_bad (_("unknown ISA or architecture %s"), name);
16834    }
16835  else if (strcmp (name, "autoextend") == 0)
16836    mips_opts.noautoextend = 0;
16837  else if (strcmp (name, "noautoextend") == 0)
16838    mips_opts.noautoextend = 1;
16839  else if (strcmp (name, "insn32") == 0)
16840    mips_opts.insn32 = true;
16841  else if (strcmp (name, "noinsn32") == 0)
16842    mips_opts.insn32 = false;
16843  else if (strcmp (name, "sym32") == 0)
16844    mips_opts.sym32 = true;
16845  else if (strcmp (name, "nosym32") == 0)
16846    mips_opts.sym32 = false;
16847  else
16848    return OPTION_TYPE_BAD;
16849
16850  return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16851}
16852
16853/* Handle the .set pseudo-op.  */
16854
16855static void
16856s_mipsset (int x ATTRIBUTE_UNUSED)
16857{
16858  enum code_option_type type = OPTION_TYPE_NORMAL;
16859  char *name = input_line_pointer, ch;
16860
16861  file_mips_check_options ();
16862
16863  while (!is_end_of_line[(unsigned char) *input_line_pointer])
16864    ++input_line_pointer;
16865  ch = *input_line_pointer;
16866  *input_line_pointer = '\0';
16867
16868  if (strchr (name, ','))
16869    {
16870      /* Generic ".set" directive; use the generic handler.  */
16871      *input_line_pointer = ch;
16872      input_line_pointer = name;
16873      s_set (0);
16874      return;
16875    }
16876
16877  if (strcmp (name, "reorder") == 0)
16878    {
16879      if (mips_opts.noreorder)
16880	end_noreorder ();
16881    }
16882  else if (strcmp (name, "noreorder") == 0)
16883    {
16884      if (!mips_opts.noreorder)
16885	start_noreorder ();
16886    }
16887  else if (strcmp (name, "macro") == 0)
16888    mips_opts.warn_about_macros = 0;
16889  else if (strcmp (name, "nomacro") == 0)
16890    {
16891      if (mips_opts.noreorder == 0)
16892	as_bad (_("`noreorder' must be set before `nomacro'"));
16893      mips_opts.warn_about_macros = 1;
16894    }
16895  else if (strcmp (name, "gp=default") == 0)
16896    mips_opts.gp = file_mips_opts.gp;
16897  else if (strcmp (name, "fp=default") == 0)
16898    mips_opts.fp = file_mips_opts.fp;
16899  else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16900    {
16901      mips_opts.isa = file_mips_opts.isa;
16902      mips_opts.arch = file_mips_opts.arch;
16903      mips_opts.init_ase = file_mips_opts.init_ase;
16904      mips_opts.gp = file_mips_opts.gp;
16905      mips_opts.fp = file_mips_opts.fp;
16906    }
16907  else if (strcmp (name, "push") == 0)
16908    {
16909      struct mips_option_stack *s;
16910
16911      s = XNEW (struct mips_option_stack);
16912      s->next = mips_opts_stack;
16913      s->options = mips_opts;
16914      mips_opts_stack = s;
16915    }
16916  else if (strcmp (name, "pop") == 0)
16917    {
16918      struct mips_option_stack *s;
16919
16920      s = mips_opts_stack;
16921      if (s == NULL)
16922	as_bad (_(".set pop with no .set push"));
16923      else
16924	{
16925	  /* If we're changing the reorder mode we need to handle
16926             delay slots correctly.  */
16927	  if (s->options.noreorder && ! mips_opts.noreorder)
16928	    start_noreorder ();
16929	  else if (! s->options.noreorder && mips_opts.noreorder)
16930	    end_noreorder ();
16931
16932	  mips_opts = s->options;
16933	  mips_opts_stack = s->next;
16934	  free (s);
16935	}
16936    }
16937  else
16938    {
16939      type = parse_code_option (name);
16940      if (type == OPTION_TYPE_BAD)
16941	as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16942    }
16943
16944  /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16945     registers based on what is supported by the arch/cpu.  */
16946  if (type == OPTION_TYPE_ISA)
16947    {
16948      switch (mips_opts.isa)
16949	{
16950	case 0:
16951	  break;
16952	case ISA_MIPS1:
16953	  /* MIPS I cannot support FPXX.  */
16954	  mips_opts.fp = 32;
16955	  /* fall-through.  */
16956	case ISA_MIPS2:
16957	case ISA_MIPS32:
16958	case ISA_MIPS32R2:
16959	case ISA_MIPS32R3:
16960	case ISA_MIPS32R5:
16961	  mips_opts.gp = 32;
16962	  if (mips_opts.fp != 0)
16963	    mips_opts.fp = 32;
16964	  break;
16965	case ISA_MIPS32R6:
16966	  mips_opts.gp = 32;
16967	  mips_opts.fp = 64;
16968	  break;
16969	case ISA_MIPS3:
16970	case ISA_MIPS4:
16971	case ISA_MIPS5:
16972	case ISA_MIPS64:
16973	case ISA_MIPS64R2:
16974	case ISA_MIPS64R3:
16975	case ISA_MIPS64R5:
16976	case ISA_MIPS64R6:
16977	  mips_opts.gp = 64;
16978	  if (mips_opts.fp != 0)
16979	    {
16980	      if (mips_opts.arch == CPU_R5900)
16981		mips_opts.fp = 32;
16982	      else
16983		mips_opts.fp = 64;
16984	    }
16985	  break;
16986	default:
16987	  as_bad (_("unknown ISA level %s"), name + 4);
16988	  break;
16989	}
16990    }
16991
16992  mips_check_options (&mips_opts, false);
16993
16994  mips_check_isa_supports_ases ();
16995  *input_line_pointer = ch;
16996  demand_empty_rest_of_line ();
16997}
16998
16999/* Handle the .module pseudo-op.  */
17000
17001static void
17002s_module (int ignore ATTRIBUTE_UNUSED)
17003{
17004  char *name = input_line_pointer, ch;
17005
17006  while (!is_end_of_line[(unsigned char) *input_line_pointer])
17007    ++input_line_pointer;
17008  ch = *input_line_pointer;
17009  *input_line_pointer = '\0';
17010
17011  if (!file_mips_opts_checked)
17012    {
17013      if (parse_code_option (name) == OPTION_TYPE_BAD)
17014	as_bad (_(".module used with unrecognized symbol: %s\n"), name);
17015
17016      /* Update module level settings from mips_opts.  */
17017      file_mips_opts = mips_opts;
17018    }
17019  else
17020    as_bad (_(".module is not permitted after generating code"));
17021
17022  *input_line_pointer = ch;
17023  demand_empty_rest_of_line ();
17024}
17025
17026/* Handle the .abicalls pseudo-op.  I believe this is equivalent to
17027   .option pic2.  It means to generate SVR4 PIC calls.  */
17028
17029static void
17030s_abicalls (int ignore ATTRIBUTE_UNUSED)
17031{
17032  mips_pic = SVR4_PIC;
17033  mips_abicalls = true;
17034
17035  if (g_switch_seen && g_switch_value != 0)
17036    as_warn (_("-G may not be used with SVR4 PIC code"));
17037  g_switch_value = 0;
17038
17039  bfd_set_gp_size (stdoutput, 0);
17040  demand_empty_rest_of_line ();
17041}
17042
17043/* Handle the .cpload pseudo-op.  This is used when generating SVR4
17044   PIC code.  It sets the $gp register for the function based on the
17045   function address, which is in the register named in the argument.
17046   This uses a relocation against _gp_disp, which is handled specially
17047   by the linker.  The result is:
17048	lui	$gp,%hi(_gp_disp)
17049	addiu	$gp,$gp,%lo(_gp_disp)
17050	addu	$gp,$gp,.cpload argument
17051   The .cpload argument is normally $25 == $t9.
17052
17053   The -mno-shared option changes this to:
17054	lui	$gp,%hi(__gnu_local_gp)
17055	addiu	$gp,$gp,%lo(__gnu_local_gp)
17056   and the argument is ignored.  This saves an instruction, but the
17057   resulting code is not position independent; it uses an absolute
17058   address for __gnu_local_gp.  Thus code assembled with -mno-shared
17059   can go into an ordinary executable, but not into a shared library.  */
17060
17061static void
17062s_cpload (int ignore ATTRIBUTE_UNUSED)
17063{
17064  expressionS ex;
17065  int reg;
17066  int in_shared;
17067
17068  file_mips_check_options ();
17069
17070  /* If we are not generating SVR4 PIC code, or if this is NewABI code,
17071     .cpload is ignored.  */
17072  if (mips_pic != SVR4_PIC || HAVE_NEWABI)
17073    {
17074      s_ignore (0);
17075      return;
17076    }
17077
17078  if (mips_opts.mips16)
17079    {
17080      as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
17081      ignore_rest_of_line ();
17082      return;
17083    }
17084
17085  /* .cpload should be in a .set noreorder section.  */
17086  if (mips_opts.noreorder == 0)
17087    as_warn (_(".cpload not in noreorder section"));
17088
17089  reg = tc_get_register (0);
17090
17091  /* If we need to produce a 64-bit address, we are better off using
17092     the default instruction sequence.  */
17093  in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
17094
17095  ex.X_op = O_symbol;
17096  ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
17097                                         "__gnu_local_gp");
17098  ex.X_op_symbol = NULL;
17099  ex.X_add_number = 0;
17100
17101  /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
17102  symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
17103
17104  mips_mark_labels ();
17105  mips_assembling_insn = true;
17106
17107  macro_start ();
17108  macro_build_lui (&ex, mips_gp_register);
17109  macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
17110	       mips_gp_register, BFD_RELOC_LO16);
17111  if (in_shared)
17112    macro_build (NULL, "addu", "d,v,t", mips_gp_register,
17113		 mips_gp_register, reg);
17114  macro_end ();
17115
17116  mips_assembling_insn = false;
17117  demand_empty_rest_of_line ();
17118}
17119
17120/* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
17121     .cpsetup $reg1, offset|$reg2, label
17122
17123   If offset is given, this results in:
17124     sd		$gp, offset($sp)
17125     lui	$gp, %hi(%neg(%gp_rel(label)))
17126     addiu	$gp, $gp, %lo(%neg(%gp_rel(label)))
17127     daddu	$gp, $gp, $reg1
17128
17129   If $reg2 is given, this results in:
17130     or		$reg2, $gp, $0
17131     lui	$gp, %hi(%neg(%gp_rel(label)))
17132     addiu	$gp, $gp, %lo(%neg(%gp_rel(label)))
17133     daddu	$gp, $gp, $reg1
17134   $reg1 is normally $25 == $t9.
17135
17136   The -mno-shared option replaces the last three instructions with
17137	lui	$gp,%hi(_gp)
17138	addiu	$gp,$gp,%lo(_gp)  */
17139
17140static void
17141s_cpsetup (int ignore ATTRIBUTE_UNUSED)
17142{
17143  expressionS ex_off;
17144  expressionS ex_sym;
17145  int reg1;
17146
17147  file_mips_check_options ();
17148
17149  /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
17150     We also need NewABI support.  */
17151  if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17152    {
17153      s_ignore (0);
17154      return;
17155    }
17156
17157  if (mips_opts.mips16)
17158    {
17159      as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
17160      ignore_rest_of_line ();
17161      return;
17162    }
17163
17164  reg1 = tc_get_register (0);
17165  SKIP_WHITESPACE ();
17166  if (*input_line_pointer != ',')
17167    {
17168      as_bad (_("missing argument separator ',' for .cpsetup"));
17169      return;
17170    }
17171  else
17172    ++input_line_pointer;
17173  SKIP_WHITESPACE ();
17174  if (*input_line_pointer == '$')
17175    {
17176      mips_cpreturn_register = tc_get_register (0);
17177      mips_cpreturn_offset = -1;
17178    }
17179  else
17180    {
17181      mips_cpreturn_offset = get_absolute_expression ();
17182      mips_cpreturn_register = -1;
17183    }
17184  SKIP_WHITESPACE ();
17185  if (*input_line_pointer != ',')
17186    {
17187      as_bad (_("missing argument separator ',' for .cpsetup"));
17188      return;
17189    }
17190  else
17191    ++input_line_pointer;
17192  SKIP_WHITESPACE ();
17193  expression (&ex_sym);
17194
17195  mips_mark_labels ();
17196  mips_assembling_insn = true;
17197
17198  macro_start ();
17199  if (mips_cpreturn_register == -1)
17200    {
17201      ex_off.X_op = O_constant;
17202      ex_off.X_add_symbol = NULL;
17203      ex_off.X_op_symbol = NULL;
17204      ex_off.X_add_number = mips_cpreturn_offset;
17205
17206      macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
17207		   BFD_RELOC_LO16, SP);
17208    }
17209  else
17210    move_register (mips_cpreturn_register, mips_gp_register);
17211
17212  if (mips_in_shared || HAVE_64BIT_SYMBOLS)
17213    {
17214      macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
17215		   -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
17216		   BFD_RELOC_HI16_S);
17217
17218      macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
17219		   mips_gp_register, -1, BFD_RELOC_GPREL16,
17220		   BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
17221
17222      macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
17223		   mips_gp_register, reg1);
17224    }
17225  else
17226    {
17227      expressionS ex;
17228
17229      ex.X_op = O_symbol;
17230      ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
17231      ex.X_op_symbol = NULL;
17232      ex.X_add_number = 0;
17233
17234      /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
17235      symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
17236
17237      macro_build_lui (&ex, mips_gp_register);
17238      macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
17239		   mips_gp_register, BFD_RELOC_LO16);
17240    }
17241
17242  macro_end ();
17243
17244  mips_assembling_insn = false;
17245  demand_empty_rest_of_line ();
17246}
17247
17248static void
17249s_cplocal (int ignore ATTRIBUTE_UNUSED)
17250{
17251  file_mips_check_options ();
17252
17253  /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
17254     .cplocal is ignored.  */
17255  if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17256    {
17257      s_ignore (0);
17258      return;
17259    }
17260
17261  if (mips_opts.mips16)
17262    {
17263      as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
17264      ignore_rest_of_line ();
17265      return;
17266    }
17267
17268  mips_gp_register = tc_get_register (0);
17269  demand_empty_rest_of_line ();
17270}
17271
17272/* Handle the .cprestore pseudo-op.  This stores $gp into a given
17273   offset from $sp.  The offset is remembered, and after making a PIC
17274   call $gp is restored from that location.  */
17275
17276static void
17277s_cprestore (int ignore ATTRIBUTE_UNUSED)
17278{
17279  expressionS ex;
17280
17281  file_mips_check_options ();
17282
17283  /* If we are not generating SVR4 PIC code, or if this is NewABI code,
17284     .cprestore is ignored.  */
17285  if (mips_pic != SVR4_PIC || HAVE_NEWABI)
17286    {
17287      s_ignore (0);
17288      return;
17289    }
17290
17291  if (mips_opts.mips16)
17292    {
17293      as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
17294      ignore_rest_of_line ();
17295      return;
17296    }
17297
17298  mips_cprestore_offset = get_absolute_expression ();
17299  mips_cprestore_valid = 1;
17300
17301  ex.X_op = O_constant;
17302  ex.X_add_symbol = NULL;
17303  ex.X_op_symbol = NULL;
17304  ex.X_add_number = mips_cprestore_offset;
17305
17306  mips_mark_labels ();
17307  mips_assembling_insn = true;
17308
17309  macro_start ();
17310  macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
17311				SP, HAVE_64BIT_ADDRESSES);
17312  macro_end ();
17313
17314  mips_assembling_insn = false;
17315  demand_empty_rest_of_line ();
17316}
17317
17318/* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
17319   was given in the preceding .cpsetup, it results in:
17320     ld		$gp, offset($sp)
17321
17322   If a register $reg2 was given there, it results in:
17323     or		$gp, $reg2, $0  */
17324
17325static void
17326s_cpreturn (int ignore ATTRIBUTE_UNUSED)
17327{
17328  expressionS ex;
17329
17330  file_mips_check_options ();
17331
17332  /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
17333     We also need NewABI support.  */
17334  if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17335    {
17336      s_ignore (0);
17337      return;
17338    }
17339
17340  if (mips_opts.mips16)
17341    {
17342      as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
17343      ignore_rest_of_line ();
17344      return;
17345    }
17346
17347  mips_mark_labels ();
17348  mips_assembling_insn = true;
17349
17350  macro_start ();
17351  if (mips_cpreturn_register == -1)
17352    {
17353      ex.X_op = O_constant;
17354      ex.X_add_symbol = NULL;
17355      ex.X_op_symbol = NULL;
17356      ex.X_add_number = mips_cpreturn_offset;
17357
17358      macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
17359    }
17360  else
17361    move_register (mips_gp_register, mips_cpreturn_register);
17362
17363  macro_end ();
17364
17365  mips_assembling_insn = false;
17366  demand_empty_rest_of_line ();
17367}
17368
17369/* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
17370   pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
17371   DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
17372   debug information or MIPS16 TLS.  */
17373
17374static void
17375s_tls_rel_directive (const size_t bytes, const char *dirstr,
17376		     bfd_reloc_code_real_type rtype)
17377{
17378  expressionS ex;
17379  char *p;
17380
17381  expression (&ex);
17382
17383  if (ex.X_op != O_symbol)
17384    {
17385      as_bad (_("unsupported use of %s"), dirstr);
17386      ignore_rest_of_line ();
17387    }
17388
17389  p = frag_more (bytes);
17390  md_number_to_chars (p, 0, bytes);
17391  fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false, rtype);
17392  demand_empty_rest_of_line ();
17393  mips_clear_insn_labels ();
17394}
17395
17396/* Handle .dtprelword.  */
17397
17398static void
17399s_dtprelword (int ignore ATTRIBUTE_UNUSED)
17400{
17401  s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
17402}
17403
17404/* Handle .dtpreldword.  */
17405
17406static void
17407s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
17408{
17409  s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
17410}
17411
17412/* Handle .tprelword.  */
17413
17414static void
17415s_tprelword (int ignore ATTRIBUTE_UNUSED)
17416{
17417  s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
17418}
17419
17420/* Handle .tpreldword.  */
17421
17422static void
17423s_tpreldword (int ignore ATTRIBUTE_UNUSED)
17424{
17425  s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
17426}
17427
17428/* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
17429   code.  It sets the offset to use in gp_rel relocations.  */
17430
17431static void
17432s_gpvalue (int ignore ATTRIBUTE_UNUSED)
17433{
17434  /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
17435     We also need NewABI support.  */
17436  if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17437    {
17438      s_ignore (0);
17439      return;
17440    }
17441
17442  mips_gprel_offset = get_absolute_expression ();
17443
17444  demand_empty_rest_of_line ();
17445}
17446
17447/* Handle the .gpword pseudo-op.  This is used when generating PIC
17448   code.  It generates a 32 bit GP relative reloc.  */
17449
17450static void
17451s_gpword (int ignore ATTRIBUTE_UNUSED)
17452{
17453  segment_info_type *si;
17454  struct insn_label_list *l;
17455  expressionS ex;
17456  char *p;
17457
17458  /* When not generating PIC code, this is treated as .word.  */
17459  if (mips_pic != SVR4_PIC)
17460    {
17461      s_cons (2);
17462      return;
17463    }
17464
17465  si = seg_info (now_seg);
17466  l = si->label_list;
17467  mips_emit_delays ();
17468  if (auto_align)
17469    mips_align (2, 0, l);
17470
17471  expression (&ex);
17472  mips_clear_insn_labels ();
17473
17474  if (ex.X_op != O_symbol || ex.X_add_number != 0)
17475    {
17476      as_bad (_("unsupported use of .gpword"));
17477      ignore_rest_of_line ();
17478    }
17479
17480  p = frag_more (4);
17481  md_number_to_chars (p, 0, 4);
17482  fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, false,
17483	       BFD_RELOC_GPREL32);
17484
17485  demand_empty_rest_of_line ();
17486}
17487
17488static void
17489s_gpdword (int ignore ATTRIBUTE_UNUSED)
17490{
17491  segment_info_type *si;
17492  struct insn_label_list *l;
17493  expressionS ex;
17494  char *p;
17495
17496  /* When not generating PIC code, this is treated as .dword.  */
17497  if (mips_pic != SVR4_PIC)
17498    {
17499      s_cons (3);
17500      return;
17501    }
17502
17503  si = seg_info (now_seg);
17504  l = si->label_list;
17505  mips_emit_delays ();
17506  if (auto_align)
17507    mips_align (3, 0, l);
17508
17509  expression (&ex);
17510  mips_clear_insn_labels ();
17511
17512  if (ex.X_op != O_symbol || ex.X_add_number != 0)
17513    {
17514      as_bad (_("unsupported use of .gpdword"));
17515      ignore_rest_of_line ();
17516    }
17517
17518  p = frag_more (8);
17519  md_number_to_chars (p, 0, 8);
17520  fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, false,
17521	       BFD_RELOC_GPREL32)->fx_tcbit = 1;
17522
17523  /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17524  fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17525	   false, BFD_RELOC_64)->fx_tcbit = 1;
17526
17527  demand_empty_rest_of_line ();
17528}
17529
17530/* Handle the .ehword pseudo-op.  This is used when generating unwinding
17531   tables.  It generates a R_MIPS_EH reloc.  */
17532
17533static void
17534s_ehword (int ignore ATTRIBUTE_UNUSED)
17535{
17536  expressionS ex;
17537  char *p;
17538
17539  mips_emit_delays ();
17540
17541  expression (&ex);
17542  mips_clear_insn_labels ();
17543
17544  if (ex.X_op != O_symbol || ex.X_add_number != 0)
17545    {
17546      as_bad (_("unsupported use of .ehword"));
17547      ignore_rest_of_line ();
17548    }
17549
17550  p = frag_more (4);
17551  md_number_to_chars (p, 0, 4);
17552  fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, false,
17553	       BFD_RELOC_32_PCREL);
17554
17555  demand_empty_rest_of_line ();
17556}
17557
17558/* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17559   tables in SVR4 PIC code.  */
17560
17561static void
17562s_cpadd (int ignore ATTRIBUTE_UNUSED)
17563{
17564  int reg;
17565
17566  file_mips_check_options ();
17567
17568  /* This is ignored when not generating SVR4 PIC code.  */
17569  if (mips_pic != SVR4_PIC)
17570    {
17571      s_ignore (0);
17572      return;
17573    }
17574
17575  mips_mark_labels ();
17576  mips_assembling_insn = true;
17577
17578  /* Add $gp to the register named as an argument.  */
17579  macro_start ();
17580  reg = tc_get_register (0);
17581  macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17582  macro_end ();
17583
17584  mips_assembling_insn = false;
17585  demand_empty_rest_of_line ();
17586}
17587
17588/* Handle the .insn pseudo-op.  This marks instruction labels in
17589   mips16/micromips mode.  This permits the linker to handle them specially,
17590   such as generating jalx instructions when needed.  We also make
17591   them odd for the duration of the assembly, in order to generate the
17592   right sort of code.  We will make them even in the adjust_symtab
17593   routine, while leaving them marked.  This is convenient for the
17594   debugger and the disassembler.  The linker knows to make them odd
17595   again.  */
17596
17597static void
17598s_insn (int ignore ATTRIBUTE_UNUSED)
17599{
17600  file_mips_check_options ();
17601  file_ase_mips16 |= mips_opts.mips16;
17602  file_ase_micromips |= mips_opts.micromips;
17603
17604  mips_mark_labels ();
17605
17606  demand_empty_rest_of_line ();
17607}
17608
17609/* Handle the .nan pseudo-op.  */
17610
17611static void
17612s_nan (int ignore ATTRIBUTE_UNUSED)
17613{
17614  static const char str_legacy[] = "legacy";
17615  static const char str_2008[] = "2008";
17616  size_t i;
17617
17618  for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
17619
17620  if (i == sizeof (str_2008) - 1
17621      && memcmp (input_line_pointer, str_2008, i) == 0)
17622    mips_nan2008 = 1;
17623  else if (i == sizeof (str_legacy) - 1
17624	   && memcmp (input_line_pointer, str_legacy, i) == 0)
17625    {
17626      if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
17627	mips_nan2008 = 0;
17628      else
17629	as_bad (_("`%s' does not support legacy NaN"),
17630	          mips_cpu_info_from_isa (file_mips_opts.isa)->name);
17631    }
17632  else
17633    as_bad (_("bad .nan directive"));
17634
17635  input_line_pointer += i;
17636  demand_empty_rest_of_line ();
17637}
17638
17639/* Handle a .stab[snd] directive.  Ideally these directives would be
17640   implemented in a transparent way, so that removing them would not
17641   have any effect on the generated instructions.  However, s_stab
17642   internally changes the section, so in practice we need to decide
17643   now whether the preceding label marks compressed code.  We do not
17644   support changing the compression mode of a label after a .stab*
17645   directive, such as in:
17646
17647   foo:
17648	.stabs ...
17649	.set mips16
17650
17651   so the current mode wins.  */
17652
17653static void
17654s_mips_stab (int type)
17655{
17656  file_mips_check_options ();
17657  mips_mark_labels ();
17658  s_stab (type);
17659}
17660
17661/* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17662
17663static void
17664s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17665{
17666  char *name;
17667  int c;
17668  symbolS *symbolP;
17669  expressionS exp;
17670
17671  c = get_symbol_name (&name);
17672  symbolP = symbol_find_or_make (name);
17673  S_SET_WEAK (symbolP);
17674  *input_line_pointer = c;
17675
17676  SKIP_WHITESPACE_AFTER_NAME ();
17677
17678  if (! is_end_of_line[(unsigned char) *input_line_pointer])
17679    {
17680      if (S_IS_DEFINED (symbolP))
17681	{
17682	  as_bad (_("ignoring attempt to redefine symbol %s"),
17683		  S_GET_NAME (symbolP));
17684	  ignore_rest_of_line ();
17685	  return;
17686	}
17687
17688      if (*input_line_pointer == ',')
17689	{
17690	  ++input_line_pointer;
17691	  SKIP_WHITESPACE ();
17692	}
17693
17694      expression (&exp);
17695      if (exp.X_op != O_symbol)
17696	{
17697	  as_bad (_("bad .weakext directive"));
17698	  ignore_rest_of_line ();
17699	  return;
17700	}
17701      symbol_set_value_expression (symbolP, &exp);
17702    }
17703
17704  demand_empty_rest_of_line ();
17705}
17706
17707/* Parse a register string into a number.  Called from the ECOFF code
17708   to parse .frame.  The argument is non-zero if this is the frame
17709   register, so that we can record it in mips_frame_reg.  */
17710
17711int
17712tc_get_register (int frame)
17713{
17714  unsigned int reg;
17715
17716  SKIP_WHITESPACE ();
17717  if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17718    reg = 0;
17719  if (frame)
17720    {
17721      mips_frame_reg = reg != 0 ? reg : SP;
17722      mips_frame_reg_valid = 1;
17723      mips_cprestore_valid = 0;
17724    }
17725  return reg;
17726}
17727
17728valueT
17729md_section_align (asection *seg, valueT addr)
17730{
17731  int align = bfd_section_alignment (seg);
17732
17733  /* We don't need to align ELF sections to the full alignment.
17734     However, Irix 5 may prefer that we align them at least to a 16
17735     byte boundary.  We don't bother to align the sections if we
17736     are targeted for an embedded system.  */
17737  if (startswith (TARGET_OS, "elf"))
17738    return addr;
17739  if (align > 4)
17740    align = 4;
17741
17742  return ((addr + (1 << align) - 1) & -(1 << align));
17743}
17744
17745/* Utility routine, called from above as well.  If called while the
17746   input file is still being read, it's only an approximation.  (For
17747   example, a symbol may later become defined which appeared to be
17748   undefined earlier.)  */
17749
17750static int
17751nopic_need_relax (symbolS *sym, int before_relaxing)
17752{
17753  if (sym == 0)
17754    return 0;
17755
17756  if (g_switch_value > 0)
17757    {
17758      const char *symname;
17759      int change;
17760
17761      /* Find out whether this symbol can be referenced off the $gp
17762	 register.  It can be if it is smaller than the -G size or if
17763	 it is in the .sdata or .sbss section.  Certain symbols can
17764	 not be referenced off the $gp, although it appears as though
17765	 they can.  */
17766      symname = S_GET_NAME (sym);
17767      if (symname != (const char *) NULL
17768	  && (strcmp (symname, "eprol") == 0
17769	      || strcmp (symname, "etext") == 0
17770	      || strcmp (symname, "_gp") == 0
17771	      || strcmp (symname, "edata") == 0
17772	      || strcmp (symname, "_fbss") == 0
17773	      || strcmp (symname, "_fdata") == 0
17774	      || strcmp (symname, "_ftext") == 0
17775	      || strcmp (symname, "end") == 0
17776	      || strcmp (symname, "_gp_disp") == 0))
17777	change = 1;
17778      else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17779	       && (0
17780#ifndef NO_ECOFF_DEBUGGING
17781		   || (symbol_get_obj (sym)->ecoff_extern_size != 0
17782		       && (symbol_get_obj (sym)->ecoff_extern_size
17783			   <= g_switch_value))
17784#endif
17785		   /* We must defer this decision until after the whole
17786		      file has been read, since there might be a .extern
17787		      after the first use of this symbol.  */
17788		   || (before_relaxing
17789#ifndef NO_ECOFF_DEBUGGING
17790		       && symbol_get_obj (sym)->ecoff_extern_size == 0
17791#endif
17792		       && S_GET_VALUE (sym) == 0)
17793		   || (S_GET_VALUE (sym) != 0
17794		       && S_GET_VALUE (sym) <= g_switch_value)))
17795	change = 0;
17796      else
17797	{
17798	  const char *segname;
17799
17800	  segname = segment_name (S_GET_SEGMENT (sym));
17801	  gas_assert (strcmp (segname, ".lit8") != 0
17802		  && strcmp (segname, ".lit4") != 0);
17803	  change = (strcmp (segname, ".sdata") != 0
17804		    && strcmp (segname, ".sbss") != 0
17805		    && !startswith (segname, ".sdata.")
17806		    && !startswith (segname, ".sbss.")
17807		    && !startswith (segname, ".gnu.linkonce.sb.")
17808		    && !startswith (segname, ".gnu.linkonce.s."));
17809	}
17810      return change;
17811    }
17812  else
17813    /* We are not optimizing for the $gp register.  */
17814    return 1;
17815}
17816
17817
17818/* Return true if the given symbol should be considered local for SVR4 PIC.  */
17819
17820static bool
17821pic_need_relax (symbolS *sym)
17822{
17823  asection *symsec;
17824
17825  /* Handle the case of a symbol equated to another symbol.  */
17826  while (symbol_equated_reloc_p (sym))
17827    {
17828      symbolS *n;
17829
17830      /* It's possible to get a loop here in a badly written program.  */
17831      n = symbol_get_value_expression (sym)->X_add_symbol;
17832      if (n == sym)
17833	break;
17834      sym = n;
17835    }
17836
17837  if (symbol_section_p (sym))
17838    return true;
17839
17840  symsec = S_GET_SEGMENT (sym);
17841
17842  /* This must duplicate the test in adjust_reloc_syms.  */
17843  return (!bfd_is_und_section (symsec)
17844	  && !bfd_is_abs_section (symsec)
17845	  && !bfd_is_com_section (symsec)
17846	  /* A global or weak symbol is treated as external.  */
17847	  && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17848}
17849
17850/* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17851   convert a section-relative value VAL to the equivalent PC-relative
17852   value.  */
17853
17854static offsetT
17855mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17856		  offsetT val, long stretch)
17857{
17858  fragS *sym_frag;
17859  addressT addr;
17860
17861  gas_assert (pcrel_op->root.root.type == OP_PCREL);
17862
17863  sym_frag = symbol_get_frag (fragp->fr_symbol);
17864
17865  /* If the relax_marker of the symbol fragment differs from the
17866     relax_marker of this fragment, we have not yet adjusted the
17867     symbol fragment fr_address.  We want to add in STRETCH in
17868     order to get a better estimate of the address.  This
17869     particularly matters because of the shift bits.  */
17870  if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17871    {
17872      fragS *f;
17873
17874      /* Adjust stretch for any alignment frag.  Note that if have
17875	 been expanding the earlier code, the symbol may be
17876	 defined in what appears to be an earlier frag.  FIXME:
17877	 This doesn't handle the fr_subtype field, which specifies
17878	 a maximum number of bytes to skip when doing an
17879	 alignment.  */
17880      for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17881	{
17882	  if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17883	    {
17884	      if (stretch < 0)
17885		stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17886	      else
17887		stretch &= ~((1 << (int) f->fr_offset) - 1);
17888	      if (stretch == 0)
17889		break;
17890	    }
17891	}
17892      if (f != NULL)
17893	val += stretch;
17894    }
17895
17896  addr = fragp->fr_address + fragp->fr_fix;
17897
17898  /* The base address rules are complicated.  The base address of
17899     a branch is the following instruction.  The base address of a
17900     PC relative load or add is the instruction itself, but if it
17901     is in a delay slot (in which case it can not be extended) use
17902     the address of the instruction whose delay slot it is in.  */
17903  if (pcrel_op->include_isa_bit)
17904    {
17905      addr += 2;
17906
17907      /* If we are currently assuming that this frag should be
17908	 extended, then the current address is two bytes higher.  */
17909      if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17910	addr += 2;
17911
17912      /* Ignore the low bit in the target, since it will be set
17913	 for a text label.  */
17914      val &= -2;
17915    }
17916  else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17917    addr -= 4;
17918  else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17919    addr -= 2;
17920
17921  val -= addr & -(1 << pcrel_op->align_log2);
17922
17923  return val;
17924}
17925
17926/* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17927   extended opcode.  SEC is the section the frag is in.  */
17928
17929static int
17930mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17931{
17932  const struct mips_int_operand *operand;
17933  offsetT val;
17934  segT symsec;
17935  int type;
17936
17937  if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17938    return 0;
17939  if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17940    return 1;
17941
17942  symsec = S_GET_SEGMENT (fragp->fr_symbol);
17943  type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17944  operand = mips16_immed_operand (type, false);
17945  if (S_FORCE_RELOC (fragp->fr_symbol, true)
17946      || (operand->root.type == OP_PCREL
17947	  ? sec != symsec
17948	  : !bfd_is_abs_section (symsec)))
17949    return 1;
17950
17951  val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17952
17953  if (operand->root.type == OP_PCREL)
17954    {
17955      const struct mips_pcrel_operand *pcrel_op;
17956      offsetT maxtiny;
17957
17958      if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17959	return 1;
17960
17961      pcrel_op = (const struct mips_pcrel_operand *) operand;
17962      val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17963
17964      /* If any of the shifted bits are set, we must use an extended
17965         opcode.  If the address depends on the size of this
17966         instruction, this can lead to a loop, so we arrange to always
17967         use an extended opcode.  */
17968      if ((val & ((1 << operand->shift) - 1)) != 0)
17969	{
17970	  fragp->fr_subtype =
17971	    RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17972	  return 1;
17973	}
17974
17975      /* If we are about to mark a frag as extended because the value
17976         is precisely the next value above maxtiny, then there is a
17977         chance of an infinite loop as in the following code:
17978	     la	$4,foo
17979	     .skip	1020
17980	     .align	2
17981	   foo:
17982	 In this case when the la is extended, foo is 0x3fc bytes
17983	 away, so the la can be shrunk, but then foo is 0x400 away, so
17984	 the la must be extended.  To avoid this loop, we mark the
17985	 frag as extended if it was small, and is about to become
17986	 extended with the next value above maxtiny.  */
17987      maxtiny = mips_int_operand_max (operand);
17988      if (val == maxtiny + (1 << operand->shift)
17989	  && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17990	{
17991	  fragp->fr_subtype =
17992	    RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17993	  return 1;
17994	}
17995    }
17996
17997  return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17998}
17999
18000/* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
18001   macro expansion.  SEC is the section the frag is in.  We only
18002   support PC-relative instructions (LA, DLA, LW, LD) here, in
18003   non-PIC code using 32-bit addressing.  */
18004
18005static int
18006mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
18007{
18008  const struct mips_pcrel_operand *pcrel_op;
18009  const struct mips_int_operand *operand;
18010  offsetT val;
18011  segT symsec;
18012  int type;
18013
18014  gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
18015
18016  if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18017    return 0;
18018  if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
18019    return 0;
18020
18021  type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18022  switch (type)
18023    {
18024    case 'A':
18025    case 'B':
18026    case 'E':
18027      symsec = S_GET_SEGMENT (fragp->fr_symbol);
18028      if (bfd_is_abs_section (symsec))
18029	return 1;
18030      if (RELAX_MIPS16_PIC (fragp->fr_subtype))
18031	return 0;
18032      if (S_FORCE_RELOC (fragp->fr_symbol, true) || sec != symsec)
18033	return 1;
18034
18035      operand = mips16_immed_operand (type, true);
18036      val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18037      pcrel_op = (const struct mips_pcrel_operand *) operand;
18038      val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
18039
18040      return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
18041
18042    default:
18043      return 0;
18044    }
18045}
18046
18047/* Compute the length of a branch sequence, and adjust the
18048   RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
18049   worst-case length is computed, with UPDATE being used to indicate
18050   whether an unconditional (-1), branch-likely (+1) or regular (0)
18051   branch is to be computed.  */
18052static int
18053relaxed_branch_length (fragS *fragp, asection *sec, int update)
18054{
18055  bool toofar;
18056  int length;
18057
18058  if (fragp
18059      && S_IS_DEFINED (fragp->fr_symbol)
18060      && !S_IS_WEAK (fragp->fr_symbol)
18061      && sec == S_GET_SEGMENT (fragp->fr_symbol))
18062    {
18063      addressT addr;
18064      offsetT val;
18065
18066      val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18067
18068      addr = fragp->fr_address + fragp->fr_fix + 4;
18069
18070      val -= addr;
18071
18072      toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
18073    }
18074  else
18075    /* If the symbol is not defined or it's in a different segment,
18076       we emit the long sequence.  */
18077    toofar = true;
18078
18079  if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18080    fragp->fr_subtype
18081      = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
18082			     RELAX_BRANCH_PIC (fragp->fr_subtype),
18083			     RELAX_BRANCH_UNCOND (fragp->fr_subtype),
18084			     RELAX_BRANCH_LIKELY (fragp->fr_subtype),
18085			     RELAX_BRANCH_LINK (fragp->fr_subtype),
18086			     toofar);
18087
18088  length = 4;
18089  if (toofar)
18090    {
18091      if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
18092	length += 8;
18093
18094      if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
18095	{
18096	  /* Additional space for PIC loading of target address.  */
18097	  length += 8;
18098	  if (mips_opts.isa == ISA_MIPS1)
18099	    /* Additional space for $at-stabilizing nop.  */
18100	    length += 4;
18101	}
18102
18103      /* If branch is conditional.  */
18104      if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
18105	length += 8;
18106    }
18107
18108  return length;
18109}
18110
18111/* Get a FRAG's branch instruction delay slot size, either from the
18112   short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
18113   or SHORT_INSN_SIZE otherwise.  */
18114
18115static int
18116frag_branch_delay_slot_size (fragS *fragp, bool al, int short_insn_size)
18117{
18118  char *buf = fragp->fr_literal + fragp->fr_fix;
18119
18120  if (al)
18121    return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
18122  else
18123    return short_insn_size;
18124}
18125
18126/* Compute the length of a branch sequence, and adjust the
18127   RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
18128   worst-case length is computed, with UPDATE being used to indicate
18129   whether an unconditional (-1), or regular (0) branch is to be
18130   computed.  */
18131
18132static int
18133relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
18134{
18135  bool insn32 = true;
18136  bool nods = true;
18137  bool pic = true;
18138  bool al = true;
18139  int short_insn_size;
18140  bool toofar;
18141  int length;
18142
18143  if (fragp)
18144    {
18145      insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18146      nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18147      pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18148      al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18149    }
18150  short_insn_size = insn32 ? 4 : 2;
18151
18152  if (fragp
18153      && S_IS_DEFINED (fragp->fr_symbol)
18154      && !S_IS_WEAK (fragp->fr_symbol)
18155      && sec == S_GET_SEGMENT (fragp->fr_symbol))
18156    {
18157      addressT addr;
18158      offsetT val;
18159
18160      val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18161      /* Ignore the low bit in the target, since it will be set
18162	 for a text label.  */
18163      if ((val & 1) != 0)
18164	--val;
18165
18166      addr = fragp->fr_address + fragp->fr_fix + 4;
18167
18168      val -= addr;
18169
18170      toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
18171    }
18172  else
18173    /* If the symbol is not defined or it's in a different segment,
18174       we emit the long sequence.  */
18175    toofar = true;
18176
18177  if (fragp && update
18178      && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18179    fragp->fr_subtype = (toofar
18180			 ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
18181			 : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
18182
18183  length = 4;
18184  if (toofar)
18185    {
18186      bool compact_known = fragp != NULL;
18187      bool compact = false;
18188      bool uncond;
18189
18190      if (fragp)
18191	{
18192	  compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18193	  uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
18194	}
18195      else
18196	uncond = update < 0;
18197
18198      /* If label is out of range, we turn branch <br>:
18199
18200		<br>	label			# 4 bytes
18201	    0:
18202
18203         into:
18204
18205		j	label			# 4 bytes
18206		nop				# 2/4 bytes if
18207						#  compact && (!PIC || insn32)
18208	    0:
18209       */
18210      if ((!pic || insn32) && (!compact_known || compact))
18211	length += short_insn_size;
18212
18213      /* If assembling PIC code, we further turn:
18214
18215			j	label			# 4 bytes
18216
18217         into:
18218
18219			lw/ld	at, %got(label)(gp)	# 4 bytes
18220			d/addiu	at, %lo(label)		# 4 bytes
18221			jr/c	at			# 2/4 bytes
18222       */
18223      if (pic)
18224	length += 4 + short_insn_size;
18225
18226      /* Add an extra nop if the jump has no compact form and we need
18227         to fill the delay slot.  */
18228      if ((!pic || al) && nods)
18229	length += (fragp
18230		   ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
18231		   : short_insn_size);
18232
18233      /* If branch <br> is conditional, we prepend negated branch <brneg>:
18234
18235			<brneg>	0f			# 4 bytes
18236			nop				# 2/4 bytes if !compact
18237       */
18238      if (!uncond)
18239	length += (compact_known && compact) ? 4 : 4 + short_insn_size;
18240    }
18241  else if (nods)
18242    {
18243      /* Add an extra nop to fill the delay slot.  */
18244      gas_assert (fragp);
18245      length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
18246    }
18247
18248  return length;
18249}
18250
18251/* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
18252   bit accordingly.  */
18253
18254static int
18255relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
18256{
18257  bool toofar;
18258
18259  if (fragp
18260      && S_IS_DEFINED (fragp->fr_symbol)
18261      && !S_IS_WEAK (fragp->fr_symbol)
18262      && sec == S_GET_SEGMENT (fragp->fr_symbol))
18263    {
18264      addressT addr;
18265      offsetT val;
18266      int type;
18267
18268      val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18269      /* Ignore the low bit in the target, since it will be set
18270	 for a text label.  */
18271      if ((val & 1) != 0)
18272	--val;
18273
18274      /* Assume this is a 2-byte branch.  */
18275      addr = fragp->fr_address + fragp->fr_fix + 2;
18276
18277      /* We try to avoid the infinite loop by not adding 2 more bytes for
18278	 long branches.  */
18279
18280      val -= addr;
18281
18282      type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18283      if (type == 'D')
18284	toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
18285      else if (type == 'E')
18286	toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
18287      else
18288	abort ();
18289    }
18290  else
18291    /* If the symbol is not defined or it's in a different segment,
18292       we emit a normal 32-bit branch.  */
18293    toofar = true;
18294
18295  if (fragp && update
18296      && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18297    fragp->fr_subtype
18298      = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
18299	       : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
18300
18301  if (toofar)
18302    return 4;
18303
18304  return 2;
18305}
18306
18307/* Estimate the size of a frag before relaxing.  Unless this is the
18308   mips16, we are not really relaxing here, and the final size is
18309   encoded in the subtype information.  For the mips16, we have to
18310   decide whether we are using an extended opcode or not.  */
18311
18312int
18313md_estimate_size_before_relax (fragS *fragp, asection *segtype)
18314{
18315  int change;
18316
18317  if (RELAX_BRANCH_P (fragp->fr_subtype))
18318    {
18319
18320      fragp->fr_var = relaxed_branch_length (fragp, segtype, false);
18321
18322      return fragp->fr_var;
18323    }
18324
18325  if (RELAX_MIPS16_P (fragp->fr_subtype))
18326    {
18327      /* We don't want to modify the EXTENDED bit here; it might get us
18328	 into infinite loops.  We change it only in mips_relax_frag().  */
18329      if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18330	return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 8 : 12;
18331      else
18332	return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
18333    }
18334
18335  if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18336    {
18337      int length = 4;
18338
18339      if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18340	length = relaxed_micromips_16bit_branch_length (fragp, segtype, false);
18341      if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18342	length = relaxed_micromips_32bit_branch_length (fragp, segtype, false);
18343      fragp->fr_var = length;
18344
18345      return length;
18346    }
18347
18348  if (mips_pic == VXWORKS_PIC)
18349    /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
18350    change = 0;
18351  else if (RELAX_PIC (fragp->fr_subtype))
18352    change = pic_need_relax (fragp->fr_symbol);
18353  else
18354    change = nopic_need_relax (fragp->fr_symbol, 0);
18355
18356  if (change)
18357    {
18358      fragp->fr_subtype |= RELAX_USE_SECOND;
18359      return -RELAX_FIRST (fragp->fr_subtype);
18360    }
18361  else
18362    return -RELAX_SECOND (fragp->fr_subtype);
18363}
18364
18365/* This is called to see whether a reloc against a defined symbol
18366   should be converted into a reloc against a section.  */
18367
18368int
18369mips_fix_adjustable (fixS *fixp)
18370{
18371  if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
18372      || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18373    return 0;
18374
18375  if (fixp->fx_addsy == NULL)
18376    return 1;
18377
18378  /* Allow relocs used for EH tables.  */
18379  if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
18380    return 1;
18381
18382  /* If symbol SYM is in a mergeable section, relocations of the form
18383     SYM + 0 can usually be made section-relative.  The mergeable data
18384     is then identified by the section offset rather than by the symbol.
18385
18386     However, if we're generating REL LO16 relocations, the offset is split
18387     between the LO16 and partnering high part relocation.  The linker will
18388     need to recalculate the complete offset in order to correctly identify
18389     the merge data.
18390
18391     The linker has traditionally not looked for the partnering high part
18392     relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
18393     placed anywhere.  Rather than break backwards compatibility by changing
18394     this, it seems better not to force the issue, and instead keep the
18395     original symbol.  This will work with either linker behavior.  */
18396  if ((lo16_reloc_p (fixp->fx_r_type)
18397       || reloc_needs_lo_p (fixp->fx_r_type))
18398      && HAVE_IN_PLACE_ADDENDS
18399      && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
18400    return 0;
18401
18402  /* There is no place to store an in-place offset for JALR relocations.  */
18403  if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
18404    return 0;
18405
18406  /* Likewise an in-range offset of limited PC-relative relocations may
18407     overflow the in-place relocatable field if recalculated against the
18408     start address of the symbol's containing section.
18409
18410     Also, PC relative relocations for MIPS R6 need to be symbol rather than
18411     section relative to allow linker relaxations to be performed later on.  */
18412  if (limited_pcrel_reloc_p (fixp->fx_r_type)
18413      && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
18414    return 0;
18415
18416  /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
18417     to a floating-point stub.  The same is true for non-R_MIPS16_26
18418     relocations against MIPS16 functions; in this case, the stub becomes
18419     the function's canonical address.
18420
18421     Floating-point stubs are stored in unique .mips16.call.* or
18422     .mips16.fn.* sections.  If a stub T for function F is in section S,
18423     the first relocation in section S must be against F; this is how the
18424     linker determines the target function.  All relocations that might
18425     resolve to T must also be against F.  We therefore have the following
18426     restrictions, which are given in an intentionally-redundant way:
18427
18428       1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
18429	  symbols.
18430
18431       2. We cannot reduce a stub's relocations against non-MIPS16 symbols
18432	  if that stub might be used.
18433
18434       3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
18435	  symbols.
18436
18437       4. We cannot reduce a stub's relocations against MIPS16 symbols if
18438	  that stub might be used.
18439
18440     There is a further restriction:
18441
18442       5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
18443	  R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
18444	  R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
18445	  R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
18446	  against MIPS16 or microMIPS symbols because we need to keep the
18447	  MIPS16 or microMIPS symbol for the purpose of mode mismatch
18448	  detection and JAL or BAL to JALX instruction conversion in the
18449	  linker.
18450
18451     For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
18452     against a MIPS16 symbol.  We deal with (5) by additionally leaving
18453     alone any jump and branch relocations against a microMIPS symbol.
18454
18455     We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
18456     relocation against some symbol R, no relocation against R may be
18457     reduced.  (Note that this deals with (2) as well as (1) because
18458     relocations against global symbols will never be reduced on ELF
18459     targets.)  This approach is a little simpler than trying to detect
18460     stub sections, and gives the "all or nothing" per-symbol consistency
18461     that we have for MIPS16 symbols.  */
18462  if (fixp->fx_subsy == NULL
18463      && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
18464	  || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
18465	      && (jmp_reloc_p (fixp->fx_r_type)
18466		  || b_reloc_p (fixp->fx_r_type)))
18467	  || *symbol_get_tc (fixp->fx_addsy)))
18468    return 0;
18469
18470  return 1;
18471}
18472
18473/* Translate internal representation of relocation info to BFD target
18474   format.  */
18475
18476arelent **
18477tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
18478{
18479  static arelent *retval[4];
18480  arelent *reloc;
18481  bfd_reloc_code_real_type code;
18482
18483  memset (retval, 0, sizeof(retval));
18484  reloc = retval[0] = XCNEW (arelent);
18485  reloc->sym_ptr_ptr = XNEW (asymbol *);
18486  *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
18487  reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
18488
18489  if (fixp->fx_pcrel)
18490    {
18491      gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
18492		  || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
18493		  || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
18494		  || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
18495		  || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
18496		  || fixp->fx_r_type == BFD_RELOC_32_PCREL
18497		  || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
18498		  || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
18499		  || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
18500		  || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
18501		  || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
18502		  || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
18503
18504      /* At this point, fx_addnumber is "symbol offset - pcrel address".
18505	 Relocations want only the symbol offset.  */
18506      switch (fixp->fx_r_type)
18507	{
18508	case BFD_RELOC_MIPS_18_PCREL_S3:
18509	  reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
18510	  break;
18511	default:
18512	  reloc->addend = fixp->fx_addnumber + reloc->address;
18513	  break;
18514	}
18515    }
18516  else if (HAVE_IN_PLACE_ADDENDS
18517	   && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
18518	   && (read_compressed_insn (fixp->fx_frag->fr_literal
18519				     + fixp->fx_where, 4) >> 26) == 0x3c)
18520    {
18521      /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
18522         addend accordingly.  */
18523      reloc->addend = fixp->fx_addnumber >> 1;
18524    }
18525  else
18526    reloc->addend = fixp->fx_addnumber;
18527
18528  /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18529     entry to be used in the relocation's section offset.  */
18530  if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18531    {
18532      reloc->address = reloc->addend;
18533      reloc->addend = 0;
18534    }
18535
18536  code = fixp->fx_r_type;
18537
18538  reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18539  if (reloc->howto == NULL)
18540    {
18541      as_bad_where (fixp->fx_file, fixp->fx_line,
18542		    _("cannot represent %s relocation in this object file"
18543		      " format"),
18544		    bfd_get_reloc_code_name (code));
18545      retval[0] = NULL;
18546    }
18547
18548  return retval;
18549}
18550
18551/* Relax a machine dependent frag.  This returns the amount by which
18552   the current size of the frag should change.  */
18553
18554int
18555mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18556{
18557  if (RELAX_BRANCH_P (fragp->fr_subtype))
18558    {
18559      offsetT old_var = fragp->fr_var;
18560
18561      fragp->fr_var = relaxed_branch_length (fragp, sec, true);
18562
18563      return fragp->fr_var - old_var;
18564    }
18565
18566  if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18567    {
18568      offsetT old_var = fragp->fr_var;
18569      offsetT new_var = 4;
18570
18571      if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18572	new_var = relaxed_micromips_16bit_branch_length (fragp, sec, true);
18573      if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18574	new_var = relaxed_micromips_32bit_branch_length (fragp, sec, true);
18575      fragp->fr_var = new_var;
18576
18577      return new_var - old_var;
18578    }
18579
18580  if (! RELAX_MIPS16_P (fragp->fr_subtype))
18581    return 0;
18582
18583  if (!mips16_extended_frag (fragp, sec, stretch))
18584    {
18585      if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18586	{
18587	  fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18588	  return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -6 : -10;
18589	}
18590      else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18591	{
18592	  fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18593	  return -2;
18594	}
18595      else
18596	return 0;
18597    }
18598  else if (!mips16_macro_frag (fragp, sec, stretch))
18599    {
18600      if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18601	{
18602	  fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18603	  fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18604	  return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -4 : -8;
18605	}
18606      else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18607	{
18608	  fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18609	  return 2;
18610	}
18611      else
18612	return 0;
18613    }
18614  else
18615    {
18616      if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18617	return 0;
18618      else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18619	{
18620	  fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18621	  fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18622	  return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 4 : 8;
18623	}
18624      else
18625	{
18626	  fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18627	  return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 6 : 10;
18628	}
18629    }
18630
18631  return 0;
18632}
18633
18634/* Convert a machine dependent frag.  */
18635
18636void
18637md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18638{
18639  if (RELAX_BRANCH_P (fragp->fr_subtype))
18640    {
18641      char *buf;
18642      unsigned long insn;
18643      fixS *fixp;
18644
18645      buf = fragp->fr_literal + fragp->fr_fix;
18646      insn = read_insn (buf);
18647
18648      if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18649	{
18650	  /* We generate a fixup instead of applying it right now
18651	     because, if there are linker relaxations, we're going to
18652	     need the relocations.  */
18653	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18654			  fragp->fr_symbol, fragp->fr_offset,
18655			  true, BFD_RELOC_16_PCREL_S2);
18656	  fixp->fx_file = fragp->fr_file;
18657	  fixp->fx_line = fragp->fr_line;
18658
18659	  buf = write_insn (buf, insn);
18660	}
18661      else
18662	{
18663	  int i;
18664
18665	  as_warn_where (fragp->fr_file, fragp->fr_line,
18666			 _("relaxed out-of-range branch into a jump"));
18667
18668	  if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18669	    goto uncond;
18670
18671	  if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18672	    {
18673	      /* Reverse the branch.  */
18674	      switch ((insn >> 28) & 0xf)
18675		{
18676		case 4:
18677		  if ((insn & 0xff000000) == 0x47000000
18678		      || (insn & 0xff600000) == 0x45600000)
18679		    {
18680		      /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18681			 reversed by tweaking bit 23.  */
18682		      insn ^= 0x00800000;
18683		    }
18684		  else
18685		    {
18686		      /* bc[0-3][tf]l? instructions can have the condition
18687			 reversed by tweaking a single TF bit, and their
18688			 opcodes all have 0x4???????.  */
18689		      gas_assert ((insn & 0xf3e00000) == 0x41000000);
18690		      insn ^= 0x00010000;
18691		    }
18692		  break;
18693
18694		case 0:
18695		  /* bltz	0x04000000	bgez	0x04010000
18696		     bltzal	0x04100000	bgezal	0x04110000  */
18697		  gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18698		  insn ^= 0x00010000;
18699		  break;
18700
18701		case 1:
18702		  /* beq	0x10000000	bne	0x14000000
18703		     blez	0x18000000	bgtz	0x1c000000  */
18704		  insn ^= 0x04000000;
18705		  break;
18706
18707		default:
18708		  abort ();
18709		}
18710	    }
18711
18712	  if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18713	    {
18714	      /* Clear the and-link bit.  */
18715	      gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18716
18717	      /* bltzal		0x04100000	bgezal	0x04110000
18718		 bltzall	0x04120000	bgezall	0x04130000  */
18719	      insn &= ~0x00100000;
18720	    }
18721
18722	  /* Branch over the branch (if the branch was likely) or the
18723	     full jump (not likely case).  Compute the offset from the
18724	     current instruction to branch to.  */
18725	  if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18726	    i = 16;
18727	  else
18728	    {
18729	      /* How many bytes in instructions we've already emitted?  */
18730	      i = buf - fragp->fr_literal - fragp->fr_fix;
18731	      /* How many bytes in instructions from here to the end?  */
18732	      i = fragp->fr_var - i;
18733	    }
18734	  /* Convert to instruction count.  */
18735	  i >>= 2;
18736	  /* Branch counts from the next instruction.  */
18737	  i--;
18738	  insn |= i;
18739	  /* Branch over the jump.  */
18740	  buf = write_insn (buf, insn);
18741
18742	  /* nop */
18743	  buf = write_insn (buf, 0);
18744
18745	  if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18746	    {
18747	      /* beql $0, $0, 2f */
18748	      insn = 0x50000000;
18749	      /* Compute the PC offset from the current instruction to
18750		 the end of the variable frag.  */
18751	      /* How many bytes in instructions we've already emitted?  */
18752	      i = buf - fragp->fr_literal - fragp->fr_fix;
18753	      /* How many bytes in instructions from here to the end?  */
18754	      i = fragp->fr_var - i;
18755	      /* Convert to instruction count.  */
18756	      i >>= 2;
18757	      /* Don't decrement i, because we want to branch over the
18758		 delay slot.  */
18759	      insn |= i;
18760
18761	      buf = write_insn (buf, insn);
18762	      buf = write_insn (buf, 0);
18763	    }
18764
18765	uncond:
18766	  if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18767	    {
18768	      /* j or jal.  */
18769	      insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18770		      ? 0x0c000000 : 0x08000000);
18771
18772	      fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18773			      fragp->fr_symbol, fragp->fr_offset,
18774			      false, BFD_RELOC_MIPS_JMP);
18775	      fixp->fx_file = fragp->fr_file;
18776	      fixp->fx_line = fragp->fr_line;
18777
18778	      buf = write_insn (buf, insn);
18779	    }
18780	  else
18781	    {
18782	      unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18783
18784	      /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18785	      insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18786	      insn |= at << OP_SH_RT;
18787
18788	      fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18789			      fragp->fr_symbol, fragp->fr_offset,
18790			      false, BFD_RELOC_MIPS_GOT16);
18791	      fixp->fx_file = fragp->fr_file;
18792	      fixp->fx_line = fragp->fr_line;
18793
18794	      buf = write_insn (buf, insn);
18795
18796	      if (mips_opts.isa == ISA_MIPS1)
18797		/* nop */
18798		buf = write_insn (buf, 0);
18799
18800	      /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18801	      insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18802	      insn |= at << OP_SH_RS | at << OP_SH_RT;
18803
18804	      fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18805			      fragp->fr_symbol, fragp->fr_offset,
18806			      false, BFD_RELOC_LO16);
18807	      fixp->fx_file = fragp->fr_file;
18808	      fixp->fx_line = fragp->fr_line;
18809
18810	      buf = write_insn (buf, insn);
18811
18812	      /* j(al)r $at.  */
18813	      if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18814		insn = 0x0000f809;
18815	      else
18816		insn = 0x00000008;
18817	      insn |= at << OP_SH_RS;
18818
18819	      buf = write_insn (buf, insn);
18820	    }
18821	}
18822
18823      fragp->fr_fix += fragp->fr_var;
18824      gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18825      return;
18826    }
18827
18828  /* Relax microMIPS branches.  */
18829  if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18830    {
18831      char *buf = fragp->fr_literal + fragp->fr_fix;
18832      bool compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18833      bool insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18834      bool nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18835      bool pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18836      bool al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18837      int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18838      bool short_ds;
18839      unsigned long insn;
18840      fixS *fixp;
18841
18842      fragp->fr_fix += fragp->fr_var;
18843
18844      /* Handle 16-bit branches that fit or are forced to fit.  */
18845      if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18846	{
18847	  /* We generate a fixup instead of applying it right now,
18848	     because if there is linker relaxation, we're going to
18849	     need the relocations.  */
18850	  switch (type)
18851	    {
18852	    case 'D':
18853	      fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18854			      fragp->fr_symbol, fragp->fr_offset,
18855			      true, BFD_RELOC_MICROMIPS_10_PCREL_S1);
18856	      break;
18857	    case 'E':
18858	      fixp = fix_new (fragp, buf - fragp->fr_literal, 2,
18859			      fragp->fr_symbol, fragp->fr_offset,
18860			      true, BFD_RELOC_MICROMIPS_7_PCREL_S1);
18861	      break;
18862	    default:
18863	      abort ();
18864	    }
18865
18866	  fixp->fx_file = fragp->fr_file;
18867	  fixp->fx_line = fragp->fr_line;
18868
18869	  /* These relocations can have an addend that won't fit in
18870	     2 octets.  */
18871	  fixp->fx_no_overflow = 1;
18872
18873	  return;
18874	}
18875
18876      /* Handle 32-bit branches that fit or are forced to fit.  */
18877      if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18878	  || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18879	{
18880	  /* We generate a fixup instead of applying it right now,
18881	     because if there is linker relaxation, we're going to
18882	     need the relocations.  */
18883	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18884			  fragp->fr_symbol, fragp->fr_offset,
18885			  true, BFD_RELOC_MICROMIPS_16_PCREL_S1);
18886	  fixp->fx_file = fragp->fr_file;
18887	  fixp->fx_line = fragp->fr_line;
18888
18889	  if (type == 0)
18890	    {
18891	      insn = read_compressed_insn (buf, 4);
18892	      buf += 4;
18893
18894	      if (nods)
18895		{
18896		  /* Check the short-delay-slot bit.  */
18897		  if (!al || (insn & 0x02000000) != 0)
18898		    buf = write_compressed_insn (buf, 0x0c00, 2);
18899		  else
18900		    buf = write_compressed_insn (buf, 0x00000000, 4);
18901		}
18902
18903	      gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18904	      return;
18905	    }
18906	}
18907
18908      /* Relax 16-bit branches to 32-bit branches.  */
18909      if (type != 0)
18910	{
18911	  insn = read_compressed_insn (buf, 2);
18912
18913	  if ((insn & 0xfc00) == 0xcc00)		/* b16  */
18914	    insn = 0x94000000;				/* beq  */
18915	  else if ((insn & 0xdc00) == 0x8c00)		/* beqz16/bnez16  */
18916	    {
18917	      unsigned long regno;
18918
18919	      regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18920	      regno = micromips_to_32_reg_d_map [regno];
18921	      insn = ((insn & 0x2000) << 16) | 0x94000000;	/* beq/bne  */
18922	      insn |= regno << MICROMIPSOP_SH_RS;
18923	    }
18924	  else
18925	    abort ();
18926
18927	  /* Nothing else to do, just write it out.  */
18928	  if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18929	      || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18930	    {
18931	      buf = write_compressed_insn (buf, insn, 4);
18932	      if (nods)
18933		buf = write_compressed_insn (buf, 0x0c00, 2);
18934	      gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18935	      return;
18936	    }
18937	}
18938      else
18939	insn = read_compressed_insn (buf, 4);
18940
18941      /* Relax 32-bit branches to a sequence of instructions.  */
18942      as_warn_where (fragp->fr_file, fragp->fr_line,
18943		     _("relaxed out-of-range branch into a jump"));
18944
18945      /* Set the short-delay-slot bit.  */
18946      short_ds = !al || (insn & 0x02000000) != 0;
18947
18948      if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18949	{
18950	  symbolS *l;
18951
18952	  /* Reverse the branch.  */
18953	  if ((insn & 0xfc000000) == 0x94000000			/* beq  */
18954	      || (insn & 0xfc000000) == 0xb4000000)		/* bne  */
18955	    insn ^= 0x20000000;
18956	  else if ((insn & 0xffe00000) == 0x40000000		/* bltz  */
18957		   || (insn & 0xffe00000) == 0x40400000		/* bgez  */
18958		   || (insn & 0xffe00000) == 0x40800000		/* blez  */
18959		   || (insn & 0xffe00000) == 0x40c00000		/* bgtz  */
18960		   || (insn & 0xffe00000) == 0x40a00000		/* bnezc  */
18961		   || (insn & 0xffe00000) == 0x40e00000		/* beqzc  */
18962		   || (insn & 0xffe00000) == 0x40200000		/* bltzal  */
18963		   || (insn & 0xffe00000) == 0x40600000		/* bgezal  */
18964		   || (insn & 0xffe00000) == 0x42200000		/* bltzals  */
18965		   || (insn & 0xffe00000) == 0x42600000)	/* bgezals  */
18966	    insn ^= 0x00400000;
18967	  else if ((insn & 0xffe30000) == 0x43800000		/* bc1f  */
18968		   || (insn & 0xffe30000) == 0x43a00000		/* bc1t  */
18969		   || (insn & 0xffe30000) == 0x42800000		/* bc2f  */
18970		   || (insn & 0xffe30000) == 0x42a00000)	/* bc2t  */
18971	    insn ^= 0x00200000;
18972	  else if ((insn & 0xff000000) == 0x83000000		/* BZ.df
18973								   BNZ.df  */
18974		    || (insn & 0xff600000) == 0x81600000)	/* BZ.V
18975								   BNZ.V */
18976	    insn ^= 0x00800000;
18977	  else
18978	    abort ();
18979
18980	  if (al)
18981	    {
18982	      /* Clear the and-link and short-delay-slot bits.  */
18983	      gas_assert ((insn & 0xfda00000) == 0x40200000);
18984
18985	      /* bltzal  0x40200000	bgezal  0x40600000  */
18986	      /* bltzals 0x42200000	bgezals 0x42600000  */
18987	      insn &= ~0x02200000;
18988	    }
18989
18990	  /* Make a label at the end for use with the branch.  */
18991	  l = symbol_new (micromips_label_name (), asec, fragp, fragp->fr_fix);
18992	  micromips_label_inc ();
18993	  S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18994
18995	  /* Refer to it.  */
18996	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, true,
18997			  BFD_RELOC_MICROMIPS_16_PCREL_S1);
18998	  fixp->fx_file = fragp->fr_file;
18999	  fixp->fx_line = fragp->fr_line;
19000
19001	  /* Branch over the jump.  */
19002	  buf = write_compressed_insn (buf, insn, 4);
19003
19004	  if (!compact)
19005	    {
19006	      /* nop  */
19007	      if (insn32)
19008		buf = write_compressed_insn (buf, 0x00000000, 4);
19009	      else
19010		buf = write_compressed_insn (buf, 0x0c00, 2);
19011	    }
19012	}
19013
19014      if (!pic)
19015	{
19016	  unsigned long jal = (short_ds || nods
19017			       ? 0x74000000 : 0xf4000000);	/* jal/s  */
19018
19019	  /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
19020	  insn = al ? jal : 0xd4000000;
19021
19022	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
19023			  fragp->fr_symbol, fragp->fr_offset,
19024			  false, BFD_RELOC_MICROMIPS_JMP);
19025	  fixp->fx_file = fragp->fr_file;
19026	  fixp->fx_line = fragp->fr_line;
19027
19028	  buf = write_compressed_insn (buf, insn, 4);
19029
19030	  if (compact || nods)
19031	    {
19032	      /* nop  */
19033	      if (insn32)
19034		buf = write_compressed_insn (buf, 0x00000000, 4);
19035	      else
19036		buf = write_compressed_insn (buf, 0x0c00, 2);
19037	    }
19038	}
19039      else
19040	{
19041	  unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
19042
19043	  /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
19044	  insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
19045	  insn |= at << MICROMIPSOP_SH_RT;
19046
19047	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
19048			  fragp->fr_symbol, fragp->fr_offset,
19049			  false, BFD_RELOC_MICROMIPS_GOT16);
19050	  fixp->fx_file = fragp->fr_file;
19051	  fixp->fx_line = fragp->fr_line;
19052
19053	  buf = write_compressed_insn (buf, insn, 4);
19054
19055	  /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
19056	  insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
19057	  insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
19058
19059	  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
19060			  fragp->fr_symbol, fragp->fr_offset,
19061			  false, BFD_RELOC_MICROMIPS_LO16);
19062	  fixp->fx_file = fragp->fr_file;
19063	  fixp->fx_line = fragp->fr_line;
19064
19065	  buf = write_compressed_insn (buf, insn, 4);
19066
19067	  if (insn32)
19068	    {
19069	      /* jr/jalr $at  */
19070	      insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
19071	      insn |= at << MICROMIPSOP_SH_RS;
19072
19073	      buf = write_compressed_insn (buf, insn, 4);
19074
19075	      if (compact || nods)
19076		/* nop  */
19077		buf = write_compressed_insn (buf, 0x00000000, 4);
19078	    }
19079	  else
19080	    {
19081	      /* jr/jrc/jalr/jalrs $at  */
19082	      unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;	/* jalr/s  */
19083	      unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
19084
19085	      insn = al ? jalr : jr;
19086	      insn |= at << MICROMIPSOP_SH_MJ;
19087
19088	      buf = write_compressed_insn (buf, insn, 2);
19089	      if (al && nods)
19090		{
19091		  /* nop  */
19092		  if (short_ds)
19093		    buf = write_compressed_insn (buf, 0x0c00, 2);
19094		  else
19095		    buf = write_compressed_insn (buf, 0x00000000, 4);
19096		}
19097	    }
19098	}
19099
19100      gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
19101      return;
19102    }
19103
19104  if (RELAX_MIPS16_P (fragp->fr_subtype))
19105    {
19106      int type;
19107      const struct mips_int_operand *operand;
19108      offsetT val;
19109      char *buf;
19110      unsigned int user_length;
19111      bool need_reloc;
19112      unsigned long insn;
19113      bool mac;
19114      bool ext;
19115      segT symsec;
19116
19117      type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
19118      operand = mips16_immed_operand (type, false);
19119
19120      mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
19121      ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
19122      val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
19123
19124      symsec = S_GET_SEGMENT (fragp->fr_symbol);
19125      need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, true)
19126		    || (operand->root.type == OP_PCREL && !mac
19127			? asec != symsec
19128			: !bfd_is_abs_section (symsec)));
19129
19130      if (operand->root.type == OP_PCREL && !mac)
19131	{
19132	  const struct mips_pcrel_operand *pcrel_op;
19133
19134	  pcrel_op = (const struct mips_pcrel_operand *) operand;
19135
19136	  if (pcrel_op->include_isa_bit && !need_reloc)
19137	    {
19138	      if (!mips_ignore_branch_isa
19139		  && !ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
19140		as_bad_where (fragp->fr_file, fragp->fr_line,
19141			      _("branch to a symbol in another ISA mode"));
19142	      else if ((fragp->fr_offset & 0x1) != 0)
19143		as_bad_where (fragp->fr_file, fragp->fr_line,
19144			      _("branch to misaligned address (0x%lx)"),
19145			      (long) (resolve_symbol_value (fragp->fr_symbol)
19146				      + (fragp->fr_offset & ~1)));
19147	    }
19148
19149	  val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
19150
19151	  /* Make sure the section winds up with the alignment we have
19152             assumed.  */
19153	  if (operand->shift > 0)
19154	    record_alignment (asec, operand->shift);
19155	}
19156
19157      if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
19158	  || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
19159	{
19160	  if (mac)
19161	    as_warn_where (fragp->fr_file, fragp->fr_line,
19162			   _("macro instruction expanded into multiple "
19163			     "instructions in a branch delay slot"));
19164	  else if (ext)
19165	    as_warn_where (fragp->fr_file, fragp->fr_line,
19166			   _("extended instruction in a branch delay slot"));
19167	}
19168      else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
19169	as_warn_where (fragp->fr_file, fragp->fr_line,
19170		       _("macro instruction expanded into multiple "
19171			 "instructions"));
19172
19173      buf = fragp->fr_literal + fragp->fr_fix;
19174
19175      insn = read_compressed_insn (buf, 2);
19176      if (ext)
19177	insn |= MIPS16_EXTEND;
19178
19179      if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
19180	user_length = 4;
19181      else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
19182	user_length = 2;
19183      else
19184	user_length = 0;
19185
19186      if (mac)
19187	{
19188	  unsigned long reg;
19189	  unsigned long new;
19190	  unsigned long op;
19191	  bool e2;
19192
19193	  gas_assert (type == 'A' || type == 'B' || type == 'E');
19194	  gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
19195
19196	  e2 = RELAX_MIPS16_E2 (fragp->fr_subtype);
19197
19198	  if (need_reloc)
19199	    {
19200	      fixS *fixp;
19201
19202	      gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
19203
19204	      fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
19205			      fragp->fr_symbol, fragp->fr_offset,
19206			      false, BFD_RELOC_MIPS16_HI16_S);
19207	      fixp->fx_file = fragp->fr_file;
19208	      fixp->fx_line = fragp->fr_line;
19209
19210	      fixp = fix_new (fragp, buf - fragp->fr_literal + (e2 ? 4 : 8), 4,
19211			      fragp->fr_symbol, fragp->fr_offset,
19212			      false, BFD_RELOC_MIPS16_LO16);
19213	      fixp->fx_file = fragp->fr_file;
19214	      fixp->fx_line = fragp->fr_line;
19215
19216	      val = 0;
19217	    }
19218
19219	  switch (insn & 0xf800)
19220	    {
19221	    case 0x0800:					/* ADDIU */
19222	      reg = (insn >> 8) & 0x7;
19223	      op = 0xf0004800 | (reg << 8);
19224	      break;
19225	    case 0xb000:					/* LW */
19226	      reg = (insn >> 8) & 0x7;
19227	      op = 0xf0009800 | (reg << 8) | (reg << 5);
19228	      break;
19229	    case 0xf800:					/* I64 */
19230	      reg = (insn >> 5) & 0x7;
19231	      switch (insn & 0x0700)
19232		{
19233		case 0x0400:					/* LD */
19234		  op = 0xf0003800 | (reg << 8) | (reg << 5);
19235		  break;
19236		case 0x0600:					/* DADDIU */
19237		  op = 0xf000fd00 | (reg << 5);
19238		  break;
19239		default:
19240		  abort ();
19241		}
19242	      break;
19243	    default:
19244	      abort ();
19245	    }
19246
19247	  new = (e2 ? 0xf0006820 : 0xf0006800) | (reg << 8);	/* LUI/LI */
19248	  new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
19249	  buf = write_compressed_insn (buf, new, 4);
19250	  if (!e2)
19251	    {
19252	      new = 0xf4003000 | (reg << 8) | (reg << 5);	/* SLL */
19253	      buf = write_compressed_insn (buf, new, 4);
19254	    }
19255	  op |= mips16_immed_extend (val, 16);
19256	  buf = write_compressed_insn (buf, op, 4);
19257
19258	  fragp->fr_fix += e2 ? 8 : 12;
19259	}
19260      else
19261	{
19262	  unsigned int length = ext ? 4 : 2;
19263
19264	  if (need_reloc)
19265	    {
19266	      bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
19267	      fixS *fixp;
19268
19269	      switch (type)
19270		{
19271		case 'p':
19272		case 'q':
19273		  reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
19274		  break;
19275		default:
19276		  break;
19277		}
19278	      if (mac || reloc == BFD_RELOC_NONE)
19279		as_bad_where (fragp->fr_file, fragp->fr_line,
19280			      _("unsupported relocation"));
19281	      else if (ext)
19282		{
19283		  fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
19284				  fragp->fr_symbol, fragp->fr_offset,
19285				  true, reloc);
19286		  fixp->fx_file = fragp->fr_file;
19287		  fixp->fx_line = fragp->fr_line;
19288		}
19289	      else
19290		as_bad_where (fragp->fr_file, fragp->fr_line,
19291			      _("invalid unextended operand value"));
19292	    }
19293	  else
19294	    mips16_immed (fragp->fr_file, fragp->fr_line, type,
19295			  BFD_RELOC_UNUSED, val, user_length, &insn);
19296
19297	  gas_assert (mips16_opcode_length (insn) == length);
19298	  write_compressed_insn (buf, insn, length);
19299	  fragp->fr_fix += length;
19300	}
19301    }
19302  else
19303    {
19304      relax_substateT subtype = fragp->fr_subtype;
19305      bool second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
19306      bool use_second = (subtype & RELAX_USE_SECOND) != 0;
19307      unsigned int first, second;
19308      fixS *fixp;
19309
19310      first = RELAX_FIRST (subtype);
19311      second = RELAX_SECOND (subtype);
19312      fixp = (fixS *) fragp->fr_opcode;
19313
19314      /* If the delay slot chosen does not match the size of the instruction,
19315         then emit a warning.  */
19316      if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
19317	   || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
19318	{
19319	  relax_substateT s;
19320	  const char *msg;
19321
19322	  s = subtype & (RELAX_DELAY_SLOT_16BIT
19323			 | RELAX_DELAY_SLOT_SIZE_FIRST
19324			 | RELAX_DELAY_SLOT_SIZE_SECOND);
19325	  msg = macro_warning (s);
19326	  if (msg != NULL)
19327	    as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
19328	  subtype &= ~s;
19329	}
19330
19331      /* Possibly emit a warning if we've chosen the longer option.  */
19332      if (use_second == second_longer)
19333	{
19334	  relax_substateT s;
19335	  const char *msg;
19336
19337	  s = (subtype
19338	       & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
19339	  msg = macro_warning (s);
19340	  if (msg != NULL)
19341	    as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
19342	  subtype &= ~s;
19343	}
19344
19345      /* Go through all the fixups for the first sequence.  Disable them
19346	 (by marking them as done) if we're going to use the second
19347	 sequence instead.  */
19348      while (fixp
19349	     && fixp->fx_frag == fragp
19350	     && fixp->fx_where + second < fragp->fr_fix)
19351	{
19352	  if (subtype & RELAX_USE_SECOND)
19353	    fixp->fx_done = 1;
19354	  fixp = fixp->fx_next;
19355	}
19356
19357      /* Go through the fixups for the second sequence.  Disable them if
19358	 we're going to use the first sequence, otherwise adjust their
19359	 addresses to account for the relaxation.  */
19360      while (fixp && fixp->fx_frag == fragp)
19361	{
19362	  if (subtype & RELAX_USE_SECOND)
19363	    fixp->fx_where -= first;
19364	  else
19365	    fixp->fx_done = 1;
19366	  fixp = fixp->fx_next;
19367	}
19368
19369      /* Now modify the frag contents.  */
19370      if (subtype & RELAX_USE_SECOND)
19371	{
19372	  char *start;
19373
19374	  start = fragp->fr_literal + fragp->fr_fix - first - second;
19375	  memmove (start, start + first, second);
19376	  fragp->fr_fix -= first;
19377	}
19378      else
19379	fragp->fr_fix -= second;
19380    }
19381}
19382
19383/* This function is called after the relocs have been generated.
19384   We've been storing mips16 text labels as odd.  Here we convert them
19385   back to even for the convenience of the debugger.  */
19386
19387void
19388mips_frob_file_after_relocs (void)
19389{
19390  asymbol **syms;
19391  unsigned int count, i;
19392
19393  syms = bfd_get_outsymbols (stdoutput);
19394  count = bfd_get_symcount (stdoutput);
19395  for (i = 0; i < count; i++, syms++)
19396    if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
19397	&& ((*syms)->value & 1) != 0)
19398      {
19399	(*syms)->value &= ~1;
19400	/* If the symbol has an odd size, it was probably computed
19401	   incorrectly, so adjust that as well.  */
19402	if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
19403	  ++elf_symbol (*syms)->internal_elf_sym.st_size;
19404      }
19405}
19406
19407/* This function is called whenever a label is defined, including fake
19408   labels instantiated off the dot special symbol.  It is used when
19409   handling branch delays; if a branch has a label, we assume we cannot
19410   move it.  This also bumps the value of the symbol by 1 in compressed
19411   code.  */
19412
19413static void
19414mips_record_label (symbolS *sym)
19415{
19416  segment_info_type *si = seg_info (now_seg);
19417  struct insn_label_list *l;
19418
19419  if (free_insn_labels == NULL)
19420    l = XNEW (struct insn_label_list);
19421  else
19422    {
19423      l = free_insn_labels;
19424      free_insn_labels = l->next;
19425    }
19426
19427  l->label = sym;
19428  l->next = si->label_list;
19429  si->label_list = l;
19430}
19431
19432/* This function is called as tc_frob_label() whenever a label is defined
19433   and adds a DWARF-2 record we only want for true labels.  */
19434
19435void
19436mips_define_label (symbolS *sym)
19437{
19438  mips_record_label (sym);
19439  dwarf2_emit_label (sym);
19440}
19441
19442/* This function is called by tc_new_dot_label whenever a new dot symbol
19443   is defined.  */
19444
19445void
19446mips_add_dot_label (symbolS *sym)
19447{
19448  mips_record_label (sym);
19449  if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
19450    mips_compressed_mark_label (sym);
19451}
19452
19453/* Converting ASE flags from internal to .MIPS.abiflags values.  */
19454static unsigned int
19455mips_convert_ase_flags (int ase)
19456{
19457  unsigned int ext_ases = 0;
19458
19459  if (ase & ASE_DSP)
19460    ext_ases |= AFL_ASE_DSP;
19461  if (ase & ASE_DSPR2)
19462    ext_ases |= AFL_ASE_DSPR2;
19463  if (ase & ASE_DSPR3)
19464    ext_ases |= AFL_ASE_DSPR3;
19465  if (ase & ASE_EVA)
19466    ext_ases |= AFL_ASE_EVA;
19467  if (ase & ASE_MCU)
19468    ext_ases |= AFL_ASE_MCU;
19469  if (ase & ASE_MDMX)
19470    ext_ases |= AFL_ASE_MDMX;
19471  if (ase & ASE_MIPS3D)
19472    ext_ases |= AFL_ASE_MIPS3D;
19473  if (ase & ASE_MT)
19474    ext_ases |= AFL_ASE_MT;
19475  if (ase & ASE_SMARTMIPS)
19476    ext_ases |= AFL_ASE_SMARTMIPS;
19477  if (ase & ASE_VIRT)
19478    ext_ases |= AFL_ASE_VIRT;
19479  if (ase & ASE_MSA)
19480    ext_ases |= AFL_ASE_MSA;
19481  if (ase & ASE_XPA)
19482    ext_ases |= AFL_ASE_XPA;
19483  if (ase & ASE_MIPS16E2)
19484    ext_ases |= file_ase_mips16 ? AFL_ASE_MIPS16E2 : 0;
19485  if (ase & ASE_CRC)
19486    ext_ases |= AFL_ASE_CRC;
19487  if (ase & ASE_GINV)
19488    ext_ases |= AFL_ASE_GINV;
19489  if (ase & ASE_LOONGSON_MMI)
19490    ext_ases |= AFL_ASE_LOONGSON_MMI;
19491  if (ase & ASE_LOONGSON_CAM)
19492    ext_ases |= AFL_ASE_LOONGSON_CAM;
19493  if (ase & ASE_LOONGSON_EXT)
19494    ext_ases |= AFL_ASE_LOONGSON_EXT;
19495  if (ase & ASE_LOONGSON_EXT2)
19496    ext_ases |= AFL_ASE_LOONGSON_EXT2;
19497
19498  return ext_ases;
19499}
19500/* Some special processing for a MIPS ELF file.  */
19501
19502void
19503mips_elf_final_processing (void)
19504{
19505  int fpabi;
19506  Elf_Internal_ABIFlags_v0 flags;
19507
19508  flags.version = 0;
19509  flags.isa_rev = 0;
19510  switch (file_mips_opts.isa)
19511    {
19512    case INSN_ISA1:
19513      flags.isa_level = 1;
19514      break;
19515    case INSN_ISA2:
19516      flags.isa_level = 2;
19517      break;
19518    case INSN_ISA3:
19519      flags.isa_level = 3;
19520      break;
19521    case INSN_ISA4:
19522      flags.isa_level = 4;
19523      break;
19524    case INSN_ISA5:
19525      flags.isa_level = 5;
19526      break;
19527    case INSN_ISA32:
19528      flags.isa_level = 32;
19529      flags.isa_rev = 1;
19530      break;
19531    case INSN_ISA32R2:
19532      flags.isa_level = 32;
19533      flags.isa_rev = 2;
19534      break;
19535    case INSN_ISA32R3:
19536      flags.isa_level = 32;
19537      flags.isa_rev = 3;
19538      break;
19539    case INSN_ISA32R5:
19540      flags.isa_level = 32;
19541      flags.isa_rev = 5;
19542      break;
19543    case INSN_ISA32R6:
19544      flags.isa_level = 32;
19545      flags.isa_rev = 6;
19546      break;
19547    case INSN_ISA64:
19548      flags.isa_level = 64;
19549      flags.isa_rev = 1;
19550      break;
19551    case INSN_ISA64R2:
19552      flags.isa_level = 64;
19553      flags.isa_rev = 2;
19554      break;
19555    case INSN_ISA64R3:
19556      flags.isa_level = 64;
19557      flags.isa_rev = 3;
19558      break;
19559    case INSN_ISA64R5:
19560      flags.isa_level = 64;
19561      flags.isa_rev = 5;
19562      break;
19563    case INSN_ISA64R6:
19564      flags.isa_level = 64;
19565      flags.isa_rev = 6;
19566      break;
19567    }
19568
19569  flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
19570  flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
19571		    : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
19572		    : (file_mips_opts.fp == 64) ? AFL_REG_64
19573		    : AFL_REG_32;
19574  flags.cpr2_size = AFL_REG_NONE;
19575  flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19576                                           Tag_GNU_MIPS_ABI_FP);
19577  flags.isa_ext = bfd_mips_isa_ext (stdoutput);
19578  flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
19579  if (file_ase_mips16)
19580    flags.ases |= AFL_ASE_MIPS16;
19581  if (file_ase_micromips)
19582    flags.ases |= AFL_ASE_MICROMIPS;
19583  flags.flags1 = 0;
19584  if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
19585       || file_mips_opts.fp == 64)
19586      && file_mips_opts.oddspreg)
19587    flags.flags1 |= AFL_FLAGS1_ODDSPREG;
19588  flags.flags2 = 0;
19589
19590  bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
19591				     ((Elf_External_ABIFlags_v0 *)
19592				     mips_flags_frag));
19593
19594  /* Write out the register information.  */
19595  if (mips_abi != N64_ABI)
19596    {
19597      Elf32_RegInfo s;
19598
19599      s.ri_gprmask = mips_gprmask;
19600      s.ri_cprmask[0] = mips_cprmask[0];
19601      s.ri_cprmask[1] = mips_cprmask[1];
19602      s.ri_cprmask[2] = mips_cprmask[2];
19603      s.ri_cprmask[3] = mips_cprmask[3];
19604      /* The gp_value field is set by the MIPS ELF backend.  */
19605
19606      bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
19607				       ((Elf32_External_RegInfo *)
19608					mips_regmask_frag));
19609    }
19610  else
19611    {
19612      Elf64_Internal_RegInfo s;
19613
19614      s.ri_gprmask = mips_gprmask;
19615      s.ri_pad = 0;
19616      s.ri_cprmask[0] = mips_cprmask[0];
19617      s.ri_cprmask[1] = mips_cprmask[1];
19618      s.ri_cprmask[2] = mips_cprmask[2];
19619      s.ri_cprmask[3] = mips_cprmask[3];
19620      /* The gp_value field is set by the MIPS ELF backend.  */
19621
19622      bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
19623				       ((Elf64_External_RegInfo *)
19624					mips_regmask_frag));
19625    }
19626
19627  /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
19628     sort of BFD interface for this.  */
19629  if (mips_any_noreorder)
19630    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
19631  if (mips_pic != NO_PIC)
19632    {
19633      elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19634      elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19635    }
19636  if (mips_abicalls)
19637    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19638
19639  /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19640     defined at present; this might need to change in future.  */
19641  if (file_ase_mips16)
19642    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19643  if (file_ase_micromips)
19644    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19645  if (file_mips_opts.ase & ASE_MDMX)
19646    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19647
19648  /* Set the MIPS ELF ABI flags.  */
19649  if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19650    elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19651  else if (mips_abi == O64_ABI)
19652    elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19653  else if (mips_abi == EABI_ABI)
19654    {
19655      if (file_mips_opts.gp == 64)
19656	elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19657      else
19658	elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19659    }
19660
19661  /* Nothing to do for N32_ABI or N64_ABI.  */
19662
19663  if (mips_32bitmode)
19664    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19665
19666  if (mips_nan2008 == 1)
19667    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19668
19669  /* 32 bit code with 64 bit FP registers.  */
19670  fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19671				    Tag_GNU_MIPS_ABI_FP);
19672  if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19673    elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19674}
19675
19676typedef struct proc {
19677  symbolS *func_sym;
19678  symbolS *func_end_sym;
19679  unsigned long reg_mask;
19680  unsigned long reg_offset;
19681  unsigned long fpreg_mask;
19682  unsigned long fpreg_offset;
19683  unsigned long frame_offset;
19684  unsigned long frame_reg;
19685  unsigned long pc_reg;
19686} procS;
19687
19688static procS cur_proc;
19689static procS *cur_proc_ptr;
19690static int numprocs;
19691
19692/* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19693   as "2", and a normal nop as "0".  */
19694
19695#define NOP_OPCODE_MIPS		0
19696#define NOP_OPCODE_MIPS16	1
19697#define NOP_OPCODE_MICROMIPS	2
19698
19699char
19700mips_nop_opcode (void)
19701{
19702  if (seg_info (now_seg)->tc_segment_info_data.micromips)
19703    return NOP_OPCODE_MICROMIPS;
19704  else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19705    return NOP_OPCODE_MIPS16;
19706  else
19707    return NOP_OPCODE_MIPS;
19708}
19709
19710/* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19711   32-bit microMIPS NOPs here (if applicable).  */
19712
19713void
19714mips_handle_align (fragS *fragp)
19715{
19716  char nop_opcode;
19717  char *p;
19718  int bytes, size, excess;
19719  valueT opcode;
19720
19721  if (fragp->fr_type != rs_align_code)
19722    return;
19723
19724  p = fragp->fr_literal + fragp->fr_fix;
19725  nop_opcode = *p;
19726  switch (nop_opcode)
19727    {
19728    case NOP_OPCODE_MICROMIPS:
19729      opcode = micromips_nop32_insn.insn_opcode;
19730      size = 4;
19731      break;
19732    case NOP_OPCODE_MIPS16:
19733      opcode = mips16_nop_insn.insn_opcode;
19734      size = 2;
19735      break;
19736    case NOP_OPCODE_MIPS:
19737    default:
19738      opcode = nop_insn.insn_opcode;
19739      size = 4;
19740      break;
19741    }
19742
19743  bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19744  excess = bytes % size;
19745
19746  /* Handle the leading part if we're not inserting a whole number of
19747     instructions, and make it the end of the fixed part of the frag.
19748     Try to fit in a short microMIPS NOP if applicable and possible,
19749     and use zeroes otherwise.  */
19750  gas_assert (excess < 4);
19751  fragp->fr_fix += excess;
19752  switch (excess)
19753    {
19754    case 3:
19755      *p++ = '\0';
19756      /* Fall through.  */
19757    case 2:
19758      if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19759	{
19760	  p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19761	  break;
19762	}
19763      *p++ = '\0';
19764      /* Fall through.  */
19765    case 1:
19766      *p++ = '\0';
19767      /* Fall through.  */
19768    case 0:
19769      break;
19770    }
19771
19772  md_number_to_chars (p, opcode, size);
19773  fragp->fr_var = size;
19774}
19775
19776static long
19777get_number (void)
19778{
19779  int negative = 0;
19780  long val = 0;
19781
19782  if (*input_line_pointer == '-')
19783    {
19784      ++input_line_pointer;
19785      negative = 1;
19786    }
19787  if (!ISDIGIT (*input_line_pointer))
19788    as_bad (_("expected simple number"));
19789  if (input_line_pointer[0] == '0')
19790    {
19791      if (input_line_pointer[1] == 'x')
19792	{
19793	  input_line_pointer += 2;
19794	  while (ISXDIGIT (*input_line_pointer))
19795	    {
19796	      val <<= 4;
19797	      val |= hex_value (*input_line_pointer++);
19798	    }
19799	  return negative ? -val : val;
19800	}
19801      else
19802	{
19803	  ++input_line_pointer;
19804	  while (ISDIGIT (*input_line_pointer))
19805	    {
19806	      val <<= 3;
19807	      val |= *input_line_pointer++ - '0';
19808	    }
19809	  return negative ? -val : val;
19810	}
19811    }
19812  if (!ISDIGIT (*input_line_pointer))
19813    {
19814      printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19815	      *input_line_pointer, *input_line_pointer);
19816      as_warn (_("invalid number"));
19817      return -1;
19818    }
19819  while (ISDIGIT (*input_line_pointer))
19820    {
19821      val *= 10;
19822      val += *input_line_pointer++ - '0';
19823    }
19824  return negative ? -val : val;
19825}
19826
19827/* The .file directive; just like the usual .file directive, but there
19828   is an initial number which is the ECOFF file index.  In the non-ECOFF
19829   case .file implies DWARF-2.  */
19830
19831static void
19832s_mips_file (int x ATTRIBUTE_UNUSED)
19833{
19834  static int first_file_directive = 0;
19835
19836  if (ECOFF_DEBUGGING)
19837    {
19838      get_number ();
19839      s_file (0);
19840    }
19841  else
19842    {
19843      char *filename;
19844
19845      filename = dwarf2_directive_filename ();
19846
19847      /* Versions of GCC up to 3.1 start files with a ".file"
19848	 directive even for stabs output.  Make sure that this
19849	 ".file" is handled.  Note that you need a version of GCC
19850         after 3.1 in order to support DWARF-2 on MIPS.  */
19851      if (filename != NULL && ! first_file_directive)
19852	{
19853	  new_logical_line (filename, -1);
19854	  s_file_string (filename);
19855	}
19856      first_file_directive = 1;
19857    }
19858}
19859
19860/* The .loc directive, implying DWARF-2.  */
19861
19862static void
19863s_mips_loc (int x ATTRIBUTE_UNUSED)
19864{
19865  if (!ECOFF_DEBUGGING)
19866    dwarf2_directive_loc (0);
19867}
19868
19869/* The .end directive.  */
19870
19871static void
19872s_mips_end (int x ATTRIBUTE_UNUSED)
19873{
19874  symbolS *p;
19875
19876  /* Following functions need their own .frame and .cprestore directives.  */
19877  mips_frame_reg_valid = 0;
19878  mips_cprestore_valid = 0;
19879
19880  if (!is_end_of_line[(unsigned char) *input_line_pointer])
19881    {
19882      p = get_symbol ();
19883      demand_empty_rest_of_line ();
19884    }
19885  else
19886    p = NULL;
19887
19888  if ((bfd_section_flags (now_seg) & SEC_CODE) == 0)
19889    as_warn (_(".end not in text section"));
19890
19891  if (!cur_proc_ptr)
19892    {
19893      as_warn (_(".end directive without a preceding .ent directive"));
19894      demand_empty_rest_of_line ();
19895      return;
19896    }
19897
19898  if (p != NULL)
19899    {
19900      gas_assert (S_GET_NAME (p));
19901      if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19902	as_warn (_(".end symbol does not match .ent symbol"));
19903
19904      if (debug_type == DEBUG_STABS)
19905	stabs_generate_asm_endfunc (S_GET_NAME (p),
19906				    S_GET_NAME (p));
19907    }
19908  else
19909    as_warn (_(".end directive missing or unknown symbol"));
19910
19911  /* Create an expression to calculate the size of the function.  */
19912  if (p && cur_proc_ptr)
19913    {
19914      OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19915      expressionS *exp = XNEW (expressionS);
19916
19917      obj->size = exp;
19918      exp->X_op = O_subtract;
19919      exp->X_add_symbol = symbol_temp_new_now ();
19920      exp->X_op_symbol = p;
19921      exp->X_add_number = 0;
19922
19923      cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19924    }
19925
19926#ifdef md_flush_pending_output
19927  md_flush_pending_output ();
19928#endif
19929
19930  /* Generate a .pdr section.  */
19931  if (!ECOFF_DEBUGGING && mips_flag_pdr)
19932    {
19933      segT saved_seg = now_seg;
19934      subsegT saved_subseg = now_subseg;
19935      expressionS exp;
19936      char *fragp;
19937
19938      gas_assert (pdr_seg);
19939      subseg_set (pdr_seg, 0);
19940
19941      /* Write the symbol.  */
19942      exp.X_op = O_symbol;
19943      exp.X_add_symbol = p;
19944      exp.X_add_number = 0;
19945      emit_expr (&exp, 4);
19946
19947      fragp = frag_more (7 * 4);
19948
19949      md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19950      md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19951      md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19952      md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19953      md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19954      md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19955      md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19956
19957      subseg_set (saved_seg, saved_subseg);
19958    }
19959
19960  cur_proc_ptr = NULL;
19961}
19962
19963/* The .aent and .ent directives.  */
19964
19965static void
19966s_mips_ent (int aent)
19967{
19968  symbolS *symbolP;
19969
19970  symbolP = get_symbol ();
19971  if (*input_line_pointer == ',')
19972    ++input_line_pointer;
19973  SKIP_WHITESPACE ();
19974  if (ISDIGIT (*input_line_pointer)
19975      || *input_line_pointer == '-')
19976    get_number ();
19977
19978  if ((bfd_section_flags (now_seg) & SEC_CODE) == 0)
19979    as_warn (_(".ent or .aent not in text section"));
19980
19981  if (!aent && cur_proc_ptr)
19982    as_warn (_("missing .end"));
19983
19984  if (!aent)
19985    {
19986      /* This function needs its own .frame and .cprestore directives.  */
19987      mips_frame_reg_valid = 0;
19988      mips_cprestore_valid = 0;
19989
19990      cur_proc_ptr = &cur_proc;
19991      memset (cur_proc_ptr, '\0', sizeof (procS));
19992
19993      cur_proc_ptr->func_sym = symbolP;
19994
19995      ++numprocs;
19996
19997      if (debug_type == DEBUG_STABS)
19998        stabs_generate_asm_func (S_GET_NAME (symbolP),
19999				 S_GET_NAME (symbolP));
20000    }
20001
20002  symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
20003
20004  demand_empty_rest_of_line ();
20005}
20006
20007/* The .frame directive. If the mdebug section is present (IRIX 5 native)
20008   then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
20009   s_mips_frame is used so that we can set the PDR information correctly.
20010   We can't use the ecoff routines because they make reference to the ecoff
20011   symbol table (in the mdebug section).  */
20012
20013static void
20014s_mips_frame (int ignore ATTRIBUTE_UNUSED)
20015{
20016  if (ECOFF_DEBUGGING)
20017    s_ignore (ignore);
20018  else
20019    {
20020      long val;
20021
20022      if (cur_proc_ptr == (procS *) NULL)
20023	{
20024	  as_warn (_(".frame outside of .ent"));
20025	  demand_empty_rest_of_line ();
20026	  return;
20027	}
20028
20029      cur_proc_ptr->frame_reg = tc_get_register (1);
20030
20031      SKIP_WHITESPACE ();
20032      if (*input_line_pointer++ != ','
20033	  || get_absolute_expression_and_terminator (&val) != ',')
20034	{
20035	  as_warn (_("bad .frame directive"));
20036	  --input_line_pointer;
20037	  demand_empty_rest_of_line ();
20038	  return;
20039	}
20040
20041      cur_proc_ptr->frame_offset = val;
20042      cur_proc_ptr->pc_reg = tc_get_register (0);
20043
20044      demand_empty_rest_of_line ();
20045    }
20046}
20047
20048/* The .fmask and .mask directives. If the mdebug section is present
20049   (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
20050   embedded targets, s_mips_mask is used so that we can set the PDR
20051   information correctly. We can't use the ecoff routines because they
20052   make reference to the ecoff symbol table (in the mdebug section).  */
20053
20054static void
20055s_mips_mask (int reg_type)
20056{
20057  if (ECOFF_DEBUGGING)
20058    s_ignore (reg_type);
20059  else
20060    {
20061      long mask, off;
20062
20063      if (cur_proc_ptr == (procS *) NULL)
20064	{
20065	  as_warn (_(".mask/.fmask outside of .ent"));
20066	  demand_empty_rest_of_line ();
20067	  return;
20068	}
20069
20070      if (get_absolute_expression_and_terminator (&mask) != ',')
20071	{
20072	  as_warn (_("bad .mask/.fmask directive"));
20073	  --input_line_pointer;
20074	  demand_empty_rest_of_line ();
20075	  return;
20076	}
20077
20078      off = get_absolute_expression ();
20079
20080      if (reg_type == 'F')
20081	{
20082	  cur_proc_ptr->fpreg_mask = mask;
20083	  cur_proc_ptr->fpreg_offset = off;
20084	}
20085      else
20086	{
20087	  cur_proc_ptr->reg_mask = mask;
20088	  cur_proc_ptr->reg_offset = off;
20089	}
20090
20091      demand_empty_rest_of_line ();
20092    }
20093}
20094
20095/* A table describing all the processors gas knows about.  Names are
20096   matched in the order listed.
20097
20098   To ease comparison, please keep this table in the same order as
20099   gcc's mips_cpu_info_table[].  */
20100static const struct mips_cpu_info mips_cpu_info_table[] =
20101{
20102  /* Entries for generic ISAs.  */
20103  { "mips1",          MIPS_CPU_IS_ISA, 0,	ISA_MIPS1,    CPU_R3000 },
20104  { "mips2",          MIPS_CPU_IS_ISA, 0,	ISA_MIPS2,    CPU_R6000 },
20105  { "mips3",          MIPS_CPU_IS_ISA, 0,	ISA_MIPS3,    CPU_R4000 },
20106  { "mips4",          MIPS_CPU_IS_ISA, 0,	ISA_MIPS4,    CPU_R8000 },
20107  { "mips5",          MIPS_CPU_IS_ISA, 0,	ISA_MIPS5,    CPU_MIPS5 },
20108  { "mips32",         MIPS_CPU_IS_ISA, 0,	ISA_MIPS32,   CPU_MIPS32 },
20109  { "mips32r2",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS32R2, CPU_MIPS32R2 },
20110  { "mips32r3",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS32R3, CPU_MIPS32R3 },
20111  { "mips32r5",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS32R5, CPU_MIPS32R5 },
20112  { "mips32r6",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS32R6, CPU_MIPS32R6 },
20113  { "mips64",         MIPS_CPU_IS_ISA, 0,	ISA_MIPS64,   CPU_MIPS64 },
20114  { "mips64r2",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS64R2, CPU_MIPS64R2 },
20115  { "mips64r3",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS64R3, CPU_MIPS64R3 },
20116  { "mips64r5",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS64R5, CPU_MIPS64R5 },
20117  { "mips64r6",       MIPS_CPU_IS_ISA, 0,	ISA_MIPS64R6, CPU_MIPS64R6 },
20118
20119  /* MIPS I */
20120  { "r3000",          0, 0,			ISA_MIPS1,    CPU_R3000 },
20121  { "r2000",          0, 0,			ISA_MIPS1,    CPU_R3000 },
20122  { "r3900",          0, 0,			ISA_MIPS1,    CPU_R3900 },
20123
20124  /* MIPS II */
20125  { "r6000",          0, 0,			ISA_MIPS2,    CPU_R6000 },
20126
20127  /* MIPS III */
20128  { "r4000",          0, 0,			ISA_MIPS3,    CPU_R4000 },
20129  { "r4010",          0, 0,			ISA_MIPS2,    CPU_R4010 },
20130  { "vr4100",         0, 0,			ISA_MIPS3,    CPU_VR4100 },
20131  { "vr4111",         0, 0,			ISA_MIPS3,    CPU_R4111 },
20132  { "vr4120",         0, 0,			ISA_MIPS3,    CPU_VR4120 },
20133  { "vr4130",         0, 0,			ISA_MIPS3,    CPU_VR4120 },
20134  { "vr4181",         0, 0,			ISA_MIPS3,    CPU_R4111 },
20135  { "vr4300",         0, 0,			ISA_MIPS3,    CPU_R4300 },
20136  { "r4400",          0, 0,			ISA_MIPS3,    CPU_R4400 },
20137  { "r4600",          0, 0,			ISA_MIPS3,    CPU_R4600 },
20138  { "orion",          0, 0,			ISA_MIPS3,    CPU_R4600 },
20139  { "r4650",          0, 0,			ISA_MIPS3,    CPU_R4650 },
20140  { "r5900",          0, 0,			ISA_MIPS3,    CPU_R5900 },
20141  /* ST Microelectronics Loongson 2E and 2F cores.  */
20142  { "loongson2e",     0, 0,			ISA_MIPS3,    CPU_LOONGSON_2E },
20143  { "loongson2f",     0, ASE_LOONGSON_MMI,	ISA_MIPS3,    CPU_LOONGSON_2F },
20144
20145  /* MIPS IV */
20146  { "r8000",          0, 0,			ISA_MIPS4,    CPU_R8000 },
20147  { "r10000",         0, 0,			ISA_MIPS4,    CPU_R10000 },
20148  { "r12000",         0, 0,			ISA_MIPS4,    CPU_R12000 },
20149  { "r14000",         0, 0,			ISA_MIPS4,    CPU_R14000 },
20150  { "r16000",         0, 0,			ISA_MIPS4,    CPU_R16000 },
20151  { "vr5000",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20152  { "vr5400",         0, 0,			ISA_MIPS4,    CPU_VR5400 },
20153  { "vr5500",         0, 0,			ISA_MIPS4,    CPU_VR5500 },
20154  { "rm5200",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20155  { "rm5230",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20156  { "rm5231",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20157  { "rm5261",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20158  { "rm5721",         0, 0,			ISA_MIPS4,    CPU_R5000 },
20159  { "rm7000",         0, 0,			ISA_MIPS4,    CPU_RM7000 },
20160  { "rm9000",         0, 0,			ISA_MIPS4,    CPU_RM9000 },
20161
20162  /* MIPS 32 */
20163  { "4kc",            0, 0,			ISA_MIPS32,   CPU_MIPS32 },
20164  { "4km",            0, 0,			ISA_MIPS32,   CPU_MIPS32 },
20165  { "4kp",            0, 0,			ISA_MIPS32,   CPU_MIPS32 },
20166  { "4ksc",           0, ASE_SMARTMIPS,		ISA_MIPS32,   CPU_MIPS32 },
20167
20168  /* MIPS 32 Release 2 */
20169  { "4kec",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20170  { "4kem",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20171  { "4kep",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20172  { "4ksd",           0, ASE_SMARTMIPS,		ISA_MIPS32R2, CPU_MIPS32R2 },
20173  { "m4k",            0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20174  { "m4kp",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20175  { "m14k",           0, ASE_MCU,		ISA_MIPS32R2, CPU_MIPS32R2 },
20176  { "m14kc",          0, ASE_MCU,		ISA_MIPS32R2, CPU_MIPS32R2 },
20177  { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
20178						ISA_MIPS32R2, CPU_MIPS32R2 },
20179  { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
20180						ISA_MIPS32R2, CPU_MIPS32R2 },
20181  { "24kc",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20182  { "24kf2_1",        0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20183  { "24kf",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20184  { "24kf1_1",        0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20185  /* Deprecated forms of the above.  */
20186  { "24kfx",          0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20187  { "24kx",           0, 0,			ISA_MIPS32R2, CPU_MIPS32R2 },
20188  /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
20189  { "24kec",          0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20190  { "24kef2_1",       0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20191  { "24kef",          0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20192  { "24kef1_1",       0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20193  /* Deprecated forms of the above.  */
20194  { "24kefx",         0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20195  { "24kex",          0, ASE_DSP,		ISA_MIPS32R2, CPU_MIPS32R2 },
20196  /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
20197  { "34kc",           0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20198  { "34kf2_1",        0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20199  { "34kf",           0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20200  { "34kf1_1",        0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20201  /* Deprecated forms of the above.  */
20202  { "34kfx",          0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20203  { "34kx",           0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20204  /* 34Kn is a 34kc without DSP.  */
20205  { "34kn",           0, ASE_MT,		ISA_MIPS32R2, CPU_MIPS32R2 },
20206  /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
20207  { "74kc",           0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20208  { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20209  { "74kf",           0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20210  { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20211  { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20212  /* Deprecated forms of the above.  */
20213  { "74kfx",          0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20214  { "74kx",           0, ASE_DSP | ASE_DSPR2,	ISA_MIPS32R2, CPU_MIPS32R2 },
20215  /* 1004K cores are multiprocessor versions of the 34K.  */
20216  { "1004kc",         0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20217  { "1004kf2_1",      0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20218  { "1004kf",         0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20219  { "1004kf1_1",      0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20220  /* interaptiv is the new name for 1004kf.  */
20221  { "interaptiv",     0, ASE_DSP | ASE_MT,	ISA_MIPS32R2, CPU_MIPS32R2 },
20222  { "interaptiv-mr2", 0,
20223    ASE_DSP | ASE_EVA | ASE_MT | ASE_MIPS16E2 | ASE_MIPS16E2_MT,
20224    ISA_MIPS32R3, CPU_INTERAPTIV_MR2 },
20225  /* M5100 family.  */
20226  { "m5100",          0, ASE_MCU,		ISA_MIPS32R5, CPU_MIPS32R5 },
20227  { "m5101",          0, ASE_MCU,		ISA_MIPS32R5, CPU_MIPS32R5 },
20228  /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
20229  { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,	ISA_MIPS32R5, CPU_MIPS32R5 },
20230
20231  /* MIPS 64 */
20232  { "5kc",            0, 0,			ISA_MIPS64,   CPU_MIPS64 },
20233  { "5kf",            0, 0,			ISA_MIPS64,   CPU_MIPS64 },
20234  { "20kc",           0, ASE_MIPS3D,		ISA_MIPS64,   CPU_MIPS64 },
20235  { "25kf",           0, ASE_MIPS3D,		ISA_MIPS64,   CPU_MIPS64 },
20236
20237  /* Broadcom SB-1 CPU core.  */
20238  { "sb1",            0, ASE_MIPS3D | ASE_MDMX,	ISA_MIPS64,   CPU_SB1 },
20239  /* Broadcom SB-1A CPU core.  */
20240  { "sb1a",           0, ASE_MIPS3D | ASE_MDMX,	ISA_MIPS64,   CPU_SB1 },
20241
20242  /* MIPS 64 Release 2.  */
20243  /* Loongson CPU core.  */
20244  /* -march=loongson3a is an alias of -march=gs464 for compatibility.  */
20245  { "loongson3a",     0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT,
20246     ISA_MIPS64R2,	CPU_GS464 },
20247  { "gs464",          0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT,
20248     ISA_MIPS64R2,	CPU_GS464 },
20249  { "gs464e",         0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT
20250     | ASE_LOONGSON_EXT2,	ISA_MIPS64R2,	CPU_GS464E },
20251  { "gs264e",         0, ASE_LOONGSON_MMI | ASE_LOONGSON_CAM | ASE_LOONGSON_EXT
20252     | ASE_LOONGSON_EXT2 | ASE_MSA | ASE_MSA64,	ISA_MIPS64R2,	CPU_GS264E },
20253
20254  /* Cavium Networks Octeon CPU core.  */
20255  { "octeon",	      0, 0,			ISA_MIPS64R2, CPU_OCTEON },
20256  { "octeon+",	      0, 0,			ISA_MIPS64R2, CPU_OCTEONP },
20257  { "octeon2",	      0, 0,			ISA_MIPS64R2, CPU_OCTEON2 },
20258  { "octeon3",	      0, ASE_VIRT | ASE_VIRT64,	ISA_MIPS64R5, CPU_OCTEON3 },
20259
20260  /* RMI Xlr */
20261  { "xlr",	      0, 0,			ISA_MIPS64,   CPU_XLR },
20262
20263  /* Broadcom XLP.
20264     XLP is mostly like XLR, with the prominent exception that it is
20265     MIPS64R2 rather than MIPS64.  */
20266  { "xlp",	      0, 0,			ISA_MIPS64R2, CPU_XLR },
20267
20268  /* MIPS 64 Release 6.  */
20269  { "i6400",	      0, ASE_VIRT | ASE_MSA,	ISA_MIPS64R6, CPU_MIPS64R6},
20270  { "i6500",	      0, ASE_VIRT | ASE_MSA | ASE_CRC | ASE_GINV,
20271						ISA_MIPS64R6, CPU_MIPS64R6},
20272  { "p6600",	      0, ASE_VIRT | ASE_MSA,	ISA_MIPS64R6, CPU_MIPS64R6},
20273
20274  /* End marker.  */
20275  { NULL, 0, 0, 0, 0 }
20276};
20277
20278
20279/* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
20280   with a final "000" replaced by "k".  Ignore case.
20281
20282   Note: this function is shared between GCC and GAS.  */
20283
20284static bool
20285mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
20286{
20287  while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
20288    given++, canonical++;
20289
20290  return ((*given == 0 && *canonical == 0)
20291	  || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
20292}
20293
20294
20295/* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
20296   CPU name.  We've traditionally allowed a lot of variation here.
20297
20298   Note: this function is shared between GCC and GAS.  */
20299
20300static bool
20301mips_matching_cpu_name_p (const char *canonical, const char *given)
20302{
20303  /* First see if the name matches exactly, or with a final "000"
20304     turned into "k".  */
20305  if (mips_strict_matching_cpu_name_p (canonical, given))
20306    return true;
20307
20308  /* If not, try comparing based on numerical designation alone.
20309     See if GIVEN is an unadorned number, or 'r' followed by a number.  */
20310  if (TOLOWER (*given) == 'r')
20311    given++;
20312  if (!ISDIGIT (*given))
20313    return false;
20314
20315  /* Skip over some well-known prefixes in the canonical name,
20316     hoping to find a number there too.  */
20317  if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
20318    canonical += 2;
20319  else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
20320    canonical += 2;
20321  else if (TOLOWER (canonical[0]) == 'r')
20322    canonical += 1;
20323
20324  return mips_strict_matching_cpu_name_p (canonical, given);
20325}
20326
20327
20328/* Parse an option that takes the name of a processor as its argument.
20329   OPTION is the name of the option and CPU_STRING is the argument.
20330   Return the corresponding processor enumeration if the CPU_STRING is
20331   recognized, otherwise report an error and return null.
20332
20333   A similar function exists in GCC.  */
20334
20335static const struct mips_cpu_info *
20336mips_parse_cpu (const char *option, const char *cpu_string)
20337{
20338  const struct mips_cpu_info *p;
20339
20340  /* 'from-abi' selects the most compatible architecture for the given
20341     ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
20342     EABIs, we have to decide whether we're using the 32-bit or 64-bit
20343     version.  Look first at the -mgp options, if given, otherwise base
20344     the choice on MIPS_DEFAULT_64BIT.
20345
20346     Treat NO_ABI like the EABIs.  One reason to do this is that the
20347     plain 'mips' and 'mips64' configs have 'from-abi' as their default
20348     architecture.  This code picks MIPS I for 'mips' and MIPS III for
20349     'mips64', just as we did in the days before 'from-abi'.  */
20350  if (strcasecmp (cpu_string, "from-abi") == 0)
20351    {
20352      if (ABI_NEEDS_32BIT_REGS (mips_abi))
20353	return mips_cpu_info_from_isa (ISA_MIPS1);
20354
20355      if (ABI_NEEDS_64BIT_REGS (mips_abi))
20356	return mips_cpu_info_from_isa (ISA_MIPS3);
20357
20358      if (file_mips_opts.gp >= 0)
20359	return mips_cpu_info_from_isa (file_mips_opts.gp == 32
20360				       ? ISA_MIPS1 : ISA_MIPS3);
20361
20362      return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
20363				     ? ISA_MIPS3
20364				     : ISA_MIPS1);
20365    }
20366
20367  /* 'default' has traditionally been a no-op.  Probably not very useful.  */
20368  if (strcasecmp (cpu_string, "default") == 0)
20369    return 0;
20370
20371  for (p = mips_cpu_info_table; p->name != 0; p++)
20372    if (mips_matching_cpu_name_p (p->name, cpu_string))
20373      return p;
20374
20375  as_bad (_("bad value (%s) for %s"), cpu_string, option);
20376  return 0;
20377}
20378
20379/* Return the canonical processor information for ISA (a member of the
20380   ISA_MIPS* enumeration).  */
20381
20382static const struct mips_cpu_info *
20383mips_cpu_info_from_isa (int isa)
20384{
20385  int i;
20386
20387  for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
20388    if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
20389	&& isa == mips_cpu_info_table[i].isa)
20390      return (&mips_cpu_info_table[i]);
20391
20392  return NULL;
20393}
20394
20395static const struct mips_cpu_info *
20396mips_cpu_info_from_arch (int arch)
20397{
20398  int i;
20399
20400  for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
20401    if (arch == mips_cpu_info_table[i].cpu)
20402      return (&mips_cpu_info_table[i]);
20403
20404  return NULL;
20405}
20406
20407static void
20408show (FILE *stream, const char *string, int *col_p, int *first_p)
20409{
20410  if (*first_p)
20411    {
20412      fprintf (stream, "%24s", "");
20413      *col_p = 24;
20414    }
20415  else
20416    {
20417      fprintf (stream, ", ");
20418      *col_p += 2;
20419    }
20420
20421  if (*col_p + strlen (string) > 72)
20422    {
20423      fprintf (stream, "\n%24s", "");
20424      *col_p = 24;
20425    }
20426
20427  fprintf (stream, "%s", string);
20428  *col_p += strlen (string);
20429
20430  *first_p = 0;
20431}
20432
20433void
20434md_show_usage (FILE *stream)
20435{
20436  int column, first;
20437  size_t i;
20438
20439  fprintf (stream, _("\
20440MIPS options:\n\
20441-EB			generate big endian output\n\
20442-EL			generate little endian output\n\
20443-g, -g2			do not remove unneeded NOPs or swap branches\n\
20444-G NUM			allow referencing objects up to NUM bytes\n\
20445			implicitly with the gp register [default 8]\n"));
20446  fprintf (stream, _("\
20447-mips1			generate MIPS ISA I instructions\n\
20448-mips2			generate MIPS ISA II instructions\n\
20449-mips3			generate MIPS ISA III instructions\n\
20450-mips4			generate MIPS ISA IV instructions\n\
20451-mips5                  generate MIPS ISA V instructions\n\
20452-mips32                 generate MIPS32 ISA instructions\n\
20453-mips32r2               generate MIPS32 release 2 ISA instructions\n\
20454-mips32r3               generate MIPS32 release 3 ISA instructions\n\
20455-mips32r5               generate MIPS32 release 5 ISA instructions\n\
20456-mips32r6               generate MIPS32 release 6 ISA instructions\n\
20457-mips64                 generate MIPS64 ISA instructions\n\
20458-mips64r2               generate MIPS64 release 2 ISA instructions\n\
20459-mips64r3               generate MIPS64 release 3 ISA instructions\n\
20460-mips64r5               generate MIPS64 release 5 ISA instructions\n\
20461-mips64r6               generate MIPS64 release 6 ISA instructions\n\
20462-march=CPU/-mtune=CPU	generate code/schedule for CPU, where CPU is one of:\n"));
20463
20464  first = 1;
20465
20466  for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
20467    show (stream, mips_cpu_info_table[i].name, &column, &first);
20468  show (stream, "from-abi", &column, &first);
20469  fputc ('\n', stream);
20470
20471  fprintf (stream, _("\
20472-mCPU			equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
20473-no-mCPU		don't generate code specific to CPU.\n\
20474			For -mCPU and -no-mCPU, CPU must be one of:\n"));
20475
20476  first = 1;
20477
20478  show (stream, "3900", &column, &first);
20479  show (stream, "4010", &column, &first);
20480  show (stream, "4100", &column, &first);
20481  show (stream, "4650", &column, &first);
20482  fputc ('\n', stream);
20483
20484  fprintf (stream, _("\
20485-mips16			generate mips16 instructions\n\
20486-no-mips16		do not generate mips16 instructions\n"));
20487  fprintf (stream, _("\
20488-mmips16e2		generate MIPS16e2 instructions\n\
20489-mno-mips16e2		do not generate MIPS16e2 instructions\n"));
20490  fprintf (stream, _("\
20491-mmicromips		generate microMIPS instructions\n\
20492-mno-micromips		do not generate microMIPS instructions\n"));
20493  fprintf (stream, _("\
20494-msmartmips		generate smartmips instructions\n\
20495-mno-smartmips		do not generate smartmips instructions\n"));
20496  fprintf (stream, _("\
20497-mdsp			generate DSP instructions\n\
20498-mno-dsp		do not generate DSP instructions\n"));
20499  fprintf (stream, _("\
20500-mdspr2			generate DSP R2 instructions\n\
20501-mno-dspr2		do not generate DSP R2 instructions\n"));
20502  fprintf (stream, _("\
20503-mdspr3			generate DSP R3 instructions\n\
20504-mno-dspr3		do not generate DSP R3 instructions\n"));
20505  fprintf (stream, _("\
20506-mmt			generate MT instructions\n\
20507-mno-mt			do not generate MT instructions\n"));
20508  fprintf (stream, _("\
20509-mmcu			generate MCU instructions\n\
20510-mno-mcu		do not generate MCU instructions\n"));
20511  fprintf (stream, _("\
20512-mmsa			generate MSA instructions\n\
20513-mno-msa		do not generate MSA instructions\n"));
20514  fprintf (stream, _("\
20515-mxpa			generate eXtended Physical Address (XPA) instructions\n\
20516-mno-xpa		do not generate eXtended Physical Address (XPA) instructions\n"));
20517  fprintf (stream, _("\
20518-mvirt			generate Virtualization instructions\n\
20519-mno-virt		do not generate Virtualization instructions\n"));
20520  fprintf (stream, _("\
20521-mcrc			generate CRC instructions\n\
20522-mno-crc		do not generate CRC instructions\n"));
20523  fprintf (stream, _("\
20524-mginv			generate Global INValidate (GINV) instructions\n\
20525-mno-ginv		do not generate Global INValidate instructions\n"));
20526  fprintf (stream, _("\
20527-mloongson-mmi		generate Loongson MultiMedia extensions Instructions (MMI) instructions\n\
20528-mno-loongson-mmi	do not generate Loongson MultiMedia extensions Instructions\n"));
20529  fprintf (stream, _("\
20530-mloongson-cam		generate Loongson Content Address Memory (CAM) instructions\n\
20531-mno-loongson-cam	do not generate Loongson Content Address Memory Instructions\n"));
20532  fprintf (stream, _("\
20533-mloongson-ext		generate Loongson EXTensions (EXT) instructions\n\
20534-mno-loongson-ext	do not generate Loongson EXTensions Instructions\n"));
20535  fprintf (stream, _("\
20536-mloongson-ext2		generate Loongson EXTensions R2 (EXT2) instructions\n\
20537-mno-loongson-ext2	do not generate Loongson EXTensions R2 Instructions\n"));
20538  fprintf (stream, _("\
20539-minsn32		only generate 32-bit microMIPS instructions\n\
20540-mno-insn32		generate all microMIPS instructions\n"));
20541#if DEFAULT_MIPS_FIX_LOONGSON3_LLSC
20542  fprintf (stream, _("\
20543-mfix-loongson3-llsc	work around Loongson3 LL/SC errata, default\n\
20544-mno-fix-loongson3-llsc	disable work around Loongson3 LL/SC errata\n"));
20545#else
20546  fprintf (stream, _("\
20547-mfix-loongson3-llsc	work around Loongson3 LL/SC errata\n\
20548-mno-fix-loongson3-llsc	disable work around Loongson3 LL/SC errata, default\n"));
20549#endif
20550  fprintf (stream, _("\
20551-mfix-loongson2f-jump	work around Loongson2F JUMP instructions\n\
20552-mfix-loongson2f-nop	work around Loongson2F NOP errata\n\
20553-mfix-loongson2f-btb	work around Loongson2F BTB errata\n\
20554-mfix-loongson3-llsc	work around Loongson3 LL/SC errata\n\
20555-mno-fix-loongson3-llsc	disable work around Loongson3 LL/SC errata\n\
20556-mfix-vr4120		work around certain VR4120 errata\n\
20557-mfix-vr4130		work around VR4130 mflo/mfhi errata\n\
20558-mfix-24k		insert a nop after ERET and DERET instructions\n\
20559-mfix-cn63xxp1		work around CN63XXP1 PREF errata\n\
20560-mfix-r5900		work around R5900 short loop errata\n\
20561-mgp32			use 32-bit GPRs, regardless of the chosen ISA\n\
20562-mfp32			use 32-bit FPRs, regardless of the chosen ISA\n\
20563-msym32			assume all symbols have 32-bit values\n\
20564-O0			do not remove unneeded NOPs, do not swap branches\n\
20565-O, -O1			remove unneeded NOPs, do not swap branches\n\
20566-O2			remove unneeded NOPs and swap branches\n\
20567--trap, --no-break	trap exception on div by 0 and mult overflow\n\
20568--break, --no-trap	break exception on div by 0 and mult overflow\n"));
20569  fprintf (stream, _("\
20570-mhard-float		allow floating-point instructions\n\
20571-msoft-float		do not allow floating-point instructions\n\
20572-msingle-float		only allow 32-bit floating-point operations\n\
20573-mdouble-float		allow 32-bit and 64-bit floating-point operations\n\
20574--[no-]construct-floats	[dis]allow floating point values to be constructed\n\
20575--[no-]relax-branch	[dis]allow out-of-range branches to be relaxed\n\
20576-mignore-branch-isa	accept invalid branches requiring an ISA mode switch\n\
20577-mno-ignore-branch-isa	reject invalid branches requiring an ISA mode switch\n\
20578-mnan=ENCODING		select an IEEE 754 NaN encoding convention, either of:\n"));
20579
20580  first = 1;
20581
20582  show (stream, "legacy", &column, &first);
20583  show (stream, "2008", &column, &first);
20584
20585  fputc ('\n', stream);
20586
20587  fprintf (stream, _("\
20588-KPIC, -call_shared	generate SVR4 position independent code\n\
20589-call_nonpic		generate non-PIC code that can operate with DSOs\n\
20590-mvxworks-pic		generate VxWorks position independent code\n\
20591-non_shared		do not generate code that can operate with DSOs\n\
20592-xgot			assume a 32 bit GOT\n\
20593-mpdr, -mno-pdr		enable/disable creation of .pdr sections\n\
20594-mshared, -mno-shared   disable/enable .cpload optimization for\n\
20595                        position dependent (non shared) code\n\
20596-mabi=ABI		create ABI conformant object file for:\n"));
20597
20598  first = 1;
20599
20600  show (stream, "32", &column, &first);
20601  show (stream, "o64", &column, &first);
20602  show (stream, "n32", &column, &first);
20603  show (stream, "64", &column, &first);
20604  show (stream, "eabi", &column, &first);
20605
20606  fputc ('\n', stream);
20607
20608  fprintf (stream, _("\
20609-32			create o32 ABI object file%s\n"),
20610	   MIPS_DEFAULT_ABI == O32_ABI ? _(" (default)") : "");
20611  fprintf (stream, _("\
20612-n32			create n32 ABI object file%s\n"),
20613	   MIPS_DEFAULT_ABI == N32_ABI ? _(" (default)") : "");
20614  fprintf (stream, _("\
20615-64			create 64 ABI object file%s\n"),
20616	   MIPS_DEFAULT_ABI == N64_ABI ? _(" (default)") : "");
20617}
20618
20619#ifdef TE_IRIX
20620enum dwarf2_format
20621mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
20622{
20623  if (HAVE_64BIT_SYMBOLS)
20624    return dwarf2_format_64bit_irix;
20625  else
20626    return dwarf2_format_32bit;
20627}
20628#endif
20629
20630int
20631mips_dwarf2_addr_size (void)
20632{
20633  if (HAVE_64BIT_OBJECTS)
20634    return 8;
20635  else
20636    return 4;
20637}
20638
20639/* Standard calling conventions leave the CFA at SP on entry.  */
20640void
20641mips_cfi_frame_initial_instructions (void)
20642{
20643  cfi_add_CFA_def_cfa_register (SP);
20644}
20645
20646int
20647tc_mips_regname_to_dw2regnum (char *regname)
20648{
20649  unsigned int regnum = -1;
20650  unsigned int reg;
20651
20652  if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
20653    regnum = reg;
20654
20655  return regnum;
20656}
20657
20658/* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
20659   Given a symbolic attribute NAME, return the proper integer value.
20660   Returns -1 if the attribute is not known.  */
20661
20662int
20663mips_convert_symbolic_attribute (const char *name)
20664{
20665  static const struct
20666  {
20667    const char * name;
20668    const int    tag;
20669  }
20670  attribute_table[] =
20671    {
20672#define T(tag) {#tag, tag}
20673      T (Tag_GNU_MIPS_ABI_FP),
20674      T (Tag_GNU_MIPS_ABI_MSA),
20675#undef T
20676    };
20677  unsigned int i;
20678
20679  if (name == NULL)
20680    return -1;
20681
20682  for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
20683    if (streq (name, attribute_table[i].name))
20684      return attribute_table[i].tag;
20685
20686  return -1;
20687}
20688
20689void
20690md_mips_end (void)
20691{
20692  int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
20693
20694  mips_emit_delays ();
20695  if (cur_proc_ptr)
20696    as_warn (_("missing .end at end of assembly"));
20697
20698  /* Just in case no code was emitted, do the consistency check.  */
20699  file_mips_check_options ();
20700
20701  /* Set a floating-point ABI if the user did not.  */
20702  if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20703    {
20704      /* Perform consistency checks on the floating-point ABI.  */
20705      fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20706					Tag_GNU_MIPS_ABI_FP);
20707      if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20708	check_fpabi (fpabi);
20709    }
20710  else
20711    {
20712      /* Soft-float gets precedence over single-float, the two options should
20713         not be used together so this should not matter.  */
20714      if (file_mips_opts.soft_float == 1)
20715	fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20716      /* Single-float gets precedence over all double_float cases.  */
20717      else if (file_mips_opts.single_float == 1)
20718	fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20719      else
20720	{
20721	  switch (file_mips_opts.fp)
20722	    {
20723	    case 32:
20724	      if (file_mips_opts.gp == 32)
20725		fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20726	      break;
20727	    case 0:
20728	      fpabi = Val_GNU_MIPS_ABI_FP_XX;
20729	      break;
20730	    case 64:
20731	      if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20732		fpabi = Val_GNU_MIPS_ABI_FP_64A;
20733	      else if (file_mips_opts.gp == 32)
20734		fpabi = Val_GNU_MIPS_ABI_FP_64;
20735	      else
20736		fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20737	      break;
20738	    }
20739	}
20740
20741      bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20742				Tag_GNU_MIPS_ABI_FP, fpabi);
20743    }
20744}
20745
20746/*  Returns the relocation type required for a particular CFI encoding.  */
20747
20748bfd_reloc_code_real_type
20749mips_cfi_reloc_for_encoding (int encoding)
20750{
20751  if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20752    return BFD_RELOC_32_PCREL;
20753  else return BFD_RELOC_NONE;
20754}
20755