4814a699fe6e92ee807df4fa1f55219957f1b1ef
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2014 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.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef 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.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92
93 #define ZERO 0
94 #define ATREG 1
95 #define S0  16
96 #define S7  23
97 #define TREG 24
98 #define PIC_CALL_REG 25
99 #define KT0 26
100 #define KT1 27
101 #define GP  28
102 #define SP  29
103 #define FP  30
104 #define RA  31
105
106 #define ILLEGAL_REG (32)
107
108 #define AT  mips_opts.at
109
110 extern int target_big_endian;
111
112 /* The name of the readonly data section.  */
113 #define RDATA_SECTION_NAME ".rodata"
114
115 /* Ways in which an instruction can be "appended" to the output.  */
116 enum append_method {
117   /* Just add it normally.  */
118   APPEND_ADD,
119
120   /* Add it normally and then add a nop.  */
121   APPEND_ADD_WITH_NOP,
122
123   /* Turn an instruction with a delay slot into a "compact" version.  */
124   APPEND_ADD_COMPACT,
125
126   /* Insert the instruction before the last one.  */
127   APPEND_SWAP
128 };
129
130 /* Information about an instruction, including its format, operands
131    and fixups.  */
132 struct mips_cl_insn
133 {
134   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
135   const struct mips_opcode *insn_mo;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  If we have
139      decided to use an extended MIPS16 instruction, this includes the
140      extension.  */
141   unsigned long insn_opcode;
142
143   /* The frag that contains the instruction.  */
144   struct frag *frag;
145
146   /* The offset into FRAG of the first instruction byte.  */
147   long where;
148
149   /* The relocs associated with the instruction, if any.  */
150   fixS *fixp[3];
151
152   /* True if this entry cannot be moved from its current position.  */
153   unsigned int fixed_p : 1;
154
155   /* True if this instruction occurred in a .set noreorder block.  */
156   unsigned int noreorder_p : 1;
157
158   /* True for mips16 instructions that jump to an absolute address.  */
159   unsigned int mips16_absolute_jump_p : 1;
160
161   /* True if this instruction is complete.  */
162   unsigned int complete_p : 1;
163
164   /* True if this instruction is cleared from history by unconditional
165      branch.  */
166   unsigned int cleared_p : 1;
167 };
168
169 /* The ABI to use.  */
170 enum mips_abi_level
171 {
172   NO_ABI = 0,
173   O32_ABI,
174   O64_ABI,
175   N32_ABI,
176   N64_ABI,
177   EABI_ABI
178 };
179
180 /* MIPS ABI we are using for this output file.  */
181 static enum mips_abi_level mips_abi = NO_ABI;
182
183 /* Whether or not we have code that can call pic code.  */
184 int mips_abicalls = FALSE;
185
186 /* Whether or not we have code which can be put into a shared
187    library.  */
188 static bfd_boolean mips_in_shared = TRUE;
189
190 /* This is the set of options which may be modified by the .set
191    pseudo-op.  We use a struct so that .set push and .set pop are more
192    reliable.  */
193
194 struct mips_set_options
195 {
196   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
197      if it has not been initialized.  Changed by `.set mipsN', and the
198      -mipsN command line option, and the default CPU.  */
199   int isa;
200   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
201      <asename>', by command line options, and based on the default
202      architecture.  */
203   int ase;
204   /* Whether we are assembling for the mips16 processor.  0 if we are
205      not, 1 if we are, and -1 if the value has not been initialized.
206      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
207      -nomips16 command line options, and the default CPU.  */
208   int mips16;
209   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
210      1 if we are, and -1 if the value has not been initialized.  Changed
211      by `.set micromips' and `.set nomicromips', and the -mmicromips
212      and -mno-micromips command line options, and the default CPU.  */
213   int micromips;
214   /* Non-zero if we should not reorder instructions.  Changed by `.set
215      reorder' and `.set noreorder'.  */
216   int noreorder;
217   /* Non-zero if we should not permit the register designated "assembler
218      temporary" to be used in instructions.  The value is the register
219      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
220      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
221   unsigned int at;
222   /* Non-zero if we should warn when a macro instruction expands into
223      more than one machine instruction.  Changed by `.set nomacro' and
224      `.set macro'.  */
225   int warn_about_macros;
226   /* Non-zero if we should not move instructions.  Changed by `.set
227      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
228   int nomove;
229   /* Non-zero if we should not optimize branches by moving the target
230      of the branch into the delay slot.  Actually, we don't perform
231      this optimization anyhow.  Changed by `.set bopt' and `.set
232      nobopt'.  */
233   int nobopt;
234   /* Non-zero if we should not autoextend mips16 instructions.
235      Changed by `.set autoextend' and `.set noautoextend'.  */
236   int noautoextend;
237   /* True if we should only emit 32-bit microMIPS instructions.
238      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
239      and -mno-insn32 command line options.  */
240   bfd_boolean insn32;
241   /* Restrict general purpose registers and floating point registers
242      to 32 bit.  This is initially determined when -mgp32 or -mfp32
243      is passed but can changed if the assembler code uses .set mipsN.  */
244   int gp;
245   int fp;
246   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
247      command line option, and the default CPU.  */
248   int arch;
249   /* True if ".set sym32" is in effect.  */
250   bfd_boolean sym32;
251   /* True if floating-point operations are not allowed.  Changed by .set
252      softfloat or .set hardfloat, by command line options -msoft-float or
253      -mhard-float.  The default is false.  */
254   bfd_boolean soft_float;
255
256   /* True if only single-precision floating-point operations are allowed.
257      Changed by .set singlefloat or .set doublefloat, command-line options
258      -msingle-float or -mdouble-float.  The default is false.  */
259   bfd_boolean single_float;
260 };
261
262 /* Specifies whether module level options have been checked yet.  */
263 static bfd_boolean file_mips_opts_checked = FALSE;
264
265 /* True if -mnan=2008, false if -mnan=legacy.  */
266 static bfd_boolean mips_flag_nan2008 = FALSE;
267
268 /* This is the struct we use to hold the module level set of options.
269    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
270    fp fields to -1 to indicate that they have not been initialized.  */
271
272 static struct mips_set_options file_mips_opts =
273 {
274   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
275   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
276   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
277   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
278   /* soft_float */ FALSE, /* single_float */ FALSE
279 };
280
281 /* This is similar to file_mips_opts, but for the current set of options.  */
282
283 static struct mips_set_options mips_opts =
284 {
285   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
286   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
287   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
288   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
289   /* soft_float */ FALSE, /* single_float */ FALSE
290 };
291
292 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
293 static unsigned int file_ase_explicit;
294
295 /* These variables are filled in with the masks of registers used.
296    The object format code reads them and puts them in the appropriate
297    place.  */
298 unsigned long mips_gprmask;
299 unsigned long mips_cprmask[4];
300
301 /* True if any MIPS16 code was produced.  */
302 static int file_ase_mips16;
303
304 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
305                               || mips_opts.isa == ISA_MIPS32R2          \
306                               || mips_opts.isa == ISA_MIPS32R3          \
307                               || mips_opts.isa == ISA_MIPS32R5          \
308                               || mips_opts.isa == ISA_MIPS64            \
309                               || mips_opts.isa == ISA_MIPS64R2          \
310                               || mips_opts.isa == ISA_MIPS64R3          \
311                               || mips_opts.isa == ISA_MIPS64R5)
312
313 /* True if any microMIPS code was produced.  */
314 static int file_ase_micromips;
315
316 /* True if we want to create R_MIPS_JALR for jalr $25.  */
317 #ifdef TE_IRIX
318 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
319 #else
320 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
321    because there's no place for any addend, the only acceptable
322    expression is a bare symbol.  */
323 #define MIPS_JALR_HINT_P(EXPR) \
324   (!HAVE_IN_PLACE_ADDENDS \
325    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
326 #endif
327
328 /* The argument of the -march= flag.  The architecture we are assembling.  */
329 static const char *mips_arch_string;
330
331 /* The argument of the -mtune= flag.  The architecture for which we
332    are optimizing.  */
333 static int mips_tune = CPU_UNKNOWN;
334 static const char *mips_tune_string;
335
336 /* True when generating 32-bit code for a 64-bit processor.  */
337 static int mips_32bitmode = 0;
338
339 /* True if the given ABI requires 32-bit registers.  */
340 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
341
342 /* Likewise 64-bit registers.  */
343 #define ABI_NEEDS_64BIT_REGS(ABI)       \
344   ((ABI) == N32_ABI                     \
345    || (ABI) == N64_ABI                  \
346    || (ABI) == O64_ABI)
347
348 /*  Return true if ISA supports 64 bit wide gp registers.  */
349 #define ISA_HAS_64BIT_REGS(ISA)         \
350   ((ISA) == ISA_MIPS3                   \
351    || (ISA) == ISA_MIPS4                \
352    || (ISA) == ISA_MIPS5                \
353    || (ISA) == ISA_MIPS64               \
354    || (ISA) == ISA_MIPS64R2             \
355    || (ISA) == ISA_MIPS64R3             \
356    || (ISA) == ISA_MIPS64R5)
357
358 /*  Return true if ISA supports 64 bit wide float registers.  */
359 #define ISA_HAS_64BIT_FPRS(ISA)         \
360   ((ISA) == ISA_MIPS3                   \
361    || (ISA) == ISA_MIPS4                \
362    || (ISA) == ISA_MIPS5                \
363    || (ISA) == ISA_MIPS32R2             \
364    || (ISA) == ISA_MIPS32R3             \
365    || (ISA) == ISA_MIPS32R5             \
366    || (ISA) == ISA_MIPS64               \
367    || (ISA) == ISA_MIPS64R2             \
368    || (ISA) == ISA_MIPS64R3             \
369    || (ISA) == ISA_MIPS64R5             )
370
371 /* Return true if ISA supports 64-bit right rotate (dror et al.)
372    instructions.  */
373 #define ISA_HAS_DROR(ISA)               \
374   ((ISA) == ISA_MIPS64R2                \
375    || (ISA) == ISA_MIPS64R3             \
376    || (ISA) == ISA_MIPS64R5             \
377    || (mips_opts.micromips              \
378        && ISA_HAS_64BIT_REGS (ISA))     \
379    )
380
381 /* Return true if ISA supports 32-bit right rotate (ror et al.)
382    instructions.  */
383 #define ISA_HAS_ROR(ISA)                \
384   ((ISA) == ISA_MIPS32R2                \
385    || (ISA) == ISA_MIPS32R3             \
386    || (ISA) == ISA_MIPS32R5             \
387    || (ISA) == ISA_MIPS64R2             \
388    || (ISA) == ISA_MIPS64R3             \
389    || (ISA) == ISA_MIPS64R5             \
390    || (mips_opts.ase & ASE_SMARTMIPS)   \
391    || mips_opts.micromips               \
392    )
393
394 /* Return true if ISA supports single-precision floats in odd registers.  */
395 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
396   ((ISA) == ISA_MIPS32                  \
397    || (ISA) == ISA_MIPS32R2             \
398    || (ISA) == ISA_MIPS32R3             \
399    || (ISA) == ISA_MIPS32R5             \
400    || (ISA) == ISA_MIPS64               \
401    || (ISA) == ISA_MIPS64R2             \
402    || (ISA) == ISA_MIPS64R3             \
403    || (ISA) == ISA_MIPS64R5)
404
405 /* Return true if ISA supports move to/from high part of a 64-bit
406    floating-point register. */
407 #define ISA_HAS_MXHC1(ISA)              \
408   ((ISA) == ISA_MIPS32R2                \
409    || (ISA) == ISA_MIPS32R3             \
410    || (ISA) == ISA_MIPS32R5             \
411    || (ISA) == ISA_MIPS64R2             \
412    || (ISA) == ISA_MIPS64R3             \
413    || (ISA) == ISA_MIPS64R5)
414
415 #define GPR_SIZE \
416     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
417      ? 32 \
418      : mips_opts.gp)
419
420 #define FPR_SIZE \
421     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
422      ? 32 \
423      : mips_opts.fp)
424
425 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
426
427 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
428
429 /* True if relocations are stored in-place.  */
430 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
431
432 /* The ABI-derived address size.  */
433 #define HAVE_64BIT_ADDRESSES \
434   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
435 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
436
437 /* The size of symbolic constants (i.e., expressions of the form
438    "SYMBOL" or "SYMBOL + OFFSET").  */
439 #define HAVE_32BIT_SYMBOLS \
440   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
441 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
442
443 /* Addresses are loaded in different ways, depending on the address size
444    in use.  The n32 ABI Documentation also mandates the use of additions
445    with overflow checking, but existing implementations don't follow it.  */
446 #define ADDRESS_ADD_INSN                                                \
447    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
448
449 #define ADDRESS_ADDI_INSN                                               \
450    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
451
452 #define ADDRESS_LOAD_INSN                                               \
453    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
454
455 #define ADDRESS_STORE_INSN                                              \
456    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
457
458 /* Return true if the given CPU supports the MIPS16 ASE.  */
459 #define CPU_HAS_MIPS16(cpu)                                             \
460    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
461     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
462
463 /* Return true if the given CPU supports the microMIPS ASE.  */
464 #define CPU_HAS_MICROMIPS(cpu)  0
465
466 /* True if CPU has a dror instruction.  */
467 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
468
469 /* True if CPU has a ror instruction.  */
470 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
471
472 /* True if CPU is in the Octeon family */
473 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
474
475 /* True if CPU has seq/sne and seqi/snei instructions.  */
476 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
477
478 /* True, if CPU has support for ldc1 and sdc1. */
479 #define CPU_HAS_LDC1_SDC1(CPU)  \
480    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
481
482 /* True if mflo and mfhi can be immediately followed by instructions
483    which write to the HI and LO registers.
484
485    According to MIPS specifications, MIPS ISAs I, II, and III need
486    (at least) two instructions between the reads of HI/LO and
487    instructions which write them, and later ISAs do not.  Contradicting
488    the MIPS specifications, some MIPS IV processor user manuals (e.g.
489    the UM for the NEC Vr5000) document needing the instructions between
490    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
491    MIPS64 and later ISAs to have the interlocks, plus any specific
492    earlier-ISA CPUs for which CPU documentation declares that the
493    instructions are really interlocked.  */
494 #define hilo_interlocks \
495   (mips_opts.isa == ISA_MIPS32                        \
496    || mips_opts.isa == ISA_MIPS32R2                   \
497    || mips_opts.isa == ISA_MIPS32R3                   \
498    || mips_opts.isa == ISA_MIPS32R5                   \
499    || mips_opts.isa == ISA_MIPS64                     \
500    || mips_opts.isa == ISA_MIPS64R2                   \
501    || mips_opts.isa == ISA_MIPS64R3                   \
502    || mips_opts.isa == ISA_MIPS64R5                   \
503    || mips_opts.arch == CPU_R4010                     \
504    || mips_opts.arch == CPU_R5900                     \
505    || mips_opts.arch == CPU_R10000                    \
506    || mips_opts.arch == CPU_R12000                    \
507    || mips_opts.arch == CPU_R14000                    \
508    || mips_opts.arch == CPU_R16000                    \
509    || mips_opts.arch == CPU_RM7000                    \
510    || mips_opts.arch == CPU_VR5500                    \
511    || mips_opts.micromips                             \
512    )
513
514 /* Whether the processor uses hardware interlocks to protect reads
515    from the GPRs after they are loaded from memory, and thus does not
516    require nops to be inserted.  This applies to instructions marked
517    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
518    level I and microMIPS mode instructions are always interlocked.  */
519 #define gpr_interlocks                                \
520   (mips_opts.isa != ISA_MIPS1                         \
521    || mips_opts.arch == CPU_R3900                     \
522    || mips_opts.arch == CPU_R5900                     \
523    || mips_opts.micromips                             \
524    )
525
526 /* Whether the processor uses hardware interlocks to avoid delays
527    required by coprocessor instructions, and thus does not require
528    nops to be inserted.  This applies to instructions marked
529    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
530    between instructions marked INSN_WRITE_COND_CODE and ones marked
531    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
532    levels I, II, and III and microMIPS mode instructions are always
533    interlocked.  */
534 /* Itbl support may require additional care here.  */
535 #define cop_interlocks                                \
536   ((mips_opts.isa != ISA_MIPS1                        \
537     && mips_opts.isa != ISA_MIPS2                     \
538     && mips_opts.isa != ISA_MIPS3)                    \
539    || mips_opts.arch == CPU_R4300                     \
540    || mips_opts.micromips                             \
541    )
542
543 /* Whether the processor uses hardware interlocks to protect reads
544    from coprocessor registers after they are loaded from memory, and
545    thus does not require nops to be inserted.  This applies to
546    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
547    requires at MIPS ISA level I and microMIPS mode instructions are
548    always interlocked.  */
549 #define cop_mem_interlocks                            \
550   (mips_opts.isa != ISA_MIPS1                         \
551    || mips_opts.micromips                             \
552    )
553
554 /* Is this a mfhi or mflo instruction?  */
555 #define MF_HILO_INSN(PINFO) \
556   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
557
558 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
559    has been selected.  This implies, in particular, that addresses of text
560    labels have their LSB set.  */
561 #define HAVE_CODE_COMPRESSION                                           \
562   ((mips_opts.mips16 | mips_opts.micromips) != 0)
563
564 /* The minimum and maximum signed values that can be stored in a GPR.  */
565 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
566 #define GPR_SMIN (-GPR_SMAX - 1)
567
568 /* MIPS PIC level.  */
569
570 enum mips_pic_level mips_pic;
571
572 /* 1 if we should generate 32 bit offsets from the $gp register in
573    SVR4_PIC mode.  Currently has no meaning in other modes.  */
574 static int mips_big_got = 0;
575
576 /* 1 if trap instructions should used for overflow rather than break
577    instructions.  */
578 static int mips_trap = 0;
579
580 /* 1 if double width floating point constants should not be constructed
581    by assembling two single width halves into two single width floating
582    point registers which just happen to alias the double width destination
583    register.  On some architectures this aliasing can be disabled by a bit
584    in the status register, and the setting of this bit cannot be determined
585    automatically at assemble time.  */
586 static int mips_disable_float_construction;
587
588 /* Non-zero if any .set noreorder directives were used.  */
589
590 static int mips_any_noreorder;
591
592 /* Non-zero if nops should be inserted when the register referenced in
593    an mfhi/mflo instruction is read in the next two instructions.  */
594 static int mips_7000_hilo_fix;
595
596 /* The size of objects in the small data section.  */
597 static unsigned int g_switch_value = 8;
598 /* Whether the -G option was used.  */
599 static int g_switch_seen = 0;
600
601 #define N_RMASK 0xc4
602 #define N_VFP   0xd4
603
604 /* If we can determine in advance that GP optimization won't be
605    possible, we can skip the relaxation stuff that tries to produce
606    GP-relative references.  This makes delay slot optimization work
607    better.
608
609    This function can only provide a guess, but it seems to work for
610    gcc output.  It needs to guess right for gcc, otherwise gcc
611    will put what it thinks is a GP-relative instruction in a branch
612    delay slot.
613
614    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
615    fixed it for the non-PIC mode.  KR 95/04/07  */
616 static int nopic_need_relax (symbolS *, int);
617
618 /* handle of the OPCODE hash table */
619 static struct hash_control *op_hash = NULL;
620
621 /* The opcode hash table we use for the mips16.  */
622 static struct hash_control *mips16_op_hash = NULL;
623
624 /* The opcode hash table we use for the microMIPS ASE.  */
625 static struct hash_control *micromips_op_hash = NULL;
626
627 /* This array holds the chars that always start a comment.  If the
628     pre-processor is disabled, these aren't very useful */
629 const char comment_chars[] = "#";
630
631 /* This array holds the chars that only start a comment at the beginning of
632    a line.  If the line seems to have the form '# 123 filename'
633    .line and .file directives will appear in the pre-processed output */
634 /* Note that input_file.c hand checks for '#' at the beginning of the
635    first line of the input file.  This is because the compiler outputs
636    #NO_APP at the beginning of its output.  */
637 /* Also note that C style comments are always supported.  */
638 const char line_comment_chars[] = "#";
639
640 /* This array holds machine specific line separator characters.  */
641 const char line_separator_chars[] = ";";
642
643 /* Chars that can be used to separate mant from exp in floating point nums */
644 const char EXP_CHARS[] = "eE";
645
646 /* Chars that mean this number is a floating point constant */
647 /* As in 0f12.456 */
648 /* or    0d1.2345e12 */
649 const char FLT_CHARS[] = "rRsSfFdDxXpP";
650
651 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
652    changed in read.c .  Ideally it shouldn't have to know about it at all,
653    but nothing is ideal around here.
654  */
655
656 /* Types of printf format used for instruction-related error messages.
657    "I" means int ("%d") and "S" means string ("%s"). */
658 enum mips_insn_error_format {
659   ERR_FMT_PLAIN,
660   ERR_FMT_I,
661   ERR_FMT_SS,
662 };
663
664 /* Information about an error that was found while assembling the current
665    instruction.  */
666 struct mips_insn_error {
667   /* We sometimes need to match an instruction against more than one
668      opcode table entry.  Errors found during this matching are reported
669      against a particular syntactic argument rather than against the
670      instruction as a whole.  We grade these messages so that errors
671      against argument N have a greater priority than an error against
672      any argument < N, since the former implies that arguments up to N
673      were acceptable and that the opcode entry was therefore a closer match.
674      If several matches report an error against the same argument,
675      we only use that error if it is the same in all cases.
676
677      min_argnum is the minimum argument number for which an error message
678      should be accepted.  It is 0 if MSG is against the instruction as
679      a whole.  */
680   int min_argnum;
681
682   /* The printf()-style message, including its format and arguments.  */
683   enum mips_insn_error_format format;
684   const char *msg;
685   union {
686     int i;
687     const char *ss[2];
688   } u;
689 };
690
691 /* The error that should be reported for the current instruction.  */
692 static struct mips_insn_error insn_error;
693
694 static int auto_align = 1;
695
696 /* When outputting SVR4 PIC code, the assembler needs to know the
697    offset in the stack frame from which to restore the $gp register.
698    This is set by the .cprestore pseudo-op, and saved in this
699    variable.  */
700 static offsetT mips_cprestore_offset = -1;
701
702 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
703    more optimizations, it can use a register value instead of a memory-saved
704    offset and even an other register than $gp as global pointer.  */
705 static offsetT mips_cpreturn_offset = -1;
706 static int mips_cpreturn_register = -1;
707 static int mips_gp_register = GP;
708 static int mips_gprel_offset = 0;
709
710 /* Whether mips_cprestore_offset has been set in the current function
711    (or whether it has already been warned about, if not).  */
712 static int mips_cprestore_valid = 0;
713
714 /* This is the register which holds the stack frame, as set by the
715    .frame pseudo-op.  This is needed to implement .cprestore.  */
716 static int mips_frame_reg = SP;
717
718 /* Whether mips_frame_reg has been set in the current function
719    (or whether it has already been warned about, if not).  */
720 static int mips_frame_reg_valid = 0;
721
722 /* To output NOP instructions correctly, we need to keep information
723    about the previous two instructions.  */
724
725 /* Whether we are optimizing.  The default value of 2 means to remove
726    unneeded NOPs and swap branch instructions when possible.  A value
727    of 1 means to not swap branches.  A value of 0 means to always
728    insert NOPs.  */
729 static int mips_optimize = 2;
730
731 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
732    equivalent to seeing no -g option at all.  */
733 static int mips_debug = 0;
734
735 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
736 #define MAX_VR4130_NOPS 4
737
738 /* The maximum number of NOPs needed to fill delay slots.  */
739 #define MAX_DELAY_NOPS 2
740
741 /* The maximum number of NOPs needed for any purpose.  */
742 #define MAX_NOPS 4
743
744 /* A list of previous instructions, with index 0 being the most recent.
745    We need to look back MAX_NOPS instructions when filling delay slots
746    or working around processor errata.  We need to look back one
747    instruction further if we're thinking about using history[0] to
748    fill a branch delay slot.  */
749 static struct mips_cl_insn history[1 + MAX_NOPS];
750
751 /* Arrays of operands for each instruction.  */
752 #define MAX_OPERANDS 6
753 struct mips_operand_array {
754   const struct mips_operand *operand[MAX_OPERANDS];
755 };
756 static struct mips_operand_array *mips_operands;
757 static struct mips_operand_array *mips16_operands;
758 static struct mips_operand_array *micromips_operands;
759
760 /* Nop instructions used by emit_nop.  */
761 static struct mips_cl_insn nop_insn;
762 static struct mips_cl_insn mips16_nop_insn;
763 static struct mips_cl_insn micromips_nop16_insn;
764 static struct mips_cl_insn micromips_nop32_insn;
765
766 /* The appropriate nop for the current mode.  */
767 #define NOP_INSN (mips_opts.mips16                                      \
768                   ? &mips16_nop_insn                                    \
769                   : (mips_opts.micromips                                \
770                      ? (mips_opts.insn32                                \
771                         ? &micromips_nop32_insn                         \
772                         : &micromips_nop16_insn)                        \
773                      : &nop_insn))
774
775 /* The size of NOP_INSN in bytes.  */
776 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
777                         || (mips_opts.micromips && !mips_opts.insn32))  \
778                        ? 2 : 4)
779
780 /* If this is set, it points to a frag holding nop instructions which
781    were inserted before the start of a noreorder section.  If those
782    nops turn out to be unnecessary, the size of the frag can be
783    decreased.  */
784 static fragS *prev_nop_frag;
785
786 /* The number of nop instructions we created in prev_nop_frag.  */
787 static int prev_nop_frag_holds;
788
789 /* The number of nop instructions that we know we need in
790    prev_nop_frag.  */
791 static int prev_nop_frag_required;
792
793 /* The number of instructions we've seen since prev_nop_frag.  */
794 static int prev_nop_frag_since;
795
796 /* Relocations against symbols are sometimes done in two parts, with a HI
797    relocation and a LO relocation.  Each relocation has only 16 bits of
798    space to store an addend.  This means that in order for the linker to
799    handle carries correctly, it must be able to locate both the HI and
800    the LO relocation.  This means that the relocations must appear in
801    order in the relocation table.
802
803    In order to implement this, we keep track of each unmatched HI
804    relocation.  We then sort them so that they immediately precede the
805    corresponding LO relocation.  */
806
807 struct mips_hi_fixup
808 {
809   /* Next HI fixup.  */
810   struct mips_hi_fixup *next;
811   /* This fixup.  */
812   fixS *fixp;
813   /* The section this fixup is in.  */
814   segT seg;
815 };
816
817 /* The list of unmatched HI relocs.  */
818
819 static struct mips_hi_fixup *mips_hi_fixup_list;
820
821 /* The frag containing the last explicit relocation operator.
822    Null if explicit relocations have not been used.  */
823
824 static fragS *prev_reloc_op_frag;
825
826 /* Map mips16 register numbers to normal MIPS register numbers.  */
827
828 static const unsigned int mips16_to_32_reg_map[] =
829 {
830   16, 17, 2, 3, 4, 5, 6, 7
831 };
832
833 /* Map microMIPS register numbers to normal MIPS register numbers.  */
834
835 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
836
837 /* The microMIPS registers with type h.  */
838 static const unsigned int micromips_to_32_reg_h_map1[] =
839 {
840   5, 5, 6, 4, 4, 4, 4, 4
841 };
842 static const unsigned int micromips_to_32_reg_h_map2[] =
843 {
844   6, 7, 7, 21, 22, 5, 6, 7
845 };
846
847 /* The microMIPS registers with type m.  */
848 static const unsigned int micromips_to_32_reg_m_map[] =
849 {
850   0, 17, 2, 3, 16, 18, 19, 20
851 };
852
853 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
854
855 /* Classifies the kind of instructions we're interested in when
856    implementing -mfix-vr4120.  */
857 enum fix_vr4120_class
858 {
859   FIX_VR4120_MACC,
860   FIX_VR4120_DMACC,
861   FIX_VR4120_MULT,
862   FIX_VR4120_DMULT,
863   FIX_VR4120_DIV,
864   FIX_VR4120_MTHILO,
865   NUM_FIX_VR4120_CLASSES
866 };
867
868 /* ...likewise -mfix-loongson2f-jump.  */
869 static bfd_boolean mips_fix_loongson2f_jump;
870
871 /* ...likewise -mfix-loongson2f-nop.  */
872 static bfd_boolean mips_fix_loongson2f_nop;
873
874 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
875 static bfd_boolean mips_fix_loongson2f;
876
877 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
878    there must be at least one other instruction between an instruction
879    of type X and an instruction of type Y.  */
880 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
881
882 /* True if -mfix-vr4120 is in force.  */
883 static int mips_fix_vr4120;
884
885 /* ...likewise -mfix-vr4130.  */
886 static int mips_fix_vr4130;
887
888 /* ...likewise -mfix-24k.  */
889 static int mips_fix_24k;
890
891 /* ...likewise -mfix-rm7000  */
892 static int mips_fix_rm7000;
893
894 /* ...likewise -mfix-cn63xxp1 */
895 static bfd_boolean mips_fix_cn63xxp1;
896
897 /* We don't relax branches by default, since this causes us to expand
898    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
899    fail to compute the offset before expanding the macro to the most
900    efficient expansion.  */
901
902 static int mips_relax_branch;
903 \f
904 /* The expansion of many macros depends on the type of symbol that
905    they refer to.  For example, when generating position-dependent code,
906    a macro that refers to a symbol may have two different expansions,
907    one which uses GP-relative addresses and one which uses absolute
908    addresses.  When generating SVR4-style PIC, a macro may have
909    different expansions for local and global symbols.
910
911    We handle these situations by generating both sequences and putting
912    them in variant frags.  In position-dependent code, the first sequence
913    will be the GP-relative one and the second sequence will be the
914    absolute one.  In SVR4 PIC, the first sequence will be for global
915    symbols and the second will be for local symbols.
916
917    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
918    SECOND are the lengths of the two sequences in bytes.  These fields
919    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
920    the subtype has the following flags:
921
922    RELAX_USE_SECOND
923         Set if it has been decided that we should use the second
924         sequence instead of the first.
925
926    RELAX_SECOND_LONGER
927         Set in the first variant frag if the macro's second implementation
928         is longer than its first.  This refers to the macro as a whole,
929         not an individual relaxation.
930
931    RELAX_NOMACRO
932         Set in the first variant frag if the macro appeared in a .set nomacro
933         block and if one alternative requires a warning but the other does not.
934
935    RELAX_DELAY_SLOT
936         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
937         delay slot.
938
939    RELAX_DELAY_SLOT_16BIT
940         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
941         16-bit instruction.
942
943    RELAX_DELAY_SLOT_SIZE_FIRST
944         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
945         the macro is of the wrong size for the branch delay slot.
946
947    RELAX_DELAY_SLOT_SIZE_SECOND
948         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
949         the macro is of the wrong size for the branch delay slot.
950
951    The frag's "opcode" points to the first fixup for relaxable code.
952
953    Relaxable macros are generated using a sequence such as:
954
955       relax_start (SYMBOL);
956       ... generate first expansion ...
957       relax_switch ();
958       ... generate second expansion ...
959       relax_end ();
960
961    The code and fixups for the unwanted alternative are discarded
962    by md_convert_frag.  */
963 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
964
965 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
966 #define RELAX_SECOND(X) ((X) & 0xff)
967 #define RELAX_USE_SECOND 0x10000
968 #define RELAX_SECOND_LONGER 0x20000
969 #define RELAX_NOMACRO 0x40000
970 #define RELAX_DELAY_SLOT 0x80000
971 #define RELAX_DELAY_SLOT_16BIT 0x100000
972 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
973 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
974
975 /* Branch without likely bit.  If label is out of range, we turn:
976
977         beq reg1, reg2, label
978         delay slot
979
980    into
981
982         bne reg1, reg2, 0f
983         nop
984         j label
985      0: delay slot
986
987    with the following opcode replacements:
988
989         beq <-> bne
990         blez <-> bgtz
991         bltz <-> bgez
992         bc1f <-> bc1t
993
994         bltzal <-> bgezal  (with jal label instead of j label)
995
996    Even though keeping the delay slot instruction in the delay slot of
997    the branch would be more efficient, it would be very tricky to do
998    correctly, because we'd have to introduce a variable frag *after*
999    the delay slot instruction, and expand that instead.  Let's do it
1000    the easy way for now, even if the branch-not-taken case now costs
1001    one additional instruction.  Out-of-range branches are not supposed
1002    to be common, anyway.
1003
1004    Branch likely.  If label is out of range, we turn:
1005
1006         beql reg1, reg2, label
1007         delay slot (annulled if branch not taken)
1008
1009    into
1010
1011         beql reg1, reg2, 1f
1012         nop
1013         beql $0, $0, 2f
1014         nop
1015      1: j[al] label
1016         delay slot (executed only if branch taken)
1017      2:
1018
1019    It would be possible to generate a shorter sequence by losing the
1020    likely bit, generating something like:
1021
1022         bne reg1, reg2, 0f
1023         nop
1024         j[al] label
1025         delay slot (executed only if branch taken)
1026      0:
1027
1028         beql -> bne
1029         bnel -> beq
1030         blezl -> bgtz
1031         bgtzl -> blez
1032         bltzl -> bgez
1033         bgezl -> bltz
1034         bc1fl -> bc1t
1035         bc1tl -> bc1f
1036
1037         bltzall -> bgezal  (with jal label instead of j label)
1038         bgezall -> bltzal  (ditto)
1039
1040
1041    but it's not clear that it would actually improve performance.  */
1042 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1043   ((relax_substateT)                                            \
1044    (0xc0000000                                                  \
1045     | ((at) & 0x1f)                                             \
1046     | ((toofar) ? 0x20 : 0)                                     \
1047     | ((link) ? 0x40 : 0)                                       \
1048     | ((likely) ? 0x80 : 0)                                     \
1049     | ((uncond) ? 0x100 : 0)))
1050 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1051 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1052 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1053 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1054 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1055 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1056
1057 /* For mips16 code, we use an entirely different form of relaxation.
1058    mips16 supports two versions of most instructions which take
1059    immediate values: a small one which takes some small value, and a
1060    larger one which takes a 16 bit value.  Since branches also follow
1061    this pattern, relaxing these values is required.
1062
1063    We can assemble both mips16 and normal MIPS code in a single
1064    object.  Therefore, we need to support this type of relaxation at
1065    the same time that we support the relaxation described above.  We
1066    use the high bit of the subtype field to distinguish these cases.
1067
1068    The information we store for this type of relaxation is the
1069    argument code found in the opcode file for this relocation, whether
1070    the user explicitly requested a small or extended form, and whether
1071    the relocation is in a jump or jal delay slot.  That tells us the
1072    size of the value, and how it should be stored.  We also store
1073    whether the fragment is considered to be extended or not.  We also
1074    store whether this is known to be a branch to a different section,
1075    whether we have tried to relax this frag yet, and whether we have
1076    ever extended a PC relative fragment because of a shift count.  */
1077 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1078   (0x80000000                                                   \
1079    | ((type) & 0xff)                                            \
1080    | ((small) ? 0x100 : 0)                                      \
1081    | ((ext) ? 0x200 : 0)                                        \
1082    | ((dslot) ? 0x400 : 0)                                      \
1083    | ((jal_dslot) ? 0x800 : 0))
1084 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1085 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1086 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1087 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1088 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1089 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1090 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1091 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1092 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1093 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1094 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1095 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1096
1097 /* For microMIPS code, we use relaxation similar to one we use for
1098    MIPS16 code.  Some instructions that take immediate values support
1099    two encodings: a small one which takes some small value, and a
1100    larger one which takes a 16 bit value.  As some branches also follow
1101    this pattern, relaxing these values is required.
1102
1103    We can assemble both microMIPS and normal MIPS code in a single
1104    object.  Therefore, we need to support this type of relaxation at
1105    the same time that we support the relaxation described above.  We
1106    use one of the high bits of the subtype field to distinguish these
1107    cases.
1108
1109    The information we store for this type of relaxation is the argument
1110    code found in the opcode file for this relocation, the register
1111    selected as the assembler temporary, whether the branch is
1112    unconditional, whether it is compact, whether it stores the link
1113    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1114    branches to a sequence of instructions is enabled, and whether the
1115    displacement of a branch is too large to fit as an immediate argument
1116    of a 16-bit and a 32-bit branch, respectively.  */
1117 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1118                                relax32, toofar16, toofar32)     \
1119   (0x40000000                                                   \
1120    | ((type) & 0xff)                                            \
1121    | (((at) & 0x1f) << 8)                                       \
1122    | ((uncond) ? 0x2000 : 0)                                    \
1123    | ((compact) ? 0x4000 : 0)                                   \
1124    | ((link) ? 0x8000 : 0)                                      \
1125    | ((relax32) ? 0x10000 : 0)                                  \
1126    | ((toofar16) ? 0x20000 : 0)                                 \
1127    | ((toofar32) ? 0x40000 : 0))
1128 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1129 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1130 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1131 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1132 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1133 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1134 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1135
1136 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1137 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1138 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1139 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1140 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1141 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1142
1143 /* Sign-extend 16-bit value X.  */
1144 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1145
1146 /* Is the given value a sign-extended 32-bit value?  */
1147 #define IS_SEXT_32BIT_NUM(x)                                            \
1148   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1149    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1150
1151 /* Is the given value a sign-extended 16-bit value?  */
1152 #define IS_SEXT_16BIT_NUM(x)                                            \
1153   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1154    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1155
1156 /* Is the given value a sign-extended 12-bit value?  */
1157 #define IS_SEXT_12BIT_NUM(x)                                            \
1158   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1159
1160 /* Is the given value a sign-extended 9-bit value?  */
1161 #define IS_SEXT_9BIT_NUM(x)                                             \
1162   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1163
1164 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1165 #define IS_ZEXT_32BIT_NUM(x)                                            \
1166   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1167    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1168
1169 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1170    SHIFT places.  */
1171 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1172   (((STRUCT) >> (SHIFT)) & (MASK))
1173
1174 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1175 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1176   (!(MICROMIPS) \
1177    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1178    : EXTRACT_BITS ((INSN).insn_opcode, \
1179                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1180 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1181   EXTRACT_BITS ((INSN).insn_opcode, \
1182                 MIPS16OP_MASK_##FIELD, \
1183                 MIPS16OP_SH_##FIELD)
1184
1185 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1186 #define MIPS16_EXTEND (0xf000U << 16)
1187 \f
1188 /* Whether or not we are emitting a branch-likely macro.  */
1189 static bfd_boolean emit_branch_likely_macro = FALSE;
1190
1191 /* Global variables used when generating relaxable macros.  See the
1192    comment above RELAX_ENCODE for more details about how relaxation
1193    is used.  */
1194 static struct {
1195   /* 0 if we're not emitting a relaxable macro.
1196      1 if we're emitting the first of the two relaxation alternatives.
1197      2 if we're emitting the second alternative.  */
1198   int sequence;
1199
1200   /* The first relaxable fixup in the current frag.  (In other words,
1201      the first fixup that refers to relaxable code.)  */
1202   fixS *first_fixup;
1203
1204   /* sizes[0] says how many bytes of the first alternative are stored in
1205      the current frag.  Likewise sizes[1] for the second alternative.  */
1206   unsigned int sizes[2];
1207
1208   /* The symbol on which the choice of sequence depends.  */
1209   symbolS *symbol;
1210 } mips_relax;
1211 \f
1212 /* Global variables used to decide whether a macro needs a warning.  */
1213 static struct {
1214   /* True if the macro is in a branch delay slot.  */
1215   bfd_boolean delay_slot_p;
1216
1217   /* Set to the length in bytes required if the macro is in a delay slot
1218      that requires a specific length of instruction, otherwise zero.  */
1219   unsigned int delay_slot_length;
1220
1221   /* For relaxable macros, sizes[0] is the length of the first alternative
1222      in bytes and sizes[1] is the length of the second alternative.
1223      For non-relaxable macros, both elements give the length of the
1224      macro in bytes.  */
1225   unsigned int sizes[2];
1226
1227   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1228      instruction of the first alternative in bytes and first_insn_sizes[1]
1229      is the length of the first instruction of the second alternative.
1230      For non-relaxable macros, both elements give the length of the first
1231      instruction in bytes.
1232
1233      Set to zero if we haven't yet seen the first instruction.  */
1234   unsigned int first_insn_sizes[2];
1235
1236   /* For relaxable macros, insns[0] is the number of instructions for the
1237      first alternative and insns[1] is the number of instructions for the
1238      second alternative.
1239
1240      For non-relaxable macros, both elements give the number of
1241      instructions for the macro.  */
1242   unsigned int insns[2];
1243
1244   /* The first variant frag for this macro.  */
1245   fragS *first_frag;
1246 } mips_macro_warning;
1247 \f
1248 /* Prototypes for static functions.  */
1249
1250 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1251
1252 static void append_insn
1253   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1254    bfd_boolean expansionp);
1255 static void mips_no_prev_insn (void);
1256 static void macro_build (expressionS *, const char *, const char *, ...);
1257 static void mips16_macro_build
1258   (expressionS *, const char *, const char *, va_list *);
1259 static void load_register (int, expressionS *, int);
1260 static void macro_start (void);
1261 static void macro_end (void);
1262 static void macro (struct mips_cl_insn *ip, char *str);
1263 static void mips16_macro (struct mips_cl_insn * ip);
1264 static void mips_ip (char *str, struct mips_cl_insn * ip);
1265 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1266 static void mips16_immed
1267   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1268    unsigned int, unsigned long *);
1269 static size_t my_getSmallExpression
1270   (expressionS *, bfd_reloc_code_real_type *, char *);
1271 static void my_getExpression (expressionS *, char *);
1272 static void s_align (int);
1273 static void s_change_sec (int);
1274 static void s_change_section (int);
1275 static void s_cons (int);
1276 static void s_float_cons (int);
1277 static void s_mips_globl (int);
1278 static void s_option (int);
1279 static void s_mipsset (int);
1280 static void s_abicalls (int);
1281 static void s_cpload (int);
1282 static void s_cpsetup (int);
1283 static void s_cplocal (int);
1284 static void s_cprestore (int);
1285 static void s_cpreturn (int);
1286 static void s_dtprelword (int);
1287 static void s_dtpreldword (int);
1288 static void s_tprelword (int);
1289 static void s_tpreldword (int);
1290 static void s_gpvalue (int);
1291 static void s_gpword (int);
1292 static void s_gpdword (int);
1293 static void s_ehword (int);
1294 static void s_cpadd (int);
1295 static void s_insn (int);
1296 static void s_nan (int);
1297 static void s_module (int);
1298 static void s_mips_ent (int);
1299 static void s_mips_end (int);
1300 static void s_mips_frame (int);
1301 static void s_mips_mask (int reg_type);
1302 static void s_mips_stab (int);
1303 static void s_mips_weakext (int);
1304 static void s_mips_file (int);
1305 static void s_mips_loc (int);
1306 static bfd_boolean pic_need_relax (symbolS *, asection *);
1307 static int relaxed_branch_length (fragS *, asection *, int);
1308 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1309 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1310 static void file_mips_check_options (void);
1311
1312 /* Table and functions used to map between CPU/ISA names, and
1313    ISA levels, and CPU numbers.  */
1314
1315 struct mips_cpu_info
1316 {
1317   const char *name;           /* CPU or ISA name.  */
1318   int flags;                  /* MIPS_CPU_* flags.  */
1319   int ase;                    /* Set of ASEs implemented by the CPU.  */
1320   int isa;                    /* ISA level.  */
1321   int cpu;                    /* CPU number (default CPU if ISA).  */
1322 };
1323
1324 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1325
1326 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1327 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1328 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1329 \f
1330 /* Command-line options.  */
1331 const char *md_shortopts = "O::g::G:";
1332
1333 enum options
1334   {
1335     OPTION_MARCH = OPTION_MD_BASE,
1336     OPTION_MTUNE,
1337     OPTION_MIPS1,
1338     OPTION_MIPS2,
1339     OPTION_MIPS3,
1340     OPTION_MIPS4,
1341     OPTION_MIPS5,
1342     OPTION_MIPS32,
1343     OPTION_MIPS64,
1344     OPTION_MIPS32R2,
1345     OPTION_MIPS32R3,
1346     OPTION_MIPS32R5,
1347     OPTION_MIPS64R2,
1348     OPTION_MIPS64R3,
1349     OPTION_MIPS64R5,
1350     OPTION_MIPS16,
1351     OPTION_NO_MIPS16,
1352     OPTION_MIPS3D,
1353     OPTION_NO_MIPS3D,
1354     OPTION_MDMX,
1355     OPTION_NO_MDMX,
1356     OPTION_DSP,
1357     OPTION_NO_DSP,
1358     OPTION_MT,
1359     OPTION_NO_MT,
1360     OPTION_VIRT,
1361     OPTION_NO_VIRT,
1362     OPTION_MSA,
1363     OPTION_NO_MSA,
1364     OPTION_SMARTMIPS,
1365     OPTION_NO_SMARTMIPS,
1366     OPTION_DSPR2,
1367     OPTION_NO_DSPR2,
1368     OPTION_EVA,
1369     OPTION_NO_EVA,
1370     OPTION_XPA,
1371     OPTION_NO_XPA,
1372     OPTION_MICROMIPS,
1373     OPTION_NO_MICROMIPS,
1374     OPTION_MCU,
1375     OPTION_NO_MCU,
1376     OPTION_COMPAT_ARCH_BASE,
1377     OPTION_M4650,
1378     OPTION_NO_M4650,
1379     OPTION_M4010,
1380     OPTION_NO_M4010,
1381     OPTION_M4100,
1382     OPTION_NO_M4100,
1383     OPTION_M3900,
1384     OPTION_NO_M3900,
1385     OPTION_M7000_HILO_FIX,
1386     OPTION_MNO_7000_HILO_FIX,
1387     OPTION_FIX_24K,
1388     OPTION_NO_FIX_24K,
1389     OPTION_FIX_RM7000,
1390     OPTION_NO_FIX_RM7000,
1391     OPTION_FIX_LOONGSON2F_JUMP,
1392     OPTION_NO_FIX_LOONGSON2F_JUMP,
1393     OPTION_FIX_LOONGSON2F_NOP,
1394     OPTION_NO_FIX_LOONGSON2F_NOP,
1395     OPTION_FIX_VR4120,
1396     OPTION_NO_FIX_VR4120,
1397     OPTION_FIX_VR4130,
1398     OPTION_NO_FIX_VR4130,
1399     OPTION_FIX_CN63XXP1,
1400     OPTION_NO_FIX_CN63XXP1,
1401     OPTION_TRAP,
1402     OPTION_BREAK,
1403     OPTION_EB,
1404     OPTION_EL,
1405     OPTION_FP32,
1406     OPTION_GP32,
1407     OPTION_CONSTRUCT_FLOATS,
1408     OPTION_NO_CONSTRUCT_FLOATS,
1409     OPTION_FP64,
1410     OPTION_GP64,
1411     OPTION_RELAX_BRANCH,
1412     OPTION_NO_RELAX_BRANCH,
1413     OPTION_INSN32,
1414     OPTION_NO_INSN32,
1415     OPTION_MSHARED,
1416     OPTION_MNO_SHARED,
1417     OPTION_MSYM32,
1418     OPTION_MNO_SYM32,
1419     OPTION_SOFT_FLOAT,
1420     OPTION_HARD_FLOAT,
1421     OPTION_SINGLE_FLOAT,
1422     OPTION_DOUBLE_FLOAT,
1423     OPTION_32,
1424     OPTION_CALL_SHARED,
1425     OPTION_CALL_NONPIC,
1426     OPTION_NON_SHARED,
1427     OPTION_XGOT,
1428     OPTION_MABI,
1429     OPTION_N32,
1430     OPTION_64,
1431     OPTION_MDEBUG,
1432     OPTION_NO_MDEBUG,
1433     OPTION_PDR,
1434     OPTION_NO_PDR,
1435     OPTION_MVXWORKS_PIC,
1436     OPTION_NAN,
1437     OPTION_END_OF_ENUM
1438   };
1439
1440 struct option md_longopts[] =
1441 {
1442   /* Options which specify architecture.  */
1443   {"march", required_argument, NULL, OPTION_MARCH},
1444   {"mtune", required_argument, NULL, OPTION_MTUNE},
1445   {"mips0", no_argument, NULL, OPTION_MIPS1},
1446   {"mips1", no_argument, NULL, OPTION_MIPS1},
1447   {"mips2", no_argument, NULL, OPTION_MIPS2},
1448   {"mips3", no_argument, NULL, OPTION_MIPS3},
1449   {"mips4", no_argument, NULL, OPTION_MIPS4},
1450   {"mips5", no_argument, NULL, OPTION_MIPS5},
1451   {"mips32", no_argument, NULL, OPTION_MIPS32},
1452   {"mips64", no_argument, NULL, OPTION_MIPS64},
1453   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1454   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1455   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1456   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1457   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1458   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1459
1460   /* Options which specify Application Specific Extensions (ASEs).  */
1461   {"mips16", no_argument, NULL, OPTION_MIPS16},
1462   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1463   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1464   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1465   {"mdmx", no_argument, NULL, OPTION_MDMX},
1466   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1467   {"mdsp", no_argument, NULL, OPTION_DSP},
1468   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1469   {"mmt", no_argument, NULL, OPTION_MT},
1470   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1471   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1472   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1473   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1474   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1475   {"meva", no_argument, NULL, OPTION_EVA},
1476   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1477   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1478   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1479   {"mmcu", no_argument, NULL, OPTION_MCU},
1480   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1481   {"mvirt", no_argument, NULL, OPTION_VIRT},
1482   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1483   {"mmsa", no_argument, NULL, OPTION_MSA},
1484   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1485   {"mxpa", no_argument, NULL, OPTION_XPA},
1486   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1487
1488   /* Old-style architecture options.  Don't add more of these.  */
1489   {"m4650", no_argument, NULL, OPTION_M4650},
1490   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1491   {"m4010", no_argument, NULL, OPTION_M4010},
1492   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1493   {"m4100", no_argument, NULL, OPTION_M4100},
1494   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1495   {"m3900", no_argument, NULL, OPTION_M3900},
1496   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1497
1498   /* Options which enable bug fixes.  */
1499   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1500   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1501   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1502   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1503   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1504   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1505   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1506   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1507   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1508   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1509   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1510   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1511   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1512   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1513   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1514   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1515   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1516
1517   /* Miscellaneous options.  */
1518   {"trap", no_argument, NULL, OPTION_TRAP},
1519   {"no-break", no_argument, NULL, OPTION_TRAP},
1520   {"break", no_argument, NULL, OPTION_BREAK},
1521   {"no-trap", no_argument, NULL, OPTION_BREAK},
1522   {"EB", no_argument, NULL, OPTION_EB},
1523   {"EL", no_argument, NULL, OPTION_EL},
1524   {"mfp32", no_argument, NULL, OPTION_FP32},
1525   {"mgp32", no_argument, NULL, OPTION_GP32},
1526   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1527   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1528   {"mfp64", no_argument, NULL, OPTION_FP64},
1529   {"mgp64", no_argument, NULL, OPTION_GP64},
1530   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1531   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1532   {"minsn32", no_argument, NULL, OPTION_INSN32},
1533   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1534   {"mshared", no_argument, NULL, OPTION_MSHARED},
1535   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1536   {"msym32", no_argument, NULL, OPTION_MSYM32},
1537   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1538   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1539   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1540   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1541   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1542
1543   /* Strictly speaking this next option is ELF specific,
1544      but we allow it for other ports as well in order to
1545      make testing easier.  */
1546   {"32", no_argument, NULL, OPTION_32},
1547
1548   /* ELF-specific options.  */
1549   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1550   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1551   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1552   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1553   {"xgot", no_argument, NULL, OPTION_XGOT},
1554   {"mabi", required_argument, NULL, OPTION_MABI},
1555   {"n32", no_argument, NULL, OPTION_N32},
1556   {"64", no_argument, NULL, OPTION_64},
1557   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1558   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1559   {"mpdr", no_argument, NULL, OPTION_PDR},
1560   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1561   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1562   {"mnan", required_argument, NULL, OPTION_NAN},
1563
1564   {NULL, no_argument, NULL, 0}
1565 };
1566 size_t md_longopts_size = sizeof (md_longopts);
1567 \f
1568 /* Information about either an Application Specific Extension or an
1569    optional architecture feature that, for simplicity, we treat in the
1570    same way as an ASE.  */
1571 struct mips_ase
1572 {
1573   /* The name of the ASE, used in both the command-line and .set options.  */
1574   const char *name;
1575
1576   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1577      and 64-bit architectures, the flags here refer to the subset that
1578      is available on both.  */
1579   unsigned int flags;
1580
1581   /* The ASE_* flag used for instructions that are available on 64-bit
1582      architectures but that are not included in FLAGS.  */
1583   unsigned int flags64;
1584
1585   /* The command-line options that turn the ASE on and off.  */
1586   int option_on;
1587   int option_off;
1588
1589   /* The minimum required architecture revisions for MIPS32, MIPS64,
1590      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1591   int mips32_rev;
1592   int mips64_rev;
1593   int micromips32_rev;
1594   int micromips64_rev;
1595 };
1596
1597 /* A table of all supported ASEs.  */
1598 static const struct mips_ase mips_ases[] = {
1599   { "dsp", ASE_DSP, ASE_DSP64,
1600     OPTION_DSP, OPTION_NO_DSP,
1601     2, 2, 2, 2 },
1602
1603   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1604     OPTION_DSPR2, OPTION_NO_DSPR2,
1605     2, 2, 2, 2 },
1606
1607   { "eva", ASE_EVA, 0,
1608     OPTION_EVA, OPTION_NO_EVA,
1609     2, 2, 2, 2 },
1610
1611   { "mcu", ASE_MCU, 0,
1612     OPTION_MCU, OPTION_NO_MCU,
1613     2, 2, 2, 2 },
1614
1615   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1616   { "mdmx", ASE_MDMX, 0,
1617     OPTION_MDMX, OPTION_NO_MDMX,
1618     -1, 1, -1, -1 },
1619
1620   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1621   { "mips3d", ASE_MIPS3D, 0,
1622     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1623     2, 1, -1, -1 },
1624
1625   { "mt", ASE_MT, 0,
1626     OPTION_MT, OPTION_NO_MT,
1627     2, 2, -1, -1 },
1628
1629   { "smartmips", ASE_SMARTMIPS, 0,
1630     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1631     1, -1, -1, -1 },
1632
1633   { "virt", ASE_VIRT, ASE_VIRT64,
1634     OPTION_VIRT, OPTION_NO_VIRT,
1635     2, 2, 2, 2 },
1636
1637   { "msa", ASE_MSA, ASE_MSA64,
1638     OPTION_MSA, OPTION_NO_MSA,
1639     2, 2, 2, 2 },
1640
1641   { "xpa", ASE_XPA, 0,
1642     OPTION_XPA, OPTION_NO_XPA,
1643     2, 2, -1, -1 }
1644 };
1645
1646 /* The set of ASEs that require -mfp64.  */
1647 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1648
1649 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1650 static const unsigned int mips_ase_groups[] = {
1651   ASE_DSP | ASE_DSPR2
1652 };
1653 \f
1654 /* Pseudo-op table.
1655
1656    The following pseudo-ops from the Kane and Heinrich MIPS book
1657    should be defined here, but are currently unsupported: .alias,
1658    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1659
1660    The following pseudo-ops from the Kane and Heinrich MIPS book are
1661    specific to the type of debugging information being generated, and
1662    should be defined by the object format: .aent, .begin, .bend,
1663    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1664    .vreg.
1665
1666    The following pseudo-ops from the Kane and Heinrich MIPS book are
1667    not MIPS CPU specific, but are also not specific to the object file
1668    format.  This file is probably the best place to define them, but
1669    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1670
1671 static const pseudo_typeS mips_pseudo_table[] =
1672 {
1673   /* MIPS specific pseudo-ops.  */
1674   {"option", s_option, 0},
1675   {"set", s_mipsset, 0},
1676   {"rdata", s_change_sec, 'r'},
1677   {"sdata", s_change_sec, 's'},
1678   {"livereg", s_ignore, 0},
1679   {"abicalls", s_abicalls, 0},
1680   {"cpload", s_cpload, 0},
1681   {"cpsetup", s_cpsetup, 0},
1682   {"cplocal", s_cplocal, 0},
1683   {"cprestore", s_cprestore, 0},
1684   {"cpreturn", s_cpreturn, 0},
1685   {"dtprelword", s_dtprelword, 0},
1686   {"dtpreldword", s_dtpreldword, 0},
1687   {"tprelword", s_tprelword, 0},
1688   {"tpreldword", s_tpreldword, 0},
1689   {"gpvalue", s_gpvalue, 0},
1690   {"gpword", s_gpword, 0},
1691   {"gpdword", s_gpdword, 0},
1692   {"ehword", s_ehword, 0},
1693   {"cpadd", s_cpadd, 0},
1694   {"insn", s_insn, 0},
1695   {"nan", s_nan, 0},
1696   {"module", s_module, 0},
1697
1698   /* Relatively generic pseudo-ops that happen to be used on MIPS
1699      chips.  */
1700   {"asciiz", stringer, 8 + 1},
1701   {"bss", s_change_sec, 'b'},
1702   {"err", s_err, 0},
1703   {"half", s_cons, 1},
1704   {"dword", s_cons, 3},
1705   {"weakext", s_mips_weakext, 0},
1706   {"origin", s_org, 0},
1707   {"repeat", s_rept, 0},
1708
1709   /* For MIPS this is non-standard, but we define it for consistency.  */
1710   {"sbss", s_change_sec, 'B'},
1711
1712   /* These pseudo-ops are defined in read.c, but must be overridden
1713      here for one reason or another.  */
1714   {"align", s_align, 0},
1715   {"byte", s_cons, 0},
1716   {"data", s_change_sec, 'd'},
1717   {"double", s_float_cons, 'd'},
1718   {"float", s_float_cons, 'f'},
1719   {"globl", s_mips_globl, 0},
1720   {"global", s_mips_globl, 0},
1721   {"hword", s_cons, 1},
1722   {"int", s_cons, 2},
1723   {"long", s_cons, 2},
1724   {"octa", s_cons, 4},
1725   {"quad", s_cons, 3},
1726   {"section", s_change_section, 0},
1727   {"short", s_cons, 1},
1728   {"single", s_float_cons, 'f'},
1729   {"stabd", s_mips_stab, 'd'},
1730   {"stabn", s_mips_stab, 'n'},
1731   {"stabs", s_mips_stab, 's'},
1732   {"text", s_change_sec, 't'},
1733   {"word", s_cons, 2},
1734
1735   { "extern", ecoff_directive_extern, 0},
1736
1737   { NULL, NULL, 0 },
1738 };
1739
1740 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1741 {
1742   /* These pseudo-ops should be defined by the object file format.
1743      However, a.out doesn't support them, so we have versions here.  */
1744   {"aent", s_mips_ent, 1},
1745   {"bgnb", s_ignore, 0},
1746   {"end", s_mips_end, 0},
1747   {"endb", s_ignore, 0},
1748   {"ent", s_mips_ent, 0},
1749   {"file", s_mips_file, 0},
1750   {"fmask", s_mips_mask, 'F'},
1751   {"frame", s_mips_frame, 0},
1752   {"loc", s_mips_loc, 0},
1753   {"mask", s_mips_mask, 'R'},
1754   {"verstamp", s_ignore, 0},
1755   { NULL, NULL, 0 },
1756 };
1757
1758 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1759    purpose of the `.dc.a' internal pseudo-op.  */
1760
1761 int
1762 mips_address_bytes (void)
1763 {
1764   file_mips_check_options ();
1765   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1766 }
1767
1768 extern void pop_insert (const pseudo_typeS *);
1769
1770 void
1771 mips_pop_insert (void)
1772 {
1773   pop_insert (mips_pseudo_table);
1774   if (! ECOFF_DEBUGGING)
1775     pop_insert (mips_nonecoff_pseudo_table);
1776 }
1777 \f
1778 /* Symbols labelling the current insn.  */
1779
1780 struct insn_label_list
1781 {
1782   struct insn_label_list *next;
1783   symbolS *label;
1784 };
1785
1786 static struct insn_label_list *free_insn_labels;
1787 #define label_list tc_segment_info_data.labels
1788
1789 static void mips_clear_insn_labels (void);
1790 static void mips_mark_labels (void);
1791 static void mips_compressed_mark_labels (void);
1792
1793 static inline void
1794 mips_clear_insn_labels (void)
1795 {
1796   register struct insn_label_list **pl;
1797   segment_info_type *si;
1798
1799   if (now_seg)
1800     {
1801       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1802         ;
1803       
1804       si = seg_info (now_seg);
1805       *pl = si->label_list;
1806       si->label_list = NULL;
1807     }
1808 }
1809
1810 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1811
1812 static inline void
1813 mips_mark_labels (void)
1814 {
1815   if (HAVE_CODE_COMPRESSION)
1816     mips_compressed_mark_labels ();
1817 }
1818 \f
1819 static char *expr_end;
1820
1821 /* An expression in a macro instruction.  This is set by mips_ip and
1822    mips16_ip and when populated is always an O_constant.  */
1823
1824 static expressionS imm_expr;
1825
1826 /* The relocatable field in an instruction and the relocs associated
1827    with it.  These variables are used for instructions like LUI and
1828    JAL as well as true offsets.  They are also used for address
1829    operands in macros.  */
1830
1831 static expressionS offset_expr;
1832 static bfd_reloc_code_real_type offset_reloc[3]
1833   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1834
1835 /* This is set to the resulting size of the instruction to be produced
1836    by mips16_ip if an explicit extension is used or by mips_ip if an
1837    explicit size is supplied.  */
1838
1839 static unsigned int forced_insn_length;
1840
1841 /* True if we are assembling an instruction.  All dot symbols defined during
1842    this time should be treated as code labels.  */
1843
1844 static bfd_boolean mips_assembling_insn;
1845
1846 /* The pdr segment for per procedure frame/regmask info.  Not used for
1847    ECOFF debugging.  */
1848
1849 static segT pdr_seg;
1850
1851 /* The default target format to use.  */
1852
1853 #if defined (TE_FreeBSD)
1854 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1855 #elif defined (TE_TMIPS)
1856 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1857 #else
1858 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1859 #endif
1860
1861 const char *
1862 mips_target_format (void)
1863 {
1864   switch (OUTPUT_FLAVOR)
1865     {
1866     case bfd_target_elf_flavour:
1867 #ifdef TE_VXWORKS
1868       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1869         return (target_big_endian
1870                 ? "elf32-bigmips-vxworks"
1871                 : "elf32-littlemips-vxworks");
1872 #endif
1873       return (target_big_endian
1874               ? (HAVE_64BIT_OBJECTS
1875                  ? ELF_TARGET ("elf64-", "big")
1876                  : (HAVE_NEWABI
1877                     ? ELF_TARGET ("elf32-n", "big")
1878                     : ELF_TARGET ("elf32-", "big")))
1879               : (HAVE_64BIT_OBJECTS
1880                  ? ELF_TARGET ("elf64-", "little")
1881                  : (HAVE_NEWABI
1882                     ? ELF_TARGET ("elf32-n", "little")
1883                     : ELF_TARGET ("elf32-", "little"))));
1884     default:
1885       abort ();
1886       return NULL;
1887     }
1888 }
1889
1890 /* Return the ISA revision that is currently in use, or 0 if we are
1891    generating code for MIPS V or below.  */
1892
1893 static int
1894 mips_isa_rev (void)
1895 {
1896   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1897     return 2;
1898
1899   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
1900     return 3;
1901
1902   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
1903     return 5;
1904
1905   /* microMIPS implies revision 2 or above.  */
1906   if (mips_opts.micromips)
1907     return 2;
1908
1909   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1910     return 1;
1911
1912   return 0;
1913 }
1914
1915 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1916
1917 static unsigned int
1918 mips_ase_mask (unsigned int flags)
1919 {
1920   unsigned int i;
1921
1922   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1923     if (flags & mips_ase_groups[i])
1924       flags |= mips_ase_groups[i];
1925   return flags;
1926 }
1927
1928 /* Check whether the current ISA supports ASE.  Issue a warning if
1929    appropriate.  */
1930
1931 static void
1932 mips_check_isa_supports_ase (const struct mips_ase *ase)
1933 {
1934   const char *base;
1935   int min_rev, size;
1936   static unsigned int warned_isa;
1937   static unsigned int warned_fp32;
1938
1939   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1940     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1941   else
1942     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1943   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1944       && (warned_isa & ase->flags) != ase->flags)
1945     {
1946       warned_isa |= ase->flags;
1947       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1948       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1949       if (min_rev < 0)
1950         as_warn (_("the %d-bit %s architecture does not support the"
1951                    " `%s' extension"), size, base, ase->name);
1952       else
1953         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1954                  ase->name, base, size, min_rev);
1955     }
1956   if ((ase->flags & FP64_ASES)
1957       && mips_opts.fp != 64
1958       && (warned_fp32 & ase->flags) != ase->flags)
1959     {
1960       warned_fp32 |= ase->flags;
1961       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1962     }
1963 }
1964
1965 /* Check all enabled ASEs to see whether they are supported by the
1966    chosen architecture.  */
1967
1968 static void
1969 mips_check_isa_supports_ases (void)
1970 {
1971   unsigned int i, mask;
1972
1973   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1974     {
1975       mask = mips_ase_mask (mips_ases[i].flags);
1976       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1977         mips_check_isa_supports_ase (&mips_ases[i]);
1978     }
1979 }
1980
1981 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1982    that were affected.  */
1983
1984 static unsigned int
1985 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
1986               bfd_boolean enabled_p)
1987 {
1988   unsigned int mask;
1989
1990   mask = mips_ase_mask (ase->flags);
1991   opts->ase &= ~mask;
1992   if (enabled_p)
1993     opts->ase |= ase->flags;
1994   return mask;
1995 }
1996
1997 /* Return the ASE called NAME, or null if none.  */
1998
1999 static const struct mips_ase *
2000 mips_lookup_ase (const char *name)
2001 {
2002   unsigned int i;
2003
2004   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2005     if (strcmp (name, mips_ases[i].name) == 0)
2006       return &mips_ases[i];
2007   return NULL;
2008 }
2009
2010 /* Return the length of a microMIPS instruction in bytes.  If bits of
2011    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
2012    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
2013    major opcode) will require further modifications to the opcode
2014    table.  */
2015
2016 static inline unsigned int
2017 micromips_insn_length (const struct mips_opcode *mo)
2018 {
2019   return (mo->mask >> 16) == 0 ? 2 : 4;
2020 }
2021
2022 /* Return the length of MIPS16 instruction OPCODE.  */
2023
2024 static inline unsigned int
2025 mips16_opcode_length (unsigned long opcode)
2026 {
2027   return (opcode >> 16) == 0 ? 2 : 4;
2028 }
2029
2030 /* Return the length of instruction INSN.  */
2031
2032 static inline unsigned int
2033 insn_length (const struct mips_cl_insn *insn)
2034 {
2035   if (mips_opts.micromips)
2036     return micromips_insn_length (insn->insn_mo);
2037   else if (mips_opts.mips16)
2038     return mips16_opcode_length (insn->insn_opcode);
2039   else
2040     return 4;
2041 }
2042
2043 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2044
2045 static void
2046 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2047 {
2048   size_t i;
2049
2050   insn->insn_mo = mo;
2051   insn->insn_opcode = mo->match;
2052   insn->frag = NULL;
2053   insn->where = 0;
2054   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2055     insn->fixp[i] = NULL;
2056   insn->fixed_p = (mips_opts.noreorder > 0);
2057   insn->noreorder_p = (mips_opts.noreorder > 0);
2058   insn->mips16_absolute_jump_p = 0;
2059   insn->complete_p = 0;
2060   insn->cleared_p = 0;
2061 }
2062
2063 /* Get a list of all the operands in INSN.  */
2064
2065 static const struct mips_operand_array *
2066 insn_operands (const struct mips_cl_insn *insn)
2067 {
2068   if (insn->insn_mo >= &mips_opcodes[0]
2069       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2070     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2071
2072   if (insn->insn_mo >= &mips16_opcodes[0]
2073       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2074     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2075
2076   if (insn->insn_mo >= &micromips_opcodes[0]
2077       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2078     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2079
2080   abort ();
2081 }
2082
2083 /* Get a description of operand OPNO of INSN.  */
2084
2085 static const struct mips_operand *
2086 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2087 {
2088   const struct mips_operand_array *operands;
2089
2090   operands = insn_operands (insn);
2091   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2092     abort ();
2093   return operands->operand[opno];
2094 }
2095
2096 /* Install UVAL as the value of OPERAND in INSN.  */
2097
2098 static inline void
2099 insn_insert_operand (struct mips_cl_insn *insn,
2100                      const struct mips_operand *operand, unsigned int uval)
2101 {
2102   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2103 }
2104
2105 /* Extract the value of OPERAND from INSN.  */
2106
2107 static inline unsigned
2108 insn_extract_operand (const struct mips_cl_insn *insn,
2109                       const struct mips_operand *operand)
2110 {
2111   return mips_extract_operand (operand, insn->insn_opcode);
2112 }
2113
2114 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2115
2116 static void
2117 mips_record_compressed_mode (void)
2118 {
2119   segment_info_type *si;
2120
2121   si = seg_info (now_seg);
2122   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2123     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2124   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2125     si->tc_segment_info_data.micromips = mips_opts.micromips;
2126 }
2127
2128 /* Read a standard MIPS instruction from BUF.  */
2129
2130 static unsigned long
2131 read_insn (char *buf)
2132 {
2133   if (target_big_endian)
2134     return bfd_getb32 ((bfd_byte *) buf);
2135   else
2136     return bfd_getl32 ((bfd_byte *) buf);
2137 }
2138
2139 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2140    the next byte.  */
2141
2142 static char *
2143 write_insn (char *buf, unsigned int insn)
2144 {
2145   md_number_to_chars (buf, insn, 4);
2146   return buf + 4;
2147 }
2148
2149 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2150    has length LENGTH.  */
2151
2152 static unsigned long
2153 read_compressed_insn (char *buf, unsigned int length)
2154 {
2155   unsigned long insn;
2156   unsigned int i;
2157
2158   insn = 0;
2159   for (i = 0; i < length; i += 2)
2160     {
2161       insn <<= 16;
2162       if (target_big_endian)
2163         insn |= bfd_getb16 ((char *) buf);
2164       else
2165         insn |= bfd_getl16 ((char *) buf);
2166       buf += 2;
2167     }
2168   return insn;
2169 }
2170
2171 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2172    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2173
2174 static char *
2175 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2176 {
2177   unsigned int i;
2178
2179   for (i = 0; i < length; i += 2)
2180     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2181   return buf + length;
2182 }
2183
2184 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2185
2186 static void
2187 install_insn (const struct mips_cl_insn *insn)
2188 {
2189   char *f = insn->frag->fr_literal + insn->where;
2190   if (HAVE_CODE_COMPRESSION)
2191     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2192   else
2193     write_insn (f, insn->insn_opcode);
2194   mips_record_compressed_mode ();
2195 }
2196
2197 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2198    and install the opcode in the new location.  */
2199
2200 static void
2201 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2202 {
2203   size_t i;
2204
2205   insn->frag = frag;
2206   insn->where = where;
2207   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2208     if (insn->fixp[i] != NULL)
2209       {
2210         insn->fixp[i]->fx_frag = frag;
2211         insn->fixp[i]->fx_where = where;
2212       }
2213   install_insn (insn);
2214 }
2215
2216 /* Add INSN to the end of the output.  */
2217
2218 static void
2219 add_fixed_insn (struct mips_cl_insn *insn)
2220 {
2221   char *f = frag_more (insn_length (insn));
2222   move_insn (insn, frag_now, f - frag_now->fr_literal);
2223 }
2224
2225 /* Start a variant frag and move INSN to the start of the variant part,
2226    marking it as fixed.  The other arguments are as for frag_var.  */
2227
2228 static void
2229 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2230                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2231 {
2232   frag_grow (max_chars);
2233   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2234   insn->fixed_p = 1;
2235   frag_var (rs_machine_dependent, max_chars, var,
2236             subtype, symbol, offset, NULL);
2237 }
2238
2239 /* Insert N copies of INSN into the history buffer, starting at
2240    position FIRST.  Neither FIRST nor N need to be clipped.  */
2241
2242 static void
2243 insert_into_history (unsigned int first, unsigned int n,
2244                      const struct mips_cl_insn *insn)
2245 {
2246   if (mips_relax.sequence != 2)
2247     {
2248       unsigned int i;
2249
2250       for (i = ARRAY_SIZE (history); i-- > first;)
2251         if (i >= first + n)
2252           history[i] = history[i - n];
2253         else
2254           history[i] = *insn;
2255     }
2256 }
2257
2258 /* Clear the error in insn_error.  */
2259
2260 static void
2261 clear_insn_error (void)
2262 {
2263   memset (&insn_error, 0, sizeof (insn_error));
2264 }
2265
2266 /* Possibly record error message MSG for the current instruction.
2267    If the error is about a particular argument, ARGNUM is the 1-based
2268    number of that argument, otherwise it is 0.  FORMAT is the format
2269    of MSG.  Return true if MSG was used, false if the current message
2270    was kept.  */
2271
2272 static bfd_boolean
2273 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2274                        const char *msg)
2275 {
2276   if (argnum == 0)
2277     {
2278       /* Give priority to errors against specific arguments, and to
2279          the first whole-instruction message.  */
2280       if (insn_error.msg)
2281         return FALSE;
2282     }
2283   else
2284     {
2285       /* Keep insn_error if it is against a later argument.  */
2286       if (argnum < insn_error.min_argnum)
2287         return FALSE;
2288
2289       /* If both errors are against the same argument but are different,
2290          give up on reporting a specific error for this argument.
2291          See the comment about mips_insn_error for details.  */
2292       if (argnum == insn_error.min_argnum
2293           && insn_error.msg
2294           && strcmp (insn_error.msg, msg) != 0)
2295         {
2296           insn_error.msg = 0;
2297           insn_error.min_argnum += 1;
2298           return FALSE;
2299         }
2300     }
2301   insn_error.min_argnum = argnum;
2302   insn_error.format = format;
2303   insn_error.msg = msg;
2304   return TRUE;
2305 }
2306
2307 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2308    as for set_insn_error_format.  */
2309
2310 static void
2311 set_insn_error (int argnum, const char *msg)
2312 {
2313   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2314 }
2315
2316 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2317    as for set_insn_error_format.  */
2318
2319 static void
2320 set_insn_error_i (int argnum, const char *msg, int i)
2321 {
2322   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2323     insn_error.u.i = i;
2324 }
2325
2326 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2327    are as for set_insn_error_format.  */
2328
2329 static void
2330 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2331 {
2332   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2333     {
2334       insn_error.u.ss[0] = s1;
2335       insn_error.u.ss[1] = s2;
2336     }
2337 }
2338
2339 /* Report the error in insn_error, which is against assembly code STR.  */
2340
2341 static void
2342 report_insn_error (const char *str)
2343 {
2344   const char *msg;
2345
2346   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2347   switch (insn_error.format)
2348     {
2349     case ERR_FMT_PLAIN:
2350       as_bad (msg, str);
2351       break;
2352
2353     case ERR_FMT_I:
2354       as_bad (msg, insn_error.u.i, str);
2355       break;
2356
2357     case ERR_FMT_SS:
2358       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2359       break;
2360     }
2361 }
2362
2363 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2364    the idea is to make it obvious at a glance that each errata is
2365    included.  */
2366
2367 static void
2368 init_vr4120_conflicts (void)
2369 {
2370 #define CONFLICT(FIRST, SECOND) \
2371     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2372
2373   /* Errata 21 - [D]DIV[U] after [D]MACC */
2374   CONFLICT (MACC, DIV);
2375   CONFLICT (DMACC, DIV);
2376
2377   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2378   CONFLICT (DMULT, DMULT);
2379   CONFLICT (DMULT, DMACC);
2380   CONFLICT (DMACC, DMULT);
2381   CONFLICT (DMACC, DMACC);
2382
2383   /* Errata 24 - MT{LO,HI} after [D]MACC */
2384   CONFLICT (MACC, MTHILO);
2385   CONFLICT (DMACC, MTHILO);
2386
2387   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2388      instruction is executed immediately after a MACC or DMACC
2389      instruction, the result of [either instruction] is incorrect."  */
2390   CONFLICT (MACC, MULT);
2391   CONFLICT (MACC, DMULT);
2392   CONFLICT (DMACC, MULT);
2393   CONFLICT (DMACC, DMULT);
2394
2395   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2396      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2397      DDIV or DDIVU instruction, the result of the MACC or
2398      DMACC instruction is incorrect.".  */
2399   CONFLICT (DMULT, MACC);
2400   CONFLICT (DMULT, DMACC);
2401   CONFLICT (DIV, MACC);
2402   CONFLICT (DIV, DMACC);
2403
2404 #undef CONFLICT
2405 }
2406
2407 struct regname {
2408   const char *name;
2409   unsigned int num;
2410 };
2411
2412 #define RNUM_MASK       0x00000ff
2413 #define RTYPE_MASK      0x0ffff00
2414 #define RTYPE_NUM       0x0000100
2415 #define RTYPE_FPU       0x0000200
2416 #define RTYPE_FCC       0x0000400
2417 #define RTYPE_VEC       0x0000800
2418 #define RTYPE_GP        0x0001000
2419 #define RTYPE_CP0       0x0002000
2420 #define RTYPE_PC        0x0004000
2421 #define RTYPE_ACC       0x0008000
2422 #define RTYPE_CCC       0x0010000
2423 #define RTYPE_VI        0x0020000
2424 #define RTYPE_VF        0x0040000
2425 #define RTYPE_R5900_I   0x0080000
2426 #define RTYPE_R5900_Q   0x0100000
2427 #define RTYPE_R5900_R   0x0200000
2428 #define RTYPE_R5900_ACC 0x0400000
2429 #define RTYPE_MSA       0x0800000
2430 #define RWARN           0x8000000
2431
2432 #define GENERIC_REGISTER_NUMBERS \
2433     {"$0",      RTYPE_NUM | 0},  \
2434     {"$1",      RTYPE_NUM | 1},  \
2435     {"$2",      RTYPE_NUM | 2},  \
2436     {"$3",      RTYPE_NUM | 3},  \
2437     {"$4",      RTYPE_NUM | 4},  \
2438     {"$5",      RTYPE_NUM | 5},  \
2439     {"$6",      RTYPE_NUM | 6},  \
2440     {"$7",      RTYPE_NUM | 7},  \
2441     {"$8",      RTYPE_NUM | 8},  \
2442     {"$9",      RTYPE_NUM | 9},  \
2443     {"$10",     RTYPE_NUM | 10}, \
2444     {"$11",     RTYPE_NUM | 11}, \
2445     {"$12",     RTYPE_NUM | 12}, \
2446     {"$13",     RTYPE_NUM | 13}, \
2447     {"$14",     RTYPE_NUM | 14}, \
2448     {"$15",     RTYPE_NUM | 15}, \
2449     {"$16",     RTYPE_NUM | 16}, \
2450     {"$17",     RTYPE_NUM | 17}, \
2451     {"$18",     RTYPE_NUM | 18}, \
2452     {"$19",     RTYPE_NUM | 19}, \
2453     {"$20",     RTYPE_NUM | 20}, \
2454     {"$21",     RTYPE_NUM | 21}, \
2455     {"$22",     RTYPE_NUM | 22}, \
2456     {"$23",     RTYPE_NUM | 23}, \
2457     {"$24",     RTYPE_NUM | 24}, \
2458     {"$25",     RTYPE_NUM | 25}, \
2459     {"$26",     RTYPE_NUM | 26}, \
2460     {"$27",     RTYPE_NUM | 27}, \
2461     {"$28",     RTYPE_NUM | 28}, \
2462     {"$29",     RTYPE_NUM | 29}, \
2463     {"$30",     RTYPE_NUM | 30}, \
2464     {"$31",     RTYPE_NUM | 31} 
2465
2466 #define FPU_REGISTER_NAMES       \
2467     {"$f0",     RTYPE_FPU | 0},  \
2468     {"$f1",     RTYPE_FPU | 1},  \
2469     {"$f2",     RTYPE_FPU | 2},  \
2470     {"$f3",     RTYPE_FPU | 3},  \
2471     {"$f4",     RTYPE_FPU | 4},  \
2472     {"$f5",     RTYPE_FPU | 5},  \
2473     {"$f6",     RTYPE_FPU | 6},  \
2474     {"$f7",     RTYPE_FPU | 7},  \
2475     {"$f8",     RTYPE_FPU | 8},  \
2476     {"$f9",     RTYPE_FPU | 9},  \
2477     {"$f10",    RTYPE_FPU | 10}, \
2478     {"$f11",    RTYPE_FPU | 11}, \
2479     {"$f12",    RTYPE_FPU | 12}, \
2480     {"$f13",    RTYPE_FPU | 13}, \
2481     {"$f14",    RTYPE_FPU | 14}, \
2482     {"$f15",    RTYPE_FPU | 15}, \
2483     {"$f16",    RTYPE_FPU | 16}, \
2484     {"$f17",    RTYPE_FPU | 17}, \
2485     {"$f18",    RTYPE_FPU | 18}, \
2486     {"$f19",    RTYPE_FPU | 19}, \
2487     {"$f20",    RTYPE_FPU | 20}, \
2488     {"$f21",    RTYPE_FPU | 21}, \
2489     {"$f22",    RTYPE_FPU | 22}, \
2490     {"$f23",    RTYPE_FPU | 23}, \
2491     {"$f24",    RTYPE_FPU | 24}, \
2492     {"$f25",    RTYPE_FPU | 25}, \
2493     {"$f26",    RTYPE_FPU | 26}, \
2494     {"$f27",    RTYPE_FPU | 27}, \
2495     {"$f28",    RTYPE_FPU | 28}, \
2496     {"$f29",    RTYPE_FPU | 29}, \
2497     {"$f30",    RTYPE_FPU | 30}, \
2498     {"$f31",    RTYPE_FPU | 31}
2499
2500 #define FPU_CONDITION_CODE_NAMES \
2501     {"$fcc0",   RTYPE_FCC | 0},  \
2502     {"$fcc1",   RTYPE_FCC | 1},  \
2503     {"$fcc2",   RTYPE_FCC | 2},  \
2504     {"$fcc3",   RTYPE_FCC | 3},  \
2505     {"$fcc4",   RTYPE_FCC | 4},  \
2506     {"$fcc5",   RTYPE_FCC | 5},  \
2507     {"$fcc6",   RTYPE_FCC | 6},  \
2508     {"$fcc7",   RTYPE_FCC | 7}
2509
2510 #define COPROC_CONDITION_CODE_NAMES         \
2511     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2512     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2513     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2514     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2515     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2516     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2517     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2518     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2519
2520 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2521     {"$a4",     RTYPE_GP | 8},  \
2522     {"$a5",     RTYPE_GP | 9},  \
2523     {"$a6",     RTYPE_GP | 10}, \
2524     {"$a7",     RTYPE_GP | 11}, \
2525     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2526     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2527     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2528     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2529     {"$t0",     RTYPE_GP | 12}, \
2530     {"$t1",     RTYPE_GP | 13}, \
2531     {"$t2",     RTYPE_GP | 14}, \
2532     {"$t3",     RTYPE_GP | 15}
2533
2534 #define O32_SYMBOLIC_REGISTER_NAMES \
2535     {"$t0",     RTYPE_GP | 8},  \
2536     {"$t1",     RTYPE_GP | 9},  \
2537     {"$t2",     RTYPE_GP | 10}, \
2538     {"$t3",     RTYPE_GP | 11}, \
2539     {"$t4",     RTYPE_GP | 12}, \
2540     {"$t5",     RTYPE_GP | 13}, \
2541     {"$t6",     RTYPE_GP | 14}, \
2542     {"$t7",     RTYPE_GP | 15}, \
2543     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2544     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2545     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2546     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2547
2548 /* Remaining symbolic register names */
2549 #define SYMBOLIC_REGISTER_NAMES \
2550     {"$zero",   RTYPE_GP | 0},  \
2551     {"$at",     RTYPE_GP | 1},  \
2552     {"$AT",     RTYPE_GP | 1},  \
2553     {"$v0",     RTYPE_GP | 2},  \
2554     {"$v1",     RTYPE_GP | 3},  \
2555     {"$a0",     RTYPE_GP | 4},  \
2556     {"$a1",     RTYPE_GP | 5},  \
2557     {"$a2",     RTYPE_GP | 6},  \
2558     {"$a3",     RTYPE_GP | 7},  \
2559     {"$s0",     RTYPE_GP | 16}, \
2560     {"$s1",     RTYPE_GP | 17}, \
2561     {"$s2",     RTYPE_GP | 18}, \
2562     {"$s3",     RTYPE_GP | 19}, \
2563     {"$s4",     RTYPE_GP | 20}, \
2564     {"$s5",     RTYPE_GP | 21}, \
2565     {"$s6",     RTYPE_GP | 22}, \
2566     {"$s7",     RTYPE_GP | 23}, \
2567     {"$t8",     RTYPE_GP | 24}, \
2568     {"$t9",     RTYPE_GP | 25}, \
2569     {"$k0",     RTYPE_GP | 26}, \
2570     {"$kt0",    RTYPE_GP | 26}, \
2571     {"$k1",     RTYPE_GP | 27}, \
2572     {"$kt1",    RTYPE_GP | 27}, \
2573     {"$gp",     RTYPE_GP | 28}, \
2574     {"$sp",     RTYPE_GP | 29}, \
2575     {"$s8",     RTYPE_GP | 30}, \
2576     {"$fp",     RTYPE_GP | 30}, \
2577     {"$ra",     RTYPE_GP | 31}
2578
2579 #define MIPS16_SPECIAL_REGISTER_NAMES \
2580     {"$pc",     RTYPE_PC | 0}
2581
2582 #define MDMX_VECTOR_REGISTER_NAMES \
2583     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2584     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2585     {"$v2",     RTYPE_VEC | 2},  \
2586     {"$v3",     RTYPE_VEC | 3},  \
2587     {"$v4",     RTYPE_VEC | 4},  \
2588     {"$v5",     RTYPE_VEC | 5},  \
2589     {"$v6",     RTYPE_VEC | 6},  \
2590     {"$v7",     RTYPE_VEC | 7},  \
2591     {"$v8",     RTYPE_VEC | 8},  \
2592     {"$v9",     RTYPE_VEC | 9},  \
2593     {"$v10",    RTYPE_VEC | 10}, \
2594     {"$v11",    RTYPE_VEC | 11}, \
2595     {"$v12",    RTYPE_VEC | 12}, \
2596     {"$v13",    RTYPE_VEC | 13}, \
2597     {"$v14",    RTYPE_VEC | 14}, \
2598     {"$v15",    RTYPE_VEC | 15}, \
2599     {"$v16",    RTYPE_VEC | 16}, \
2600     {"$v17",    RTYPE_VEC | 17}, \
2601     {"$v18",    RTYPE_VEC | 18}, \
2602     {"$v19",    RTYPE_VEC | 19}, \
2603     {"$v20",    RTYPE_VEC | 20}, \
2604     {"$v21",    RTYPE_VEC | 21}, \
2605     {"$v22",    RTYPE_VEC | 22}, \
2606     {"$v23",    RTYPE_VEC | 23}, \
2607     {"$v24",    RTYPE_VEC | 24}, \
2608     {"$v25",    RTYPE_VEC | 25}, \
2609     {"$v26",    RTYPE_VEC | 26}, \
2610     {"$v27",    RTYPE_VEC | 27}, \
2611     {"$v28",    RTYPE_VEC | 28}, \
2612     {"$v29",    RTYPE_VEC | 29}, \
2613     {"$v30",    RTYPE_VEC | 30}, \
2614     {"$v31",    RTYPE_VEC | 31}
2615
2616 #define R5900_I_NAMES \
2617     {"$I",      RTYPE_R5900_I | 0}
2618
2619 #define R5900_Q_NAMES \
2620     {"$Q",      RTYPE_R5900_Q | 0}
2621
2622 #define R5900_R_NAMES \
2623     {"$R",      RTYPE_R5900_R | 0}
2624
2625 #define R5900_ACC_NAMES \
2626     {"$ACC",    RTYPE_R5900_ACC | 0 }
2627
2628 #define MIPS_DSP_ACCUMULATOR_NAMES \
2629     {"$ac0",    RTYPE_ACC | 0}, \
2630     {"$ac1",    RTYPE_ACC | 1}, \
2631     {"$ac2",    RTYPE_ACC | 2}, \
2632     {"$ac3",    RTYPE_ACC | 3}
2633
2634 static const struct regname reg_names[] = {
2635   GENERIC_REGISTER_NUMBERS,
2636   FPU_REGISTER_NAMES,
2637   FPU_CONDITION_CODE_NAMES,
2638   COPROC_CONDITION_CODE_NAMES,
2639
2640   /* The $txx registers depends on the abi,
2641      these will be added later into the symbol table from
2642      one of the tables below once mips_abi is set after 
2643      parsing of arguments from the command line. */
2644   SYMBOLIC_REGISTER_NAMES,
2645
2646   MIPS16_SPECIAL_REGISTER_NAMES,
2647   MDMX_VECTOR_REGISTER_NAMES,
2648   R5900_I_NAMES,
2649   R5900_Q_NAMES,
2650   R5900_R_NAMES,
2651   R5900_ACC_NAMES,
2652   MIPS_DSP_ACCUMULATOR_NAMES,
2653   {0, 0}
2654 };
2655
2656 static const struct regname reg_names_o32[] = {
2657   O32_SYMBOLIC_REGISTER_NAMES,
2658   {0, 0}
2659 };
2660
2661 static const struct regname reg_names_n32n64[] = {
2662   N32N64_SYMBOLIC_REGISTER_NAMES,
2663   {0, 0}
2664 };
2665
2666 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2667    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2668    of these register symbols, return the associated vector register,
2669    otherwise return SYMVAL itself.  */
2670
2671 static unsigned int
2672 mips_prefer_vec_regno (unsigned int symval)
2673 {
2674   if ((symval & -2) == (RTYPE_GP | 2))
2675     return RTYPE_VEC | (symval & 1);
2676   return symval;
2677 }
2678
2679 /* Return true if string [S, E) is a valid register name, storing its
2680    symbol value in *SYMVAL_PTR if so.  */
2681
2682 static bfd_boolean
2683 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2684 {
2685   char save_c;
2686   symbolS *symbol;
2687
2688   /* Terminate name.  */
2689   save_c = *e;
2690   *e = '\0';
2691
2692   /* Look up the name.  */
2693   symbol = symbol_find (s);
2694   *e = save_c;
2695
2696   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2697     return FALSE;
2698
2699   *symval_ptr = S_GET_VALUE (symbol);
2700   return TRUE;
2701 }
2702
2703 /* Return true if the string at *SPTR is a valid register name.  Allow it
2704    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2705    is nonnull.
2706
2707    When returning true, move *SPTR past the register, store the
2708    register's symbol value in *SYMVAL_PTR and the channel mask in
2709    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2710    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2711    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2712
2713 static bfd_boolean
2714 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2715                      unsigned int *channels_ptr)
2716 {
2717   char *s, *e, *m;
2718   const char *q;
2719   unsigned int channels, symval, bit;
2720
2721   /* Find end of name.  */
2722   s = e = *sptr;
2723   if (is_name_beginner (*e))
2724     ++e;
2725   while (is_part_of_name (*e))
2726     ++e;
2727
2728   channels = 0;
2729   if (!mips_parse_register_1 (s, e, &symval))
2730     {
2731       if (!channels_ptr)
2732         return FALSE;
2733
2734       /* Eat characters from the end of the string that are valid
2735          channel suffixes.  The preceding register must be $ACC or
2736          end with a digit, so there is no ambiguity.  */
2737       bit = 1;
2738       m = e;
2739       for (q = "wzyx"; *q; q++, bit <<= 1)
2740         if (m > s && m[-1] == *q)
2741           {
2742             --m;
2743             channels |= bit;
2744           }
2745
2746       if (channels == 0
2747           || !mips_parse_register_1 (s, m, &symval)
2748           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2749         return FALSE;
2750     }
2751
2752   *sptr = e;
2753   *symval_ptr = symval;
2754   if (channels_ptr)
2755     *channels_ptr = channels;
2756   return TRUE;
2757 }
2758
2759 /* Check if SPTR points at a valid register specifier according to TYPES.
2760    If so, then return 1, advance S to consume the specifier and store
2761    the register's number in REGNOP, otherwise return 0.  */
2762
2763 static int
2764 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2765 {
2766   unsigned int regno;
2767
2768   if (mips_parse_register (s, &regno, NULL))
2769     {
2770       if (types & RTYPE_VEC)
2771         regno = mips_prefer_vec_regno (regno);
2772       if (regno & types)
2773         regno &= RNUM_MASK;
2774       else
2775         regno = ~0;
2776     }
2777   else
2778     {
2779       if (types & RWARN)
2780         as_warn (_("unrecognized register name `%s'"), *s);
2781       regno = ~0;
2782     }
2783   if (regnop)
2784     *regnop = regno;
2785   return regno <= RNUM_MASK;
2786 }
2787
2788 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2789    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2790
2791 static char *
2792 mips_parse_vu0_channels (char *s, unsigned int *channels)
2793 {
2794   unsigned int i;
2795
2796   *channels = 0;
2797   for (i = 0; i < 4; i++)
2798     if (*s == "xyzw"[i])
2799       {
2800         *channels |= 1 << (3 - i);
2801         ++s;
2802       }
2803   return s;
2804 }
2805
2806 /* Token types for parsed operand lists.  */
2807 enum mips_operand_token_type {
2808   /* A plain register, e.g. $f2.  */
2809   OT_REG,
2810
2811   /* A 4-bit XYZW channel mask.  */
2812   OT_CHANNELS,
2813
2814   /* A constant vector index, e.g. [1].  */
2815   OT_INTEGER_INDEX,
2816
2817   /* A register vector index, e.g. [$2].  */
2818   OT_REG_INDEX,
2819
2820   /* A continuous range of registers, e.g. $s0-$s4.  */
2821   OT_REG_RANGE,
2822
2823   /* A (possibly relocated) expression.  */
2824   OT_INTEGER,
2825
2826   /* A floating-point value.  */
2827   OT_FLOAT,
2828
2829   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2830      before OT_REGs.  */
2831   OT_CHAR,
2832
2833   /* A doubled character, either "--" or "++".  */
2834   OT_DOUBLE_CHAR,
2835
2836   /* The end of the operand list.  */
2837   OT_END
2838 };
2839
2840 /* A parsed operand token.  */
2841 struct mips_operand_token
2842 {
2843   /* The type of token.  */
2844   enum mips_operand_token_type type;
2845   union
2846   {
2847     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2848     unsigned int regno;
2849
2850     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2851     unsigned int channels;
2852
2853     /* The integer value of an OT_INTEGER_INDEX.  */
2854     addressT index;
2855
2856     /* The two register symbol values involved in an OT_REG_RANGE.  */
2857     struct {
2858       unsigned int regno1;
2859       unsigned int regno2;
2860     } reg_range;
2861
2862     /* The value of an OT_INTEGER.  The value is represented as an
2863        expression and the relocation operators that were applied to
2864        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2865        relocation operators were used.  */
2866     struct {
2867       expressionS value;
2868       bfd_reloc_code_real_type relocs[3];
2869     } integer;
2870
2871     /* The binary data for an OT_FLOAT constant, and the number of bytes
2872        in the constant.  */
2873     struct {
2874       unsigned char data[8];
2875       int length;
2876     } flt;
2877
2878     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2879     char ch;
2880   } u;
2881 };
2882
2883 /* An obstack used to construct lists of mips_operand_tokens.  */
2884 static struct obstack mips_operand_tokens;
2885
2886 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2887
2888 static void
2889 mips_add_token (struct mips_operand_token *token,
2890                 enum mips_operand_token_type type)
2891 {
2892   token->type = type;
2893   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2894 }
2895
2896 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2897    and OT_REG tokens for them if so, and return a pointer to the first
2898    unconsumed character.  Return null otherwise.  */
2899
2900 static char *
2901 mips_parse_base_start (char *s)
2902 {
2903   struct mips_operand_token token;
2904   unsigned int regno, channels;
2905   bfd_boolean decrement_p;
2906
2907   if (*s != '(')
2908     return 0;
2909
2910   ++s;
2911   SKIP_SPACE_TABS (s);
2912
2913   /* Only match "--" as part of a base expression.  In other contexts "--X"
2914      is a double negative.  */
2915   decrement_p = (s[0] == '-' && s[1] == '-');
2916   if (decrement_p)
2917     {
2918       s += 2;
2919       SKIP_SPACE_TABS (s);
2920     }
2921
2922   /* Allow a channel specifier because that leads to better error messages
2923      than treating something like "$vf0x++" as an expression.  */
2924   if (!mips_parse_register (&s, &regno, &channels))
2925     return 0;
2926
2927   token.u.ch = '(';
2928   mips_add_token (&token, OT_CHAR);
2929
2930   if (decrement_p)
2931     {
2932       token.u.ch = '-';
2933       mips_add_token (&token, OT_DOUBLE_CHAR);
2934     }
2935
2936   token.u.regno = regno;
2937   mips_add_token (&token, OT_REG);
2938
2939   if (channels)
2940     {
2941       token.u.channels = channels;
2942       mips_add_token (&token, OT_CHANNELS);
2943     }
2944
2945   /* For consistency, only match "++" as part of base expressions too.  */
2946   SKIP_SPACE_TABS (s);
2947   if (s[0] == '+' && s[1] == '+')
2948     {
2949       s += 2;
2950       token.u.ch = '+';
2951       mips_add_token (&token, OT_DOUBLE_CHAR);
2952     }
2953
2954   return s;
2955 }
2956
2957 /* Parse one or more tokens from S.  Return a pointer to the first
2958    unconsumed character on success.  Return null if an error was found
2959    and store the error text in insn_error.  FLOAT_FORMAT is as for
2960    mips_parse_arguments.  */
2961
2962 static char *
2963 mips_parse_argument_token (char *s, char float_format)
2964 {
2965   char *end, *save_in, *err;
2966   unsigned int regno1, regno2, channels;
2967   struct mips_operand_token token;
2968
2969   /* First look for "($reg", since we want to treat that as an
2970      OT_CHAR and OT_REG rather than an expression.  */
2971   end = mips_parse_base_start (s);
2972   if (end)
2973     return end;
2974
2975   /* Handle other characters that end up as OT_CHARs.  */
2976   if (*s == ')' || *s == ',')
2977     {
2978       token.u.ch = *s;
2979       mips_add_token (&token, OT_CHAR);
2980       ++s;
2981       return s;
2982     }
2983
2984   /* Handle tokens that start with a register.  */
2985   if (mips_parse_register (&s, &regno1, &channels))
2986     {
2987       if (channels)
2988         {
2989           /* A register and a VU0 channel suffix.  */
2990           token.u.regno = regno1;
2991           mips_add_token (&token, OT_REG);
2992
2993           token.u.channels = channels;
2994           mips_add_token (&token, OT_CHANNELS);
2995           return s;
2996         }
2997
2998       SKIP_SPACE_TABS (s);
2999       if (*s == '-')
3000         {
3001           /* A register range.  */
3002           ++s;
3003           SKIP_SPACE_TABS (s);
3004           if (!mips_parse_register (&s, &regno2, NULL))
3005             {
3006               set_insn_error (0, _("invalid register range"));
3007               return 0;
3008             }
3009
3010           token.u.reg_range.regno1 = regno1;
3011           token.u.reg_range.regno2 = regno2;
3012           mips_add_token (&token, OT_REG_RANGE);
3013           return s;
3014         }
3015
3016       /* Add the register itself.  */
3017       token.u.regno = regno1;
3018       mips_add_token (&token, OT_REG);
3019
3020       /* Check for a vector index.  */
3021       if (*s == '[')
3022         {
3023           ++s;
3024           SKIP_SPACE_TABS (s);
3025           if (mips_parse_register (&s, &token.u.regno, NULL))
3026             mips_add_token (&token, OT_REG_INDEX);
3027           else
3028             {
3029               expressionS element;
3030
3031               my_getExpression (&element, s);
3032               if (element.X_op != O_constant)
3033                 {
3034                   set_insn_error (0, _("vector element must be constant"));
3035                   return 0;
3036                 }
3037               s = expr_end;
3038               token.u.index = element.X_add_number;
3039               mips_add_token (&token, OT_INTEGER_INDEX);
3040             }
3041           SKIP_SPACE_TABS (s);
3042           if (*s != ']')
3043             {
3044               set_insn_error (0, _("missing `]'"));
3045               return 0;
3046             }
3047           ++s;
3048         }
3049       return s;
3050     }
3051
3052   if (float_format)
3053     {
3054       /* First try to treat expressions as floats.  */
3055       save_in = input_line_pointer;
3056       input_line_pointer = s;
3057       err = md_atof (float_format, (char *) token.u.flt.data,
3058                      &token.u.flt.length);
3059       end = input_line_pointer;
3060       input_line_pointer = save_in;
3061       if (err && *err)
3062         {
3063           set_insn_error (0, err);
3064           return 0;
3065         }
3066       if (s != end)
3067         {
3068           mips_add_token (&token, OT_FLOAT);
3069           return end;
3070         }
3071     }
3072
3073   /* Treat everything else as an integer expression.  */
3074   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3075   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3076   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3077   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3078   s = expr_end;
3079   mips_add_token (&token, OT_INTEGER);
3080   return s;
3081 }
3082
3083 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3084    if expressions should be treated as 32-bit floating-point constants,
3085    'd' if they should be treated as 64-bit floating-point constants,
3086    or 0 if they should be treated as integer expressions (the usual case).
3087
3088    Return a list of tokens on success, otherwise return 0.  The caller
3089    must obstack_free the list after use.  */
3090
3091 static struct mips_operand_token *
3092 mips_parse_arguments (char *s, char float_format)
3093 {
3094   struct mips_operand_token token;
3095
3096   SKIP_SPACE_TABS (s);
3097   while (*s)
3098     {
3099       s = mips_parse_argument_token (s, float_format);
3100       if (!s)
3101         {
3102           obstack_free (&mips_operand_tokens,
3103                         obstack_finish (&mips_operand_tokens));
3104           return 0;
3105         }
3106       SKIP_SPACE_TABS (s);
3107     }
3108   mips_add_token (&token, OT_END);
3109   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3110 }
3111
3112 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3113    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3114
3115 static bfd_boolean
3116 is_opcode_valid (const struct mips_opcode *mo)
3117 {
3118   int isa = mips_opts.isa;
3119   int ase = mips_opts.ase;
3120   int fp_s, fp_d;
3121   unsigned int i;
3122
3123   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3124     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3125       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3126         ase |= mips_ases[i].flags64;
3127
3128   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3129     return FALSE;
3130
3131   /* Check whether the instruction or macro requires single-precision or
3132      double-precision floating-point support.  Note that this information is
3133      stored differently in the opcode table for insns and macros.  */
3134   if (mo->pinfo == INSN_MACRO)
3135     {
3136       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3137       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3138     }
3139   else
3140     {
3141       fp_s = mo->pinfo & FP_S;
3142       fp_d = mo->pinfo & FP_D;
3143     }
3144
3145   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3146     return FALSE;
3147
3148   if (fp_s && mips_opts.soft_float)
3149     return FALSE;
3150
3151   return TRUE;
3152 }
3153
3154 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3155    selected ISA and architecture.  */
3156
3157 static bfd_boolean
3158 is_opcode_valid_16 (const struct mips_opcode *mo)
3159 {
3160   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3161 }
3162
3163 /* Return TRUE if the size of the microMIPS opcode MO matches one
3164    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3165
3166 static bfd_boolean
3167 is_size_valid (const struct mips_opcode *mo)
3168 {
3169   if (!mips_opts.micromips)
3170     return TRUE;
3171
3172   if (mips_opts.insn32)
3173     {
3174       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3175         return FALSE;
3176       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3177         return FALSE;
3178     }
3179   if (!forced_insn_length)
3180     return TRUE;
3181   if (mo->pinfo == INSN_MACRO)
3182     return FALSE;
3183   return forced_insn_length == micromips_insn_length (mo);
3184 }
3185
3186 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3187    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3188
3189    We don't accept macros in 16-bit delay slots to avoid a case where
3190    a macro expansion fails because it relies on a preceding 32-bit real
3191    instruction to have matched and does not handle the operands correctly.
3192    The only macros that may expand to 16-bit instructions are JAL that
3193    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3194    and BGT (that likewise cannot be placed in a delay slot) that decay to
3195    a NOP.  In all these cases the macros precede any corresponding real
3196    instruction definitions in the opcode table, so they will match in the
3197    second pass where the size of the delay slot is ignored and therefore
3198    produce correct code.  */
3199
3200 static bfd_boolean
3201 is_delay_slot_valid (const struct mips_opcode *mo)
3202 {
3203   if (!mips_opts.micromips)
3204     return TRUE;
3205
3206   if (mo->pinfo == INSN_MACRO)
3207     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3208   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3209       && micromips_insn_length (mo) != 4)
3210     return FALSE;
3211   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3212       && micromips_insn_length (mo) != 2)
3213     return FALSE;
3214
3215   return TRUE;
3216 }
3217
3218 /* For consistency checking, verify that all bits of OPCODE are specified
3219    either by the match/mask part of the instruction definition, or by the
3220    operand list.  Also build up a list of operands in OPERANDS.
3221
3222    INSN_BITS says which bits of the instruction are significant.
3223    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3224    provides the mips_operand description of each operand.  DECODE_OPERAND
3225    is null for MIPS16 instructions.  */
3226
3227 static int
3228 validate_mips_insn (const struct mips_opcode *opcode,
3229                     unsigned long insn_bits,
3230                     const struct mips_operand *(*decode_operand) (const char *),
3231                     struct mips_operand_array *operands)
3232 {
3233   const char *s;
3234   unsigned long used_bits, doubled, undefined, opno, mask;
3235   const struct mips_operand *operand;
3236
3237   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3238   if ((mask & opcode->match) != opcode->match)
3239     {
3240       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3241               opcode->name, opcode->args);
3242       return 0;
3243     }
3244   used_bits = 0;
3245   opno = 0;
3246   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3247     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3248   for (s = opcode->args; *s; ++s)
3249     switch (*s)
3250       {
3251       case ',':
3252       case '(':
3253       case ')':
3254         break;
3255
3256       case '#':
3257         s++;
3258         break;
3259
3260       default:
3261         if (!decode_operand)
3262           operand = decode_mips16_operand (*s, FALSE);
3263         else
3264           operand = decode_operand (s);
3265         if (!operand && opcode->pinfo != INSN_MACRO)
3266           {
3267             as_bad (_("internal: unknown operand type: %s %s"),
3268                     opcode->name, opcode->args);
3269             return 0;
3270           }
3271         gas_assert (opno < MAX_OPERANDS);
3272         operands->operand[opno] = operand;
3273         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3274           {
3275             used_bits = mips_insert_operand (operand, used_bits, -1);
3276             if (operand->type == OP_MDMX_IMM_REG)
3277               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3278                  has separate entries for each format.  */
3279               used_bits &= ~(1 << (operand->lsb + 5));
3280             if (operand->type == OP_ENTRY_EXIT_LIST)
3281               used_bits &= ~(mask & 0x700);
3282           }
3283         /* Skip prefix characters.  */
3284         if (decode_operand && (*s == '+' || *s == 'm'))
3285           ++s;
3286         opno += 1;
3287         break;
3288       }
3289   doubled = used_bits & mask & insn_bits;
3290   if (doubled)
3291     {
3292       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3293                 " %s %s"), doubled, opcode->name, opcode->args);
3294       return 0;
3295     }
3296   used_bits |= mask;
3297   undefined = ~used_bits & insn_bits;
3298   if (opcode->pinfo != INSN_MACRO && undefined)
3299     {
3300       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3301               undefined, opcode->name, opcode->args);
3302       return 0;
3303     }
3304   used_bits &= ~insn_bits;
3305   if (used_bits)
3306     {
3307       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3308               used_bits, opcode->name, opcode->args);
3309       return 0;
3310     }
3311   return 1;
3312 }
3313
3314 /* The MIPS16 version of validate_mips_insn.  */
3315
3316 static int
3317 validate_mips16_insn (const struct mips_opcode *opcode,
3318                       struct mips_operand_array *operands)
3319 {
3320   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3321     {
3322       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3323          instruction.  Use TMP to describe the full instruction.  */
3324       struct mips_opcode tmp;
3325
3326       tmp = *opcode;
3327       tmp.match <<= 16;
3328       tmp.mask <<= 16;
3329       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3330     }
3331   return validate_mips_insn (opcode, 0xffff, 0, operands);
3332 }
3333
3334 /* The microMIPS version of validate_mips_insn.  */
3335
3336 static int
3337 validate_micromips_insn (const struct mips_opcode *opc,
3338                          struct mips_operand_array *operands)
3339 {
3340   unsigned long insn_bits;
3341   unsigned long major;
3342   unsigned int length;
3343
3344   if (opc->pinfo == INSN_MACRO)
3345     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3346                                operands);
3347
3348   length = micromips_insn_length (opc);
3349   if (length != 2 && length != 4)
3350     {
3351       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3352                 "%s %s"), length, opc->name, opc->args);
3353       return 0;
3354     }
3355   major = opc->match >> (10 + 8 * (length - 2));
3356   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3357       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3358     {
3359       as_bad (_("internal error: bad microMIPS opcode "
3360                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3361       return 0;
3362     }
3363
3364   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3365   insn_bits = 1 << 4 * length;
3366   insn_bits <<= 4 * length;
3367   insn_bits -= 1;
3368   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3369                              operands);
3370 }
3371
3372 /* This function is called once, at assembler startup time.  It should set up
3373    all the tables, etc. that the MD part of the assembler will need.  */
3374
3375 void
3376 md_begin (void)
3377 {
3378   const char *retval = NULL;
3379   int i = 0;
3380   int broken = 0;
3381
3382   if (mips_pic != NO_PIC)
3383     {
3384       if (g_switch_seen && g_switch_value != 0)
3385         as_bad (_("-G may not be used in position-independent code"));
3386       g_switch_value = 0;
3387     }
3388
3389   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3390     as_warn (_("could not set architecture and machine"));
3391
3392   op_hash = hash_new ();
3393
3394   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3395   for (i = 0; i < NUMOPCODES;)
3396     {
3397       const char *name = mips_opcodes[i].name;
3398
3399       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3400       if (retval != NULL)
3401         {
3402           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3403                    mips_opcodes[i].name, retval);
3404           /* Probably a memory allocation problem?  Give up now.  */
3405           as_fatal (_("broken assembler, no assembly attempted"));
3406         }
3407       do
3408         {
3409           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3410                                    decode_mips_operand, &mips_operands[i]))
3411             broken = 1;
3412           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3413             {
3414               create_insn (&nop_insn, mips_opcodes + i);
3415               if (mips_fix_loongson2f_nop)
3416                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3417               nop_insn.fixed_p = 1;
3418             }
3419           ++i;
3420         }
3421       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3422     }
3423
3424   mips16_op_hash = hash_new ();
3425   mips16_operands = XCNEWVEC (struct mips_operand_array,
3426                               bfd_mips16_num_opcodes);
3427
3428   i = 0;
3429   while (i < bfd_mips16_num_opcodes)
3430     {
3431       const char *name = mips16_opcodes[i].name;
3432
3433       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3434       if (retval != NULL)
3435         as_fatal (_("internal: can't hash `%s': %s"),
3436                   mips16_opcodes[i].name, retval);
3437       do
3438         {
3439           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3440             broken = 1;
3441           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3442             {
3443               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3444               mips16_nop_insn.fixed_p = 1;
3445             }
3446           ++i;
3447         }
3448       while (i < bfd_mips16_num_opcodes
3449              && strcmp (mips16_opcodes[i].name, name) == 0);
3450     }
3451
3452   micromips_op_hash = hash_new ();
3453   micromips_operands = XCNEWVEC (struct mips_operand_array,
3454                                  bfd_micromips_num_opcodes);
3455
3456   i = 0;
3457   while (i < bfd_micromips_num_opcodes)
3458     {
3459       const char *name = micromips_opcodes[i].name;
3460
3461       retval = hash_insert (micromips_op_hash, name,
3462                             (void *) &micromips_opcodes[i]);
3463       if (retval != NULL)
3464         as_fatal (_("internal: can't hash `%s': %s"),
3465                   micromips_opcodes[i].name, retval);
3466       do
3467         {
3468           struct mips_cl_insn *micromips_nop_insn;
3469
3470           if (!validate_micromips_insn (&micromips_opcodes[i],
3471                                         &micromips_operands[i]))
3472             broken = 1;
3473
3474           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3475             {
3476               if (micromips_insn_length (micromips_opcodes + i) == 2)
3477                 micromips_nop_insn = &micromips_nop16_insn;
3478               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3479                 micromips_nop_insn = &micromips_nop32_insn;
3480               else
3481                 continue;
3482
3483               if (micromips_nop_insn->insn_mo == NULL
3484                   && strcmp (name, "nop") == 0)
3485                 {
3486                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3487                   micromips_nop_insn->fixed_p = 1;
3488                 }
3489             }
3490         }
3491       while (++i < bfd_micromips_num_opcodes
3492              && strcmp (micromips_opcodes[i].name, name) == 0);
3493     }
3494
3495   if (broken)
3496     as_fatal (_("broken assembler, no assembly attempted"));
3497
3498   /* We add all the general register names to the symbol table.  This
3499      helps us detect invalid uses of them.  */
3500   for (i = 0; reg_names[i].name; i++) 
3501     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3502                                      reg_names[i].num, /* & RNUM_MASK, */
3503                                      &zero_address_frag));
3504   if (HAVE_NEWABI)
3505     for (i = 0; reg_names_n32n64[i].name; i++) 
3506       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3507                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3508                                        &zero_address_frag));
3509   else
3510     for (i = 0; reg_names_o32[i].name; i++) 
3511       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3512                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3513                                        &zero_address_frag));
3514
3515   for (i = 0; i < 32; i++)
3516     {
3517       char regname[7];
3518
3519       /* R5900 VU0 floating-point register.  */
3520       regname[sizeof (rename) - 1] = 0;
3521       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3522       symbol_table_insert (symbol_new (regname, reg_section,
3523                                        RTYPE_VF | i, &zero_address_frag));
3524
3525       /* R5900 VU0 integer register.  */
3526       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3527       symbol_table_insert (symbol_new (regname, reg_section,
3528                                        RTYPE_VI | i, &zero_address_frag));
3529
3530       /* MSA register.  */
3531       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3532       symbol_table_insert (symbol_new (regname, reg_section,
3533                                        RTYPE_MSA | i, &zero_address_frag));
3534     }
3535
3536   obstack_init (&mips_operand_tokens);
3537
3538   mips_no_prev_insn ();
3539
3540   mips_gprmask = 0;
3541   mips_cprmask[0] = 0;
3542   mips_cprmask[1] = 0;
3543   mips_cprmask[2] = 0;
3544   mips_cprmask[3] = 0;
3545
3546   /* set the default alignment for the text section (2**2) */
3547   record_alignment (text_section, 2);
3548
3549   bfd_set_gp_size (stdoutput, g_switch_value);
3550
3551   /* On a native system other than VxWorks, sections must be aligned
3552      to 16 byte boundaries.  When configured for an embedded ELF
3553      target, we don't bother.  */
3554   if (strncmp (TARGET_OS, "elf", 3) != 0
3555       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3556     {
3557       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3558       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3559       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3560     }
3561
3562   /* Create a .reginfo section for register masks and a .mdebug
3563      section for debugging information.  */
3564   {
3565     segT seg;
3566     subsegT subseg;
3567     flagword flags;
3568     segT sec;
3569
3570     seg = now_seg;
3571     subseg = now_subseg;
3572
3573     /* The ABI says this section should be loaded so that the
3574        running program can access it.  However, we don't load it
3575        if we are configured for an embedded target */
3576     flags = SEC_READONLY | SEC_DATA;
3577     if (strncmp (TARGET_OS, "elf", 3) != 0)
3578       flags |= SEC_ALLOC | SEC_LOAD;
3579
3580     if (mips_abi != N64_ABI)
3581       {
3582         sec = subseg_new (".reginfo", (subsegT) 0);
3583
3584         bfd_set_section_flags (stdoutput, sec, flags);
3585         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3586
3587         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3588       }
3589     else
3590       {
3591         /* The 64-bit ABI uses a .MIPS.options section rather than
3592            .reginfo section.  */
3593         sec = subseg_new (".MIPS.options", (subsegT) 0);
3594         bfd_set_section_flags (stdoutput, sec, flags);
3595         bfd_set_section_alignment (stdoutput, sec, 3);
3596
3597         /* Set up the option header.  */
3598         {
3599           Elf_Internal_Options opthdr;
3600           char *f;
3601
3602           opthdr.kind = ODK_REGINFO;
3603           opthdr.size = (sizeof (Elf_External_Options)
3604                          + sizeof (Elf64_External_RegInfo));
3605           opthdr.section = 0;
3606           opthdr.info = 0;
3607           f = frag_more (sizeof (Elf_External_Options));
3608           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3609                                          (Elf_External_Options *) f);
3610
3611           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3612         }
3613       }
3614
3615     if (ECOFF_DEBUGGING)
3616       {
3617         sec = subseg_new (".mdebug", (subsegT) 0);
3618         (void) bfd_set_section_flags (stdoutput, sec,
3619                                       SEC_HAS_CONTENTS | SEC_READONLY);
3620         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3621       }
3622     else if (mips_flag_pdr)
3623       {
3624         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3625         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3626                                       SEC_READONLY | SEC_RELOC
3627                                       | SEC_DEBUGGING);
3628         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3629       }
3630
3631     subseg_set (seg, subseg);
3632   }
3633
3634   if (mips_fix_vr4120)
3635     init_vr4120_conflicts ();
3636 }
3637
3638 /* Perform consistency checks on the current options.  */
3639
3640 static void
3641 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3642 {
3643   /* Check the size of integer registers agrees with the ABI and ISA.  */
3644   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3645     as_bad (_("`gp=64' used with a 32-bit processor"));
3646   else if (abi_checks
3647            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3648     as_bad (_("`gp=32' used with a 64-bit ABI"));
3649   else if (abi_checks
3650            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3651     as_bad (_("`gp=64' used with a 32-bit ABI"));
3652
3653   /* Check the size of the float registers agrees with the ABI and ISA.  */
3654   switch (opts->fp)
3655     {
3656     case 64:
3657       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3658         as_bad (_("`fp=64' used with a 32-bit fpu"));
3659       else if (abi_checks
3660                && ABI_NEEDS_32BIT_REGS (mips_abi)
3661                && !ISA_HAS_MXHC1 (opts->isa))
3662         as_warn (_("`fp=64' used with a 32-bit ABI"));
3663       break;
3664     case 32:
3665       if (abi_checks
3666           && ABI_NEEDS_64BIT_REGS (mips_abi))
3667         as_warn (_("`fp=32' used with a 64-bit ABI"));
3668       break;
3669     default:
3670       as_bad (_("Unknown size of floating point registers"));
3671       break;
3672     }
3673
3674   if (opts->micromips == 1 && opts->mips16 == 1)
3675     as_bad (_("`mips16' cannot be used with `micromips'"));
3676 }
3677
3678 /* Perform consistency checks on the module level options exactly once.
3679    This is a deferred check that happens:
3680      at the first .set directive
3681      or, at the first pseudo op that generates code (inc .dc.a)
3682      or, at the first instruction
3683      or, at the end.  */
3684
3685 static void
3686 file_mips_check_options (void)
3687 {
3688   const struct mips_cpu_info *arch_info = 0;
3689
3690   if (file_mips_opts_checked)
3691     return;
3692
3693   /* The following code determines the register size.
3694      Similar code was added to GCC 3.3 (see override_options() in
3695      config/mips/mips.c).  The GAS and GCC code should be kept in sync
3696      as much as possible.  */
3697
3698   if (file_mips_opts.gp < 0)
3699     {
3700       /* Infer the integer register size from the ABI and processor.
3701          Restrict ourselves to 32-bit registers if that's all the
3702          processor has, or if the ABI cannot handle 64-bit registers.  */
3703       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
3704                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
3705                           ? 32 : 64;
3706     }
3707
3708   if (file_mips_opts.fp < 0)
3709     {
3710       /* No user specified float register size.
3711          ??? GAS treats single-float processors as though they had 64-bit
3712          float registers (although it complains when double-precision
3713          instructions are used).  As things stand, saying they have 32-bit
3714          registers would lead to spurious "register must be even" messages.
3715          So here we assume float registers are never smaller than the
3716          integer ones.  */
3717       if (file_mips_opts.gp == 64)
3718         /* 64-bit integer registers implies 64-bit float registers.  */
3719         file_mips_opts.fp = 64;
3720       else if ((file_mips_opts.ase & FP64_ASES)
3721                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
3722         /* Handle ASEs that require 64-bit float registers, if possible.  */
3723         file_mips_opts.fp = 64;
3724       else
3725         /* 32-bit float registers.  */
3726         file_mips_opts.fp = 32;
3727     }
3728
3729   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
3730
3731   /* End of GCC-shared inference code.  */
3732
3733   /* This flag is set when we have a 64-bit capable CPU but use only
3734      32-bit wide registers.  Note that EABI does not use it.  */
3735   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
3736       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
3737           || mips_abi == O32_ABI))
3738     mips_32bitmode = 1;
3739
3740   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
3741     as_bad (_("trap exception not supported at ISA 1"));
3742
3743   /* If the selected architecture includes support for ASEs, enable
3744      generation of code for them.  */
3745   if (file_mips_opts.mips16 == -1)
3746     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
3747   if (file_mips_opts.micromips == -1)
3748     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
3749                                 ? 1 : 0;
3750
3751   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
3752      being selected implicitly.  */
3753   if (file_mips_opts.fp != 64)
3754     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
3755
3756   /* If the user didn't explicitly select or deselect a particular ASE,
3757      use the default setting for the CPU.  */
3758   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
3759
3760   /* Set up the current options.  These may change throughout assembly.  */
3761   mips_opts = file_mips_opts;
3762
3763   mips_check_isa_supports_ases ();
3764   mips_check_options (&file_mips_opts, TRUE);
3765   file_mips_opts_checked = TRUE;
3766
3767   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3768     as_warn (_("could not set architecture and machine"));
3769 }
3770
3771 void
3772 md_assemble (char *str)
3773 {
3774   struct mips_cl_insn insn;
3775   bfd_reloc_code_real_type unused_reloc[3]
3776     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3777
3778   file_mips_check_options ();
3779
3780   imm_expr.X_op = O_absent;
3781   offset_expr.X_op = O_absent;
3782   offset_reloc[0] = BFD_RELOC_UNUSED;
3783   offset_reloc[1] = BFD_RELOC_UNUSED;
3784   offset_reloc[2] = BFD_RELOC_UNUSED;
3785
3786   mips_mark_labels ();
3787   mips_assembling_insn = TRUE;
3788   clear_insn_error ();
3789
3790   if (mips_opts.mips16)
3791     mips16_ip (str, &insn);
3792   else
3793     {
3794       mips_ip (str, &insn);
3795       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3796             str, insn.insn_opcode));
3797     }
3798
3799   if (insn_error.msg)
3800     report_insn_error (str);
3801   else if (insn.insn_mo->pinfo == INSN_MACRO)
3802     {
3803       macro_start ();
3804       if (mips_opts.mips16)
3805         mips16_macro (&insn);
3806       else
3807         macro (&insn, str);
3808       macro_end ();
3809     }
3810   else
3811     {
3812       if (offset_expr.X_op != O_absent)
3813         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3814       else
3815         append_insn (&insn, NULL, unused_reloc, FALSE);
3816     }
3817
3818   mips_assembling_insn = FALSE;
3819 }
3820
3821 /* Convenience functions for abstracting away the differences between
3822    MIPS16 and non-MIPS16 relocations.  */
3823
3824 static inline bfd_boolean
3825 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3826 {
3827   switch (reloc)
3828     {
3829     case BFD_RELOC_MIPS16_JMP:
3830     case BFD_RELOC_MIPS16_GPREL:
3831     case BFD_RELOC_MIPS16_GOT16:
3832     case BFD_RELOC_MIPS16_CALL16:
3833     case BFD_RELOC_MIPS16_HI16_S:
3834     case BFD_RELOC_MIPS16_HI16:
3835     case BFD_RELOC_MIPS16_LO16:
3836       return TRUE;
3837
3838     default:
3839       return FALSE;
3840     }
3841 }
3842
3843 static inline bfd_boolean
3844 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3845 {
3846   switch (reloc)
3847     {
3848     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3849     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3850     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3851     case BFD_RELOC_MICROMIPS_GPREL16:
3852     case BFD_RELOC_MICROMIPS_JMP:
3853     case BFD_RELOC_MICROMIPS_HI16:
3854     case BFD_RELOC_MICROMIPS_HI16_S:
3855     case BFD_RELOC_MICROMIPS_LO16:
3856     case BFD_RELOC_MICROMIPS_LITERAL:
3857     case BFD_RELOC_MICROMIPS_GOT16:
3858     case BFD_RELOC_MICROMIPS_CALL16:
3859     case BFD_RELOC_MICROMIPS_GOT_HI16:
3860     case BFD_RELOC_MICROMIPS_GOT_LO16:
3861     case BFD_RELOC_MICROMIPS_CALL_HI16:
3862     case BFD_RELOC_MICROMIPS_CALL_LO16:
3863     case BFD_RELOC_MICROMIPS_SUB:
3864     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3865     case BFD_RELOC_MICROMIPS_GOT_OFST:
3866     case BFD_RELOC_MICROMIPS_GOT_DISP:
3867     case BFD_RELOC_MICROMIPS_HIGHEST:
3868     case BFD_RELOC_MICROMIPS_HIGHER:
3869     case BFD_RELOC_MICROMIPS_SCN_DISP:
3870     case BFD_RELOC_MICROMIPS_JALR:
3871       return TRUE;
3872
3873     default:
3874       return FALSE;
3875     }
3876 }
3877
3878 static inline bfd_boolean
3879 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3880 {
3881   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3882 }
3883
3884 static inline bfd_boolean
3885 got16_reloc_p (bfd_reloc_code_real_type reloc)
3886 {
3887   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3888           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3889 }
3890
3891 static inline bfd_boolean
3892 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3893 {
3894   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3895           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3896 }
3897
3898 static inline bfd_boolean
3899 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3900 {
3901   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3902           || reloc == BFD_RELOC_MICROMIPS_LO16);
3903 }
3904
3905 static inline bfd_boolean
3906 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3907 {
3908   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3909 }
3910
3911 static inline bfd_boolean
3912 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3913 {
3914   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3915           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3916 }
3917
3918 /* Return true if RELOC is a PC-relative relocation that does not have
3919    full address range.  */
3920
3921 static inline bfd_boolean
3922 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3923 {
3924   switch (reloc)
3925     {
3926     case BFD_RELOC_16_PCREL_S2:
3927     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3928     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3929     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3930       return TRUE;
3931
3932     case BFD_RELOC_32_PCREL:
3933       return HAVE_64BIT_ADDRESSES;
3934
3935     default:
3936       return FALSE;
3937     }
3938 }
3939
3940 /* Return true if the given relocation might need a matching %lo().
3941    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3942    need a matching %lo() when applied to local symbols.  */
3943
3944 static inline bfd_boolean
3945 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3946 {
3947   return (HAVE_IN_PLACE_ADDENDS
3948           && (hi16_reloc_p (reloc)
3949               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3950                  all GOT16 relocations evaluate to "G".  */
3951               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3952 }
3953
3954 /* Return the type of %lo() reloc needed by RELOC, given that
3955    reloc_needs_lo_p.  */
3956
3957 static inline bfd_reloc_code_real_type
3958 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3959 {
3960   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3961           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3962              : BFD_RELOC_LO16));
3963 }
3964
3965 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3966    relocation.  */
3967
3968 static inline bfd_boolean
3969 fixup_has_matching_lo_p (fixS *fixp)
3970 {
3971   return (fixp->fx_next != NULL
3972           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3973           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3974           && fixp->fx_offset == fixp->fx_next->fx_offset);
3975 }
3976
3977 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3978    says whether the labels refer to text or data.  */
3979
3980 static void
3981 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3982 {
3983   struct insn_label_list *l;
3984   valueT val;
3985
3986   for (l = labels; l != NULL; l = l->next)
3987     {
3988       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3989       symbol_set_frag (l->label, frag_now);
3990       val = (valueT) frag_now_fix ();
3991       /* MIPS16/microMIPS text labels are stored as odd.  */
3992       if (text_p && HAVE_CODE_COMPRESSION)
3993         ++val;
3994       S_SET_VALUE (l->label, val);
3995     }
3996 }
3997
3998 /* Move all labels in insn_labels to the current insertion point
3999    and treat them as text labels.  */
4000
4001 static void
4002 mips_move_text_labels (void)
4003 {
4004   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4005 }
4006
4007 static bfd_boolean
4008 s_is_linkonce (symbolS *sym, segT from_seg)
4009 {
4010   bfd_boolean linkonce = FALSE;
4011   segT symseg = S_GET_SEGMENT (sym);
4012
4013   if (symseg != from_seg && !S_IS_LOCAL (sym))
4014     {
4015       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4016         linkonce = TRUE;
4017       /* The GNU toolchain uses an extension for ELF: a section
4018          beginning with the magic string .gnu.linkonce is a
4019          linkonce section.  */
4020       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4021                    sizeof ".gnu.linkonce" - 1) == 0)
4022         linkonce = TRUE;
4023     }
4024   return linkonce;
4025 }
4026
4027 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4028    linker to handle them specially, such as generating jalx instructions
4029    when needed.  We also make them odd for the duration of the assembly,
4030    in order to generate the right sort of code.  We will make them even
4031    in the adjust_symtab routine, while leaving them marked.  This is
4032    convenient for the debugger and the disassembler.  The linker knows
4033    to make them odd again.  */
4034
4035 static void
4036 mips_compressed_mark_label (symbolS *label)
4037 {
4038   gas_assert (HAVE_CODE_COMPRESSION);
4039
4040   if (mips_opts.mips16)
4041     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4042   else
4043     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4044   if ((S_GET_VALUE (label) & 1) == 0
4045       /* Don't adjust the address if the label is global or weak, or
4046          in a link-once section, since we'll be emitting symbol reloc
4047          references to it which will be patched up by the linker, and
4048          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4049       && !S_IS_WEAK (label)
4050       && !S_IS_EXTERNAL (label)
4051       && !s_is_linkonce (label, now_seg))
4052     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4053 }
4054
4055 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4056
4057 static void
4058 mips_compressed_mark_labels (void)
4059 {
4060   struct insn_label_list *l;
4061
4062   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4063     mips_compressed_mark_label (l->label);
4064 }
4065
4066 /* End the current frag.  Make it a variant frag and record the
4067    relaxation info.  */
4068
4069 static void
4070 relax_close_frag (void)
4071 {
4072   mips_macro_warning.first_frag = frag_now;
4073   frag_var (rs_machine_dependent, 0, 0,
4074             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
4075             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4076
4077   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4078   mips_relax.first_fixup = 0;
4079 }
4080
4081 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4082    See the comment above RELAX_ENCODE for more details.  */
4083
4084 static void
4085 relax_start (symbolS *symbol)
4086 {
4087   gas_assert (mips_relax.sequence == 0);
4088   mips_relax.sequence = 1;
4089   mips_relax.symbol = symbol;
4090 }
4091
4092 /* Start generating the second version of a relaxable sequence.
4093    See the comment above RELAX_ENCODE for more details.  */
4094
4095 static void
4096 relax_switch (void)
4097 {
4098   gas_assert (mips_relax.sequence == 1);
4099   mips_relax.sequence = 2;
4100 }
4101
4102 /* End the current relaxable sequence.  */
4103
4104 static void
4105 relax_end (void)
4106 {
4107   gas_assert (mips_relax.sequence == 2);
4108   relax_close_frag ();
4109   mips_relax.sequence = 0;
4110 }
4111
4112 /* Return true if IP is a delayed branch or jump.  */
4113
4114 static inline bfd_boolean
4115 delayed_branch_p (const struct mips_cl_insn *ip)
4116 {
4117   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4118                                 | INSN_COND_BRANCH_DELAY
4119                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4120 }
4121
4122 /* Return true if IP is a compact branch or jump.  */
4123
4124 static inline bfd_boolean
4125 compact_branch_p (const struct mips_cl_insn *ip)
4126 {
4127   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4128                                  | INSN2_COND_BRANCH)) != 0;
4129 }
4130
4131 /* Return true if IP is an unconditional branch or jump.  */
4132
4133 static inline bfd_boolean
4134 uncond_branch_p (const struct mips_cl_insn *ip)
4135 {
4136   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4137           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4138 }
4139
4140 /* Return true if IP is a branch-likely instruction.  */
4141
4142 static inline bfd_boolean
4143 branch_likely_p (const struct mips_cl_insn *ip)
4144 {
4145   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4146 }
4147
4148 /* Return the type of nop that should be used to fill the delay slot
4149    of delayed branch IP.  */
4150
4151 static struct mips_cl_insn *
4152 get_delay_slot_nop (const struct mips_cl_insn *ip)
4153 {
4154   if (mips_opts.micromips
4155       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4156     return &micromips_nop32_insn;
4157   return NOP_INSN;
4158 }
4159
4160 /* Return a mask that has bit N set if OPCODE reads the register(s)
4161    in operand N.  */
4162
4163 static unsigned int
4164 insn_read_mask (const struct mips_opcode *opcode)
4165 {
4166   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4167 }
4168
4169 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4170    in operand N.  */
4171
4172 static unsigned int
4173 insn_write_mask (const struct mips_opcode *opcode)
4174 {
4175   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4176 }
4177
4178 /* Return a mask of the registers specified by operand OPERAND of INSN.
4179    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4180    is set.  */
4181
4182 static unsigned int
4183 operand_reg_mask (const struct mips_cl_insn *insn,
4184                   const struct mips_operand *operand,
4185                   unsigned int type_mask)
4186 {
4187   unsigned int uval, vsel;
4188
4189   switch (operand->type)
4190     {
4191     case OP_INT:
4192     case OP_MAPPED_INT:
4193     case OP_MSB:
4194     case OP_PCREL:
4195     case OP_PERF_REG:
4196     case OP_ADDIUSP_INT:
4197     case OP_ENTRY_EXIT_LIST:
4198     case OP_REPEAT_DEST_REG:
4199     case OP_REPEAT_PREV_REG:
4200     case OP_PC:
4201     case OP_VU0_SUFFIX:
4202     case OP_VU0_MATCH_SUFFIX:
4203     case OP_IMM_INDEX:
4204       abort ();
4205
4206     case OP_REG:
4207     case OP_OPTIONAL_REG:
4208       {
4209         const struct mips_reg_operand *reg_op;
4210
4211         reg_op = (const struct mips_reg_operand *) operand;
4212         if (!(type_mask & (1 << reg_op->reg_type)))
4213           return 0;
4214         uval = insn_extract_operand (insn, operand);
4215         return 1 << mips_decode_reg_operand (reg_op, uval);
4216       }
4217
4218     case OP_REG_PAIR:
4219       {
4220         const struct mips_reg_pair_operand *pair_op;
4221
4222         pair_op = (const struct mips_reg_pair_operand *) operand;
4223         if (!(type_mask & (1 << pair_op->reg_type)))
4224           return 0;
4225         uval = insn_extract_operand (insn, operand);
4226         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4227       }
4228
4229     case OP_CLO_CLZ_DEST:
4230       if (!(type_mask & (1 << OP_REG_GP)))
4231         return 0;
4232       uval = insn_extract_operand (insn, operand);
4233       return (1 << (uval & 31)) | (1 << (uval >> 5));
4234
4235     case OP_LWM_SWM_LIST:
4236       abort ();
4237
4238     case OP_SAVE_RESTORE_LIST:
4239       abort ();
4240
4241     case OP_MDMX_IMM_REG:
4242       if (!(type_mask & (1 << OP_REG_VEC)))
4243         return 0;
4244       uval = insn_extract_operand (insn, operand);
4245       vsel = uval >> 5;
4246       if ((vsel & 0x18) == 0x18)
4247         return 0;
4248       return 1 << (uval & 31);
4249
4250     case OP_REG_INDEX:
4251       if (!(type_mask & (1 << OP_REG_GP)))
4252         return 0;
4253       return 1 << insn_extract_operand (insn, operand);
4254     }
4255   abort ();
4256 }
4257
4258 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4259    where bit N of OPNO_MASK is set if operand N should be included.
4260    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4261    is set.  */
4262
4263 static unsigned int
4264 insn_reg_mask (const struct mips_cl_insn *insn,
4265                unsigned int type_mask, unsigned int opno_mask)
4266 {
4267   unsigned int opno, reg_mask;
4268
4269   opno = 0;
4270   reg_mask = 0;
4271   while (opno_mask != 0)
4272     {
4273       if (opno_mask & 1)
4274         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4275       opno_mask >>= 1;
4276       opno += 1;
4277     }
4278   return reg_mask;
4279 }
4280
4281 /* Return the mask of core registers that IP reads.  */
4282
4283 static unsigned int
4284 gpr_read_mask (const struct mips_cl_insn *ip)
4285 {
4286   unsigned long pinfo, pinfo2;
4287   unsigned int mask;
4288
4289   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4290   pinfo = ip->insn_mo->pinfo;
4291   pinfo2 = ip->insn_mo->pinfo2;
4292   if (pinfo & INSN_UDI)
4293     {
4294       /* UDI instructions have traditionally been assumed to read RS
4295          and RT.  */
4296       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4297       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4298     }
4299   if (pinfo & INSN_READ_GPR_24)
4300     mask |= 1 << 24;
4301   if (pinfo2 & INSN2_READ_GPR_16)
4302     mask |= 1 << 16;
4303   if (pinfo2 & INSN2_READ_SP)
4304     mask |= 1 << SP;
4305   if (pinfo2 & INSN2_READ_GPR_31)
4306     mask |= 1 << 31;
4307   /* Don't include register 0.  */
4308   return mask & ~1;
4309 }
4310
4311 /* Return the mask of core registers that IP writes.  */
4312
4313 static unsigned int
4314 gpr_write_mask (const struct mips_cl_insn *ip)
4315 {
4316   unsigned long pinfo, pinfo2;
4317   unsigned int mask;
4318
4319   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4320   pinfo = ip->insn_mo->pinfo;
4321   pinfo2 = ip->insn_mo->pinfo2;
4322   if (pinfo & INSN_WRITE_GPR_24)
4323     mask |= 1 << 24;
4324   if (pinfo & INSN_WRITE_GPR_31)
4325     mask |= 1 << 31;
4326   if (pinfo & INSN_UDI)
4327     /* UDI instructions have traditionally been assumed to write to RD.  */
4328     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4329   if (pinfo2 & INSN2_WRITE_SP)
4330     mask |= 1 << SP;
4331   /* Don't include register 0.  */
4332   return mask & ~1;
4333 }
4334
4335 /* Return the mask of floating-point registers that IP reads.  */
4336
4337 static unsigned int
4338 fpr_read_mask (const struct mips_cl_insn *ip)
4339 {
4340   unsigned long pinfo;
4341   unsigned int mask;
4342
4343   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4344                              | (1 << OP_REG_MSA)),
4345                         insn_read_mask (ip->insn_mo));
4346   pinfo = ip->insn_mo->pinfo;
4347   /* Conservatively treat all operands to an FP_D instruction are doubles.
4348      (This is overly pessimistic for things like cvt.d.s.)  */
4349   if (FPR_SIZE != 64 && (pinfo & FP_D))
4350     mask |= mask << 1;
4351   return mask;
4352 }
4353
4354 /* Return the mask of floating-point registers that IP writes.  */
4355
4356 static unsigned int
4357 fpr_write_mask (const struct mips_cl_insn *ip)
4358 {
4359   unsigned long pinfo;
4360   unsigned int mask;
4361
4362   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4363                              | (1 << OP_REG_MSA)),
4364                         insn_write_mask (ip->insn_mo));
4365   pinfo = ip->insn_mo->pinfo;
4366   /* Conservatively treat all operands to an FP_D instruction are doubles.
4367      (This is overly pessimistic for things like cvt.s.d.)  */
4368   if (FPR_SIZE != 64 && (pinfo & FP_D))
4369     mask |= mask << 1;
4370   return mask;
4371 }
4372
4373 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4374    Check whether that is allowed.  */
4375
4376 static bfd_boolean
4377 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4378 {
4379   const char *s = insn->name;
4380
4381   if (insn->pinfo == INSN_MACRO)
4382     /* Let a macro pass, we'll catch it later when it is expanded.  */
4383     return TRUE;
4384
4385   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4386     {
4387       /* Allow odd registers for single-precision ops.  */
4388       switch (insn->pinfo & (FP_S | FP_D))
4389         {
4390         case FP_S:
4391         case 0:
4392           return TRUE;
4393         case FP_D:
4394           return FALSE;
4395         default:
4396           break;
4397         }
4398
4399       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4400       s = strchr (insn->name, '.');
4401       if (s != NULL && opnum == 2)
4402         s = strchr (s + 1, '.');
4403       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4404     }
4405
4406   /* Single-precision coprocessor loads and moves are OK too.  */
4407   if ((insn->pinfo & FP_S)
4408       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4409                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4410     return TRUE;
4411
4412   return FALSE;
4413 }
4414
4415 /* Information about an instruction argument that we're trying to match.  */
4416 struct mips_arg_info
4417 {
4418   /* The instruction so far.  */
4419   struct mips_cl_insn *insn;
4420
4421   /* The first unconsumed operand token.  */
4422   struct mips_operand_token *token;
4423
4424   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4425   int opnum;
4426
4427   /* The 1-based argument number, for error reporting.  This does not
4428      count elided optional registers, etc..  */
4429   int argnum;
4430
4431   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4432   unsigned int last_regno;
4433
4434   /* If the first operand was an OP_REG, this is the register that it
4435      specified, otherwise it is ILLEGAL_REG.  */
4436   unsigned int dest_regno;
4437
4438   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4439      where it gives the lsb position.  */
4440   unsigned int last_op_int;
4441
4442   /* If true, match routines should assume that no later instruction
4443      alternative matches and should therefore be as accomodating as
4444      possible.  Match routines should not report errors if something
4445      is only invalid for !LAX_MATCH.  */
4446   bfd_boolean lax_match;
4447
4448   /* True if a reference to the current AT register was seen.  */
4449   bfd_boolean seen_at;
4450 };
4451
4452 /* Record that the argument is out of range.  */
4453
4454 static void
4455 match_out_of_range (struct mips_arg_info *arg)
4456 {
4457   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4458 }
4459
4460 /* Record that the argument isn't constant but needs to be.  */
4461
4462 static void
4463 match_not_constant (struct mips_arg_info *arg)
4464 {
4465   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4466                     arg->argnum);
4467 }
4468
4469 /* Try to match an OT_CHAR token for character CH.  Consume the token
4470    and return true on success, otherwise return false.  */
4471
4472 static bfd_boolean
4473 match_char (struct mips_arg_info *arg, char ch)
4474 {
4475   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4476     {
4477       ++arg->token;
4478       if (ch == ',')
4479         arg->argnum += 1;
4480       return TRUE;
4481     }
4482   return FALSE;
4483 }
4484
4485 /* Try to get an expression from the next tokens in ARG.  Consume the
4486    tokens and return true on success, storing the expression value in
4487    VALUE and relocation types in R.  */
4488
4489 static bfd_boolean
4490 match_expression (struct mips_arg_info *arg, expressionS *value,
4491                   bfd_reloc_code_real_type *r)
4492 {
4493   /* If the next token is a '(' that was parsed as being part of a base
4494      expression, assume we have an elided offset.  The later match will fail
4495      if this turns out to be wrong.  */
4496   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4497     {
4498       value->X_op = O_constant;
4499       value->X_add_number = 0;
4500       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4501       return TRUE;
4502     }
4503
4504   /* Reject register-based expressions such as "0+$2" and "(($2))".
4505      For plain registers the default error seems more appropriate.  */
4506   if (arg->token->type == OT_INTEGER
4507       && arg->token->u.integer.value.X_op == O_register)
4508     {
4509       set_insn_error (arg->argnum, _("register value used as expression"));
4510       return FALSE;
4511     }
4512
4513   if (arg->token->type == OT_INTEGER)
4514     {
4515       *value = arg->token->u.integer.value;
4516       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4517       ++arg->token;
4518       return TRUE;
4519     }
4520
4521   set_insn_error_i
4522     (arg->argnum, _("operand %d must be an immediate expression"),
4523      arg->argnum);
4524   return FALSE;
4525 }
4526
4527 /* Try to get a constant expression from the next tokens in ARG.  Consume
4528    the tokens and return return true on success, storing the constant value
4529    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4530    error.  */
4531
4532 static bfd_boolean
4533 match_const_int (struct mips_arg_info *arg, offsetT *value)
4534 {
4535   expressionS ex;
4536   bfd_reloc_code_real_type r[3];
4537
4538   if (!match_expression (arg, &ex, r))
4539     return FALSE;
4540
4541   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4542     *value = ex.X_add_number;
4543   else
4544     {
4545       match_not_constant (arg);
4546       return FALSE;
4547     }
4548   return TRUE;
4549 }
4550
4551 /* Return the RTYPE_* flags for a register operand of type TYPE that
4552    appears in instruction OPCODE.  */
4553
4554 static unsigned int
4555 convert_reg_type (const struct mips_opcode *opcode,
4556                   enum mips_reg_operand_type type)
4557 {
4558   switch (type)
4559     {
4560     case OP_REG_GP:
4561       return RTYPE_NUM | RTYPE_GP;
4562
4563     case OP_REG_FP:
4564       /* Allow vector register names for MDMX if the instruction is a 64-bit
4565          FPR load, store or move (including moves to and from GPRs).  */
4566       if ((mips_opts.ase & ASE_MDMX)
4567           && (opcode->pinfo & FP_D)
4568           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4569                                | INSN_COPROC_MEMORY_DELAY
4570                                | INSN_LOAD_COPROC_DELAY
4571                                | INSN_LOAD_MEMORY
4572                                | INSN_STORE_MEMORY)))
4573         return RTYPE_FPU | RTYPE_VEC;
4574       return RTYPE_FPU;
4575
4576     case OP_REG_CCC:
4577       if (opcode->pinfo & (FP_D | FP_S))
4578         return RTYPE_CCC | RTYPE_FCC;
4579       return RTYPE_CCC;
4580
4581     case OP_REG_VEC:
4582       if (opcode->membership & INSN_5400)
4583         return RTYPE_FPU;
4584       return RTYPE_FPU | RTYPE_VEC;
4585
4586     case OP_REG_ACC:
4587       return RTYPE_ACC;
4588
4589     case OP_REG_COPRO:
4590       if (opcode->name[strlen (opcode->name) - 1] == '0')
4591         return RTYPE_NUM | RTYPE_CP0;
4592       return RTYPE_NUM;
4593
4594     case OP_REG_HW:
4595       return RTYPE_NUM;
4596
4597     case OP_REG_VI:
4598       return RTYPE_NUM | RTYPE_VI;
4599
4600     case OP_REG_VF:
4601       return RTYPE_NUM | RTYPE_VF;
4602
4603     case OP_REG_R5900_I:
4604       return RTYPE_R5900_I;
4605
4606     case OP_REG_R5900_Q:
4607       return RTYPE_R5900_Q;
4608
4609     case OP_REG_R5900_R:
4610       return RTYPE_R5900_R;
4611
4612     case OP_REG_R5900_ACC:
4613       return RTYPE_R5900_ACC;
4614
4615     case OP_REG_MSA:
4616       return RTYPE_MSA;
4617
4618     case OP_REG_MSA_CTRL:
4619       return RTYPE_NUM;
4620     }
4621   abort ();
4622 }
4623
4624 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4625
4626 static void
4627 check_regno (struct mips_arg_info *arg,
4628              enum mips_reg_operand_type type, unsigned int regno)
4629 {
4630   if (AT && type == OP_REG_GP && regno == AT)
4631     arg->seen_at = TRUE;
4632
4633   if (type == OP_REG_FP
4634       && (regno & 1) != 0
4635       && FPR_SIZE != 64
4636       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4637     as_warn (_("float register should be even, was %d"), regno);
4638
4639   if (type == OP_REG_CCC)
4640     {
4641       const char *name;
4642       size_t length;
4643
4644       name = arg->insn->insn_mo->name;
4645       length = strlen (name);
4646       if ((regno & 1) != 0
4647           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4648               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4649         as_warn (_("condition code register should be even for %s, was %d"),
4650                  name, regno);
4651
4652       if ((regno & 3) != 0
4653           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4654         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4655                  name, regno);
4656     }
4657 }
4658
4659 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4660    a register of type TYPE.  Return true on success, storing the register
4661    number in *REGNO and warning about any dubious uses.  */
4662
4663 static bfd_boolean
4664 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4665              unsigned int symval, unsigned int *regno)
4666 {
4667   if (type == OP_REG_VEC)
4668     symval = mips_prefer_vec_regno (symval);
4669   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4670     return FALSE;
4671
4672   *regno = symval & RNUM_MASK;
4673   check_regno (arg, type, *regno);
4674   return TRUE;
4675 }
4676
4677 /* Try to interpret the next token in ARG as a register of type TYPE.
4678    Consume the token and return true on success, storing the register
4679    number in *REGNO.  Return false on failure.  */
4680
4681 static bfd_boolean
4682 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4683            unsigned int *regno)
4684 {
4685   if (arg->token->type == OT_REG
4686       && match_regno (arg, type, arg->token->u.regno, regno))
4687     {
4688       ++arg->token;
4689       return TRUE;
4690     }
4691   return FALSE;
4692 }
4693
4694 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4695    Consume the token and return true on success, storing the register numbers
4696    in *REGNO1 and *REGNO2.  Return false on failure.  */
4697
4698 static bfd_boolean
4699 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4700                  unsigned int *regno1, unsigned int *regno2)
4701 {
4702   if (match_reg (arg, type, regno1))
4703     {
4704       *regno2 = *regno1;
4705       return TRUE;
4706     }
4707   if (arg->token->type == OT_REG_RANGE
4708       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4709       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4710       && *regno1 <= *regno2)
4711     {
4712       ++arg->token;
4713       return TRUE;
4714     }
4715   return FALSE;
4716 }
4717
4718 /* OP_INT matcher.  */
4719
4720 static bfd_boolean
4721 match_int_operand (struct mips_arg_info *arg,
4722                    const struct mips_operand *operand_base)
4723 {
4724   const struct mips_int_operand *operand;
4725   unsigned int uval;
4726   int min_val, max_val, factor;
4727   offsetT sval;
4728
4729   operand = (const struct mips_int_operand *) operand_base;
4730   factor = 1 << operand->shift;
4731   min_val = mips_int_operand_min (operand);
4732   max_val = mips_int_operand_max (operand);
4733
4734   if (operand_base->lsb == 0
4735       && operand_base->size == 16
4736       && operand->shift == 0
4737       && operand->bias == 0
4738       && (operand->max_val == 32767 || operand->max_val == 65535))
4739     {
4740       /* The operand can be relocated.  */
4741       if (!match_expression (arg, &offset_expr, offset_reloc))
4742         return FALSE;
4743
4744       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4745         /* Relocation operators were used.  Accept the arguent and
4746            leave the relocation value in offset_expr and offset_relocs
4747            for the caller to process.  */
4748         return TRUE;
4749
4750       if (offset_expr.X_op != O_constant)
4751         {
4752           /* Accept non-constant operands if no later alternative matches,
4753              leaving it for the caller to process.  */
4754           if (!arg->lax_match)
4755             return FALSE;
4756           offset_reloc[0] = BFD_RELOC_LO16;
4757           return TRUE;
4758         }
4759
4760       /* Clear the global state; we're going to install the operand
4761          ourselves.  */
4762       sval = offset_expr.X_add_number;
4763       offset_expr.X_op = O_absent;
4764
4765       /* For compatibility with older assemblers, we accept
4766          0x8000-0xffff as signed 16-bit numbers when only
4767          signed numbers are allowed.  */
4768       if (sval > max_val)
4769         {
4770           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4771           if (!arg->lax_match && sval <= max_val)
4772             return FALSE;
4773         }
4774     }
4775   else
4776     {
4777       if (!match_const_int (arg, &sval))
4778         return FALSE;
4779     }
4780
4781   arg->last_op_int = sval;
4782
4783   if (sval < min_val || sval > max_val || sval % factor)
4784     {
4785       match_out_of_range (arg);
4786       return FALSE;
4787     }
4788
4789   uval = (unsigned int) sval >> operand->shift;
4790   uval -= operand->bias;
4791
4792   /* Handle -mfix-cn63xxp1.  */
4793   if (arg->opnum == 1
4794       && mips_fix_cn63xxp1
4795       && !mips_opts.micromips
4796       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4797     switch (uval)
4798       {
4799       case 5:
4800       case 25:
4801       case 26:
4802       case 27:
4803       case 28:
4804       case 29:
4805       case 30:
4806       case 31:
4807         /* These are ok.  */
4808         break;
4809
4810       default:
4811         /* The rest must be changed to 28.  */
4812         uval = 28;
4813         break;
4814       }
4815
4816   insn_insert_operand (arg->insn, operand_base, uval);
4817   return TRUE;
4818 }
4819
4820 /* OP_MAPPED_INT matcher.  */
4821
4822 static bfd_boolean
4823 match_mapped_int_operand (struct mips_arg_info *arg,
4824                           const struct mips_operand *operand_base)
4825 {
4826   const struct mips_mapped_int_operand *operand;
4827   unsigned int uval, num_vals;
4828   offsetT sval;
4829
4830   operand = (const struct mips_mapped_int_operand *) operand_base;
4831   if (!match_const_int (arg, &sval))
4832     return FALSE;
4833
4834   num_vals = 1 << operand_base->size;
4835   for (uval = 0; uval < num_vals; uval++)
4836     if (operand->int_map[uval] == sval)
4837       break;
4838   if (uval == num_vals)
4839     {
4840       match_out_of_range (arg);
4841       return FALSE;
4842     }
4843
4844   insn_insert_operand (arg->insn, operand_base, uval);
4845   return TRUE;
4846 }
4847
4848 /* OP_MSB matcher.  */
4849
4850 static bfd_boolean
4851 match_msb_operand (struct mips_arg_info *arg,
4852                    const struct mips_operand *operand_base)
4853 {
4854   const struct mips_msb_operand *operand;
4855   int min_val, max_val, max_high;
4856   offsetT size, sval, high;
4857
4858   operand = (const struct mips_msb_operand *) operand_base;
4859   min_val = operand->bias;
4860   max_val = min_val + (1 << operand_base->size) - 1;
4861   max_high = operand->opsize;
4862
4863   if (!match_const_int (arg, &size))
4864     return FALSE;
4865
4866   high = size + arg->last_op_int;
4867   sval = operand->add_lsb ? high : size;
4868
4869   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4870     {
4871       match_out_of_range (arg);
4872       return FALSE;
4873     }
4874   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4875   return TRUE;
4876 }
4877
4878 /* OP_REG matcher.  */
4879
4880 static bfd_boolean
4881 match_reg_operand (struct mips_arg_info *arg,
4882                    const struct mips_operand *operand_base)
4883 {
4884   const struct mips_reg_operand *operand;
4885   unsigned int regno, uval, num_vals;
4886
4887   operand = (const struct mips_reg_operand *) operand_base;
4888   if (!match_reg (arg, operand->reg_type, &regno))
4889     return FALSE;
4890
4891   if (operand->reg_map)
4892     {
4893       num_vals = 1 << operand->root.size;
4894       for (uval = 0; uval < num_vals; uval++)
4895         if (operand->reg_map[uval] == regno)
4896           break;
4897       if (num_vals == uval)
4898         return FALSE;
4899     }
4900   else
4901     uval = regno;
4902
4903   arg->last_regno = regno;
4904   if (arg->opnum == 1)
4905     arg->dest_regno = regno;
4906   insn_insert_operand (arg->insn, operand_base, uval);
4907   return TRUE;
4908 }
4909
4910 /* OP_REG_PAIR matcher.  */
4911
4912 static bfd_boolean
4913 match_reg_pair_operand (struct mips_arg_info *arg,
4914                         const struct mips_operand *operand_base)
4915 {
4916   const struct mips_reg_pair_operand *operand;
4917   unsigned int regno1, regno2, uval, num_vals;
4918
4919   operand = (const struct mips_reg_pair_operand *) operand_base;
4920   if (!match_reg (arg, operand->reg_type, &regno1)
4921       || !match_char (arg, ',')
4922       || !match_reg (arg, operand->reg_type, &regno2))
4923     return FALSE;
4924
4925   num_vals = 1 << operand_base->size;
4926   for (uval = 0; uval < num_vals; uval++)
4927     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4928       break;
4929   if (uval == num_vals)
4930     return FALSE;
4931
4932   insn_insert_operand (arg->insn, operand_base, uval);
4933   return TRUE;
4934 }
4935
4936 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4937
4938 static bfd_boolean
4939 match_pcrel_operand (struct mips_arg_info *arg)
4940 {
4941   bfd_reloc_code_real_type r[3];
4942
4943   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4944 }
4945
4946 /* OP_PERF_REG matcher.  */
4947
4948 static bfd_boolean
4949 match_perf_reg_operand (struct mips_arg_info *arg,
4950                         const struct mips_operand *operand)
4951 {
4952   offsetT sval;
4953
4954   if (!match_const_int (arg, &sval))
4955     return FALSE;
4956
4957   if (sval != 0
4958       && (sval != 1
4959           || (mips_opts.arch == CPU_R5900
4960               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4961                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4962     {
4963       set_insn_error (arg->argnum, _("invalid performance register"));
4964       return FALSE;
4965     }
4966
4967   insn_insert_operand (arg->insn, operand, sval);
4968   return TRUE;
4969 }
4970
4971 /* OP_ADDIUSP matcher.  */
4972
4973 static bfd_boolean
4974 match_addiusp_operand (struct mips_arg_info *arg,
4975                        const struct mips_operand *operand)
4976 {
4977   offsetT sval;
4978   unsigned int uval;
4979
4980   if (!match_const_int (arg, &sval))
4981     return FALSE;
4982
4983   if (sval % 4)
4984     {
4985       match_out_of_range (arg);
4986       return FALSE;
4987     }
4988
4989   sval /= 4;
4990   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4991     {
4992       match_out_of_range (arg);
4993       return FALSE;
4994     }
4995
4996   uval = (unsigned int) sval;
4997   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4998   insn_insert_operand (arg->insn, operand, uval);
4999   return TRUE;
5000 }
5001
5002 /* OP_CLO_CLZ_DEST matcher.  */
5003
5004 static bfd_boolean
5005 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5006                             const struct mips_operand *operand)
5007 {
5008   unsigned int regno;
5009
5010   if (!match_reg (arg, OP_REG_GP, &regno))
5011     return FALSE;
5012
5013   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5014   return TRUE;
5015 }
5016
5017 /* OP_LWM_SWM_LIST matcher.  */
5018
5019 static bfd_boolean
5020 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5021                             const struct mips_operand *operand)
5022 {
5023   unsigned int reglist, sregs, ra, regno1, regno2;
5024   struct mips_arg_info reset;
5025
5026   reglist = 0;
5027   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5028     return FALSE;
5029   do
5030     {
5031       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5032         {
5033           reglist |= 1 << FP;
5034           regno2 = S7;
5035         }
5036       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5037       reset = *arg;
5038     }
5039   while (match_char (arg, ',')
5040          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5041   *arg = reset;
5042
5043   if (operand->size == 2)
5044     {
5045       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5046
5047          s0, ra
5048          s0, s1, ra, s2, s3
5049          s0-s2, ra
5050
5051          and any permutations of these.  */
5052       if ((reglist & 0xfff1ffff) != 0x80010000)
5053         return FALSE;
5054
5055       sregs = (reglist >> 17) & 7;
5056       ra = 0;
5057     }
5058   else
5059     {
5060       /* The list must include at least one of ra and s0-sN,
5061          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5062          which are $23 and $30 respectively.)  E.g.:
5063
5064          ra
5065          s0
5066          ra, s0, s1, s2
5067          s0-s8
5068          s0-s5, ra
5069
5070          and any permutations of these.  */
5071       if ((reglist & 0x3f00ffff) != 0)
5072         return FALSE;
5073
5074       ra = (reglist >> 27) & 0x10;
5075       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5076     }
5077   sregs += 1;
5078   if ((sregs & -sregs) != sregs)
5079     return FALSE;
5080
5081   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5082   return TRUE;
5083 }
5084
5085 /* OP_ENTRY_EXIT_LIST matcher.  */
5086
5087 static unsigned int
5088 match_entry_exit_operand (struct mips_arg_info *arg,
5089                           const struct mips_operand *operand)
5090 {
5091   unsigned int mask;
5092   bfd_boolean is_exit;
5093
5094   /* The format is the same for both ENTRY and EXIT, but the constraints
5095      are different.  */
5096   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5097   mask = (is_exit ? 7 << 3 : 0);
5098   do
5099     {
5100       unsigned int regno1, regno2;
5101       bfd_boolean is_freg;
5102
5103       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5104         is_freg = FALSE;
5105       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5106         is_freg = TRUE;
5107       else
5108         return FALSE;
5109
5110       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5111         {
5112           mask &= ~(7 << 3);
5113           mask |= (5 + regno2) << 3;
5114         }
5115       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5116         mask |= (regno2 - 3) << 3;
5117       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5118         mask |= (regno2 - 15) << 1;
5119       else if (regno1 == RA && regno2 == RA)
5120         mask |= 1;
5121       else
5122         return FALSE;
5123     }
5124   while (match_char (arg, ','));
5125
5126   insn_insert_operand (arg->insn, operand, mask);
5127   return TRUE;
5128 }
5129
5130 /* OP_SAVE_RESTORE_LIST matcher.  */
5131
5132 static bfd_boolean
5133 match_save_restore_list_operand (struct mips_arg_info *arg)
5134 {
5135   unsigned int opcode, args, statics, sregs;
5136   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5137   offsetT frame_size;
5138
5139   opcode = arg->insn->insn_opcode;
5140   frame_size = 0;
5141   num_frame_sizes = 0;
5142   args = 0;
5143   statics = 0;
5144   sregs = 0;
5145   do
5146     {
5147       unsigned int regno1, regno2;
5148
5149       if (arg->token->type == OT_INTEGER)
5150         {
5151           /* Handle the frame size.  */
5152           if (!match_const_int (arg, &frame_size))
5153             return FALSE;
5154           num_frame_sizes += 1;
5155         }
5156       else
5157         {
5158           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5159             return FALSE;
5160
5161           while (regno1 <= regno2)
5162             {
5163               if (regno1 >= 4 && regno1 <= 7)
5164                 {
5165                   if (num_frame_sizes == 0)
5166                     /* args $a0-$a3 */
5167                     args |= 1 << (regno1 - 4);
5168                   else
5169                     /* statics $a0-$a3 */
5170                     statics |= 1 << (regno1 - 4);
5171                 }
5172               else if (regno1 >= 16 && regno1 <= 23)
5173                 /* $s0-$s7 */
5174                 sregs |= 1 << (regno1 - 16);
5175               else if (regno1 == 30)
5176                 /* $s8 */
5177                 sregs |= 1 << 8;
5178               else if (regno1 == 31)
5179                 /* Add $ra to insn.  */
5180                 opcode |= 0x40;
5181               else
5182                 return FALSE;
5183               regno1 += 1;
5184               if (regno1 == 24)
5185                 regno1 = 30;
5186             }
5187         }
5188     }
5189   while (match_char (arg, ','));
5190
5191   /* Encode args/statics combination.  */
5192   if (args & statics)
5193     return FALSE;
5194   else if (args == 0xf)
5195     /* All $a0-$a3 are args.  */
5196     opcode |= MIPS16_ALL_ARGS << 16;
5197   else if (statics == 0xf)
5198     /* All $a0-$a3 are statics.  */
5199     opcode |= MIPS16_ALL_STATICS << 16;
5200   else
5201     {
5202       /* Count arg registers.  */
5203       num_args = 0;
5204       while (args & 0x1)
5205         {
5206           args >>= 1;
5207           num_args += 1;
5208         }
5209       if (args != 0)
5210         return FALSE;
5211
5212       /* Count static registers.  */
5213       num_statics = 0;
5214       while (statics & 0x8)
5215         {
5216           statics = (statics << 1) & 0xf;
5217           num_statics += 1;
5218         }
5219       if (statics != 0)
5220         return FALSE;
5221
5222       /* Encode args/statics.  */
5223       opcode |= ((num_args << 2) | num_statics) << 16;
5224     }
5225
5226   /* Encode $s0/$s1.  */
5227   if (sregs & (1 << 0))         /* $s0 */
5228     opcode |= 0x20;
5229   if (sregs & (1 << 1))         /* $s1 */
5230     opcode |= 0x10;
5231   sregs >>= 2;
5232
5233   /* Encode $s2-$s8. */
5234   num_sregs = 0;
5235   while (sregs & 1)
5236     {
5237       sregs >>= 1;
5238       num_sregs += 1;
5239     }
5240   if (sregs != 0)
5241     return FALSE;
5242   opcode |= num_sregs << 24;
5243
5244   /* Encode frame size.  */
5245   if (num_frame_sizes == 0)
5246     {
5247       set_insn_error (arg->argnum, _("missing frame size"));
5248       return FALSE;
5249     }
5250   if (num_frame_sizes > 1)
5251     {
5252       set_insn_error (arg->argnum, _("frame size specified twice"));
5253       return FALSE;
5254     }
5255   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5256     {
5257       set_insn_error (arg->argnum, _("invalid frame size"));
5258       return FALSE;
5259     }
5260   if (frame_size != 128 || (opcode >> 16) != 0)
5261     {
5262       frame_size /= 8;
5263       opcode |= (((frame_size & 0xf0) << 16)
5264                  | (frame_size & 0x0f));
5265     }
5266
5267   /* Finally build the instruction.  */
5268   if ((opcode >> 16) != 0 || frame_size == 0)
5269     opcode |= MIPS16_EXTEND;
5270   arg->insn->insn_opcode = opcode;
5271   return TRUE;
5272 }
5273
5274 /* OP_MDMX_IMM_REG matcher.  */
5275
5276 static bfd_boolean
5277 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5278                             const struct mips_operand *operand)
5279 {
5280   unsigned int regno, uval;
5281   bfd_boolean is_qh;
5282   const struct mips_opcode *opcode;
5283
5284   /* The mips_opcode records whether this is an octobyte or quadhalf
5285      instruction.  Start out with that bit in place.  */
5286   opcode = arg->insn->insn_mo;
5287   uval = mips_extract_operand (operand, opcode->match);
5288   is_qh = (uval != 0);
5289
5290   if (arg->token->type == OT_REG)
5291     {
5292       if ((opcode->membership & INSN_5400)
5293           && strcmp (opcode->name, "rzu.ob") == 0)
5294         {
5295           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5296                             arg->argnum);
5297           return FALSE;
5298         }
5299
5300       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5301         return FALSE;
5302       ++arg->token;
5303
5304       /* Check whether this is a vector register or a broadcast of
5305          a single element.  */
5306       if (arg->token->type == OT_INTEGER_INDEX)
5307         {
5308           if (arg->token->u.index > (is_qh ? 3 : 7))
5309             {
5310               set_insn_error (arg->argnum, _("invalid element selector"));
5311               return FALSE;
5312             }
5313           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5314           ++arg->token;
5315         }
5316       else
5317         {
5318           /* A full vector.  */
5319           if ((opcode->membership & INSN_5400)
5320               && (strcmp (opcode->name, "sll.ob") == 0
5321                   || strcmp (opcode->name, "srl.ob") == 0))
5322             {
5323               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5324                                 arg->argnum);
5325               return FALSE;
5326             }
5327
5328           if (is_qh)
5329             uval |= MDMX_FMTSEL_VEC_QH << 5;
5330           else
5331             uval |= MDMX_FMTSEL_VEC_OB << 5;
5332         }
5333       uval |= regno;
5334     }
5335   else
5336     {
5337       offsetT sval;
5338
5339       if (!match_const_int (arg, &sval))
5340         return FALSE;
5341       if (sval < 0 || sval > 31)
5342         {
5343           match_out_of_range (arg);
5344           return FALSE;
5345         }
5346       uval |= (sval & 31);
5347       if (is_qh)
5348         uval |= MDMX_FMTSEL_IMM_QH << 5;
5349       else
5350         uval |= MDMX_FMTSEL_IMM_OB << 5;
5351     }
5352   insn_insert_operand (arg->insn, operand, uval);
5353   return TRUE;
5354 }
5355
5356 /* OP_IMM_INDEX matcher.  */
5357
5358 static bfd_boolean
5359 match_imm_index_operand (struct mips_arg_info *arg,
5360                          const struct mips_operand *operand)
5361 {
5362   unsigned int max_val;
5363
5364   if (arg->token->type != OT_INTEGER_INDEX)
5365     return FALSE;
5366
5367   max_val = (1 << operand->size) - 1;
5368   if (arg->token->u.index > max_val)
5369     {
5370       match_out_of_range (arg);
5371       return FALSE;
5372     }
5373   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5374   ++arg->token;
5375   return TRUE;
5376 }
5377
5378 /* OP_REG_INDEX matcher.  */
5379
5380 static bfd_boolean
5381 match_reg_index_operand (struct mips_arg_info *arg,
5382                          const struct mips_operand *operand)
5383 {
5384   unsigned int regno;
5385
5386   if (arg->token->type != OT_REG_INDEX)
5387     return FALSE;
5388
5389   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5390     return FALSE;
5391
5392   insn_insert_operand (arg->insn, operand, regno);
5393   ++arg->token;
5394   return TRUE;
5395 }
5396
5397 /* OP_PC matcher.  */
5398
5399 static bfd_boolean
5400 match_pc_operand (struct mips_arg_info *arg)
5401 {
5402   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5403     {
5404       ++arg->token;
5405       return TRUE;
5406     }
5407   return FALSE;
5408 }
5409
5410 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5411    register that we need to match.  */
5412
5413 static bfd_boolean
5414 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5415 {
5416   unsigned int regno;
5417
5418   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5419 }
5420
5421 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5422    the length of the value in bytes (4 for float, 8 for double) and
5423    USING_GPRS says whether the destination is a GPR rather than an FPR.
5424
5425    Return the constant in IMM and OFFSET as follows:
5426
5427    - If the constant should be loaded via memory, set IMM to O_absent and
5428      OFFSET to the memory address.
5429
5430    - Otherwise, if the constant should be loaded into two 32-bit registers,
5431      set IMM to the O_constant to load into the high register and OFFSET
5432      to the corresponding value for the low register.
5433
5434    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5435
5436    These constants only appear as the last operand in an instruction,
5437    and every instruction that accepts them in any variant accepts them
5438    in all variants.  This means we don't have to worry about backing out
5439    any changes if the instruction does not match.  We just match
5440    unconditionally and report an error if the constant is invalid.  */
5441
5442 static bfd_boolean
5443 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5444                       expressionS *offset, int length, bfd_boolean using_gprs)
5445 {
5446   char *p;
5447   segT seg, new_seg;
5448   subsegT subseg;
5449   const char *newname;
5450   unsigned char *data;
5451
5452   /* Where the constant is placed is based on how the MIPS assembler
5453      does things:
5454
5455      length == 4 && using_gprs  -- immediate value only
5456      length == 8 && using_gprs  -- .rdata or immediate value
5457      length == 4 && !using_gprs -- .lit4 or immediate value
5458      length == 8 && !using_gprs -- .lit8 or immediate value
5459
5460      The .lit4 and .lit8 sections are only used if permitted by the
5461      -G argument.  */
5462   if (arg->token->type != OT_FLOAT)
5463     {
5464       set_insn_error (arg->argnum, _("floating-point expression required"));
5465       return FALSE;
5466     }
5467
5468   gas_assert (arg->token->u.flt.length == length);
5469   data = arg->token->u.flt.data;
5470   ++arg->token;
5471
5472   /* Handle 32-bit constants for which an immediate value is best.  */
5473   if (length == 4
5474       && (using_gprs
5475           || g_switch_value < 4
5476           || (data[0] == 0 && data[1] == 0)
5477           || (data[2] == 0 && data[3] == 0)))
5478     {
5479       imm->X_op = O_constant;
5480       if (!target_big_endian)
5481         imm->X_add_number = bfd_getl32 (data);
5482       else
5483         imm->X_add_number = bfd_getb32 (data);
5484       offset->X_op = O_absent;
5485       return TRUE;
5486     }
5487
5488   /* Handle 64-bit constants for which an immediate value is best.  */
5489   if (length == 8
5490       && !mips_disable_float_construction
5491       /* Constants can only be constructed in GPRs and copied
5492          to FPRs if the GPRs are at least as wide as the FPRs.
5493          Force the constant into memory if we are using 64-bit FPRs
5494          but the GPRs are only 32 bits wide.  */
5495       /* ??? No longer true with the addition of MTHC1, but this
5496          is legacy code...  */
5497       && (using_gprs || !(FPR_SIZE == 64 && GPR_SIZE == 32))
5498       && ((data[0] == 0 && data[1] == 0)
5499           || (data[2] == 0 && data[3] == 0))
5500       && ((data[4] == 0 && data[5] == 0)
5501           || (data[6] == 0 && data[7] == 0)))
5502     {
5503       /* The value is simple enough to load with a couple of instructions.
5504          If using 32-bit registers, set IMM to the high order 32 bits and
5505          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5506          64 bit constant.  */
5507       if (using_gprs ? GPR_SIZE == 32 : FPR_SIZE != 64)
5508         {
5509           imm->X_op = O_constant;
5510           offset->X_op = O_constant;
5511           if (!target_big_endian)
5512             {
5513               imm->X_add_number = bfd_getl32 (data + 4);
5514               offset->X_add_number = bfd_getl32 (data);
5515             }
5516           else
5517             {
5518               imm->X_add_number = bfd_getb32 (data);
5519               offset->X_add_number = bfd_getb32 (data + 4);
5520             }
5521           if (offset->X_add_number == 0)
5522             offset->X_op = O_absent;
5523         }
5524       else
5525         {
5526           imm->X_op = O_constant;
5527           if (!target_big_endian)
5528             imm->X_add_number = bfd_getl64 (data);
5529           else
5530             imm->X_add_number = bfd_getb64 (data);
5531           offset->X_op = O_absent;
5532         }
5533       return TRUE;
5534     }
5535
5536   /* Switch to the right section.  */
5537   seg = now_seg;
5538   subseg = now_subseg;
5539   if (length == 4)
5540     {
5541       gas_assert (!using_gprs && g_switch_value >= 4);
5542       newname = ".lit4";
5543     }
5544   else
5545     {
5546       if (using_gprs || g_switch_value < 8)
5547         newname = RDATA_SECTION_NAME;
5548       else
5549         newname = ".lit8";
5550     }
5551
5552   new_seg = subseg_new (newname, (subsegT) 0);
5553   bfd_set_section_flags (stdoutput, new_seg,
5554                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5555   frag_align (length == 4 ? 2 : 3, 0, 0);
5556   if (strncmp (TARGET_OS, "elf", 3) != 0)
5557     record_alignment (new_seg, 4);
5558   else
5559     record_alignment (new_seg, length == 4 ? 2 : 3);
5560   if (seg == now_seg)
5561     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5562
5563   /* Set the argument to the current address in the section.  */
5564   imm->X_op = O_absent;
5565   offset->X_op = O_symbol;
5566   offset->X_add_symbol = symbol_temp_new_now ();
5567   offset->X_add_number = 0;
5568
5569   /* Put the floating point number into the section.  */
5570   p = frag_more (length);
5571   memcpy (p, data, length);
5572
5573   /* Switch back to the original section.  */
5574   subseg_set (seg, subseg);
5575   return TRUE;
5576 }
5577
5578 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5579    them.  */
5580
5581 static bfd_boolean
5582 match_vu0_suffix_operand (struct mips_arg_info *arg,
5583                           const struct mips_operand *operand,
5584                           bfd_boolean match_p)
5585 {
5586   unsigned int uval;
5587
5588   /* The operand can be an XYZW mask or a single 2-bit channel index
5589      (with X being 0).  */
5590   gas_assert (operand->size == 2 || operand->size == 4);
5591
5592   /* The suffix can be omitted when it is already part of the opcode.  */
5593   if (arg->token->type != OT_CHANNELS)
5594     return match_p;
5595
5596   uval = arg->token->u.channels;
5597   if (operand->size == 2)
5598     {
5599       /* Check that a single bit is set and convert it into a 2-bit index.  */
5600       if ((uval & -uval) != uval)
5601         return FALSE;
5602       uval = 4 - ffs (uval);
5603     }
5604
5605   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5606     return FALSE;
5607
5608   ++arg->token;
5609   if (!match_p)
5610     insn_insert_operand (arg->insn, operand, uval);
5611   return TRUE;
5612 }
5613
5614 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5615    of the argument text if the match is successful, otherwise return null.  */
5616
5617 static bfd_boolean
5618 match_operand (struct mips_arg_info *arg,
5619                const struct mips_operand *operand)
5620 {
5621   switch (operand->type)
5622     {
5623     case OP_INT:
5624       return match_int_operand (arg, operand);
5625
5626     case OP_MAPPED_INT:
5627       return match_mapped_int_operand (arg, operand);
5628
5629     case OP_MSB:
5630       return match_msb_operand (arg, operand);
5631
5632     case OP_REG:
5633     case OP_OPTIONAL_REG:
5634       return match_reg_operand (arg, operand);
5635
5636     case OP_REG_PAIR:
5637       return match_reg_pair_operand (arg, operand);
5638
5639     case OP_PCREL:
5640       return match_pcrel_operand (arg);
5641
5642     case OP_PERF_REG:
5643       return match_perf_reg_operand (arg, operand);
5644
5645     case OP_ADDIUSP_INT:
5646       return match_addiusp_operand (arg, operand);
5647
5648     case OP_CLO_CLZ_DEST:
5649       return match_clo_clz_dest_operand (arg, operand);
5650
5651     case OP_LWM_SWM_LIST:
5652       return match_lwm_swm_list_operand (arg, operand);
5653
5654     case OP_ENTRY_EXIT_LIST:
5655       return match_entry_exit_operand (arg, operand);
5656
5657     case OP_SAVE_RESTORE_LIST:
5658       return match_save_restore_list_operand (arg);
5659
5660     case OP_MDMX_IMM_REG:
5661       return match_mdmx_imm_reg_operand (arg, operand);
5662
5663     case OP_REPEAT_DEST_REG:
5664       return match_tied_reg_operand (arg, arg->dest_regno);
5665
5666     case OP_REPEAT_PREV_REG:
5667       return match_tied_reg_operand (arg, arg->last_regno);
5668
5669     case OP_PC:
5670       return match_pc_operand (arg);
5671
5672     case OP_VU0_SUFFIX:
5673       return match_vu0_suffix_operand (arg, operand, FALSE);
5674
5675     case OP_VU0_MATCH_SUFFIX:
5676       return match_vu0_suffix_operand (arg, operand, TRUE);
5677
5678     case OP_IMM_INDEX:
5679       return match_imm_index_operand (arg, operand);
5680
5681     case OP_REG_INDEX:
5682       return match_reg_index_operand (arg, operand);
5683     }
5684   abort ();
5685 }
5686
5687 /* ARG is the state after successfully matching an instruction.
5688    Issue any queued-up warnings.  */
5689
5690 static void
5691 check_completed_insn (struct mips_arg_info *arg)
5692 {
5693   if (arg->seen_at)
5694     {
5695       if (AT == ATREG)
5696         as_warn (_("used $at without \".set noat\""));
5697       else
5698         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5699     }
5700 }
5701
5702 /* Return true if modifying general-purpose register REG needs a delay.  */
5703
5704 static bfd_boolean
5705 reg_needs_delay (unsigned int reg)
5706 {
5707   unsigned long prev_pinfo;
5708
5709   prev_pinfo = history[0].insn_mo->pinfo;
5710   if (!mips_opts.noreorder
5711       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5712           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5713       && (gpr_write_mask (&history[0]) & (1 << reg)))
5714     return TRUE;
5715
5716   return FALSE;
5717 }
5718
5719 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5720    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5721    by VR4120 errata.  */
5722
5723 static unsigned int
5724 classify_vr4120_insn (const char *name)
5725 {
5726   if (strncmp (name, "macc", 4) == 0)
5727     return FIX_VR4120_MACC;
5728   if (strncmp (name, "dmacc", 5) == 0)
5729     return FIX_VR4120_DMACC;
5730   if (strncmp (name, "mult", 4) == 0)
5731     return FIX_VR4120_MULT;
5732   if (strncmp (name, "dmult", 5) == 0)
5733     return FIX_VR4120_DMULT;
5734   if (strstr (name, "div"))
5735     return FIX_VR4120_DIV;
5736   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5737     return FIX_VR4120_MTHILO;
5738   return NUM_FIX_VR4120_CLASSES;
5739 }
5740
5741 #define INSN_ERET       0x42000018
5742 #define INSN_DERET      0x4200001f
5743 #define INSN_DMULT      0x1c
5744 #define INSN_DMULTU     0x1d
5745
5746 /* Return the number of instructions that must separate INSN1 and INSN2,
5747    where INSN1 is the earlier instruction.  Return the worst-case value
5748    for any INSN2 if INSN2 is null.  */
5749
5750 static unsigned int
5751 insns_between (const struct mips_cl_insn *insn1,
5752                const struct mips_cl_insn *insn2)
5753 {
5754   unsigned long pinfo1, pinfo2;
5755   unsigned int mask;
5756
5757   /* If INFO2 is null, pessimistically assume that all flags are set for
5758      the second instruction.  */
5759   pinfo1 = insn1->insn_mo->pinfo;
5760   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5761
5762   /* For most targets, write-after-read dependencies on the HI and LO
5763      registers must be separated by at least two instructions.  */
5764   if (!hilo_interlocks)
5765     {
5766       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5767         return 2;
5768       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5769         return 2;
5770     }
5771
5772   /* If we're working around r7000 errata, there must be two instructions
5773      between an mfhi or mflo and any instruction that uses the result.  */
5774   if (mips_7000_hilo_fix
5775       && !mips_opts.micromips
5776       && MF_HILO_INSN (pinfo1)
5777       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5778     return 2;
5779
5780   /* If we're working around 24K errata, one instruction is required
5781      if an ERET or DERET is followed by a branch instruction.  */
5782   if (mips_fix_24k && !mips_opts.micromips)
5783     {
5784       if (insn1->insn_opcode == INSN_ERET
5785           || insn1->insn_opcode == INSN_DERET)
5786         {
5787           if (insn2 == NULL
5788               || insn2->insn_opcode == INSN_ERET
5789               || insn2->insn_opcode == INSN_DERET
5790               || delayed_branch_p (insn2))
5791             return 1;
5792         }
5793     }
5794
5795   /* If we're working around PMC RM7000 errata, there must be three
5796      nops between a dmult and a load instruction.  */
5797   if (mips_fix_rm7000 && !mips_opts.micromips)
5798     {
5799       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5800           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5801         {
5802           if (pinfo2 & INSN_LOAD_MEMORY)
5803            return 3;
5804         }
5805     }
5806
5807   /* If working around VR4120 errata, check for combinations that need
5808      a single intervening instruction.  */
5809   if (mips_fix_vr4120 && !mips_opts.micromips)
5810     {
5811       unsigned int class1, class2;
5812
5813       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5814       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5815         {
5816           if (insn2 == NULL)
5817             return 1;
5818           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5819           if (vr4120_conflicts[class1] & (1 << class2))
5820             return 1;
5821         }
5822     }
5823
5824   if (!HAVE_CODE_COMPRESSION)
5825     {
5826       /* Check for GPR or coprocessor load delays.  All such delays
5827          are on the RT register.  */
5828       /* Itbl support may require additional care here.  */
5829       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5830           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5831         {
5832           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5833             return 1;
5834         }
5835
5836       /* Check for generic coprocessor hazards.
5837
5838          This case is not handled very well.  There is no special
5839          knowledge of CP0 handling, and the coprocessors other than
5840          the floating point unit are not distinguished at all.  */
5841       /* Itbl support may require additional care here. FIXME!
5842          Need to modify this to include knowledge about
5843          user specified delays!  */
5844       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5845                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5846         {
5847           /* Handle cases where INSN1 writes to a known general coprocessor
5848              register.  There must be a one instruction delay before INSN2
5849              if INSN2 reads that register, otherwise no delay is needed.  */
5850           mask = fpr_write_mask (insn1);
5851           if (mask != 0)
5852             {
5853               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5854                 return 1;
5855             }
5856           else
5857             {
5858               /* Read-after-write dependencies on the control registers
5859                  require a two-instruction gap.  */
5860               if ((pinfo1 & INSN_WRITE_COND_CODE)
5861                   && (pinfo2 & INSN_READ_COND_CODE))
5862                 return 2;
5863
5864               /* We don't know exactly what INSN1 does.  If INSN2 is
5865                  also a coprocessor instruction, assume there must be
5866                  a one instruction gap.  */
5867               if (pinfo2 & INSN_COP)
5868                 return 1;
5869             }
5870         }
5871
5872       /* Check for read-after-write dependencies on the coprocessor
5873          control registers in cases where INSN1 does not need a general
5874          coprocessor delay.  This means that INSN1 is a floating point
5875          comparison instruction.  */
5876       /* Itbl support may require additional care here.  */
5877       else if (!cop_interlocks
5878                && (pinfo1 & INSN_WRITE_COND_CODE)
5879                && (pinfo2 & INSN_READ_COND_CODE))
5880         return 1;
5881     }
5882
5883   return 0;
5884 }
5885
5886 /* Return the number of nops that would be needed to work around the
5887    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5888    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5889    that are contained within the first IGNORE instructions of HIST.  */
5890
5891 static int
5892 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5893                  const struct mips_cl_insn *insn)
5894 {
5895   int i, j;
5896   unsigned int mask;
5897
5898   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5899      are not affected by the errata.  */
5900   if (insn != 0
5901       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5902           || strcmp (insn->insn_mo->name, "mtlo") == 0
5903           || strcmp (insn->insn_mo->name, "mthi") == 0))
5904     return 0;
5905
5906   /* Search for the first MFLO or MFHI.  */
5907   for (i = 0; i < MAX_VR4130_NOPS; i++)
5908     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5909       {
5910         /* Extract the destination register.  */
5911         mask = gpr_write_mask (&hist[i]);
5912
5913         /* No nops are needed if INSN reads that register.  */
5914         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5915           return 0;
5916
5917         /* ...or if any of the intervening instructions do.  */
5918         for (j = 0; j < i; j++)
5919           if (gpr_read_mask (&hist[j]) & mask)
5920             return 0;
5921
5922         if (i >= ignore)
5923           return MAX_VR4130_NOPS - i;
5924       }
5925   return 0;
5926 }
5927
5928 #define BASE_REG_EQ(INSN1, INSN2)       \
5929   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5930       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5931
5932 /* Return the minimum alignment for this store instruction.  */
5933
5934 static int
5935 fix_24k_align_to (const struct mips_opcode *mo)
5936 {
5937   if (strcmp (mo->name, "sh") == 0)
5938     return 2;
5939
5940   if (strcmp (mo->name, "swc1") == 0
5941       || strcmp (mo->name, "swc2") == 0
5942       || strcmp (mo->name, "sw") == 0
5943       || strcmp (mo->name, "sc") == 0
5944       || strcmp (mo->name, "s.s") == 0)
5945     return 4;
5946
5947   if (strcmp (mo->name, "sdc1") == 0
5948       || strcmp (mo->name, "sdc2") == 0
5949       || strcmp (mo->name, "s.d") == 0)
5950     return 8;
5951
5952   /* sb, swl, swr */
5953   return 1;
5954 }
5955
5956 struct fix_24k_store_info
5957   {
5958     /* Immediate offset, if any, for this store instruction.  */
5959     short off;
5960     /* Alignment required by this store instruction.  */
5961     int align_to;
5962     /* True for register offsets.  */
5963     int register_offset;
5964   };
5965
5966 /* Comparison function used by qsort.  */
5967
5968 static int
5969 fix_24k_sort (const void *a, const void *b)
5970 {
5971   const struct fix_24k_store_info *pos1 = a;
5972   const struct fix_24k_store_info *pos2 = b;
5973
5974   return (pos1->off - pos2->off);
5975 }
5976
5977 /* INSN is a store instruction.  Try to record the store information
5978    in STINFO.  Return false if the information isn't known.  */
5979
5980 static bfd_boolean
5981 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5982                            const struct mips_cl_insn *insn)
5983 {
5984   /* The instruction must have a known offset.  */
5985   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5986     return FALSE;
5987
5988   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5989   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5990   return TRUE;
5991 }
5992
5993 /* Return the number of nops that would be needed to work around the 24k
5994    "lost data on stores during refill" errata if instruction INSN
5995    immediately followed the 2 instructions described by HIST.
5996    Ignore hazards that are contained within the first IGNORE
5997    instructions of HIST.
5998
5999    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6000    for the data cache refills and store data. The following describes
6001    the scenario where the store data could be lost.
6002
6003    * A data cache miss, due to either a load or a store, causing fill
6004      data to be supplied by the memory subsystem
6005    * The first three doublewords of fill data are returned and written
6006      into the cache
6007    * A sequence of four stores occurs in consecutive cycles around the
6008      final doubleword of the fill:
6009    * Store A
6010    * Store B
6011    * Store C
6012    * Zero, One or more instructions
6013    * Store D
6014
6015    The four stores A-D must be to different doublewords of the line that
6016    is being filled. The fourth instruction in the sequence above permits
6017    the fill of the final doubleword to be transferred from the FSB into
6018    the cache. In the sequence above, the stores may be either integer
6019    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6020    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6021    different doublewords on the line. If the floating point unit is
6022    running in 1:2 mode, it is not possible to create the sequence above
6023    using only floating point store instructions.
6024
6025    In this case, the cache line being filled is incorrectly marked
6026    invalid, thereby losing the data from any store to the line that
6027    occurs between the original miss and the completion of the five
6028    cycle sequence shown above.
6029
6030    The workarounds are:
6031
6032    * Run the data cache in write-through mode.
6033    * Insert a non-store instruction between
6034      Store A and Store B or Store B and Store C.  */
6035   
6036 static int
6037 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6038               const struct mips_cl_insn *insn)
6039 {
6040   struct fix_24k_store_info pos[3];
6041   int align, i, base_offset;
6042
6043   if (ignore >= 2)
6044     return 0;
6045
6046   /* If the previous instruction wasn't a store, there's nothing to
6047      worry about.  */
6048   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6049     return 0;
6050
6051   /* If the instructions after the previous one are unknown, we have
6052      to assume the worst.  */
6053   if (!insn)
6054     return 1;
6055
6056   /* Check whether we are dealing with three consecutive stores.  */
6057   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6058       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6059     return 0;
6060
6061   /* If we don't know the relationship between the store addresses,
6062      assume the worst.  */
6063   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6064       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6065     return 1;
6066
6067   if (!fix_24k_record_store_info (&pos[0], insn)
6068       || !fix_24k_record_store_info (&pos[1], &hist[0])
6069       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6070     return 1;
6071
6072   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6073
6074   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6075      X bytes and such that the base register + X is known to be aligned
6076      to align bytes.  */
6077
6078   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6079     align = 8;
6080   else
6081     {
6082       align = pos[0].align_to;
6083       base_offset = pos[0].off;
6084       for (i = 1; i < 3; i++)
6085         if (align < pos[i].align_to)
6086           {
6087             align = pos[i].align_to;
6088             base_offset = pos[i].off;
6089           }
6090       for (i = 0; i < 3; i++)
6091         pos[i].off -= base_offset;
6092     }
6093
6094   pos[0].off &= ~align + 1;
6095   pos[1].off &= ~align + 1;
6096   pos[2].off &= ~align + 1;
6097
6098   /* If any two stores write to the same chunk, they also write to the
6099      same doubleword.  The offsets are still sorted at this point.  */
6100   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6101     return 0;
6102
6103   /* A range of at least 9 bytes is needed for the stores to be in
6104      non-overlapping doublewords.  */
6105   if (pos[2].off - pos[0].off <= 8)
6106     return 0;
6107
6108   if (pos[2].off - pos[1].off >= 24
6109       || pos[1].off - pos[0].off >= 24
6110       || pos[2].off - pos[0].off >= 32)
6111     return 0;
6112
6113   return 1;
6114 }
6115
6116 /* Return the number of nops that would be needed if instruction INSN
6117    immediately followed the MAX_NOPS instructions given by HIST,
6118    where HIST[0] is the most recent instruction.  Ignore hazards
6119    between INSN and the first IGNORE instructions in HIST.
6120
6121    If INSN is null, return the worse-case number of nops for any
6122    instruction.  */
6123
6124 static int
6125 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6126                const struct mips_cl_insn *insn)
6127 {
6128   int i, nops, tmp_nops;
6129
6130   nops = 0;
6131   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6132     {
6133       tmp_nops = insns_between (hist + i, insn) - i;
6134       if (tmp_nops > nops)
6135         nops = tmp_nops;
6136     }
6137
6138   if (mips_fix_vr4130 && !mips_opts.micromips)
6139     {
6140       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6141       if (tmp_nops > nops)
6142         nops = tmp_nops;
6143     }
6144
6145   if (mips_fix_24k && !mips_opts.micromips)
6146     {
6147       tmp_nops = nops_for_24k (ignore, hist, insn);
6148       if (tmp_nops > nops)
6149         nops = tmp_nops;
6150     }
6151
6152   return nops;
6153 }
6154
6155 /* The variable arguments provide NUM_INSNS extra instructions that
6156    might be added to HIST.  Return the largest number of nops that
6157    would be needed after the extended sequence, ignoring hazards
6158    in the first IGNORE instructions.  */
6159
6160 static int
6161 nops_for_sequence (int num_insns, int ignore,
6162                    const struct mips_cl_insn *hist, ...)
6163 {
6164   va_list args;
6165   struct mips_cl_insn buffer[MAX_NOPS];
6166   struct mips_cl_insn *cursor;
6167   int nops;
6168
6169   va_start (args, hist);
6170   cursor = buffer + num_insns;
6171   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6172   while (cursor > buffer)
6173     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6174
6175   nops = nops_for_insn (ignore, buffer, NULL);
6176   va_end (args);
6177   return nops;
6178 }
6179
6180 /* Like nops_for_insn, but if INSN is a branch, take into account the
6181    worst-case delay for the branch target.  */
6182
6183 static int
6184 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6185                          const struct mips_cl_insn *insn)
6186 {
6187   int nops, tmp_nops;
6188
6189   nops = nops_for_insn (ignore, hist, insn);
6190   if (delayed_branch_p (insn))
6191     {
6192       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6193                                     hist, insn, get_delay_slot_nop (insn));
6194       if (tmp_nops > nops)
6195         nops = tmp_nops;
6196     }
6197   else if (compact_branch_p (insn))
6198     {
6199       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6200       if (tmp_nops > nops)
6201         nops = tmp_nops;
6202     }
6203   return nops;
6204 }
6205
6206 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6207
6208 static void
6209 fix_loongson2f_nop (struct mips_cl_insn * ip)
6210 {
6211   gas_assert (!HAVE_CODE_COMPRESSION);
6212   if (strcmp (ip->insn_mo->name, "nop") == 0)
6213     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6214 }
6215
6216 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6217                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6218
6219 static void
6220 fix_loongson2f_jump (struct mips_cl_insn * ip)
6221 {
6222   gas_assert (!HAVE_CODE_COMPRESSION);
6223   if (strcmp (ip->insn_mo->name, "j") == 0
6224       || strcmp (ip->insn_mo->name, "jr") == 0
6225       || strcmp (ip->insn_mo->name, "jalr") == 0)
6226     {
6227       int sreg;
6228       expressionS ep;
6229
6230       if (! mips_opts.at)
6231         return;
6232
6233       sreg = EXTRACT_OPERAND (0, RS, *ip);
6234       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6235         return;
6236
6237       ep.X_op = O_constant;
6238       ep.X_add_number = 0xcfff0000;
6239       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6240       ep.X_add_number = 0xffff;
6241       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6242       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6243     }
6244 }
6245
6246 static void
6247 fix_loongson2f (struct mips_cl_insn * ip)
6248 {
6249   if (mips_fix_loongson2f_nop)
6250     fix_loongson2f_nop (ip);
6251
6252   if (mips_fix_loongson2f_jump)
6253     fix_loongson2f_jump (ip);
6254 }
6255
6256 /* IP is a branch that has a delay slot, and we need to fill it
6257    automatically.   Return true if we can do that by swapping IP
6258    with the previous instruction.
6259    ADDRESS_EXPR is an operand of the instruction to be used with
6260    RELOC_TYPE.  */
6261
6262 static bfd_boolean
6263 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6264                    bfd_reloc_code_real_type *reloc_type)
6265 {
6266   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6267   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6268   unsigned int fpr_read, prev_fpr_write;
6269
6270   /* -O2 and above is required for this optimization.  */
6271   if (mips_optimize < 2)
6272     return FALSE;
6273
6274   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6275   if (mips_opts.nomove)
6276     return FALSE;
6277
6278   /* We can't swap if the previous instruction's position is fixed.  */
6279   if (history[0].fixed_p)
6280     return FALSE;
6281
6282   /* If the previous previous insn was in a .set noreorder, we can't
6283      swap.  Actually, the MIPS assembler will swap in this situation.
6284      However, gcc configured -with-gnu-as will generate code like
6285
6286         .set    noreorder
6287         lw      $4,XXX
6288         .set    reorder
6289         INSN
6290         bne     $4,$0,foo
6291
6292      in which we can not swap the bne and INSN.  If gcc is not configured
6293      -with-gnu-as, it does not output the .set pseudo-ops.  */
6294   if (history[1].noreorder_p)
6295     return FALSE;
6296
6297   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6298      This means that the previous instruction was a 4-byte one anyhow.  */
6299   if (mips_opts.mips16 && history[0].fixp[0])
6300     return FALSE;
6301
6302   /* If the branch is itself the target of a branch, we can not swap.
6303      We cheat on this; all we check for is whether there is a label on
6304      this instruction.  If there are any branches to anything other than
6305      a label, users must use .set noreorder.  */
6306   if (seg_info (now_seg)->label_list)
6307     return FALSE;
6308
6309   /* If the previous instruction is in a variant frag other than this
6310      branch's one, we cannot do the swap.  This does not apply to
6311      MIPS16 code, which uses variant frags for different purposes.  */
6312   if (!mips_opts.mips16
6313       && history[0].frag
6314       && history[0].frag->fr_type == rs_machine_dependent)
6315     return FALSE;
6316
6317   /* We do not swap with instructions that cannot architecturally
6318      be placed in a branch delay slot, such as SYNC or ERET.  We
6319      also refrain from swapping with a trap instruction, since it
6320      complicates trap handlers to have the trap instruction be in
6321      a delay slot.  */
6322   prev_pinfo = history[0].insn_mo->pinfo;
6323   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6324     return FALSE;
6325
6326   /* Check for conflicts between the branch and the instructions
6327      before the candidate delay slot.  */
6328   if (nops_for_insn (0, history + 1, ip) > 0)
6329     return FALSE;
6330
6331   /* Check for conflicts between the swapped sequence and the
6332      target of the branch.  */
6333   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6334     return FALSE;
6335
6336   /* If the branch reads a register that the previous
6337      instruction sets, we can not swap.  */
6338   gpr_read = gpr_read_mask (ip);
6339   prev_gpr_write = gpr_write_mask (&history[0]);
6340   if (gpr_read & prev_gpr_write)
6341     return FALSE;
6342
6343   fpr_read = fpr_read_mask (ip);
6344   prev_fpr_write = fpr_write_mask (&history[0]);
6345   if (fpr_read & prev_fpr_write)
6346     return FALSE;
6347
6348   /* If the branch writes a register that the previous
6349      instruction sets, we can not swap.  */
6350   gpr_write = gpr_write_mask (ip);
6351   if (gpr_write & prev_gpr_write)
6352     return FALSE;
6353
6354   /* If the branch writes a register that the previous
6355      instruction reads, we can not swap.  */
6356   prev_gpr_read = gpr_read_mask (&history[0]);
6357   if (gpr_write & prev_gpr_read)
6358     return FALSE;
6359
6360   /* If one instruction sets a condition code and the
6361      other one uses a condition code, we can not swap.  */
6362   pinfo = ip->insn_mo->pinfo;
6363   if ((pinfo & INSN_READ_COND_CODE)
6364       && (prev_pinfo & INSN_WRITE_COND_CODE))
6365     return FALSE;
6366   if ((pinfo & INSN_WRITE_COND_CODE)
6367       && (prev_pinfo & INSN_READ_COND_CODE))
6368     return FALSE;
6369
6370   /* If the previous instruction uses the PC, we can not swap.  */
6371   prev_pinfo2 = history[0].insn_mo->pinfo2;
6372   if (prev_pinfo2 & INSN2_READ_PC)
6373     return FALSE;
6374
6375   /* If the previous instruction has an incorrect size for a fixed
6376      branch delay slot in microMIPS mode, we cannot swap.  */
6377   pinfo2 = ip->insn_mo->pinfo2;
6378   if (mips_opts.micromips
6379       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6380       && insn_length (history) != 2)
6381     return FALSE;
6382   if (mips_opts.micromips
6383       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6384       && insn_length (history) != 4)
6385     return FALSE;
6386
6387   /* On R5900 short loops need to be fixed by inserting a nop in
6388      the branch delay slots.
6389      A short loop can be terminated too early.  */
6390   if (mips_opts.arch == CPU_R5900
6391       /* Check if instruction has a parameter, ignore "j $31". */
6392       && (address_expr != NULL)
6393       /* Parameter must be 16 bit. */
6394       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6395       /* Branch to same segment. */
6396       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6397       /* Branch to same code fragment. */
6398       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6399       /* Can only calculate branch offset if value is known. */
6400       && symbol_constant_p(address_expr->X_add_symbol)
6401       /* Check if branch is really conditional. */
6402       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6403         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6404         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6405     {
6406       int distance;
6407       /* Check if loop is shorter than 6 instructions including
6408          branch and delay slot.  */
6409       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6410       if (distance <= 20)
6411         {
6412           int i;
6413           int rv;
6414
6415           rv = FALSE;
6416           /* When the loop includes branches or jumps,
6417              it is not a short loop. */
6418           for (i = 0; i < (distance / 4); i++)
6419             {
6420               if ((history[i].cleared_p)
6421                   || delayed_branch_p(&history[i]))
6422                 {
6423                   rv = TRUE;
6424                   break;
6425                 }
6426             }
6427           if (rv == FALSE)
6428             {
6429               /* Insert nop after branch to fix short loop. */
6430               return FALSE;
6431             }
6432         }
6433     }
6434
6435   return TRUE;
6436 }
6437
6438 /* Decide how we should add IP to the instruction stream.
6439    ADDRESS_EXPR is an operand of the instruction to be used with
6440    RELOC_TYPE.  */
6441
6442 static enum append_method
6443 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6444                    bfd_reloc_code_real_type *reloc_type)
6445 {
6446   /* The relaxed version of a macro sequence must be inherently
6447      hazard-free.  */
6448   if (mips_relax.sequence == 2)
6449     return APPEND_ADD;
6450
6451   /* We must not dabble with instructions in a ".set norerorder" block.  */
6452   if (mips_opts.noreorder)
6453     return APPEND_ADD;
6454
6455   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6456   if (delayed_branch_p (ip))
6457     {
6458       if (!branch_likely_p (ip)
6459           && can_swap_branch_p (ip, address_expr, reloc_type))
6460         return APPEND_SWAP;
6461
6462       if (mips_opts.mips16
6463           && ISA_SUPPORTS_MIPS16E
6464           && gpr_read_mask (ip) != 0)
6465         return APPEND_ADD_COMPACT;
6466
6467       return APPEND_ADD_WITH_NOP;
6468     }
6469
6470   return APPEND_ADD;
6471 }
6472
6473 /* IP is a MIPS16 instruction whose opcode we have just changed.
6474    Point IP->insn_mo to the new opcode's definition.  */
6475
6476 static void
6477 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6478 {
6479   const struct mips_opcode *mo, *end;
6480
6481   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6482   for (mo = ip->insn_mo; mo < end; mo++)
6483     if ((ip->insn_opcode & mo->mask) == mo->match)
6484       {
6485         ip->insn_mo = mo;
6486         return;
6487       }
6488   abort ();
6489 }
6490
6491 /* For microMIPS macros, we need to generate a local number label
6492    as the target of branches.  */
6493 #define MICROMIPS_LABEL_CHAR            '\037'
6494 static unsigned long micromips_target_label;
6495 static char micromips_target_name[32];
6496
6497 static char *
6498 micromips_label_name (void)
6499 {
6500   char *p = micromips_target_name;
6501   char symbol_name_temporary[24];
6502   unsigned long l;
6503   int i;
6504
6505   if (*p)
6506     return p;
6507
6508   i = 0;
6509   l = micromips_target_label;
6510 #ifdef LOCAL_LABEL_PREFIX
6511   *p++ = LOCAL_LABEL_PREFIX;
6512 #endif
6513   *p++ = 'L';
6514   *p++ = MICROMIPS_LABEL_CHAR;
6515   do
6516     {
6517       symbol_name_temporary[i++] = l % 10 + '0';
6518       l /= 10;
6519     }
6520   while (l != 0);
6521   while (i > 0)
6522     *p++ = symbol_name_temporary[--i];
6523   *p = '\0';
6524
6525   return micromips_target_name;
6526 }
6527
6528 static void
6529 micromips_label_expr (expressionS *label_expr)
6530 {
6531   label_expr->X_op = O_symbol;
6532   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6533   label_expr->X_add_number = 0;
6534 }
6535
6536 static void
6537 micromips_label_inc (void)
6538 {
6539   micromips_target_label++;
6540   *micromips_target_name = '\0';
6541 }
6542
6543 static void
6544 micromips_add_label (void)
6545 {
6546   symbolS *s;
6547
6548   s = colon (micromips_label_name ());
6549   micromips_label_inc ();
6550   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6551 }
6552
6553 /* If assembling microMIPS code, then return the microMIPS reloc
6554    corresponding to the requested one if any.  Otherwise return
6555    the reloc unchanged.  */
6556
6557 static bfd_reloc_code_real_type
6558 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6559 {
6560   static const bfd_reloc_code_real_type relocs[][2] =
6561     {
6562       /* Keep sorted incrementally by the left-hand key.  */
6563       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6564       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6565       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6566       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6567       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6568       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6569       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6570       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6571       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6572       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6573       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6574       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6575       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6576       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6577       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6578       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6579       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6580       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6581       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6582       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6583       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6584       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6585       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6586       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6587       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6588       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6589       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6590     };
6591   bfd_reloc_code_real_type r;
6592   size_t i;
6593
6594   if (!mips_opts.micromips)
6595     return reloc;
6596   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6597     {
6598       r = relocs[i][0];
6599       if (r > reloc)
6600         return reloc;
6601       if (r == reloc)
6602         return relocs[i][1];
6603     }
6604   return reloc;
6605 }
6606
6607 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6608    Return true on success, storing the resolved value in RESULT.  */
6609
6610 static bfd_boolean
6611 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6612                  offsetT *result)
6613 {
6614   switch (reloc)
6615     {
6616     case BFD_RELOC_MIPS_HIGHEST:
6617     case BFD_RELOC_MICROMIPS_HIGHEST:
6618       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6619       return TRUE;
6620
6621     case BFD_RELOC_MIPS_HIGHER:
6622     case BFD_RELOC_MICROMIPS_HIGHER:
6623       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6624       return TRUE;
6625
6626     case BFD_RELOC_HI16_S:
6627     case BFD_RELOC_MICROMIPS_HI16_S:
6628     case BFD_RELOC_MIPS16_HI16_S:
6629       *result = ((operand + 0x8000) >> 16) & 0xffff;
6630       return TRUE;
6631
6632     case BFD_RELOC_HI16:
6633     case BFD_RELOC_MICROMIPS_HI16:
6634     case BFD_RELOC_MIPS16_HI16:
6635       *result = (operand >> 16) & 0xffff;
6636       return TRUE;
6637
6638     case BFD_RELOC_LO16:
6639     case BFD_RELOC_MICROMIPS_LO16:
6640     case BFD_RELOC_MIPS16_LO16:
6641       *result = operand & 0xffff;
6642       return TRUE;
6643
6644     case BFD_RELOC_UNUSED:
6645       *result = operand;
6646       return TRUE;
6647
6648     default:
6649       return FALSE;
6650     }
6651 }
6652
6653 /* Output an instruction.  IP is the instruction information.
6654    ADDRESS_EXPR is an operand of the instruction to be used with
6655    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6656    a macro expansion.  */
6657
6658 static void
6659 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6660              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6661 {
6662   unsigned long prev_pinfo2, pinfo;
6663   bfd_boolean relaxed_branch = FALSE;
6664   enum append_method method;
6665   bfd_boolean relax32;
6666   int branch_disp;
6667
6668   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6669     fix_loongson2f (ip);
6670
6671   file_ase_mips16 |= mips_opts.mips16;
6672   file_ase_micromips |= mips_opts.micromips;
6673
6674   prev_pinfo2 = history[0].insn_mo->pinfo2;
6675   pinfo = ip->insn_mo->pinfo;
6676
6677   if (mips_opts.micromips
6678       && !expansionp
6679       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6680            && micromips_insn_length (ip->insn_mo) != 2)
6681           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6682               && micromips_insn_length (ip->insn_mo) != 4)))
6683     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6684              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6685
6686   if (address_expr == NULL)
6687     ip->complete_p = 1;
6688   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6689            && reloc_type[1] == BFD_RELOC_UNUSED
6690            && reloc_type[2] == BFD_RELOC_UNUSED
6691            && address_expr->X_op == O_constant)
6692     {
6693       switch (*reloc_type)
6694         {
6695         case BFD_RELOC_MIPS_JMP:
6696           {
6697             int shift;
6698
6699             shift = mips_opts.micromips ? 1 : 2;
6700             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6701               as_bad (_("jump to misaligned address (0x%lx)"),
6702                       (unsigned long) address_expr->X_add_number);
6703             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6704                                 & 0x3ffffff);
6705             ip->complete_p = 1;
6706           }
6707           break;
6708
6709         case BFD_RELOC_MIPS16_JMP:
6710           if ((address_expr->X_add_number & 3) != 0)
6711             as_bad (_("jump to misaligned address (0x%lx)"),
6712                     (unsigned long) address_expr->X_add_number);
6713           ip->insn_opcode |=
6714             (((address_expr->X_add_number & 0x7c0000) << 3)
6715                | ((address_expr->X_add_number & 0xf800000) >> 7)
6716                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6717           ip->complete_p = 1;
6718           break;
6719
6720         case BFD_RELOC_16_PCREL_S2:
6721           {
6722             int shift;
6723
6724             shift = mips_opts.micromips ? 1 : 2;
6725             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6726               as_bad (_("branch to misaligned address (0x%lx)"),
6727                       (unsigned long) address_expr->X_add_number);
6728             if (!mips_relax_branch)
6729               {
6730                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6731                     & ~((1 << (shift + 16)) - 1))
6732                   as_bad (_("branch address range overflow (0x%lx)"),
6733                           (unsigned long) address_expr->X_add_number);
6734                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6735                                     & 0xffff);
6736               }
6737           }
6738           break;
6739
6740         default:
6741           {
6742             offsetT value;
6743
6744             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6745                                  &value))
6746               {
6747                 ip->insn_opcode |= value & 0xffff;
6748                 ip->complete_p = 1;
6749               }
6750           }
6751           break;
6752         }
6753     }
6754
6755   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6756     {
6757       /* There are a lot of optimizations we could do that we don't.
6758          In particular, we do not, in general, reorder instructions.
6759          If you use gcc with optimization, it will reorder
6760          instructions and generally do much more optimization then we
6761          do here; repeating all that work in the assembler would only
6762          benefit hand written assembly code, and does not seem worth
6763          it.  */
6764       int nops = (mips_optimize == 0
6765                   ? nops_for_insn (0, history, NULL)
6766                   : nops_for_insn_or_target (0, history, ip));
6767       if (nops > 0)
6768         {
6769           fragS *old_frag;
6770           unsigned long old_frag_offset;
6771           int i;
6772
6773           old_frag = frag_now;
6774           old_frag_offset = frag_now_fix ();
6775
6776           for (i = 0; i < nops; i++)
6777             add_fixed_insn (NOP_INSN);
6778           insert_into_history (0, nops, NOP_INSN);
6779
6780           if (listing)
6781             {
6782               listing_prev_line ();
6783               /* We may be at the start of a variant frag.  In case we
6784                  are, make sure there is enough space for the frag
6785                  after the frags created by listing_prev_line.  The
6786                  argument to frag_grow here must be at least as large
6787                  as the argument to all other calls to frag_grow in
6788                  this file.  We don't have to worry about being in the
6789                  middle of a variant frag, because the variants insert
6790                  all needed nop instructions themselves.  */
6791               frag_grow (40);
6792             }
6793
6794           mips_move_text_labels ();
6795
6796 #ifndef NO_ECOFF_DEBUGGING
6797           if (ECOFF_DEBUGGING)
6798             ecoff_fix_loc (old_frag, old_frag_offset);
6799 #endif
6800         }
6801     }
6802   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6803     {
6804       int nops;
6805
6806       /* Work out how many nops in prev_nop_frag are needed by IP,
6807          ignoring hazards generated by the first prev_nop_frag_since
6808          instructions.  */
6809       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6810       gas_assert (nops <= prev_nop_frag_holds);
6811
6812       /* Enforce NOPS as a minimum.  */
6813       if (nops > prev_nop_frag_required)
6814         prev_nop_frag_required = nops;
6815
6816       if (prev_nop_frag_holds == prev_nop_frag_required)
6817         {
6818           /* Settle for the current number of nops.  Update the history
6819              accordingly (for the benefit of any future .set reorder code).  */
6820           prev_nop_frag = NULL;
6821           insert_into_history (prev_nop_frag_since,
6822                                prev_nop_frag_holds, NOP_INSN);
6823         }
6824       else
6825         {
6826           /* Allow this instruction to replace one of the nops that was
6827              tentatively added to prev_nop_frag.  */
6828           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6829           prev_nop_frag_holds--;
6830           prev_nop_frag_since++;
6831         }
6832     }
6833
6834   method = get_append_method (ip, address_expr, reloc_type);
6835   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6836
6837   dwarf2_emit_insn (0);
6838   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6839      so "move" the instruction address accordingly.
6840
6841      Also, it doesn't seem appropriate for the assembler to reorder .loc
6842      entries.  If this instruction is a branch that we are going to swap
6843      with the previous instruction, the two instructions should be
6844      treated as a unit, and the debug information for both instructions
6845      should refer to the start of the branch sequence.  Using the
6846      current position is certainly wrong when swapping a 32-bit branch
6847      and a 16-bit delay slot, since the current position would then be
6848      in the middle of a branch.  */
6849   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6850
6851   relax32 = (mips_relax_branch
6852              /* Don't try branch relaxation within .set nomacro, or within
6853                 .set noat if we use $at for PIC computations.  If it turns
6854                 out that the branch was out-of-range, we'll get an error.  */
6855              && !mips_opts.warn_about_macros
6856              && (mips_opts.at || mips_pic == NO_PIC)
6857              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6858                 as they have no complementing branches.  */
6859              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6860
6861   if (!HAVE_CODE_COMPRESSION
6862       && address_expr
6863       && relax32
6864       && *reloc_type == BFD_RELOC_16_PCREL_S2
6865       && delayed_branch_p (ip))
6866     {
6867       relaxed_branch = TRUE;
6868       add_relaxed_insn (ip, (relaxed_branch_length
6869                              (NULL, NULL,
6870                               uncond_branch_p (ip) ? -1
6871                               : branch_likely_p (ip) ? 1
6872                               : 0)), 4,
6873                         RELAX_BRANCH_ENCODE
6874                         (AT,
6875                          uncond_branch_p (ip),
6876                          branch_likely_p (ip),
6877                          pinfo & INSN_WRITE_GPR_31,
6878                          0),
6879                         address_expr->X_add_symbol,
6880                         address_expr->X_add_number);
6881       *reloc_type = BFD_RELOC_UNUSED;
6882     }
6883   else if (mips_opts.micromips
6884            && address_expr
6885            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6886                || *reloc_type > BFD_RELOC_UNUSED)
6887            && (delayed_branch_p (ip) || compact_branch_p (ip))
6888            /* Don't try branch relaxation when users specify
6889               16-bit/32-bit instructions.  */
6890            && !forced_insn_length)
6891     {
6892       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6893       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6894       int uncond = uncond_branch_p (ip) ? -1 : 0;
6895       int compact = compact_branch_p (ip);
6896       int al = pinfo & INSN_WRITE_GPR_31;
6897       int length32;
6898
6899       gas_assert (address_expr != NULL);
6900       gas_assert (!mips_relax.sequence);
6901
6902       relaxed_branch = TRUE;
6903       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6904       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6905                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6906                                                 relax32, 0, 0),
6907                         address_expr->X_add_symbol,
6908                         address_expr->X_add_number);
6909       *reloc_type = BFD_RELOC_UNUSED;
6910     }
6911   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6912     {
6913       /* We need to set up a variant frag.  */
6914       gas_assert (address_expr != NULL);
6915       add_relaxed_insn (ip, 4, 0,
6916                         RELAX_MIPS16_ENCODE
6917                         (*reloc_type - BFD_RELOC_UNUSED,
6918                          forced_insn_length == 2, forced_insn_length == 4,
6919                          delayed_branch_p (&history[0]),
6920                          history[0].mips16_absolute_jump_p),
6921                         make_expr_symbol (address_expr), 0);
6922     }
6923   else if (mips_opts.mips16 && insn_length (ip) == 2)
6924     {
6925       if (!delayed_branch_p (ip))
6926         /* Make sure there is enough room to swap this instruction with
6927            a following jump instruction.  */
6928         frag_grow (6);
6929       add_fixed_insn (ip);
6930     }
6931   else
6932     {
6933       if (mips_opts.mips16
6934           && mips_opts.noreorder
6935           && delayed_branch_p (&history[0]))
6936         as_warn (_("extended instruction in delay slot"));
6937
6938       if (mips_relax.sequence)
6939         {
6940           /* If we've reached the end of this frag, turn it into a variant
6941              frag and record the information for the instructions we've
6942              written so far.  */
6943           if (frag_room () < 4)
6944             relax_close_frag ();
6945           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6946         }
6947
6948       if (mips_relax.sequence != 2)
6949         {
6950           if (mips_macro_warning.first_insn_sizes[0] == 0)
6951             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6952           mips_macro_warning.sizes[0] += insn_length (ip);
6953           mips_macro_warning.insns[0]++;
6954         }
6955       if (mips_relax.sequence != 1)
6956         {
6957           if (mips_macro_warning.first_insn_sizes[1] == 0)
6958             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6959           mips_macro_warning.sizes[1] += insn_length (ip);
6960           mips_macro_warning.insns[1]++;
6961         }
6962
6963       if (mips_opts.mips16)
6964         {
6965           ip->fixed_p = 1;
6966           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6967         }
6968       add_fixed_insn (ip);
6969     }
6970
6971   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6972     {
6973       bfd_reloc_code_real_type final_type[3];
6974       reloc_howto_type *howto0;
6975       reloc_howto_type *howto;
6976       int i;
6977
6978       /* Perform any necessary conversion to microMIPS relocations
6979          and find out how many relocations there actually are.  */
6980       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6981         final_type[i] = micromips_map_reloc (reloc_type[i]);
6982
6983       /* In a compound relocation, it is the final (outermost)
6984          operator that determines the relocated field.  */
6985       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6986       if (!howto)
6987         abort ();
6988
6989       if (i > 1)
6990         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6991       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6992                                  bfd_get_reloc_size (howto),
6993                                  address_expr,
6994                                  howto0 && howto0->pc_relative,
6995                                  final_type[0]);
6996
6997       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6998       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6999         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7000
7001       /* These relocations can have an addend that won't fit in
7002          4 octets for 64bit assembly.  */
7003       if (GPR_SIZE == 64
7004           && ! howto->partial_inplace
7005           && (reloc_type[0] == BFD_RELOC_16
7006               || reloc_type[0] == BFD_RELOC_32
7007               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7008               || reloc_type[0] == BFD_RELOC_GPREL16
7009               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7010               || reloc_type[0] == BFD_RELOC_GPREL32
7011               || reloc_type[0] == BFD_RELOC_64
7012               || reloc_type[0] == BFD_RELOC_CTOR
7013               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7014               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7015               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7016               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7017               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7018               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7019               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7020               || hi16_reloc_p (reloc_type[0])
7021               || lo16_reloc_p (reloc_type[0])))
7022         ip->fixp[0]->fx_no_overflow = 1;
7023
7024       /* These relocations can have an addend that won't fit in 2 octets.  */
7025       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7026           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7027         ip->fixp[0]->fx_no_overflow = 1;
7028
7029       if (mips_relax.sequence)
7030         {
7031           if (mips_relax.first_fixup == 0)
7032             mips_relax.first_fixup = ip->fixp[0];
7033         }
7034       else if (reloc_needs_lo_p (*reloc_type))
7035         {
7036           struct mips_hi_fixup *hi_fixup;
7037
7038           /* Reuse the last entry if it already has a matching %lo.  */
7039           hi_fixup = mips_hi_fixup_list;
7040           if (hi_fixup == 0
7041               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7042             {
7043               hi_fixup = ((struct mips_hi_fixup *)
7044                           xmalloc (sizeof (struct mips_hi_fixup)));
7045               hi_fixup->next = mips_hi_fixup_list;
7046               mips_hi_fixup_list = hi_fixup;
7047             }
7048           hi_fixup->fixp = ip->fixp[0];
7049           hi_fixup->seg = now_seg;
7050         }
7051
7052       /* Add fixups for the second and third relocations, if given.
7053          Note that the ABI allows the second relocation to be
7054          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7055          moment we only use RSS_UNDEF, but we could add support
7056          for the others if it ever becomes necessary.  */
7057       for (i = 1; i < 3; i++)
7058         if (reloc_type[i] != BFD_RELOC_UNUSED)
7059           {
7060             ip->fixp[i] = fix_new (ip->frag, ip->where,
7061                                    ip->fixp[0]->fx_size, NULL, 0,
7062                                    FALSE, final_type[i]);
7063
7064             /* Use fx_tcbit to mark compound relocs.  */
7065             ip->fixp[0]->fx_tcbit = 1;
7066             ip->fixp[i]->fx_tcbit = 1;
7067           }
7068     }
7069   install_insn (ip);
7070
7071   /* Update the register mask information.  */
7072   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7073   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7074
7075   switch (method)
7076     {
7077     case APPEND_ADD:
7078       insert_into_history (0, 1, ip);
7079       break;
7080
7081     case APPEND_ADD_WITH_NOP:
7082       {
7083         struct mips_cl_insn *nop;
7084
7085         insert_into_history (0, 1, ip);
7086         nop = get_delay_slot_nop (ip);
7087         add_fixed_insn (nop);
7088         insert_into_history (0, 1, nop);
7089         if (mips_relax.sequence)
7090           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7091       }
7092       break;
7093
7094     case APPEND_ADD_COMPACT:
7095       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7096       gas_assert (mips_opts.mips16);
7097       ip->insn_opcode |= 0x0080;
7098       find_altered_mips16_opcode (ip);
7099       install_insn (ip);
7100       insert_into_history (0, 1, ip);
7101       break;
7102
7103     case APPEND_SWAP:
7104       {
7105         struct mips_cl_insn delay = history[0];
7106         if (mips_opts.mips16)
7107           {
7108             know (delay.frag == ip->frag);
7109             move_insn (ip, delay.frag, delay.where);
7110             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7111           }
7112         else if (relaxed_branch || delay.frag != ip->frag)
7113           {
7114             /* Add the delay slot instruction to the end of the
7115                current frag and shrink the fixed part of the
7116                original frag.  If the branch occupies the tail of
7117                the latter, move it backwards to cover the gap.  */
7118             delay.frag->fr_fix -= branch_disp;
7119             if (delay.frag == ip->frag)
7120               move_insn (ip, ip->frag, ip->where - branch_disp);
7121             add_fixed_insn (&delay);
7122           }
7123         else
7124           {
7125             move_insn (&delay, ip->frag,
7126                        ip->where - branch_disp + insn_length (ip));
7127             move_insn (ip, history[0].frag, history[0].where);
7128           }
7129         history[0] = *ip;
7130         delay.fixed_p = 1;
7131         insert_into_history (0, 1, &delay);
7132       }
7133       break;
7134     }
7135
7136   /* If we have just completed an unconditional branch, clear the history.  */
7137   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7138       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7139     {
7140       unsigned int i;
7141
7142       mips_no_prev_insn ();
7143
7144       for (i = 0; i < ARRAY_SIZE (history); i++)
7145         history[i].cleared_p = 1;
7146     }
7147
7148   /* We need to emit a label at the end of branch-likely macros.  */
7149   if (emit_branch_likely_macro)
7150     {
7151       emit_branch_likely_macro = FALSE;
7152       micromips_add_label ();
7153     }
7154
7155   /* We just output an insn, so the next one doesn't have a label.  */
7156   mips_clear_insn_labels ();
7157 }
7158
7159 /* Forget that there was any previous instruction or label.
7160    When BRANCH is true, the branch history is also flushed.  */
7161
7162 static void
7163 mips_no_prev_insn (void)
7164 {
7165   prev_nop_frag = NULL;
7166   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7167   mips_clear_insn_labels ();
7168 }
7169
7170 /* This function must be called before we emit something other than
7171    instructions.  It is like mips_no_prev_insn except that it inserts
7172    any NOPS that might be needed by previous instructions.  */
7173
7174 void
7175 mips_emit_delays (void)
7176 {
7177   if (! mips_opts.noreorder)
7178     {
7179       int nops = nops_for_insn (0, history, NULL);
7180       if (nops > 0)
7181         {
7182           while (nops-- > 0)
7183             add_fixed_insn (NOP_INSN);
7184           mips_move_text_labels ();
7185         }
7186     }
7187   mips_no_prev_insn ();
7188 }
7189
7190 /* Start a (possibly nested) noreorder block.  */
7191
7192 static void
7193 start_noreorder (void)
7194 {
7195   if (mips_opts.noreorder == 0)
7196     {
7197       unsigned int i;
7198       int nops;
7199
7200       /* None of the instructions before the .set noreorder can be moved.  */
7201       for (i = 0; i < ARRAY_SIZE (history); i++)
7202         history[i].fixed_p = 1;
7203
7204       /* Insert any nops that might be needed between the .set noreorder
7205          block and the previous instructions.  We will later remove any
7206          nops that turn out not to be needed.  */
7207       nops = nops_for_insn (0, history, NULL);
7208       if (nops > 0)
7209         {
7210           if (mips_optimize != 0)
7211             {
7212               /* Record the frag which holds the nop instructions, so
7213                  that we can remove them if we don't need them.  */
7214               frag_grow (nops * NOP_INSN_SIZE);
7215               prev_nop_frag = frag_now;
7216               prev_nop_frag_holds = nops;
7217               prev_nop_frag_required = 0;
7218               prev_nop_frag_since = 0;
7219             }
7220
7221           for (; nops > 0; --nops)
7222             add_fixed_insn (NOP_INSN);
7223
7224           /* Move on to a new frag, so that it is safe to simply
7225              decrease the size of prev_nop_frag.  */
7226           frag_wane (frag_now);
7227           frag_new (0);
7228           mips_move_text_labels ();
7229         }
7230       mips_mark_labels ();
7231       mips_clear_insn_labels ();
7232     }
7233   mips_opts.noreorder++;
7234   mips_any_noreorder = 1;
7235 }
7236
7237 /* End a nested noreorder block.  */
7238
7239 static void
7240 end_noreorder (void)
7241 {
7242   mips_opts.noreorder--;
7243   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7244     {
7245       /* Commit to inserting prev_nop_frag_required nops and go back to
7246          handling nop insertion the .set reorder way.  */
7247       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7248                                 * NOP_INSN_SIZE);
7249       insert_into_history (prev_nop_frag_since,
7250                            prev_nop_frag_required, NOP_INSN);
7251       prev_nop_frag = NULL;
7252     }
7253 }
7254
7255 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7256    higher bits unset.  */
7257
7258 static void
7259 normalize_constant_expr (expressionS *ex)
7260 {
7261   if (ex->X_op == O_constant
7262       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7263     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7264                         - 0x80000000);
7265 }
7266
7267 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7268    all higher bits unset.  */
7269
7270 static void
7271 normalize_address_expr (expressionS *ex)
7272 {
7273   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7274         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7275       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7276     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7277                         - 0x80000000);
7278 }
7279
7280 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7281    Return true if the match was successful.
7282
7283    OPCODE_EXTRA is a value that should be ORed into the opcode
7284    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7285    there are more alternatives after OPCODE and SOFT_MATCH is
7286    as for mips_arg_info.  */
7287
7288 static bfd_boolean
7289 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7290             struct mips_operand_token *tokens, unsigned int opcode_extra,
7291             bfd_boolean lax_match, bfd_boolean complete_p)
7292 {
7293   const char *args;
7294   struct mips_arg_info arg;
7295   const struct mips_operand *operand;
7296   char c;
7297
7298   imm_expr.X_op = O_absent;
7299   offset_expr.X_op = O_absent;
7300   offset_reloc[0] = BFD_RELOC_UNUSED;
7301   offset_reloc[1] = BFD_RELOC_UNUSED;
7302   offset_reloc[2] = BFD_RELOC_UNUSED;
7303
7304   create_insn (insn, opcode);
7305   /* When no opcode suffix is specified, assume ".xyzw". */
7306   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7307     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7308   else
7309     insn->insn_opcode |= opcode_extra;
7310   memset (&arg, 0, sizeof (arg));
7311   arg.insn = insn;
7312   arg.token = tokens;
7313   arg.argnum = 1;
7314   arg.last_regno = ILLEGAL_REG;
7315   arg.dest_regno = ILLEGAL_REG;
7316   arg.lax_match = lax_match;
7317   for (args = opcode->args;; ++args)
7318     {
7319       if (arg.token->type == OT_END)
7320         {
7321           /* Handle unary instructions in which only one operand is given.
7322              The source is then the same as the destination.  */
7323           if (arg.opnum == 1 && *args == ',')
7324             {
7325               operand = (mips_opts.micromips
7326                          ? decode_micromips_operand (args + 1)
7327                          : decode_mips_operand (args + 1));
7328               if (operand && mips_optional_operand_p (operand))
7329                 {
7330                   arg.token = tokens;
7331                   arg.argnum = 1;
7332                   continue;
7333                 }
7334             }
7335
7336           /* Treat elided base registers as $0.  */
7337           if (strcmp (args, "(b)") == 0)
7338             args += 3;
7339
7340           if (args[0] == '+')
7341             switch (args[1])
7342               {
7343               case 'K':
7344               case 'N':
7345                 /* The register suffix is optional. */
7346                 args += 2;
7347                 break;
7348               }
7349
7350           /* Fail the match if there were too few operands.  */
7351           if (*args)
7352             return FALSE;
7353
7354           /* Successful match.  */
7355           if (!complete_p)
7356             return TRUE;
7357           clear_insn_error ();
7358           if (arg.dest_regno == arg.last_regno
7359               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7360             {
7361               if (arg.opnum == 2)
7362                 set_insn_error
7363                   (0, _("source and destination must be different"));
7364               else if (arg.last_regno == 31)
7365                 set_insn_error
7366                   (0, _("a destination register must be supplied"));
7367             }
7368           else if (arg.last_regno == 31
7369                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7370                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7371             set_insn_error (0, _("the source register must not be $31"));
7372           check_completed_insn (&arg);
7373           return TRUE;
7374         }
7375
7376       /* Fail the match if the line has too many operands.   */
7377       if (*args == 0)
7378         return FALSE;
7379
7380       /* Handle characters that need to match exactly.  */
7381       if (*args == '(' || *args == ')' || *args == ',')
7382         {
7383           if (match_char (&arg, *args))
7384             continue;
7385           return FALSE;
7386         }
7387       if (*args == '#')
7388         {
7389           ++args;
7390           if (arg.token->type == OT_DOUBLE_CHAR
7391               && arg.token->u.ch == *args)
7392             {
7393               ++arg.token;
7394               continue;
7395             }
7396           return FALSE;
7397         }
7398
7399       /* Handle special macro operands.  Work out the properties of
7400          other operands.  */
7401       arg.opnum += 1;
7402       switch (*args)
7403         {
7404         case '+':
7405           switch (args[1])
7406             {
7407             case 'i':
7408               *offset_reloc = BFD_RELOC_MIPS_JMP;
7409               break;
7410             }
7411           break;
7412
7413         case 'I':
7414           if (!match_const_int (&arg, &imm_expr.X_add_number))
7415             return FALSE;
7416           imm_expr.X_op = O_constant;
7417           if (GPR_SIZE == 32)
7418             normalize_constant_expr (&imm_expr);
7419           continue;
7420
7421         case 'A':
7422           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7423             {
7424               /* Assume that the offset has been elided and that what
7425                  we saw was a base register.  The match will fail later
7426                  if that assumption turns out to be wrong.  */
7427               offset_expr.X_op = O_constant;
7428               offset_expr.X_add_number = 0;
7429             }
7430           else
7431             {
7432               if (!match_expression (&arg, &offset_expr, offset_reloc))
7433                 return FALSE;
7434               normalize_address_expr (&offset_expr);
7435             }
7436           continue;
7437
7438         case 'F':
7439           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7440                                      8, TRUE))
7441             return FALSE;
7442           continue;
7443
7444         case 'L':
7445           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7446                                      8, FALSE))
7447             return FALSE;
7448           continue;
7449
7450         case 'f':
7451           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7452                                      4, TRUE))
7453             return FALSE;
7454           continue;
7455
7456         case 'l':
7457           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7458                                      4, FALSE))
7459             return FALSE;
7460           continue;
7461
7462         case 'p':
7463           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7464           break;
7465
7466         case 'a':
7467           *offset_reloc = BFD_RELOC_MIPS_JMP;
7468           break;
7469
7470         case 'm':
7471           gas_assert (mips_opts.micromips);
7472           c = args[1];
7473           switch (c)
7474             {
7475             case 'D':
7476             case 'E':
7477               if (!forced_insn_length)
7478                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7479               else if (c == 'D')
7480                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7481               else
7482                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7483               break;
7484             }
7485           break;
7486         }
7487
7488       operand = (mips_opts.micromips
7489                  ? decode_micromips_operand (args)
7490                  : decode_mips_operand (args));
7491       if (!operand)
7492         abort ();
7493
7494       /* Skip prefixes.  */
7495       if (*args == '+' || *args == 'm')
7496         args++;
7497
7498       if (mips_optional_operand_p (operand)
7499           && args[1] == ','
7500           && (arg.token[0].type != OT_REG
7501               || arg.token[1].type == OT_END))
7502         {
7503           /* Assume that the register has been elided and is the
7504              same as the first operand.  */
7505           arg.token = tokens;
7506           arg.argnum = 1;
7507         }
7508
7509       if (!match_operand (&arg, operand))
7510         return FALSE;
7511     }
7512 }
7513
7514 /* Like match_insn, but for MIPS16.  */
7515
7516 static bfd_boolean
7517 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7518                    struct mips_operand_token *tokens)
7519 {
7520   const char *args;
7521   const struct mips_operand *operand;
7522   const struct mips_operand *ext_operand;
7523   struct mips_arg_info arg;
7524   int relax_char;
7525
7526   create_insn (insn, opcode);
7527   imm_expr.X_op = O_absent;
7528   offset_expr.X_op = O_absent;
7529   offset_reloc[0] = BFD_RELOC_UNUSED;
7530   offset_reloc[1] = BFD_RELOC_UNUSED;
7531   offset_reloc[2] = BFD_RELOC_UNUSED;
7532   relax_char = 0;
7533
7534   memset (&arg, 0, sizeof (arg));
7535   arg.insn = insn;
7536   arg.token = tokens;
7537   arg.argnum = 1;
7538   arg.last_regno = ILLEGAL_REG;
7539   arg.dest_regno = ILLEGAL_REG;
7540   relax_char = 0;
7541   for (args = opcode->args;; ++args)
7542     {
7543       int c;
7544
7545       if (arg.token->type == OT_END)
7546         {
7547           offsetT value;
7548
7549           /* Handle unary instructions in which only one operand is given.
7550              The source is then the same as the destination.  */
7551           if (arg.opnum == 1 && *args == ',')
7552             {
7553               operand = decode_mips16_operand (args[1], FALSE);
7554               if (operand && mips_optional_operand_p (operand))
7555                 {
7556                   arg.token = tokens;
7557                   arg.argnum = 1;
7558                   continue;
7559                 }
7560             }
7561
7562           /* Fail the match if there were too few operands.  */
7563           if (*args)
7564             return FALSE;
7565
7566           /* Successful match.  Stuff the immediate value in now, if
7567              we can.  */
7568           clear_insn_error ();
7569           if (opcode->pinfo == INSN_MACRO)
7570             {
7571               gas_assert (relax_char == 0 || relax_char == 'p');
7572               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7573             }
7574           else if (relax_char
7575                    && offset_expr.X_op == O_constant
7576                    && calculate_reloc (*offset_reloc,
7577                                        offset_expr.X_add_number,
7578                                        &value))
7579             {
7580               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7581                             forced_insn_length, &insn->insn_opcode);
7582               offset_expr.X_op = O_absent;
7583               *offset_reloc = BFD_RELOC_UNUSED;
7584             }
7585           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7586             {
7587               if (forced_insn_length == 2)
7588                 set_insn_error (0, _("invalid unextended operand value"));
7589               forced_insn_length = 4;
7590               insn->insn_opcode |= MIPS16_EXTEND;
7591             }
7592           else if (relax_char)
7593             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7594
7595           check_completed_insn (&arg);
7596           return TRUE;
7597         }
7598
7599       /* Fail the match if the line has too many operands.   */
7600       if (*args == 0)
7601         return FALSE;
7602
7603       /* Handle characters that need to match exactly.  */
7604       if (*args == '(' || *args == ')' || *args == ',')
7605         {
7606           if (match_char (&arg, *args))
7607             continue;
7608           return FALSE;
7609         }
7610
7611       arg.opnum += 1;
7612       c = *args;
7613       switch (c)
7614         {
7615         case 'p':
7616         case 'q':
7617         case 'A':
7618         case 'B':
7619         case 'E':
7620           relax_char = c;
7621           break;
7622
7623         case 'I':
7624           if (!match_const_int (&arg, &imm_expr.X_add_number))
7625             return FALSE;
7626           imm_expr.X_op = O_constant;
7627           if (GPR_SIZE == 32)
7628             normalize_constant_expr (&imm_expr);
7629           continue;
7630
7631         case 'a':
7632         case 'i':
7633           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7634           insn->insn_opcode <<= 16;
7635           break;
7636         }
7637
7638       operand = decode_mips16_operand (c, FALSE);
7639       if (!operand)
7640         abort ();
7641
7642       /* '6' is a special case.  It is used for BREAK and SDBBP,
7643          whose operands are only meaningful to the software that decodes
7644          them.  This means that there is no architectural reason why
7645          they cannot be prefixed by EXTEND, but in practice,
7646          exception handlers will only look at the instruction
7647          itself.  We therefore allow '6' to be extended when
7648          disassembling but not when assembling.  */
7649       if (operand->type != OP_PCREL && c != '6')
7650         {
7651           ext_operand = decode_mips16_operand (c, TRUE);
7652           if (operand != ext_operand)
7653             {
7654               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7655                 {
7656                   offset_expr.X_op = O_constant;
7657                   offset_expr.X_add_number = 0;
7658                   relax_char = c;
7659                   continue;
7660                 }
7661
7662               /* We need the OT_INTEGER check because some MIPS16
7663                  immediate variants are listed before the register ones.  */
7664               if (arg.token->type != OT_INTEGER
7665                   || !match_expression (&arg, &offset_expr, offset_reloc))
7666                 return FALSE;
7667
7668               /* '8' is used for SLTI(U) and has traditionally not
7669                  been allowed to take relocation operators.  */
7670               if (offset_reloc[0] != BFD_RELOC_UNUSED
7671                   && (ext_operand->size != 16 || c == '8'))
7672                 return FALSE;
7673
7674               relax_char = c;
7675               continue;
7676             }
7677         }
7678
7679       if (mips_optional_operand_p (operand)
7680           && args[1] == ','
7681           && (arg.token[0].type != OT_REG
7682               || arg.token[1].type == OT_END))
7683         {
7684           /* Assume that the register has been elided and is the
7685              same as the first operand.  */
7686           arg.token = tokens;
7687           arg.argnum = 1;
7688         }
7689
7690       if (!match_operand (&arg, operand))
7691         return FALSE;
7692     }
7693 }
7694
7695 /* Record that the current instruction is invalid for the current ISA.  */
7696
7697 static void
7698 match_invalid_for_isa (void)
7699 {
7700   set_insn_error_ss
7701     (0, _("opcode not supported on this processor: %s (%s)"),
7702      mips_cpu_info_from_arch (mips_opts.arch)->name,
7703      mips_cpu_info_from_isa (mips_opts.isa)->name);
7704 }
7705
7706 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7707    Return true if a definite match or failure was found, storing any match
7708    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7709    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7710    tried and failed to match under normal conditions and now want to try a
7711    more relaxed match.  */
7712
7713 static bfd_boolean
7714 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7715              const struct mips_opcode *past, struct mips_operand_token *tokens,
7716              int opcode_extra, bfd_boolean lax_match)
7717 {
7718   const struct mips_opcode *opcode;
7719   const struct mips_opcode *invalid_delay_slot;
7720   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7721
7722   /* Search for a match, ignoring alternatives that don't satisfy the
7723      current ISA or forced_length.  */
7724   invalid_delay_slot = 0;
7725   seen_valid_for_isa = FALSE;
7726   seen_valid_for_size = FALSE;
7727   opcode = first;
7728   do
7729     {
7730       gas_assert (strcmp (opcode->name, first->name) == 0);
7731       if (is_opcode_valid (opcode))
7732         {
7733           seen_valid_for_isa = TRUE;
7734           if (is_size_valid (opcode))
7735             {
7736               bfd_boolean delay_slot_ok;
7737
7738               seen_valid_for_size = TRUE;
7739               delay_slot_ok = is_delay_slot_valid (opcode);
7740               if (match_insn (insn, opcode, tokens, opcode_extra,
7741                               lax_match, delay_slot_ok))
7742                 {
7743                   if (!delay_slot_ok)
7744                     {
7745                       if (!invalid_delay_slot)
7746                         invalid_delay_slot = opcode;
7747                     }
7748                   else
7749                     return TRUE;
7750                 }
7751             }
7752         }
7753       ++opcode;
7754     }
7755   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7756
7757   /* If the only matches we found had the wrong length for the delay slot,
7758      pick the first such match.  We'll issue an appropriate warning later.  */
7759   if (invalid_delay_slot)
7760     {
7761       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7762                       lax_match, TRUE))
7763         return TRUE;
7764       abort ();
7765     }
7766
7767   /* Handle the case where we didn't try to match an instruction because
7768      all the alternatives were incompatible with the current ISA.  */
7769   if (!seen_valid_for_isa)
7770     {
7771       match_invalid_for_isa ();
7772       return TRUE;
7773     }
7774
7775   /* Handle the case where we didn't try to match an instruction because
7776      all the alternatives were of the wrong size.  */
7777   if (!seen_valid_for_size)
7778     {
7779       if (mips_opts.insn32)
7780         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7781       else
7782         set_insn_error_i
7783           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7784            8 * forced_insn_length);
7785       return TRUE;
7786     }
7787
7788   return FALSE;
7789 }
7790
7791 /* Like match_insns, but for MIPS16.  */
7792
7793 static bfd_boolean
7794 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7795                     struct mips_operand_token *tokens)
7796 {
7797   const struct mips_opcode *opcode;
7798   bfd_boolean seen_valid_for_isa;
7799
7800   /* Search for a match, ignoring alternatives that don't satisfy the
7801      current ISA.  There are no separate entries for extended forms so
7802      we deal with forced_length later.  */
7803   seen_valid_for_isa = FALSE;
7804   opcode = first;
7805   do
7806     {
7807       gas_assert (strcmp (opcode->name, first->name) == 0);
7808       if (is_opcode_valid_16 (opcode))
7809         {
7810           seen_valid_for_isa = TRUE;
7811           if (match_mips16_insn (insn, opcode, tokens))
7812             return TRUE;
7813         }
7814       ++opcode;
7815     }
7816   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7817          && strcmp (opcode->name, first->name) == 0);
7818
7819   /* Handle the case where we didn't try to match an instruction because
7820      all the alternatives were incompatible with the current ISA.  */
7821   if (!seen_valid_for_isa)
7822     {
7823       match_invalid_for_isa ();
7824       return TRUE;
7825     }
7826
7827   return FALSE;
7828 }
7829
7830 /* Set up global variables for the start of a new macro.  */
7831
7832 static void
7833 macro_start (void)
7834 {
7835   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7836   memset (&mips_macro_warning.first_insn_sizes, 0,
7837           sizeof (mips_macro_warning.first_insn_sizes));
7838   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7839   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7840                                      && delayed_branch_p (&history[0]));
7841   switch (history[0].insn_mo->pinfo2
7842           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7843     {
7844     case INSN2_BRANCH_DELAY_32BIT:
7845       mips_macro_warning.delay_slot_length = 4;
7846       break;
7847     case INSN2_BRANCH_DELAY_16BIT:
7848       mips_macro_warning.delay_slot_length = 2;
7849       break;
7850     default:
7851       mips_macro_warning.delay_slot_length = 0;
7852       break;
7853     }
7854   mips_macro_warning.first_frag = NULL;
7855 }
7856
7857 /* Given that a macro is longer than one instruction or of the wrong size,
7858    return the appropriate warning for it.  Return null if no warning is
7859    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7860    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7861    and RELAX_NOMACRO.  */
7862
7863 static const char *
7864 macro_warning (relax_substateT subtype)
7865 {
7866   if (subtype & RELAX_DELAY_SLOT)
7867     return _("macro instruction expanded into multiple instructions"
7868              " in a branch delay slot");
7869   else if (subtype & RELAX_NOMACRO)
7870     return _("macro instruction expanded into multiple instructions");
7871   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7872                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7873     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7874             ? _("macro instruction expanded into a wrong size instruction"
7875                 " in a 16-bit branch delay slot")
7876             : _("macro instruction expanded into a wrong size instruction"
7877                 " in a 32-bit branch delay slot"));
7878   else
7879     return 0;
7880 }
7881
7882 /* Finish up a macro.  Emit warnings as appropriate.  */
7883
7884 static void
7885 macro_end (void)
7886 {
7887   /* Relaxation warning flags.  */
7888   relax_substateT subtype = 0;
7889
7890   /* Check delay slot size requirements.  */
7891   if (mips_macro_warning.delay_slot_length == 2)
7892     subtype |= RELAX_DELAY_SLOT_16BIT;
7893   if (mips_macro_warning.delay_slot_length != 0)
7894     {
7895       if (mips_macro_warning.delay_slot_length
7896           != mips_macro_warning.first_insn_sizes[0])
7897         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7898       if (mips_macro_warning.delay_slot_length
7899           != mips_macro_warning.first_insn_sizes[1])
7900         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7901     }
7902
7903   /* Check instruction count requirements.  */
7904   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7905     {
7906       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7907         subtype |= RELAX_SECOND_LONGER;
7908       if (mips_opts.warn_about_macros)
7909         subtype |= RELAX_NOMACRO;
7910       if (mips_macro_warning.delay_slot_p)
7911         subtype |= RELAX_DELAY_SLOT;
7912     }
7913
7914   /* If both alternatives fail to fill a delay slot correctly,
7915      emit the warning now.  */
7916   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7917       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7918     {
7919       relax_substateT s;
7920       const char *msg;
7921
7922       s = subtype & (RELAX_DELAY_SLOT_16BIT
7923                      | RELAX_DELAY_SLOT_SIZE_FIRST
7924                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7925       msg = macro_warning (s);
7926       if (msg != NULL)
7927         as_warn ("%s", msg);
7928       subtype &= ~s;
7929     }
7930
7931   /* If both implementations are longer than 1 instruction, then emit the
7932      warning now.  */
7933   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7934     {
7935       relax_substateT s;
7936       const char *msg;
7937
7938       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7939       msg = macro_warning (s);
7940       if (msg != NULL)
7941         as_warn ("%s", msg);
7942       subtype &= ~s;
7943     }
7944
7945   /* If any flags still set, then one implementation might need a warning
7946      and the other either will need one of a different kind or none at all.
7947      Pass any remaining flags over to relaxation.  */
7948   if (mips_macro_warning.first_frag != NULL)
7949     mips_macro_warning.first_frag->fr_subtype |= subtype;
7950 }
7951
7952 /* Instruction operand formats used in macros that vary between
7953    standard MIPS and microMIPS code.  */
7954
7955 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7956 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7957 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7958 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7959 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7960 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7961 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7962 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7963
7964 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7965 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7966 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7967 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7968 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7969 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7970 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7971 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7972
7973 /* Read a macro's relocation codes from *ARGS and store them in *R.
7974    The first argument in *ARGS will be either the code for a single
7975    relocation or -1 followed by the three codes that make up a
7976    composite relocation.  */
7977
7978 static void
7979 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7980 {
7981   int i, next;
7982
7983   next = va_arg (*args, int);
7984   if (next >= 0)
7985     r[0] = (bfd_reloc_code_real_type) next;
7986   else
7987     {
7988       for (i = 0; i < 3; i++)
7989         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7990       /* This function is only used for 16-bit relocation fields.
7991          To make the macro code simpler, treat an unrelocated value
7992          in the same way as BFD_RELOC_LO16.  */
7993       if (r[0] == BFD_RELOC_UNUSED)
7994         r[0] = BFD_RELOC_LO16;
7995     }
7996 }
7997
7998 /* Build an instruction created by a macro expansion.  This is passed
7999    a pointer to the count of instructions created so far, an
8000    expression, the name of the instruction to build, an operand format
8001    string, and corresponding arguments.  */
8002
8003 static void
8004 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8005 {
8006   const struct mips_opcode *mo = NULL;
8007   bfd_reloc_code_real_type r[3];
8008   const struct mips_opcode *amo;
8009   const struct mips_operand *operand;
8010   struct hash_control *hash;
8011   struct mips_cl_insn insn;
8012   va_list args;
8013   unsigned int uval;
8014
8015   va_start (args, fmt);
8016
8017   if (mips_opts.mips16)
8018     {
8019       mips16_macro_build (ep, name, fmt, &args);
8020       va_end (args);
8021       return;
8022     }
8023
8024   r[0] = BFD_RELOC_UNUSED;
8025   r[1] = BFD_RELOC_UNUSED;
8026   r[2] = BFD_RELOC_UNUSED;
8027   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8028   amo = (struct mips_opcode *) hash_find (hash, name);
8029   gas_assert (amo);
8030   gas_assert (strcmp (name, amo->name) == 0);
8031
8032   do
8033     {
8034       /* Search until we get a match for NAME.  It is assumed here that
8035          macros will never generate MDMX, MIPS-3D, or MT instructions.
8036          We try to match an instruction that fulfils the branch delay
8037          slot instruction length requirement (if any) of the previous
8038          instruction.  While doing this we record the first instruction
8039          seen that matches all the other conditions and use it anyway
8040          if the requirement cannot be met; we will issue an appropriate
8041          warning later on.  */
8042       if (strcmp (fmt, amo->args) == 0
8043           && amo->pinfo != INSN_MACRO
8044           && is_opcode_valid (amo)
8045           && is_size_valid (amo))
8046         {
8047           if (is_delay_slot_valid (amo))
8048             {
8049               mo = amo;
8050               break;
8051             }
8052           else if (!mo)
8053             mo = amo;
8054         }
8055
8056       ++amo;
8057       gas_assert (amo->name);
8058     }
8059   while (strcmp (name, amo->name) == 0);
8060
8061   gas_assert (mo);
8062   create_insn (&insn, mo);
8063   for (; *fmt; ++fmt)
8064     {
8065       switch (*fmt)
8066         {
8067         case ',':
8068         case '(':
8069         case ')':
8070         case 'z':
8071           break;
8072
8073         case 'i':
8074         case 'j':
8075           macro_read_relocs (&args, r);
8076           gas_assert (*r == BFD_RELOC_GPREL16
8077                       || *r == BFD_RELOC_MIPS_HIGHER
8078                       || *r == BFD_RELOC_HI16_S
8079                       || *r == BFD_RELOC_LO16
8080                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8081           break;
8082
8083         case 'o':
8084           macro_read_relocs (&args, r);
8085           break;
8086
8087         case 'u':
8088           macro_read_relocs (&args, r);
8089           gas_assert (ep != NULL
8090                       && (ep->X_op == O_constant
8091                           || (ep->X_op == O_symbol
8092                               && (*r == BFD_RELOC_MIPS_HIGHEST
8093                                   || *r == BFD_RELOC_HI16_S
8094                                   || *r == BFD_RELOC_HI16
8095                                   || *r == BFD_RELOC_GPREL16
8096                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8097                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8098           break;
8099
8100         case 'p':
8101           gas_assert (ep != NULL);
8102
8103           /*
8104            * This allows macro() to pass an immediate expression for
8105            * creating short branches without creating a symbol.
8106            *
8107            * We don't allow branch relaxation for these branches, as
8108            * they should only appear in ".set nomacro" anyway.
8109            */
8110           if (ep->X_op == O_constant)
8111             {
8112               /* For microMIPS we always use relocations for branches.
8113                  So we should not resolve immediate values.  */
8114               gas_assert (!mips_opts.micromips);
8115
8116               if ((ep->X_add_number & 3) != 0)
8117                 as_bad (_("branch to misaligned address (0x%lx)"),
8118                         (unsigned long) ep->X_add_number);
8119               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8120                 as_bad (_("branch address range overflow (0x%lx)"),
8121                         (unsigned long) ep->X_add_number);
8122               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8123               ep = NULL;
8124             }
8125           else
8126             *r = BFD_RELOC_16_PCREL_S2;
8127           break;
8128
8129         case 'a':
8130           gas_assert (ep != NULL);
8131           *r = BFD_RELOC_MIPS_JMP;
8132           break;
8133
8134         default:
8135           operand = (mips_opts.micromips
8136                      ? decode_micromips_operand (fmt)
8137                      : decode_mips_operand (fmt));
8138           if (!operand)
8139             abort ();
8140
8141           uval = va_arg (args, int);
8142           if (operand->type == OP_CLO_CLZ_DEST)
8143             uval |= (uval << 5);
8144           insn_insert_operand (&insn, operand, uval);
8145
8146           if (*fmt == '+' || *fmt == 'm')
8147             ++fmt;
8148           break;
8149         }
8150     }
8151   va_end (args);
8152   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8153
8154   append_insn (&insn, ep, r, TRUE);
8155 }
8156
8157 static void
8158 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8159                     va_list *args)
8160 {
8161   struct mips_opcode *mo;
8162   struct mips_cl_insn insn;
8163   const struct mips_operand *operand;
8164   bfd_reloc_code_real_type r[3]
8165     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8166
8167   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8168   gas_assert (mo);
8169   gas_assert (strcmp (name, mo->name) == 0);
8170
8171   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8172     {
8173       ++mo;
8174       gas_assert (mo->name);
8175       gas_assert (strcmp (name, mo->name) == 0);
8176     }
8177
8178   create_insn (&insn, mo);
8179   for (; *fmt; ++fmt)
8180     {
8181       int c;
8182
8183       c = *fmt;
8184       switch (c)
8185         {
8186         case ',':
8187         case '(':
8188         case ')':
8189           break;
8190
8191         case '0':
8192         case 'S':
8193         case 'P':
8194         case 'R':
8195           break;
8196
8197         case '<':
8198         case '>':
8199         case '4':
8200         case '5':
8201         case 'H':
8202         case 'W':
8203         case 'D':
8204         case 'j':
8205         case '8':
8206         case 'V':
8207         case 'C':
8208         case 'U':
8209         case 'k':
8210         case 'K':
8211         case 'p':
8212         case 'q':
8213           {
8214             offsetT value;
8215
8216             gas_assert (ep != NULL);
8217
8218             if (ep->X_op != O_constant)
8219               *r = (int) BFD_RELOC_UNUSED + c;
8220             else if (calculate_reloc (*r, ep->X_add_number, &value))
8221               {
8222                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8223                 ep = NULL;
8224                 *r = BFD_RELOC_UNUSED;
8225               }
8226           }
8227           break;
8228
8229         default:
8230           operand = decode_mips16_operand (c, FALSE);
8231           if (!operand)
8232             abort ();
8233
8234           insn_insert_operand (&insn, operand, va_arg (*args, int));
8235           break;
8236         }
8237     }
8238
8239   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8240
8241   append_insn (&insn, ep, r, TRUE);
8242 }
8243
8244 /*
8245  * Generate a "jalr" instruction with a relocation hint to the called
8246  * function.  This occurs in NewABI PIC code.
8247  */
8248 static void
8249 macro_build_jalr (expressionS *ep, int cprestore)
8250 {
8251   static const bfd_reloc_code_real_type jalr_relocs[2]
8252     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8253   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8254   const char *jalr;
8255   char *f = NULL;
8256
8257   if (MIPS_JALR_HINT_P (ep))
8258     {
8259       frag_grow (8);
8260       f = frag_more (0);
8261     }
8262   if (mips_opts.micromips)
8263     {
8264       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8265               ? "jalr" : "jalrs");
8266       if (MIPS_JALR_HINT_P (ep)
8267           || mips_opts.insn32
8268           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8269         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8270       else
8271         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8272     }
8273   else
8274     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8275   if (MIPS_JALR_HINT_P (ep))
8276     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8277 }
8278
8279 /*
8280  * Generate a "lui" instruction.
8281  */
8282 static void
8283 macro_build_lui (expressionS *ep, int regnum)
8284 {
8285   gas_assert (! mips_opts.mips16);
8286
8287   if (ep->X_op != O_constant)
8288     {
8289       gas_assert (ep->X_op == O_symbol);
8290       /* _gp_disp is a special case, used from s_cpload.
8291          __gnu_local_gp is used if mips_no_shared.  */
8292       gas_assert (mips_pic == NO_PIC
8293               || (! HAVE_NEWABI
8294                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8295               || (! mips_in_shared
8296                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8297                              "__gnu_local_gp") == 0));
8298     }
8299
8300   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8301 }
8302
8303 /* Generate a sequence of instructions to do a load or store from a constant
8304    offset off of a base register (breg) into/from a target register (treg),
8305    using AT if necessary.  */
8306 static void
8307 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8308                               int treg, int breg, int dbl)
8309 {
8310   gas_assert (ep->X_op == O_constant);
8311
8312   /* Sign-extending 32-bit constants makes their handling easier.  */
8313   if (!dbl)
8314     normalize_constant_expr (ep);
8315
8316   /* Right now, this routine can only handle signed 32-bit constants.  */
8317   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8318     as_warn (_("operand overflow"));
8319
8320   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8321     {
8322       /* Signed 16-bit offset will fit in the op.  Easy!  */
8323       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8324     }
8325   else
8326     {
8327       /* 32-bit offset, need multiple instructions and AT, like:
8328            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8329            addu     $tempreg,$tempreg,$breg
8330            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8331          to handle the complete offset.  */
8332       macro_build_lui (ep, AT);
8333       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8334       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8335
8336       if (!mips_opts.at)
8337         as_bad (_("macro used $at after \".set noat\""));
8338     }
8339 }
8340
8341 /*                      set_at()
8342  * Generates code to set the $at register to true (one)
8343  * if reg is less than the immediate expression.
8344  */
8345 static void
8346 set_at (int reg, int unsignedp)
8347 {
8348   if (imm_expr.X_add_number >= -0x8000
8349       && imm_expr.X_add_number < 0x8000)
8350     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8351                  AT, reg, BFD_RELOC_LO16);
8352   else
8353     {
8354       load_register (AT, &imm_expr, GPR_SIZE == 64);
8355       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8356     }
8357 }
8358
8359 /* Count the leading zeroes by performing a binary chop. This is a
8360    bulky bit of source, but performance is a LOT better for the
8361    majority of values than a simple loop to count the bits:
8362        for (lcnt = 0; (lcnt < 32); lcnt++)
8363          if ((v) & (1 << (31 - lcnt)))
8364            break;
8365   However it is not code size friendly, and the gain will drop a bit
8366   on certain cached systems.
8367 */
8368 #define COUNT_TOP_ZEROES(v)             \
8369   (((v) & ~0xffff) == 0                 \
8370    ? ((v) & ~0xff) == 0                 \
8371      ? ((v) & ~0xf) == 0                \
8372        ? ((v) & ~0x3) == 0              \
8373          ? ((v) & ~0x1) == 0            \
8374            ? !(v)                       \
8375              ? 32                       \
8376              : 31                       \
8377            : 30                         \
8378          : ((v) & ~0x7) == 0            \
8379            ? 29                         \
8380            : 28                         \
8381        : ((v) & ~0x3f) == 0             \
8382          ? ((v) & ~0x1f) == 0           \
8383            ? 27                         \
8384            : 26                         \
8385          : ((v) & ~0x7f) == 0           \
8386            ? 25                         \
8387            : 24                         \
8388      : ((v) & ~0xfff) == 0              \
8389        ? ((v) & ~0x3ff) == 0            \
8390          ? ((v) & ~0x1ff) == 0          \
8391            ? 23                         \
8392            : 22                         \
8393          : ((v) & ~0x7ff) == 0          \
8394            ? 21                         \
8395            : 20                         \
8396        : ((v) & ~0x3fff) == 0           \
8397          ? ((v) & ~0x1fff) == 0         \
8398            ? 19                         \
8399            : 18                         \
8400          : ((v) & ~0x7fff) == 0         \
8401            ? 17                         \
8402            : 16                         \
8403    : ((v) & ~0xffffff) == 0             \
8404      ? ((v) & ~0xfffff) == 0            \
8405        ? ((v) & ~0x3ffff) == 0          \
8406          ? ((v) & ~0x1ffff) == 0        \
8407            ? 15                         \
8408            : 14                         \
8409          : ((v) & ~0x7ffff) == 0        \
8410            ? 13                         \
8411            : 12                         \
8412        : ((v) & ~0x3fffff) == 0         \
8413          ? ((v) & ~0x1fffff) == 0       \
8414            ? 11                         \
8415            : 10                         \
8416          : ((v) & ~0x7fffff) == 0       \
8417            ? 9                          \
8418            : 8                          \
8419      : ((v) & ~0xfffffff) == 0          \
8420        ? ((v) & ~0x3ffffff) == 0        \
8421          ? ((v) & ~0x1ffffff) == 0      \
8422            ? 7                          \
8423            : 6                          \
8424          : ((v) & ~0x7ffffff) == 0      \
8425            ? 5                          \
8426            : 4                          \
8427        : ((v) & ~0x3fffffff) == 0       \
8428          ? ((v) & ~0x1fffffff) == 0     \
8429            ? 3                          \
8430            : 2                          \
8431          : ((v) & ~0x7fffffff) == 0     \
8432            ? 1                          \
8433            : 0)
8434
8435 /*                      load_register()
8436  *  This routine generates the least number of instructions necessary to load
8437  *  an absolute expression value into a register.
8438  */
8439 static void
8440 load_register (int reg, expressionS *ep, int dbl)
8441 {
8442   int freg;
8443   expressionS hi32, lo32;
8444
8445   if (ep->X_op != O_big)
8446     {
8447       gas_assert (ep->X_op == O_constant);
8448
8449       /* Sign-extending 32-bit constants makes their handling easier.  */
8450       if (!dbl)
8451         normalize_constant_expr (ep);
8452
8453       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8454         {
8455           /* We can handle 16 bit signed values with an addiu to
8456              $zero.  No need to ever use daddiu here, since $zero and
8457              the result are always correct in 32 bit mode.  */
8458           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8459           return;
8460         }
8461       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8462         {
8463           /* We can handle 16 bit unsigned values with an ori to
8464              $zero.  */
8465           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8466           return;
8467         }
8468       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8469         {
8470           /* 32 bit values require an lui.  */
8471           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8472           if ((ep->X_add_number & 0xffff) != 0)
8473             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8474           return;
8475         }
8476     }
8477
8478   /* The value is larger than 32 bits.  */
8479
8480   if (!dbl || GPR_SIZE == 32)
8481     {
8482       char value[32];
8483
8484       sprintf_vma (value, ep->X_add_number);
8485       as_bad (_("number (0x%s) larger than 32 bits"), value);
8486       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8487       return;
8488     }
8489
8490   if (ep->X_op != O_big)
8491     {
8492       hi32 = *ep;
8493       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8494       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8495       hi32.X_add_number &= 0xffffffff;
8496       lo32 = *ep;
8497       lo32.X_add_number &= 0xffffffff;
8498     }
8499   else
8500     {
8501       gas_assert (ep->X_add_number > 2);
8502       if (ep->X_add_number == 3)
8503         generic_bignum[3] = 0;
8504       else if (ep->X_add_number > 4)
8505         as_bad (_("number larger than 64 bits"));
8506       lo32.X_op = O_constant;
8507       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8508       hi32.X_op = O_constant;
8509       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8510     }
8511
8512   if (hi32.X_add_number == 0)
8513     freg = 0;
8514   else
8515     {
8516       int shift, bit;
8517       unsigned long hi, lo;
8518
8519       if (hi32.X_add_number == (offsetT) 0xffffffff)
8520         {
8521           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8522             {
8523               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8524               return;
8525             }
8526           if (lo32.X_add_number & 0x80000000)
8527             {
8528               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8529               if (lo32.X_add_number & 0xffff)
8530                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8531               return;
8532             }
8533         }
8534
8535       /* Check for 16bit shifted constant.  We know that hi32 is
8536          non-zero, so start the mask on the first bit of the hi32
8537          value.  */
8538       shift = 17;
8539       do
8540         {
8541           unsigned long himask, lomask;
8542
8543           if (shift < 32)
8544             {
8545               himask = 0xffff >> (32 - shift);
8546               lomask = (0xffff << shift) & 0xffffffff;
8547             }
8548           else
8549             {
8550               himask = 0xffff << (shift - 32);
8551               lomask = 0;
8552             }
8553           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8554               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8555             {
8556               expressionS tmp;
8557
8558               tmp.X_op = O_constant;
8559               if (shift < 32)
8560                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8561                                     | (lo32.X_add_number >> shift));
8562               else
8563                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8564               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8565               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8566                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8567               return;
8568             }
8569           ++shift;
8570         }
8571       while (shift <= (64 - 16));
8572
8573       /* Find the bit number of the lowest one bit, and store the
8574          shifted value in hi/lo.  */
8575       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8576       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8577       if (lo != 0)
8578         {
8579           bit = 0;
8580           while ((lo & 1) == 0)
8581             {
8582               lo >>= 1;
8583               ++bit;
8584             }
8585           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8586           hi >>= bit;
8587         }
8588       else
8589         {
8590           bit = 32;
8591           while ((hi & 1) == 0)
8592             {
8593               hi >>= 1;
8594               ++bit;
8595             }
8596           lo = hi;
8597           hi = 0;
8598         }
8599
8600       /* Optimize if the shifted value is a (power of 2) - 1.  */
8601       if ((hi == 0 && ((lo + 1) & lo) == 0)
8602           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8603         {
8604           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8605           if (shift != 0)
8606             {
8607               expressionS tmp;
8608
8609               /* This instruction will set the register to be all
8610                  ones.  */
8611               tmp.X_op = O_constant;
8612               tmp.X_add_number = (offsetT) -1;
8613               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8614               if (bit != 0)
8615                 {
8616                   bit += shift;
8617                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8618                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8619                 }
8620               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8621                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8622               return;
8623             }
8624         }
8625
8626       /* Sign extend hi32 before calling load_register, because we can
8627          generally get better code when we load a sign extended value.  */
8628       if ((hi32.X_add_number & 0x80000000) != 0)
8629         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8630       load_register (reg, &hi32, 0);
8631       freg = reg;
8632     }
8633   if ((lo32.X_add_number & 0xffff0000) == 0)
8634     {
8635       if (freg != 0)
8636         {
8637           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8638           freg = reg;
8639         }
8640     }
8641   else
8642     {
8643       expressionS mid16;
8644
8645       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8646         {
8647           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8648           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8649           return;
8650         }
8651
8652       if (freg != 0)
8653         {
8654           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8655           freg = reg;
8656         }
8657       mid16 = lo32;
8658       mid16.X_add_number >>= 16;
8659       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8660       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8661       freg = reg;
8662     }
8663   if ((lo32.X_add_number & 0xffff) != 0)
8664     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8665 }
8666
8667 static inline void
8668 load_delay_nop (void)
8669 {
8670   if (!gpr_interlocks)
8671     macro_build (NULL, "nop", "");
8672 }
8673
8674 /* Load an address into a register.  */
8675
8676 static void
8677 load_address (int reg, expressionS *ep, int *used_at)
8678 {
8679   if (ep->X_op != O_constant
8680       && ep->X_op != O_symbol)
8681     {
8682       as_bad (_("expression too complex"));
8683       ep->X_op = O_constant;
8684     }
8685
8686   if (ep->X_op == O_constant)
8687     {
8688       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8689       return;
8690     }
8691
8692   if (mips_pic == NO_PIC)
8693     {
8694       /* If this is a reference to a GP relative symbol, we want
8695            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8696          Otherwise we want
8697            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8698            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8699          If we have an addend, we always use the latter form.
8700
8701          With 64bit address space and a usable $at we want
8702            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8703            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8704            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8705            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8706            dsll32       $reg,0
8707            daddu        $reg,$reg,$at
8708
8709          If $at is already in use, we use a path which is suboptimal
8710          on superscalar processors.
8711            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8712            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8713            dsll         $reg,16
8714            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8715            dsll         $reg,16
8716            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8717
8718          For GP relative symbols in 64bit address space we can use
8719          the same sequence as in 32bit address space.  */
8720       if (HAVE_64BIT_SYMBOLS)
8721         {
8722           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8723               && !nopic_need_relax (ep->X_add_symbol, 1))
8724             {
8725               relax_start (ep->X_add_symbol);
8726               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8727                            mips_gp_register, BFD_RELOC_GPREL16);
8728               relax_switch ();
8729             }
8730
8731           if (*used_at == 0 && mips_opts.at)
8732             {
8733               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8734               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8735               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8736                            BFD_RELOC_MIPS_HIGHER);
8737               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8738               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8739               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8740               *used_at = 1;
8741             }
8742           else
8743             {
8744               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8745               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8746                            BFD_RELOC_MIPS_HIGHER);
8747               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8748               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8749               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8750               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8751             }
8752
8753           if (mips_relax.sequence)
8754             relax_end ();
8755         }
8756       else
8757         {
8758           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8759               && !nopic_need_relax (ep->X_add_symbol, 1))
8760             {
8761               relax_start (ep->X_add_symbol);
8762               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8763                            mips_gp_register, BFD_RELOC_GPREL16);
8764               relax_switch ();
8765             }
8766           macro_build_lui (ep, reg);
8767           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8768                        reg, reg, BFD_RELOC_LO16);
8769           if (mips_relax.sequence)
8770             relax_end ();
8771         }
8772     }
8773   else if (!mips_big_got)
8774     {
8775       expressionS ex;
8776
8777       /* If this is a reference to an external symbol, we want
8778            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8779          Otherwise we want
8780            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8781            nop
8782            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8783          If there is a constant, it must be added in after.
8784
8785          If we have NewABI, we want
8786            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8787          unless we're referencing a global symbol with a non-zero
8788          offset, in which case cst must be added separately.  */
8789       if (HAVE_NEWABI)
8790         {
8791           if (ep->X_add_number)
8792             {
8793               ex.X_add_number = ep->X_add_number;
8794               ep->X_add_number = 0;
8795               relax_start (ep->X_add_symbol);
8796               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8797                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8798               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8799                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8800               ex.X_op = O_constant;
8801               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8802                            reg, reg, BFD_RELOC_LO16);
8803               ep->X_add_number = ex.X_add_number;
8804               relax_switch ();
8805             }
8806           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8807                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8808           if (mips_relax.sequence)
8809             relax_end ();
8810         }
8811       else
8812         {
8813           ex.X_add_number = ep->X_add_number;
8814           ep->X_add_number = 0;
8815           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8816                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8817           load_delay_nop ();
8818           relax_start (ep->X_add_symbol);
8819           relax_switch ();
8820           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8821                        BFD_RELOC_LO16);
8822           relax_end ();
8823
8824           if (ex.X_add_number != 0)
8825             {
8826               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8827                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8828               ex.X_op = O_constant;
8829               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8830                            reg, reg, BFD_RELOC_LO16);
8831             }
8832         }
8833     }
8834   else if (mips_big_got)
8835     {
8836       expressionS ex;
8837
8838       /* This is the large GOT case.  If this is a reference to an
8839          external symbol, we want
8840            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8841            addu         $reg,$reg,$gp
8842            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8843
8844          Otherwise, for a reference to a local symbol in old ABI, we want
8845            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8846            nop
8847            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8848          If there is a constant, it must be added in after.
8849
8850          In the NewABI, for local symbols, with or without offsets, we want:
8851            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8852            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8853       */
8854       if (HAVE_NEWABI)
8855         {
8856           ex.X_add_number = ep->X_add_number;
8857           ep->X_add_number = 0;
8858           relax_start (ep->X_add_symbol);
8859           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8860           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8861                        reg, reg, mips_gp_register);
8862           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8863                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8864           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8865             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8866           else if (ex.X_add_number)
8867             {
8868               ex.X_op = O_constant;
8869               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8870                            BFD_RELOC_LO16);
8871             }
8872
8873           ep->X_add_number = ex.X_add_number;
8874           relax_switch ();
8875           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8876                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8877           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8878                        BFD_RELOC_MIPS_GOT_OFST);
8879           relax_end ();
8880         }
8881       else
8882         {
8883           ex.X_add_number = ep->X_add_number;
8884           ep->X_add_number = 0;
8885           relax_start (ep->X_add_symbol);
8886           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8887           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8888                        reg, reg, mips_gp_register);
8889           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8890                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8891           relax_switch ();
8892           if (reg_needs_delay (mips_gp_register))
8893             {
8894               /* We need a nop before loading from $gp.  This special
8895                  check is required because the lui which starts the main
8896                  instruction stream does not refer to $gp, and so will not
8897                  insert the nop which may be required.  */
8898               macro_build (NULL, "nop", "");
8899             }
8900           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8901                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8902           load_delay_nop ();
8903           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8904                        BFD_RELOC_LO16);
8905           relax_end ();
8906
8907           if (ex.X_add_number != 0)
8908             {
8909               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8910                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8911               ex.X_op = O_constant;
8912               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8913                            BFD_RELOC_LO16);
8914             }
8915         }
8916     }
8917   else
8918     abort ();
8919
8920   if (!mips_opts.at && *used_at == 1)
8921     as_bad (_("macro used $at after \".set noat\""));
8922 }
8923
8924 /* Move the contents of register SOURCE into register DEST.  */
8925
8926 static void
8927 move_register (int dest, int source)
8928 {
8929   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8930      instruction specifically requires a 32-bit one.  */
8931   if (mips_opts.micromips
8932       && !mips_opts.insn32
8933       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8934     macro_build (NULL, "move", "mp,mj", dest, source);
8935   else
8936     macro_build (NULL, GPR_SIZE == 32 ? "addu" : "daddu", "d,v,t",
8937                  dest, source, 0);
8938 }
8939
8940 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8941    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8942    The two alternatives are:
8943
8944    Global symbol                Local sybmol
8945    -------------                ------------
8946    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8947    ...                          ...
8948    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8949
8950    load_got_offset emits the first instruction and add_got_offset
8951    emits the second for a 16-bit offset or add_got_offset_hilo emits
8952    a sequence to add a 32-bit offset using a scratch register.  */
8953
8954 static void
8955 load_got_offset (int dest, expressionS *local)
8956 {
8957   expressionS global;
8958
8959   global = *local;
8960   global.X_add_number = 0;
8961
8962   relax_start (local->X_add_symbol);
8963   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8964                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8965   relax_switch ();
8966   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8967                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8968   relax_end ();
8969 }
8970
8971 static void
8972 add_got_offset (int dest, expressionS *local)
8973 {
8974   expressionS global;
8975
8976   global.X_op = O_constant;
8977   global.X_op_symbol = NULL;
8978   global.X_add_symbol = NULL;
8979   global.X_add_number = local->X_add_number;
8980
8981   relax_start (local->X_add_symbol);
8982   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8983                dest, dest, BFD_RELOC_LO16);
8984   relax_switch ();
8985   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8986   relax_end ();
8987 }
8988
8989 static void
8990 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8991 {
8992   expressionS global;
8993   int hold_mips_optimize;
8994
8995   global.X_op = O_constant;
8996   global.X_op_symbol = NULL;
8997   global.X_add_symbol = NULL;
8998   global.X_add_number = local->X_add_number;
8999
9000   relax_start (local->X_add_symbol);
9001   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9002   relax_switch ();
9003   /* Set mips_optimize around the lui instruction to avoid
9004      inserting an unnecessary nop after the lw.  */
9005   hold_mips_optimize = mips_optimize;
9006   mips_optimize = 2;
9007   macro_build_lui (&global, tmp);
9008   mips_optimize = hold_mips_optimize;
9009   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9010   relax_end ();
9011
9012   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9013 }
9014
9015 /* Emit a sequence of instructions to emulate a branch likely operation.
9016    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9017    is its complementing branch with the original condition negated.
9018    CALL is set if the original branch specified the link operation.
9019    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9020
9021    Code like this is produced in the noreorder mode:
9022
9023         BRNEG   <args>, 1f
9024          nop
9025         b       <sym>
9026          delay slot (executed only if branch taken)
9027     1:
9028
9029    or, if CALL is set:
9030
9031         BRNEG   <args>, 1f
9032          nop
9033         bal     <sym>
9034          delay slot (executed only if branch taken)
9035     1:
9036
9037    In the reorder mode the delay slot would be filled with a nop anyway,
9038    so code produced is simply:
9039
9040         BR      <args>, <sym>
9041          nop
9042
9043    This function is used when producing code for the microMIPS ASE that
9044    does not implement branch likely instructions in hardware.  */
9045
9046 static void
9047 macro_build_branch_likely (const char *br, const char *brneg,
9048                            int call, expressionS *ep, const char *fmt,
9049                            unsigned int sreg, unsigned int treg)
9050 {
9051   int noreorder = mips_opts.noreorder;
9052   expressionS expr1;
9053
9054   gas_assert (mips_opts.micromips);
9055   start_noreorder ();
9056   if (noreorder)
9057     {
9058       micromips_label_expr (&expr1);
9059       macro_build (&expr1, brneg, fmt, sreg, treg);
9060       macro_build (NULL, "nop", "");
9061       macro_build (ep, call ? "bal" : "b", "p");
9062
9063       /* Set to true so that append_insn adds a label.  */
9064       emit_branch_likely_macro = TRUE;
9065     }
9066   else
9067     {
9068       macro_build (ep, br, fmt, sreg, treg);
9069       macro_build (NULL, "nop", "");
9070     }
9071   end_noreorder ();
9072 }
9073
9074 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9075    the condition code tested.  EP specifies the branch target.  */
9076
9077 static void
9078 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9079 {
9080   const int call = 0;
9081   const char *brneg;
9082   const char *br;
9083
9084   switch (type)
9085     {
9086     case M_BC1FL:
9087       br = "bc1f";
9088       brneg = "bc1t";
9089       break;
9090     case M_BC1TL:
9091       br = "bc1t";
9092       brneg = "bc1f";
9093       break;
9094     case M_BC2FL:
9095       br = "bc2f";
9096       brneg = "bc2t";
9097       break;
9098     case M_BC2TL:
9099       br = "bc2t";
9100       brneg = "bc2f";
9101       break;
9102     default:
9103       abort ();
9104     }
9105   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9106 }
9107
9108 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9109    the register tested.  EP specifies the branch target.  */
9110
9111 static void
9112 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9113 {
9114   const char *brneg = NULL;
9115   const char *br;
9116   int call = 0;
9117
9118   switch (type)
9119     {
9120     case M_BGEZ:
9121       br = "bgez";
9122       break;
9123     case M_BGEZL:
9124       br = mips_opts.micromips ? "bgez" : "bgezl";
9125       brneg = "bltz";
9126       break;
9127     case M_BGEZALL:
9128       gas_assert (mips_opts.micromips);
9129       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9130       brneg = "bltz";
9131       call = 1;
9132       break;
9133     case M_BGTZ:
9134       br = "bgtz";
9135       break;
9136     case M_BGTZL:
9137       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9138       brneg = "blez";
9139       break;
9140     case M_BLEZ:
9141       br = "blez";
9142       break;
9143     case M_BLEZL:
9144       br = mips_opts.micromips ? "blez" : "blezl";
9145       brneg = "bgtz";
9146       break;
9147     case M_BLTZ:
9148       br = "bltz";
9149       break;
9150     case M_BLTZL:
9151       br = mips_opts.micromips ? "bltz" : "bltzl";
9152       brneg = "bgez";
9153       break;
9154     case M_BLTZALL:
9155       gas_assert (mips_opts.micromips);
9156       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9157       brneg = "bgez";
9158       call = 1;
9159       break;
9160     default:
9161       abort ();
9162     }
9163   if (mips_opts.micromips && brneg)
9164     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9165   else
9166     macro_build (ep, br, "s,p", sreg);
9167 }
9168
9169 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9170    TREG as the registers tested.  EP specifies the branch target.  */
9171
9172 static void
9173 macro_build_branch_rsrt (int type, expressionS *ep,
9174                          unsigned int sreg, unsigned int treg)
9175 {
9176   const char *brneg = NULL;
9177   const int call = 0;
9178   const char *br;
9179
9180   switch (type)
9181     {
9182     case M_BEQ:
9183     case M_BEQ_I:
9184       br = "beq";
9185       break;
9186     case M_BEQL:
9187     case M_BEQL_I:
9188       br = mips_opts.micromips ? "beq" : "beql";
9189       brneg = "bne";
9190       break;
9191     case M_BNE:
9192     case M_BNE_I:
9193       br = "bne";
9194       break;
9195     case M_BNEL:
9196     case M_BNEL_I:
9197       br = mips_opts.micromips ? "bne" : "bnel";
9198       brneg = "beq";
9199       break;
9200     default:
9201       abort ();
9202     }
9203   if (mips_opts.micromips && brneg)
9204     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9205   else
9206     macro_build (ep, br, "s,t,p", sreg, treg);
9207 }
9208
9209 /* Return the high part that should be loaded in order to make the low
9210    part of VALUE accessible using an offset of OFFBITS bits.  */
9211
9212 static offsetT
9213 offset_high_part (offsetT value, unsigned int offbits)
9214 {
9215   offsetT bias;
9216   addressT low_mask;
9217
9218   if (offbits == 0)
9219     return value;
9220   bias = 1 << (offbits - 1);
9221   low_mask = bias * 2 - 1;
9222   return (value + bias) & ~low_mask;
9223 }
9224
9225 /* Return true if the value stored in offset_expr and offset_reloc
9226    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9227    amount that the caller wants to add without inducing overflow
9228    and ALIGN is the known alignment of the value in bytes.  */
9229
9230 static bfd_boolean
9231 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9232 {
9233   if (offbits == 16)
9234     {
9235       /* Accept any relocation operator if overflow isn't a concern.  */
9236       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9237         return TRUE;
9238
9239       /* These relocations are guaranteed not to overflow in correct links.  */
9240       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9241           || gprel16_reloc_p (*offset_reloc))
9242         return TRUE;
9243     }
9244   if (offset_expr.X_op == O_constant
9245       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9246       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9247     return TRUE;
9248   return FALSE;
9249 }
9250
9251 /*
9252  *                      Build macros
9253  *   This routine implements the seemingly endless macro or synthesized
9254  * instructions and addressing modes in the mips assembly language. Many
9255  * of these macros are simple and are similar to each other. These could
9256  * probably be handled by some kind of table or grammar approach instead of
9257  * this verbose method. Others are not simple macros but are more like
9258  * optimizing code generation.
9259  *   One interesting optimization is when several store macros appear
9260  * consecutively that would load AT with the upper half of the same address.
9261  * The ensuing load upper instructions are ommited. This implies some kind
9262  * of global optimization. We currently only optimize within a single macro.
9263  *   For many of the load and store macros if the address is specified as a
9264  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9265  * first load register 'at' with zero and use it as the base register. The
9266  * mips assembler simply uses register $zero. Just one tiny optimization
9267  * we're missing.
9268  */
9269 static void
9270 macro (struct mips_cl_insn *ip, char *str)
9271 {
9272   const struct mips_operand_array *operands;
9273   unsigned int breg, i;
9274   unsigned int tempreg;
9275   int mask;
9276   int used_at = 0;
9277   expressionS label_expr;
9278   expressionS expr1;
9279   expressionS *ep;
9280   const char *s;
9281   const char *s2;
9282   const char *fmt;
9283   int likely = 0;
9284   int coproc = 0;
9285   int offbits = 16;
9286   int call = 0;
9287   int jals = 0;
9288   int dbl = 0;
9289   int imm = 0;
9290   int ust = 0;
9291   int lp = 0;
9292   bfd_boolean large_offset;
9293   int off;
9294   int hold_mips_optimize;
9295   unsigned int align;
9296   unsigned int op[MAX_OPERANDS];
9297
9298   gas_assert (! mips_opts.mips16);
9299
9300   operands = insn_operands (ip);
9301   for (i = 0; i < MAX_OPERANDS; i++)
9302     if (operands->operand[i])
9303       op[i] = insn_extract_operand (ip, operands->operand[i]);
9304     else
9305       op[i] = -1;
9306
9307   mask = ip->insn_mo->mask;
9308
9309   label_expr.X_op = O_constant;
9310   label_expr.X_op_symbol = NULL;
9311   label_expr.X_add_symbol = NULL;
9312   label_expr.X_add_number = 0;
9313
9314   expr1.X_op = O_constant;
9315   expr1.X_op_symbol = NULL;
9316   expr1.X_add_symbol = NULL;
9317   expr1.X_add_number = 1;
9318   align = 1;
9319
9320   switch (mask)
9321     {
9322     case M_DABS:
9323       dbl = 1;
9324     case M_ABS:
9325       /*    bgez    $a0,1f
9326             move    v0,$a0
9327             sub     v0,$zero,$a0
9328          1:
9329        */
9330
9331       start_noreorder ();
9332
9333       if (mips_opts.micromips)
9334         micromips_label_expr (&label_expr);
9335       else
9336         label_expr.X_add_number = 8;
9337       macro_build (&label_expr, "bgez", "s,p", op[1]);
9338       if (op[0] == op[1])
9339         macro_build (NULL, "nop", "");
9340       else
9341         move_register (op[0], op[1]);
9342       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9343       if (mips_opts.micromips)
9344         micromips_add_label ();
9345
9346       end_noreorder ();
9347       break;
9348
9349     case M_ADD_I:
9350       s = "addi";
9351       s2 = "add";
9352       goto do_addi;
9353     case M_ADDU_I:
9354       s = "addiu";
9355       s2 = "addu";
9356       goto do_addi;
9357     case M_DADD_I:
9358       dbl = 1;
9359       s = "daddi";
9360       s2 = "dadd";
9361       if (!mips_opts.micromips)
9362         goto do_addi;
9363       if (imm_expr.X_add_number >= -0x200
9364           && imm_expr.X_add_number < 0x200)
9365         {
9366           macro_build (NULL, s, "t,r,.", op[0], op[1],
9367                        (int) imm_expr.X_add_number);
9368           break;
9369         }
9370       goto do_addi_i;
9371     case M_DADDU_I:
9372       dbl = 1;
9373       s = "daddiu";
9374       s2 = "daddu";
9375     do_addi:
9376       if (imm_expr.X_add_number >= -0x8000
9377           && imm_expr.X_add_number < 0x8000)
9378         {
9379           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9380           break;
9381         }
9382     do_addi_i:
9383       used_at = 1;
9384       load_register (AT, &imm_expr, dbl);
9385       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9386       break;
9387
9388     case M_AND_I:
9389       s = "andi";
9390       s2 = "and";
9391       goto do_bit;
9392     case M_OR_I:
9393       s = "ori";
9394       s2 = "or";
9395       goto do_bit;
9396     case M_NOR_I:
9397       s = "";
9398       s2 = "nor";
9399       goto do_bit;
9400     case M_XOR_I:
9401       s = "xori";
9402       s2 = "xor";
9403     do_bit:
9404       if (imm_expr.X_add_number >= 0
9405           && imm_expr.X_add_number < 0x10000)
9406         {
9407           if (mask != M_NOR_I)
9408             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9409           else
9410             {
9411               macro_build (&imm_expr, "ori", "t,r,i",
9412                            op[0], op[1], BFD_RELOC_LO16);
9413               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9414             }
9415           break;
9416         }
9417
9418       used_at = 1;
9419       load_register (AT, &imm_expr, GPR_SIZE == 64);
9420       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9421       break;
9422
9423     case M_BALIGN:
9424       switch (imm_expr.X_add_number)
9425         {
9426         case 0:
9427           macro_build (NULL, "nop", "");
9428           break;
9429         case 2:
9430           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9431           break;
9432         case 1:
9433         case 3:
9434           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9435                        (int) imm_expr.X_add_number);
9436           break;
9437         default:
9438           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9439                   (unsigned long) imm_expr.X_add_number);
9440           break;
9441         }
9442       break;
9443
9444     case M_BC1FL:
9445     case M_BC1TL:
9446     case M_BC2FL:
9447     case M_BC2TL:
9448       gas_assert (mips_opts.micromips);
9449       macro_build_branch_ccl (mask, &offset_expr,
9450                               EXTRACT_OPERAND (1, BCC, *ip));
9451       break;
9452
9453     case M_BEQ_I:
9454     case M_BEQL_I:
9455     case M_BNE_I:
9456     case M_BNEL_I:
9457       if (imm_expr.X_add_number == 0)
9458         op[1] = 0;
9459       else
9460         {
9461           op[1] = AT;
9462           used_at = 1;
9463           load_register (op[1], &imm_expr, GPR_SIZE == 64);
9464         }
9465       /* Fall through.  */
9466     case M_BEQL:
9467     case M_BNEL:
9468       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9469       break;
9470
9471     case M_BGEL:
9472       likely = 1;
9473     case M_BGE:
9474       if (op[1] == 0)
9475         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9476       else if (op[0] == 0)
9477         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9478       else
9479         {
9480           used_at = 1;
9481           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9482           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9483                                    &offset_expr, AT, ZERO);
9484         }
9485       break;
9486
9487     case M_BGEZL:
9488     case M_BGEZALL:
9489     case M_BGTZL:
9490     case M_BLEZL:
9491     case M_BLTZL:
9492     case M_BLTZALL:
9493       macro_build_branch_rs (mask, &offset_expr, op[0]);
9494       break;
9495
9496     case M_BGTL_I:
9497       likely = 1;
9498     case M_BGT_I:
9499       /* Check for > max integer.  */
9500       if (imm_expr.X_add_number >= GPR_SMAX)
9501         {
9502         do_false:
9503           /* Result is always false.  */
9504           if (! likely)
9505             macro_build (NULL, "nop", "");
9506           else
9507             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9508           break;
9509         }
9510       ++imm_expr.X_add_number;
9511       /* FALLTHROUGH */
9512     case M_BGE_I:
9513     case M_BGEL_I:
9514       if (mask == M_BGEL_I)
9515         likely = 1;
9516       if (imm_expr.X_add_number == 0)
9517         {
9518           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9519                                  &offset_expr, op[0]);
9520           break;
9521         }
9522       if (imm_expr.X_add_number == 1)
9523         {
9524           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9525                                  &offset_expr, op[0]);
9526           break;
9527         }
9528       if (imm_expr.X_add_number <= GPR_SMIN)
9529         {
9530         do_true:
9531           /* result is always true */
9532           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9533           macro_build (&offset_expr, "b", "p");
9534           break;
9535         }
9536       used_at = 1;
9537       set_at (op[0], 0);
9538       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9539                                &offset_expr, AT, ZERO);
9540       break;
9541
9542     case M_BGEUL:
9543       likely = 1;
9544     case M_BGEU:
9545       if (op[1] == 0)
9546         goto do_true;
9547       else if (op[0] == 0)
9548         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9549                                  &offset_expr, ZERO, op[1]);
9550       else
9551         {
9552           used_at = 1;
9553           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9554           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9555                                    &offset_expr, AT, ZERO);
9556         }
9557       break;
9558
9559     case M_BGTUL_I:
9560       likely = 1;
9561     case M_BGTU_I:
9562       if (op[0] == 0
9563           || (GPR_SIZE == 32
9564               && imm_expr.X_add_number == -1))
9565         goto do_false;
9566       ++imm_expr.X_add_number;
9567       /* FALLTHROUGH */
9568     case M_BGEU_I:
9569     case M_BGEUL_I:
9570       if (mask == M_BGEUL_I)
9571         likely = 1;
9572       if (imm_expr.X_add_number == 0)
9573         goto do_true;
9574       else if (imm_expr.X_add_number == 1)
9575         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9576                                  &offset_expr, op[0], ZERO);
9577       else
9578         {
9579           used_at = 1;
9580           set_at (op[0], 1);
9581           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9582                                    &offset_expr, AT, ZERO);
9583         }
9584       break;
9585
9586     case M_BGTL:
9587       likely = 1;
9588     case M_BGT:
9589       if (op[1] == 0)
9590         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9591       else if (op[0] == 0)
9592         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9593       else
9594         {
9595           used_at = 1;
9596           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9597           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9598                                    &offset_expr, AT, ZERO);
9599         }
9600       break;
9601
9602     case M_BGTUL:
9603       likely = 1;
9604     case M_BGTU:
9605       if (op[1] == 0)
9606         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9607                                  &offset_expr, op[0], ZERO);
9608       else if (op[0] == 0)
9609         goto do_false;
9610       else
9611         {
9612           used_at = 1;
9613           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9614           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9615                                    &offset_expr, AT, ZERO);
9616         }
9617       break;
9618
9619     case M_BLEL:
9620       likely = 1;
9621     case M_BLE:
9622       if (op[1] == 0)
9623         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9624       else if (op[0] == 0)
9625         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9626       else
9627         {
9628           used_at = 1;
9629           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9630           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9631                                    &offset_expr, AT, ZERO);
9632         }
9633       break;
9634
9635     case M_BLEL_I:
9636       likely = 1;
9637     case M_BLE_I:
9638       if (imm_expr.X_add_number >= GPR_SMAX)
9639         goto do_true;
9640       ++imm_expr.X_add_number;
9641       /* FALLTHROUGH */
9642     case M_BLT_I:
9643     case M_BLTL_I:
9644       if (mask == M_BLTL_I)
9645         likely = 1;
9646       if (imm_expr.X_add_number == 0)
9647         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9648       else if (imm_expr.X_add_number == 1)
9649         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9650       else
9651         {
9652           used_at = 1;
9653           set_at (op[0], 0);
9654           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9655                                    &offset_expr, AT, ZERO);
9656         }
9657       break;
9658
9659     case M_BLEUL:
9660       likely = 1;
9661     case M_BLEU:
9662       if (op[1] == 0)
9663         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9664                                  &offset_expr, op[0], ZERO);
9665       else if (op[0] == 0)
9666         goto do_true;
9667       else
9668         {
9669           used_at = 1;
9670           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9671           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9672                                    &offset_expr, AT, ZERO);
9673         }
9674       break;
9675
9676     case M_BLEUL_I:
9677       likely = 1;
9678     case M_BLEU_I:
9679       if (op[0] == 0
9680           || (GPR_SIZE == 32
9681               && imm_expr.X_add_number == -1))
9682         goto do_true;
9683       ++imm_expr.X_add_number;
9684       /* FALLTHROUGH */
9685     case M_BLTU_I:
9686     case M_BLTUL_I:
9687       if (mask == M_BLTUL_I)
9688         likely = 1;
9689       if (imm_expr.X_add_number == 0)
9690         goto do_false;
9691       else if (imm_expr.X_add_number == 1)
9692         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9693                                  &offset_expr, op[0], ZERO);
9694       else
9695         {
9696           used_at = 1;
9697           set_at (op[0], 1);
9698           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9699                                    &offset_expr, AT, ZERO);
9700         }
9701       break;
9702
9703     case M_BLTL:
9704       likely = 1;
9705     case M_BLT:
9706       if (op[1] == 0)
9707         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9708       else if (op[0] == 0)
9709         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9710       else
9711         {
9712           used_at = 1;
9713           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9714           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9715                                    &offset_expr, AT, ZERO);
9716         }
9717       break;
9718
9719     case M_BLTUL:
9720       likely = 1;
9721     case M_BLTU:
9722       if (op[1] == 0)
9723         goto do_false;
9724       else if (op[0] == 0)
9725         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9726                                  &offset_expr, ZERO, op[1]);
9727       else
9728         {
9729           used_at = 1;
9730           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9731           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9732                                    &offset_expr, AT, ZERO);
9733         }
9734       break;
9735
9736     case M_DDIV_3:
9737       dbl = 1;
9738     case M_DIV_3:
9739       s = "mflo";
9740       goto do_div3;
9741     case M_DREM_3:
9742       dbl = 1;
9743     case M_REM_3:
9744       s = "mfhi";
9745     do_div3:
9746       if (op[2] == 0)
9747         {
9748           as_warn (_("divide by zero"));
9749           if (mips_trap)
9750             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9751           else
9752             macro_build (NULL, "break", BRK_FMT, 7);
9753           break;
9754         }
9755
9756       start_noreorder ();
9757       if (mips_trap)
9758         {
9759           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9760           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9761         }
9762       else
9763         {
9764           if (mips_opts.micromips)
9765             micromips_label_expr (&label_expr);
9766           else
9767             label_expr.X_add_number = 8;
9768           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9769           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9770           macro_build (NULL, "break", BRK_FMT, 7);
9771           if (mips_opts.micromips)
9772             micromips_add_label ();
9773         }
9774       expr1.X_add_number = -1;
9775       used_at = 1;
9776       load_register (AT, &expr1, dbl);
9777       if (mips_opts.micromips)
9778         micromips_label_expr (&label_expr);
9779       else
9780         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9781       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9782       if (dbl)
9783         {
9784           expr1.X_add_number = 1;
9785           load_register (AT, &expr1, dbl);
9786           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9787         }
9788       else
9789         {
9790           expr1.X_add_number = 0x80000000;
9791           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9792         }
9793       if (mips_trap)
9794         {
9795           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9796           /* We want to close the noreorder block as soon as possible, so
9797              that later insns are available for delay slot filling.  */
9798           end_noreorder ();
9799         }
9800       else
9801         {
9802           if (mips_opts.micromips)
9803             micromips_label_expr (&label_expr);
9804           else
9805             label_expr.X_add_number = 8;
9806           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9807           macro_build (NULL, "nop", "");
9808
9809           /* We want to close the noreorder block as soon as possible, so
9810              that later insns are available for delay slot filling.  */
9811           end_noreorder ();
9812
9813           macro_build (NULL, "break", BRK_FMT, 6);
9814         }
9815       if (mips_opts.micromips)
9816         micromips_add_label ();
9817       macro_build (NULL, s, MFHL_FMT, op[0]);
9818       break;
9819
9820     case M_DIV_3I:
9821       s = "div";
9822       s2 = "mflo";
9823       goto do_divi;
9824     case M_DIVU_3I:
9825       s = "divu";
9826       s2 = "mflo";
9827       goto do_divi;
9828     case M_REM_3I:
9829       s = "div";
9830       s2 = "mfhi";
9831       goto do_divi;
9832     case M_REMU_3I:
9833       s = "divu";
9834       s2 = "mfhi";
9835       goto do_divi;
9836     case M_DDIV_3I:
9837       dbl = 1;
9838       s = "ddiv";
9839       s2 = "mflo";
9840       goto do_divi;
9841     case M_DDIVU_3I:
9842       dbl = 1;
9843       s = "ddivu";
9844       s2 = "mflo";
9845       goto do_divi;
9846     case M_DREM_3I:
9847       dbl = 1;
9848       s = "ddiv";
9849       s2 = "mfhi";
9850       goto do_divi;
9851     case M_DREMU_3I:
9852       dbl = 1;
9853       s = "ddivu";
9854       s2 = "mfhi";
9855     do_divi:
9856       if (imm_expr.X_add_number == 0)
9857         {
9858           as_warn (_("divide by zero"));
9859           if (mips_trap)
9860             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9861           else
9862             macro_build (NULL, "break", BRK_FMT, 7);
9863           break;
9864         }
9865       if (imm_expr.X_add_number == 1)
9866         {
9867           if (strcmp (s2, "mflo") == 0)
9868             move_register (op[0], op[1]);
9869           else
9870             move_register (op[0], ZERO);
9871           break;
9872         }
9873       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9874         {
9875           if (strcmp (s2, "mflo") == 0)
9876             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9877           else
9878             move_register (op[0], ZERO);
9879           break;
9880         }
9881
9882       used_at = 1;
9883       load_register (AT, &imm_expr, dbl);
9884       macro_build (NULL, s, "z,s,t", op[1], AT);
9885       macro_build (NULL, s2, MFHL_FMT, op[0]);
9886       break;
9887
9888     case M_DIVU_3:
9889       s = "divu";
9890       s2 = "mflo";
9891       goto do_divu3;
9892     case M_REMU_3:
9893       s = "divu";
9894       s2 = "mfhi";
9895       goto do_divu3;
9896     case M_DDIVU_3:
9897       s = "ddivu";
9898       s2 = "mflo";
9899       goto do_divu3;
9900     case M_DREMU_3:
9901       s = "ddivu";
9902       s2 = "mfhi";
9903     do_divu3:
9904       start_noreorder ();
9905       if (mips_trap)
9906         {
9907           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9908           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9909           /* We want to close the noreorder block as soon as possible, so
9910              that later insns are available for delay slot filling.  */
9911           end_noreorder ();
9912         }
9913       else
9914         {
9915           if (mips_opts.micromips)
9916             micromips_label_expr (&label_expr);
9917           else
9918             label_expr.X_add_number = 8;
9919           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9920           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9921
9922           /* We want to close the noreorder block as soon as possible, so
9923              that later insns are available for delay slot filling.  */
9924           end_noreorder ();
9925           macro_build (NULL, "break", BRK_FMT, 7);
9926           if (mips_opts.micromips)
9927             micromips_add_label ();
9928         }
9929       macro_build (NULL, s2, MFHL_FMT, op[0]);
9930       break;
9931
9932     case M_DLCA_AB:
9933       dbl = 1;
9934     case M_LCA_AB:
9935       call = 1;
9936       goto do_la;
9937     case M_DLA_AB:
9938       dbl = 1;
9939     case M_LA_AB:
9940     do_la:
9941       /* Load the address of a symbol into a register.  If breg is not
9942          zero, we then add a base register to it.  */
9943
9944       breg = op[2];
9945       if (dbl && GPR_SIZE == 32)
9946         as_warn (_("dla used to load 32-bit register"));
9947
9948       if (!dbl && HAVE_64BIT_OBJECTS)
9949         as_warn (_("la used to load 64-bit address"));
9950
9951       if (small_offset_p (0, align, 16))
9952         {
9953           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9954                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9955           break;
9956         }
9957
9958       if (mips_opts.at && (op[0] == breg))
9959         {
9960           tempreg = AT;
9961           used_at = 1;
9962         }
9963       else
9964         tempreg = op[0];
9965
9966       if (offset_expr.X_op != O_symbol
9967           && offset_expr.X_op != O_constant)
9968         {
9969           as_bad (_("expression too complex"));
9970           offset_expr.X_op = O_constant;
9971         }
9972
9973       if (offset_expr.X_op == O_constant)
9974         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9975       else if (mips_pic == NO_PIC)
9976         {
9977           /* If this is a reference to a GP relative symbol, we want
9978                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9979              Otherwise we want
9980                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9981                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9982              If we have a constant, we need two instructions anyhow,
9983              so we may as well always use the latter form.
9984
9985              With 64bit address space and a usable $at we want
9986                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9987                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9988                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9989                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9990                dsll32   $tempreg,0
9991                daddu    $tempreg,$tempreg,$at
9992
9993              If $at is already in use, we use a path which is suboptimal
9994              on superscalar processors.
9995                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9996                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9997                dsll     $tempreg,16
9998                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9999                dsll     $tempreg,16
10000                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10001
10002              For GP relative symbols in 64bit address space we can use
10003              the same sequence as in 32bit address space.  */
10004           if (HAVE_64BIT_SYMBOLS)
10005             {
10006               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10007                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10008                 {
10009                   relax_start (offset_expr.X_add_symbol);
10010                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10011                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10012                   relax_switch ();
10013                 }
10014
10015               if (used_at == 0 && mips_opts.at)
10016                 {
10017                   macro_build (&offset_expr, "lui", LUI_FMT,
10018                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10019                   macro_build (&offset_expr, "lui", LUI_FMT,
10020                                AT, BFD_RELOC_HI16_S);
10021                   macro_build (&offset_expr, "daddiu", "t,r,j",
10022                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10023                   macro_build (&offset_expr, "daddiu", "t,r,j",
10024                                AT, AT, BFD_RELOC_LO16);
10025                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10026                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10027                   used_at = 1;
10028                 }
10029               else
10030                 {
10031                   macro_build (&offset_expr, "lui", LUI_FMT,
10032                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10033                   macro_build (&offset_expr, "daddiu", "t,r,j",
10034                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10035                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10036                   macro_build (&offset_expr, "daddiu", "t,r,j",
10037                                tempreg, tempreg, BFD_RELOC_HI16_S);
10038                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10039                   macro_build (&offset_expr, "daddiu", "t,r,j",
10040                                tempreg, tempreg, BFD_RELOC_LO16);
10041                 }
10042
10043               if (mips_relax.sequence)
10044                 relax_end ();
10045             }
10046           else
10047             {
10048               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10049                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10050                 {
10051                   relax_start (offset_expr.X_add_symbol);
10052                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10053                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10054                   relax_switch ();
10055                 }
10056               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10057                 as_bad (_("offset too large"));
10058               macro_build_lui (&offset_expr, tempreg);
10059               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10060                            tempreg, tempreg, BFD_RELOC_LO16);
10061               if (mips_relax.sequence)
10062                 relax_end ();
10063             }
10064         }
10065       else if (!mips_big_got && !HAVE_NEWABI)
10066         {
10067           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10068
10069           /* If this is a reference to an external symbol, and there
10070              is no constant, we want
10071                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10072              or for lca or if tempreg is PIC_CALL_REG
10073                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10074              For a local symbol, we want
10075                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10076                nop
10077                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10078
10079              If we have a small constant, and this is a reference to
10080              an external symbol, we want
10081                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10082                nop
10083                addiu    $tempreg,$tempreg,<constant>
10084              For a local symbol, we want the same instruction
10085              sequence, but we output a BFD_RELOC_LO16 reloc on the
10086              addiu instruction.
10087
10088              If we have a large constant, and this is a reference to
10089              an external symbol, we want
10090                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10091                lui      $at,<hiconstant>
10092                addiu    $at,$at,<loconstant>
10093                addu     $tempreg,$tempreg,$at
10094              For a local symbol, we want the same instruction
10095              sequence, but we output a BFD_RELOC_LO16 reloc on the
10096              addiu instruction.
10097            */
10098
10099           if (offset_expr.X_add_number == 0)
10100             {
10101               if (mips_pic == SVR4_PIC
10102                   && breg == 0
10103                   && (call || tempreg == PIC_CALL_REG))
10104                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10105
10106               relax_start (offset_expr.X_add_symbol);
10107               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10108                            lw_reloc_type, mips_gp_register);
10109               if (breg != 0)
10110                 {
10111                   /* We're going to put in an addu instruction using
10112                      tempreg, so we may as well insert the nop right
10113                      now.  */
10114                   load_delay_nop ();
10115                 }
10116               relax_switch ();
10117               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10118                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10119               load_delay_nop ();
10120               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10121                            tempreg, tempreg, BFD_RELOC_LO16);
10122               relax_end ();
10123               /* FIXME: If breg == 0, and the next instruction uses
10124                  $tempreg, then if this variant case is used an extra
10125                  nop will be generated.  */
10126             }
10127           else if (offset_expr.X_add_number >= -0x8000
10128                    && offset_expr.X_add_number < 0x8000)
10129             {
10130               load_got_offset (tempreg, &offset_expr);
10131               load_delay_nop ();
10132               add_got_offset (tempreg, &offset_expr);
10133             }
10134           else
10135             {
10136               expr1.X_add_number = offset_expr.X_add_number;
10137               offset_expr.X_add_number =
10138                 SEXT_16BIT (offset_expr.X_add_number);
10139               load_got_offset (tempreg, &offset_expr);
10140               offset_expr.X_add_number = expr1.X_add_number;
10141               /* If we are going to add in a base register, and the
10142                  target register and the base register are the same,
10143                  then we are using AT as a temporary register.  Since
10144                  we want to load the constant into AT, we add our
10145                  current AT (from the global offset table) and the
10146                  register into the register now, and pretend we were
10147                  not using a base register.  */
10148               if (breg == op[0])
10149                 {
10150                   load_delay_nop ();
10151                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10152                                op[0], AT, breg);
10153                   breg = 0;
10154                   tempreg = op[0];
10155                 }
10156               add_got_offset_hilo (tempreg, &offset_expr, AT);
10157               used_at = 1;
10158             }
10159         }
10160       else if (!mips_big_got && HAVE_NEWABI)
10161         {
10162           int add_breg_early = 0;
10163
10164           /* If this is a reference to an external, and there is no
10165              constant, or local symbol (*), with or without a
10166              constant, we want
10167                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10168              or for lca or if tempreg is PIC_CALL_REG
10169                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10170
10171              If we have a small constant, and this is a reference to
10172              an external symbol, we want
10173                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10174                addiu    $tempreg,$tempreg,<constant>
10175
10176              If we have a large constant, and this is a reference to
10177              an external symbol, we want
10178                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10179                lui      $at,<hiconstant>
10180                addiu    $at,$at,<loconstant>
10181                addu     $tempreg,$tempreg,$at
10182
10183              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10184              local symbols, even though it introduces an additional
10185              instruction.  */
10186
10187           if (offset_expr.X_add_number)
10188             {
10189               expr1.X_add_number = offset_expr.X_add_number;
10190               offset_expr.X_add_number = 0;
10191
10192               relax_start (offset_expr.X_add_symbol);
10193               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10194                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10195
10196               if (expr1.X_add_number >= -0x8000
10197                   && expr1.X_add_number < 0x8000)
10198                 {
10199                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10200                                tempreg, tempreg, BFD_RELOC_LO16);
10201                 }
10202               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10203                 {
10204                   unsigned int dreg;
10205
10206                   /* If we are going to add in a base register, and the
10207                      target register and the base register are the same,
10208                      then we are using AT as a temporary register.  Since
10209                      we want to load the constant into AT, we add our
10210                      current AT (from the global offset table) and the
10211                      register into the register now, and pretend we were
10212                      not using a base register.  */
10213                   if (breg != op[0])
10214                     dreg = tempreg;
10215                   else
10216                     {
10217                       gas_assert (tempreg == AT);
10218                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10219                                    op[0], AT, breg);
10220                       dreg = op[0];
10221                       add_breg_early = 1;
10222                     }
10223
10224                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10225                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10226                                dreg, dreg, AT);
10227
10228                   used_at = 1;
10229                 }
10230               else
10231                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10232
10233               relax_switch ();
10234               offset_expr.X_add_number = expr1.X_add_number;
10235
10236               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10237                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10238               if (add_breg_early)
10239                 {
10240                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10241                                op[0], tempreg, breg);
10242                   breg = 0;
10243                   tempreg = op[0];
10244                 }
10245               relax_end ();
10246             }
10247           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10248             {
10249               relax_start (offset_expr.X_add_symbol);
10250               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10251                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10252               relax_switch ();
10253               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10254                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10255               relax_end ();
10256             }
10257           else
10258             {
10259               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10260                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10261             }
10262         }
10263       else if (mips_big_got && !HAVE_NEWABI)
10264         {
10265           int gpdelay;
10266           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10267           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10268           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10269
10270           /* This is the large GOT case.  If this is a reference to an
10271              external symbol, and there is no constant, we want
10272                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10273                addu     $tempreg,$tempreg,$gp
10274                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10275              or for lca or if tempreg is PIC_CALL_REG
10276                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10277                addu     $tempreg,$tempreg,$gp
10278                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10279              For a local symbol, we want
10280                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10281                nop
10282                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10283
10284              If we have a small constant, and this is a reference to
10285              an external symbol, we want
10286                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10287                addu     $tempreg,$tempreg,$gp
10288                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10289                nop
10290                addiu    $tempreg,$tempreg,<constant>
10291              For a local symbol, we want
10292                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10293                nop
10294                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10295
10296              If we have a large constant, and this is a reference to
10297              an external symbol, we want
10298                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10299                addu     $tempreg,$tempreg,$gp
10300                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10301                lui      $at,<hiconstant>
10302                addiu    $at,$at,<loconstant>
10303                addu     $tempreg,$tempreg,$at
10304              For a local symbol, we want
10305                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10306                lui      $at,<hiconstant>
10307                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10308                addu     $tempreg,$tempreg,$at
10309           */
10310
10311           expr1.X_add_number = offset_expr.X_add_number;
10312           offset_expr.X_add_number = 0;
10313           relax_start (offset_expr.X_add_symbol);
10314           gpdelay = reg_needs_delay (mips_gp_register);
10315           if (expr1.X_add_number == 0 && breg == 0
10316               && (call || tempreg == PIC_CALL_REG))
10317             {
10318               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10319               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10320             }
10321           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10322           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10323                        tempreg, tempreg, mips_gp_register);
10324           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10325                        tempreg, lw_reloc_type, tempreg);
10326           if (expr1.X_add_number == 0)
10327             {
10328               if (breg != 0)
10329                 {
10330                   /* We're going to put in an addu instruction using
10331                      tempreg, so we may as well insert the nop right
10332                      now.  */
10333                   load_delay_nop ();
10334                 }
10335             }
10336           else if (expr1.X_add_number >= -0x8000
10337                    && expr1.X_add_number < 0x8000)
10338             {
10339               load_delay_nop ();
10340               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10341                            tempreg, tempreg, BFD_RELOC_LO16);
10342             }
10343           else
10344             {
10345               unsigned int dreg;
10346
10347               /* If we are going to add in a base register, and the
10348                  target register and the base register are the same,
10349                  then we are using AT as a temporary register.  Since
10350                  we want to load the constant into AT, we add our
10351                  current AT (from the global offset table) and the
10352                  register into the register now, and pretend we were
10353                  not using a base register.  */
10354               if (breg != op[0])
10355                 dreg = tempreg;
10356               else
10357                 {
10358                   gas_assert (tempreg == AT);
10359                   load_delay_nop ();
10360                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10361                                op[0], AT, breg);
10362                   dreg = op[0];
10363                 }
10364
10365               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10366               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10367
10368               used_at = 1;
10369             }
10370           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10371           relax_switch ();
10372
10373           if (gpdelay)
10374             {
10375               /* This is needed because this instruction uses $gp, but
10376                  the first instruction on the main stream does not.  */
10377               macro_build (NULL, "nop", "");
10378             }
10379
10380           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10381                        local_reloc_type, mips_gp_register);
10382           if (expr1.X_add_number >= -0x8000
10383               && expr1.X_add_number < 0x8000)
10384             {
10385               load_delay_nop ();
10386               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10387                            tempreg, tempreg, BFD_RELOC_LO16);
10388               /* FIXME: If add_number is 0, and there was no base
10389                  register, the external symbol case ended with a load,
10390                  so if the symbol turns out to not be external, and
10391                  the next instruction uses tempreg, an unnecessary nop
10392                  will be inserted.  */
10393             }
10394           else
10395             {
10396               if (breg == op[0])
10397                 {
10398                   /* We must add in the base register now, as in the
10399                      external symbol case.  */
10400                   gas_assert (tempreg == AT);
10401                   load_delay_nop ();
10402                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10403                                op[0], AT, breg);
10404                   tempreg = op[0];
10405                   /* We set breg to 0 because we have arranged to add
10406                      it in in both cases.  */
10407                   breg = 0;
10408                 }
10409
10410               macro_build_lui (&expr1, AT);
10411               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10412                            AT, AT, BFD_RELOC_LO16);
10413               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10414                            tempreg, tempreg, AT);
10415               used_at = 1;
10416             }
10417           relax_end ();
10418         }
10419       else if (mips_big_got && HAVE_NEWABI)
10420         {
10421           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10422           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10423           int add_breg_early = 0;
10424
10425           /* This is the large GOT case.  If this is a reference to an
10426              external symbol, and there is no constant, we want
10427                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10428                add      $tempreg,$tempreg,$gp
10429                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10430              or for lca or if tempreg is PIC_CALL_REG
10431                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10432                add      $tempreg,$tempreg,$gp
10433                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10434
10435              If we have a small constant, and this is a reference to
10436              an external symbol, we want
10437                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10438                add      $tempreg,$tempreg,$gp
10439                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10440                addi     $tempreg,$tempreg,<constant>
10441
10442              If we have a large constant, and this is a reference to
10443              an external symbol, we want
10444                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10445                addu     $tempreg,$tempreg,$gp
10446                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10447                lui      $at,<hiconstant>
10448                addi     $at,$at,<loconstant>
10449                add      $tempreg,$tempreg,$at
10450
10451              If we have NewABI, and we know it's a local symbol, we want
10452                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10453                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10454              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10455
10456           relax_start (offset_expr.X_add_symbol);
10457
10458           expr1.X_add_number = offset_expr.X_add_number;
10459           offset_expr.X_add_number = 0;
10460
10461           if (expr1.X_add_number == 0 && breg == 0
10462               && (call || tempreg == PIC_CALL_REG))
10463             {
10464               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10465               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10466             }
10467           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10468           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10469                        tempreg, tempreg, mips_gp_register);
10470           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10471                        tempreg, lw_reloc_type, tempreg);
10472
10473           if (expr1.X_add_number == 0)
10474             ;
10475           else if (expr1.X_add_number >= -0x8000
10476                    && expr1.X_add_number < 0x8000)
10477             {
10478               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10479                            tempreg, tempreg, BFD_RELOC_LO16);
10480             }
10481           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10482             {
10483               unsigned int dreg;
10484
10485               /* If we are going to add in a base register, and the
10486                  target register and the base register are the same,
10487                  then we are using AT as a temporary register.  Since
10488                  we want to load the constant into AT, we add our
10489                  current AT (from the global offset table) and the
10490                  register into the register now, and pretend we were
10491                  not using a base register.  */
10492               if (breg != op[0])
10493                 dreg = tempreg;
10494               else
10495                 {
10496                   gas_assert (tempreg == AT);
10497                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10498                                op[0], AT, breg);
10499                   dreg = op[0];
10500                   add_breg_early = 1;
10501                 }
10502
10503               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10504               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10505
10506               used_at = 1;
10507             }
10508           else
10509             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10510
10511           relax_switch ();
10512           offset_expr.X_add_number = expr1.X_add_number;
10513           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10514                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10515           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10516                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10517           if (add_breg_early)
10518             {
10519               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10520                            op[0], tempreg, breg);
10521               breg = 0;
10522               tempreg = op[0];
10523             }
10524           relax_end ();
10525         }
10526       else
10527         abort ();
10528
10529       if (breg != 0)
10530         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10531       break;
10532
10533     case M_MSGSND:
10534       gas_assert (!mips_opts.micromips);
10535       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10536       break;
10537
10538     case M_MSGLD:
10539       gas_assert (!mips_opts.micromips);
10540       macro_build (NULL, "c2", "C", 0x02);
10541       break;
10542
10543     case M_MSGLD_T:
10544       gas_assert (!mips_opts.micromips);
10545       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10546       break;
10547
10548     case M_MSGWAIT:
10549       gas_assert (!mips_opts.micromips);
10550       macro_build (NULL, "c2", "C", 3);
10551       break;
10552
10553     case M_MSGWAIT_T:
10554       gas_assert (!mips_opts.micromips);
10555       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10556       break;
10557
10558     case M_J_A:
10559       /* The j instruction may not be used in PIC code, since it
10560          requires an absolute address.  We convert it to a b
10561          instruction.  */
10562       if (mips_pic == NO_PIC)
10563         macro_build (&offset_expr, "j", "a");
10564       else
10565         macro_build (&offset_expr, "b", "p");
10566       break;
10567
10568       /* The jal instructions must be handled as macros because when
10569          generating PIC code they expand to multi-instruction
10570          sequences.  Normally they are simple instructions.  */
10571     case M_JALS_1:
10572       op[1] = op[0];
10573       op[0] = RA;
10574       /* Fall through.  */
10575     case M_JALS_2:
10576       gas_assert (mips_opts.micromips);
10577       if (mips_opts.insn32)
10578         {
10579           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10580           break;
10581         }
10582       jals = 1;
10583       goto jal;
10584     case M_JAL_1:
10585       op[1] = op[0];
10586       op[0] = RA;
10587       /* Fall through.  */
10588     case M_JAL_2:
10589     jal:
10590       if (mips_pic == NO_PIC)
10591         {
10592           s = jals ? "jalrs" : "jalr";
10593           if (mips_opts.micromips
10594               && !mips_opts.insn32
10595               && op[0] == RA
10596               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10597             macro_build (NULL, s, "mj", op[1]);
10598           else
10599             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10600         }
10601       else
10602         {
10603           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10604                            && mips_cprestore_offset >= 0);
10605
10606           if (op[1] != PIC_CALL_REG)
10607             as_warn (_("MIPS PIC call to register other than $25"));
10608
10609           s = ((mips_opts.micromips
10610                 && !mips_opts.insn32
10611                 && (!mips_opts.noreorder || cprestore))
10612                ? "jalrs" : "jalr");
10613           if (mips_opts.micromips
10614               && !mips_opts.insn32
10615               && op[0] == RA
10616               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10617             macro_build (NULL, s, "mj", op[1]);
10618           else
10619             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10620           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10621             {
10622               if (mips_cprestore_offset < 0)
10623                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10624               else
10625                 {
10626                   if (!mips_frame_reg_valid)
10627                     {
10628                       as_warn (_("no .frame pseudo-op used in PIC code"));
10629                       /* Quiet this warning.  */
10630                       mips_frame_reg_valid = 1;
10631                     }
10632                   if (!mips_cprestore_valid)
10633                     {
10634                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10635                       /* Quiet this warning.  */
10636                       mips_cprestore_valid = 1;
10637                     }
10638                   if (mips_opts.noreorder)
10639                     macro_build (NULL, "nop", "");
10640                   expr1.X_add_number = mips_cprestore_offset;
10641                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10642                                                 mips_gp_register,
10643                                                 mips_frame_reg,
10644                                                 HAVE_64BIT_ADDRESSES);
10645                 }
10646             }
10647         }
10648
10649       break;
10650
10651     case M_JALS_A:
10652       gas_assert (mips_opts.micromips);
10653       if (mips_opts.insn32)
10654         {
10655           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10656           break;
10657         }
10658       jals = 1;
10659       /* Fall through.  */
10660     case M_JAL_A:
10661       if (mips_pic == NO_PIC)
10662         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10663       else if (mips_pic == SVR4_PIC)
10664         {
10665           /* If this is a reference to an external symbol, and we are
10666              using a small GOT, we want
10667                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10668                nop
10669                jalr     $ra,$25
10670                nop
10671                lw       $gp,cprestore($sp)
10672              The cprestore value is set using the .cprestore
10673              pseudo-op.  If we are using a big GOT, we want
10674                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10675                addu     $25,$25,$gp
10676                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10677                nop
10678                jalr     $ra,$25
10679                nop
10680                lw       $gp,cprestore($sp)
10681              If the symbol is not external, we want
10682                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10683                nop
10684                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10685                jalr     $ra,$25
10686                nop
10687                lw $gp,cprestore($sp)
10688
10689              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10690              sequences above, minus nops, unless the symbol is local,
10691              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10692              GOT_DISP.  */
10693           if (HAVE_NEWABI)
10694             {
10695               if (!mips_big_got)
10696                 {
10697                   relax_start (offset_expr.X_add_symbol);
10698                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10699                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10700                                mips_gp_register);
10701                   relax_switch ();
10702                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10703                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10704                                mips_gp_register);
10705                   relax_end ();
10706                 }
10707               else
10708                 {
10709                   relax_start (offset_expr.X_add_symbol);
10710                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10711                                BFD_RELOC_MIPS_CALL_HI16);
10712                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10713                                PIC_CALL_REG, mips_gp_register);
10714                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10715                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10716                                PIC_CALL_REG);
10717                   relax_switch ();
10718                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10719                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10720                                mips_gp_register);
10721                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10722                                PIC_CALL_REG, PIC_CALL_REG,
10723                                BFD_RELOC_MIPS_GOT_OFST);
10724                   relax_end ();
10725                 }
10726
10727               macro_build_jalr (&offset_expr, 0);
10728             }
10729           else
10730             {
10731               relax_start (offset_expr.X_add_symbol);
10732               if (!mips_big_got)
10733                 {
10734                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10735                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10736                                mips_gp_register);
10737                   load_delay_nop ();
10738                   relax_switch ();
10739                 }
10740               else
10741                 {
10742                   int gpdelay;
10743
10744                   gpdelay = reg_needs_delay (mips_gp_register);
10745                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10746                                BFD_RELOC_MIPS_CALL_HI16);
10747                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10748                                PIC_CALL_REG, mips_gp_register);
10749                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10750                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10751                                PIC_CALL_REG);
10752                   load_delay_nop ();
10753                   relax_switch ();
10754                   if (gpdelay)
10755                     macro_build (NULL, "nop", "");
10756                 }
10757               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10758                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10759                            mips_gp_register);
10760               load_delay_nop ();
10761               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10762                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10763               relax_end ();
10764               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10765
10766               if (mips_cprestore_offset < 0)
10767                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10768               else
10769                 {
10770                   if (!mips_frame_reg_valid)
10771                     {
10772                       as_warn (_("no .frame pseudo-op used in PIC code"));
10773                       /* Quiet this warning.  */
10774                       mips_frame_reg_valid = 1;
10775                     }
10776                   if (!mips_cprestore_valid)
10777                     {
10778                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10779                       /* Quiet this warning.  */
10780                       mips_cprestore_valid = 1;
10781                     }
10782                   if (mips_opts.noreorder)
10783                     macro_build (NULL, "nop", "");
10784                   expr1.X_add_number = mips_cprestore_offset;
10785                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10786                                                 mips_gp_register,
10787                                                 mips_frame_reg,
10788                                                 HAVE_64BIT_ADDRESSES);
10789                 }
10790             }
10791         }
10792       else if (mips_pic == VXWORKS_PIC)
10793         as_bad (_("non-PIC jump used in PIC library"));
10794       else
10795         abort ();
10796
10797       break;
10798
10799     case M_LBUE_AB:
10800       s = "lbue";
10801       fmt = "t,+j(b)";
10802       offbits = 9;
10803       goto ld_st;
10804     case M_LHUE_AB:
10805       s = "lhue";
10806       fmt = "t,+j(b)";
10807       offbits = 9;
10808       goto ld_st;
10809     case M_LBE_AB:
10810       s = "lbe";
10811       fmt = "t,+j(b)";
10812       offbits = 9;
10813       goto ld_st;
10814     case M_LHE_AB:
10815       s = "lhe";
10816       fmt = "t,+j(b)";
10817       offbits = 9;
10818       goto ld_st;
10819     case M_LLE_AB:
10820       s = "lle";
10821       fmt = "t,+j(b)";
10822       offbits = 9;
10823       goto ld_st;
10824     case M_LWE_AB:
10825       s = "lwe";
10826       fmt = "t,+j(b)";
10827       offbits = 9;
10828       goto ld_st;
10829     case M_LWLE_AB:
10830       s = "lwle";
10831       fmt = "t,+j(b)";
10832       offbits = 9;
10833       goto ld_st;
10834     case M_LWRE_AB:
10835       s = "lwre";
10836       fmt = "t,+j(b)";
10837       offbits = 9;
10838       goto ld_st;
10839     case M_SBE_AB:
10840       s = "sbe";
10841       fmt = "t,+j(b)";
10842       offbits = 9;
10843       goto ld_st;
10844     case M_SCE_AB:
10845       s = "sce";
10846       fmt = "t,+j(b)";
10847       offbits = 9;
10848       goto ld_st;
10849     case M_SHE_AB:
10850       s = "she";
10851       fmt = "t,+j(b)";
10852       offbits = 9;
10853       goto ld_st;
10854     case M_SWE_AB:
10855       s = "swe";
10856       fmt = "t,+j(b)";
10857       offbits = 9;
10858       goto ld_st;
10859     case M_SWLE_AB:
10860       s = "swle";
10861       fmt = "t,+j(b)";
10862       offbits = 9;
10863       goto ld_st;
10864     case M_SWRE_AB:
10865       s = "swre";
10866       fmt = "t,+j(b)";
10867       offbits = 9;
10868       goto ld_st;
10869     case M_ACLR_AB:
10870       s = "aclr";
10871       fmt = "\\,~(b)";
10872       offbits = 12;
10873       goto ld_st;
10874     case M_ASET_AB:
10875       s = "aset";
10876       fmt = "\\,~(b)";
10877       offbits = 12;
10878       goto ld_st;
10879     case M_LB_AB:
10880       s = "lb";
10881       fmt = "t,o(b)";
10882       goto ld;
10883     case M_LBU_AB:
10884       s = "lbu";
10885       fmt = "t,o(b)";
10886       goto ld;
10887     case M_LH_AB:
10888       s = "lh";
10889       fmt = "t,o(b)";
10890       goto ld;
10891     case M_LHU_AB:
10892       s = "lhu";
10893       fmt = "t,o(b)";
10894       goto ld;
10895     case M_LW_AB:
10896       s = "lw";
10897       fmt = "t,o(b)";
10898       goto ld;
10899     case M_LWC0_AB:
10900       gas_assert (!mips_opts.micromips);
10901       s = "lwc0";
10902       fmt = "E,o(b)";
10903       /* Itbl support may require additional care here.  */
10904       coproc = 1;
10905       goto ld_st;
10906     case M_LWC1_AB:
10907       s = "lwc1";
10908       fmt = "T,o(b)";
10909       /* Itbl support may require additional care here.  */
10910       coproc = 1;
10911       goto ld_st;
10912     case M_LWC2_AB:
10913       s = "lwc2";
10914       fmt = COP12_FMT;
10915       offbits = (mips_opts.micromips ? 12 : 16);
10916       /* Itbl support may require additional care here.  */
10917       coproc = 1;
10918       goto ld_st;
10919     case M_LWC3_AB:
10920       gas_assert (!mips_opts.micromips);
10921       s = "lwc3";
10922       fmt = "E,o(b)";
10923       /* Itbl support may require additional care here.  */
10924       coproc = 1;
10925       goto ld_st;
10926     case M_LWL_AB:
10927       s = "lwl";
10928       fmt = MEM12_FMT;
10929       offbits = (mips_opts.micromips ? 12 : 16);
10930       goto ld_st;
10931     case M_LWR_AB:
10932       s = "lwr";
10933       fmt = MEM12_FMT;
10934       offbits = (mips_opts.micromips ? 12 : 16);
10935       goto ld_st;
10936     case M_LDC1_AB:
10937       s = "ldc1";
10938       fmt = "T,o(b)";
10939       /* Itbl support may require additional care here.  */
10940       coproc = 1;
10941       goto ld_st;
10942     case M_LDC2_AB:
10943       s = "ldc2";
10944       fmt = COP12_FMT;
10945       offbits = (mips_opts.micromips ? 12 : 16);
10946       /* Itbl support may require additional care here.  */
10947       coproc = 1;
10948       goto ld_st;
10949     case M_LQC2_AB:
10950       s = "lqc2";
10951       fmt = "+7,o(b)";
10952       /* Itbl support may require additional care here.  */
10953       coproc = 1;
10954       goto ld_st;
10955     case M_LDC3_AB:
10956       s = "ldc3";
10957       fmt = "E,o(b)";
10958       /* Itbl support may require additional care here.  */
10959       coproc = 1;
10960       goto ld_st;
10961     case M_LDL_AB:
10962       s = "ldl";
10963       fmt = MEM12_FMT;
10964       offbits = (mips_opts.micromips ? 12 : 16);
10965       goto ld_st;
10966     case M_LDR_AB:
10967       s = "ldr";
10968       fmt = MEM12_FMT;
10969       offbits = (mips_opts.micromips ? 12 : 16);
10970       goto ld_st;
10971     case M_LL_AB:
10972       s = "ll";
10973       fmt = MEM12_FMT;
10974       offbits = (mips_opts.micromips ? 12 : 16);
10975       goto ld;
10976     case M_LLD_AB:
10977       s = "lld";
10978       fmt = MEM12_FMT;
10979       offbits = (mips_opts.micromips ? 12 : 16);
10980       goto ld;
10981     case M_LWU_AB:
10982       s = "lwu";
10983       fmt = MEM12_FMT;
10984       offbits = (mips_opts.micromips ? 12 : 16);
10985       goto ld;
10986     case M_LWP_AB:
10987       gas_assert (mips_opts.micromips);
10988       s = "lwp";
10989       fmt = "t,~(b)";
10990       offbits = 12;
10991       lp = 1;
10992       goto ld;
10993     case M_LDP_AB:
10994       gas_assert (mips_opts.micromips);
10995       s = "ldp";
10996       fmt = "t,~(b)";
10997       offbits = 12;
10998       lp = 1;
10999       goto ld;
11000     case M_LWM_AB:
11001       gas_assert (mips_opts.micromips);
11002       s = "lwm";
11003       fmt = "n,~(b)";
11004       offbits = 12;
11005       goto ld_st;
11006     case M_LDM_AB:
11007       gas_assert (mips_opts.micromips);
11008       s = "ldm";
11009       fmt = "n,~(b)";
11010       offbits = 12;
11011       goto ld_st;
11012
11013     ld:
11014       /* We don't want to use $0 as tempreg.  */
11015       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11016         goto ld_st;
11017       else
11018         tempreg = op[0] + lp;
11019       goto ld_noat;
11020
11021     case M_SB_AB:
11022       s = "sb";
11023       fmt = "t,o(b)";
11024       goto ld_st;
11025     case M_SH_AB:
11026       s = "sh";
11027       fmt = "t,o(b)";
11028       goto ld_st;
11029     case M_SW_AB:
11030       s = "sw";
11031       fmt = "t,o(b)";
11032       goto ld_st;
11033     case M_SWC0_AB:
11034       gas_assert (!mips_opts.micromips);
11035       s = "swc0";
11036       fmt = "E,o(b)";
11037       /* Itbl support may require additional care here.  */
11038       coproc = 1;
11039       goto ld_st;
11040     case M_SWC1_AB:
11041       s = "swc1";
11042       fmt = "T,o(b)";
11043       /* Itbl support may require additional care here.  */
11044       coproc = 1;
11045       goto ld_st;
11046     case M_SWC2_AB:
11047       s = "swc2";
11048       fmt = COP12_FMT;
11049       offbits = (mips_opts.micromips ? 12 : 16);
11050       /* Itbl support may require additional care here.  */
11051       coproc = 1;
11052       goto ld_st;
11053     case M_SWC3_AB:
11054       gas_assert (!mips_opts.micromips);
11055       s = "swc3";
11056       fmt = "E,o(b)";
11057       /* Itbl support may require additional care here.  */
11058       coproc = 1;
11059       goto ld_st;
11060     case M_SWL_AB:
11061       s = "swl";
11062       fmt = MEM12_FMT;
11063       offbits = (mips_opts.micromips ? 12 : 16);
11064       goto ld_st;
11065     case M_SWR_AB:
11066       s = "swr";
11067       fmt = MEM12_FMT;
11068       offbits = (mips_opts.micromips ? 12 : 16);
11069       goto ld_st;
11070     case M_SC_AB:
11071       s = "sc";
11072       fmt = MEM12_FMT;
11073       offbits = (mips_opts.micromips ? 12 : 16);
11074       goto ld_st;
11075     case M_SCD_AB:
11076       s = "scd";
11077       fmt = MEM12_FMT;
11078       offbits = (mips_opts.micromips ? 12 : 16);
11079       goto ld_st;
11080     case M_CACHE_AB:
11081       s = "cache";
11082       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
11083       offbits = (mips_opts.micromips ? 12 : 16);
11084       goto ld_st;
11085     case M_CACHEE_AB:
11086       s = "cachee";
11087       fmt = "k,+j(b)";
11088       offbits = 9;
11089       goto ld_st;
11090     case M_PREF_AB:
11091       s = "pref";
11092       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
11093       offbits = (mips_opts.micromips ? 12 : 16);
11094       goto ld_st;
11095     case M_PREFE_AB:
11096       s = "prefe";
11097       fmt = "k,+j(b)";
11098       offbits = 9;
11099       goto ld_st;
11100     case M_SDC1_AB:
11101       s = "sdc1";
11102       fmt = "T,o(b)";
11103       coproc = 1;
11104       /* Itbl support may require additional care here.  */
11105       goto ld_st;
11106     case M_SDC2_AB:
11107       s = "sdc2";
11108       fmt = COP12_FMT;
11109       offbits = (mips_opts.micromips ? 12 : 16);
11110       /* Itbl support may require additional care here.  */
11111       coproc = 1;
11112       goto ld_st;
11113     case M_SQC2_AB:
11114       s = "sqc2";
11115       fmt = "+7,o(b)";
11116       /* Itbl support may require additional care here.  */
11117       coproc = 1;
11118       goto ld_st;
11119     case M_SDC3_AB:
11120       gas_assert (!mips_opts.micromips);
11121       s = "sdc3";
11122       fmt = "E,o(b)";
11123       /* Itbl support may require additional care here.  */
11124       coproc = 1;
11125       goto ld_st;
11126     case M_SDL_AB:
11127       s = "sdl";
11128       fmt = MEM12_FMT;
11129       offbits = (mips_opts.micromips ? 12 : 16);
11130       goto ld_st;
11131     case M_SDR_AB:
11132       s = "sdr";
11133       fmt = MEM12_FMT;
11134       offbits = (mips_opts.micromips ? 12 : 16);
11135       goto ld_st;
11136     case M_SWP_AB:
11137       gas_assert (mips_opts.micromips);
11138       s = "swp";
11139       fmt = "t,~(b)";
11140       offbits = 12;
11141       goto ld_st;
11142     case M_SDP_AB:
11143       gas_assert (mips_opts.micromips);
11144       s = "sdp";
11145       fmt = "t,~(b)";
11146       offbits = 12;
11147       goto ld_st;
11148     case M_SWM_AB:
11149       gas_assert (mips_opts.micromips);
11150       s = "swm";
11151       fmt = "n,~(b)";
11152       offbits = 12;
11153       goto ld_st;
11154     case M_SDM_AB:
11155       gas_assert (mips_opts.micromips);
11156       s = "sdm";
11157       fmt = "n,~(b)";
11158       offbits = 12;
11159
11160     ld_st:
11161       tempreg = AT;
11162     ld_noat:
11163       breg = op[2];
11164       if (small_offset_p (0, align, 16))
11165         {
11166           /* The first case exists for M_LD_AB and M_SD_AB, which are
11167              macros for o32 but which should act like normal instructions
11168              otherwise.  */
11169           if (offbits == 16)
11170             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11171                          offset_reloc[1], offset_reloc[2], breg);
11172           else if (small_offset_p (0, align, offbits))
11173             {
11174               if (offbits == 0)
11175                 macro_build (NULL, s, fmt, op[0], breg);
11176               else
11177                 macro_build (NULL, s, fmt, op[0],
11178                              (int) offset_expr.X_add_number, breg);
11179             }
11180           else
11181             {
11182               if (tempreg == AT)
11183                 used_at = 1;
11184               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11185                            tempreg, breg, -1, offset_reloc[0],
11186                            offset_reloc[1], offset_reloc[2]);
11187               if (offbits == 0)
11188                 macro_build (NULL, s, fmt, op[0], tempreg);
11189               else
11190                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11191             }
11192           break;
11193         }
11194
11195       if (tempreg == AT)
11196         used_at = 1;
11197
11198       if (offset_expr.X_op != O_constant
11199           && offset_expr.X_op != O_symbol)
11200         {
11201           as_bad (_("expression too complex"));
11202           offset_expr.X_op = O_constant;
11203         }
11204
11205       if (HAVE_32BIT_ADDRESSES
11206           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11207         {
11208           char value [32];
11209
11210           sprintf_vma (value, offset_expr.X_add_number);
11211           as_bad (_("number (0x%s) larger than 32 bits"), value);
11212         }
11213
11214       /* A constant expression in PIC code can be handled just as it
11215          is in non PIC code.  */
11216       if (offset_expr.X_op == O_constant)
11217         {
11218           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11219                                                  offbits == 0 ? 16 : offbits);
11220           offset_expr.X_add_number -= expr1.X_add_number;
11221
11222           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11223           if (breg != 0)
11224             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11225                          tempreg, tempreg, breg);
11226           if (offbits == 0)
11227             {
11228               if (offset_expr.X_add_number != 0)
11229                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11230                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11231               macro_build (NULL, s, fmt, op[0], tempreg);
11232             }
11233           else if (offbits == 16)
11234             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11235           else
11236             macro_build (NULL, s, fmt, op[0],
11237                          (int) offset_expr.X_add_number, tempreg);
11238         }
11239       else if (offbits != 16)
11240         {
11241           /* The offset field is too narrow to be used for a low-part
11242              relocation, so load the whole address into the auxillary
11243              register.  */
11244           load_address (tempreg, &offset_expr, &used_at);
11245           if (breg != 0)
11246             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11247                          tempreg, tempreg, breg);
11248           if (offbits == 0)
11249             macro_build (NULL, s, fmt, op[0], tempreg);
11250           else
11251             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11252         }
11253       else if (mips_pic == NO_PIC)
11254         {
11255           /* If this is a reference to a GP relative symbol, and there
11256              is no base register, we want
11257                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11258              Otherwise, if there is no base register, we want
11259                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11260                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11261              If we have a constant, we need two instructions anyhow,
11262              so we always use the latter form.
11263
11264              If we have a base register, and this is a reference to a
11265              GP relative symbol, we want
11266                addu     $tempreg,$breg,$gp
11267                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11268              Otherwise we want
11269                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11270                addu     $tempreg,$tempreg,$breg
11271                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11272              With a constant we always use the latter case.
11273
11274              With 64bit address space and no base register and $at usable,
11275              we want
11276                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11277                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11278                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11279                dsll32   $tempreg,0
11280                daddu    $tempreg,$at
11281                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11282              If we have a base register, we want
11283                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11284                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11285                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11286                daddu    $at,$breg
11287                dsll32   $tempreg,0
11288                daddu    $tempreg,$at
11289                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11290
11291              Without $at we can't generate the optimal path for superscalar
11292              processors here since this would require two temporary registers.
11293                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11294                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11295                dsll     $tempreg,16
11296                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11297                dsll     $tempreg,16
11298                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11299              If we have a base register, we want
11300                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11301                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11302                dsll     $tempreg,16
11303                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11304                dsll     $tempreg,16
11305                daddu    $tempreg,$tempreg,$breg
11306                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11307
11308              For GP relative symbols in 64bit address space we can use
11309              the same sequence as in 32bit address space.  */
11310           if (HAVE_64BIT_SYMBOLS)
11311             {
11312               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11313                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11314                 {
11315                   relax_start (offset_expr.X_add_symbol);
11316                   if (breg == 0)
11317                     {
11318                       macro_build (&offset_expr, s, fmt, op[0],
11319                                    BFD_RELOC_GPREL16, mips_gp_register);
11320                     }
11321                   else
11322                     {
11323                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11324                                    tempreg, breg, mips_gp_register);
11325                       macro_build (&offset_expr, s, fmt, op[0],
11326                                    BFD_RELOC_GPREL16, tempreg);
11327                     }
11328                   relax_switch ();
11329                 }
11330
11331               if (used_at == 0 && mips_opts.at)
11332                 {
11333                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11334                                BFD_RELOC_MIPS_HIGHEST);
11335                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11336                                BFD_RELOC_HI16_S);
11337                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11338                                tempreg, BFD_RELOC_MIPS_HIGHER);
11339                   if (breg != 0)
11340                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11341                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11342                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11343                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11344                                tempreg);
11345                   used_at = 1;
11346                 }
11347               else
11348                 {
11349                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11350                                BFD_RELOC_MIPS_HIGHEST);
11351                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11352                                tempreg, BFD_RELOC_MIPS_HIGHER);
11353                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11354                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11355                                tempreg, BFD_RELOC_HI16_S);
11356                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11357                   if (breg != 0)
11358                     macro_build (NULL, "daddu", "d,v,t",
11359                                  tempreg, tempreg, breg);
11360                   macro_build (&offset_expr, s, fmt, op[0],
11361                                BFD_RELOC_LO16, tempreg);
11362                 }
11363
11364               if (mips_relax.sequence)
11365                 relax_end ();
11366               break;
11367             }
11368
11369           if (breg == 0)
11370             {
11371               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11372                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11373                 {
11374                   relax_start (offset_expr.X_add_symbol);
11375                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11376                                mips_gp_register);
11377                   relax_switch ();
11378                 }
11379               macro_build_lui (&offset_expr, tempreg);
11380               macro_build (&offset_expr, s, fmt, op[0],
11381                            BFD_RELOC_LO16, tempreg);
11382               if (mips_relax.sequence)
11383                 relax_end ();
11384             }
11385           else
11386             {
11387               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11388                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11389                 {
11390                   relax_start (offset_expr.X_add_symbol);
11391                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11392                                tempreg, breg, mips_gp_register);
11393                   macro_build (&offset_expr, s, fmt, op[0],
11394                                BFD_RELOC_GPREL16, tempreg);
11395                   relax_switch ();
11396                 }
11397               macro_build_lui (&offset_expr, tempreg);
11398               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11399                            tempreg, tempreg, breg);
11400               macro_build (&offset_expr, s, fmt, op[0],
11401                            BFD_RELOC_LO16, tempreg);
11402               if (mips_relax.sequence)
11403                 relax_end ();
11404             }
11405         }
11406       else if (!mips_big_got)
11407         {
11408           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11409
11410           /* If this is a reference to an external symbol, we want
11411                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11412                nop
11413                <op>     op[0],0($tempreg)
11414              Otherwise we want
11415                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11416                nop
11417                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11418                <op>     op[0],0($tempreg)
11419
11420              For NewABI, we want
11421                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11422                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11423
11424              If there is a base register, we add it to $tempreg before
11425              the <op>.  If there is a constant, we stick it in the
11426              <op> instruction.  We don't handle constants larger than
11427              16 bits, because we have no way to load the upper 16 bits
11428              (actually, we could handle them for the subset of cases
11429              in which we are not using $at).  */
11430           gas_assert (offset_expr.X_op == O_symbol);
11431           if (HAVE_NEWABI)
11432             {
11433               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11434                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11435               if (breg != 0)
11436                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11437                              tempreg, tempreg, breg);
11438               macro_build (&offset_expr, s, fmt, op[0],
11439                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11440               break;
11441             }
11442           expr1.X_add_number = offset_expr.X_add_number;
11443           offset_expr.X_add_number = 0;
11444           if (expr1.X_add_number < -0x8000
11445               || expr1.X_add_number >= 0x8000)
11446             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11447           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11448                        lw_reloc_type, mips_gp_register);
11449           load_delay_nop ();
11450           relax_start (offset_expr.X_add_symbol);
11451           relax_switch ();
11452           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11453                        tempreg, BFD_RELOC_LO16);
11454           relax_end ();
11455           if (breg != 0)
11456             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11457                          tempreg, tempreg, breg);
11458           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11459         }
11460       else if (mips_big_got && !HAVE_NEWABI)
11461         {
11462           int gpdelay;
11463
11464           /* If this is a reference to an external symbol, we want
11465                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11466                addu     $tempreg,$tempreg,$gp
11467                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11468                <op>     op[0],0($tempreg)
11469              Otherwise we want
11470                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11471                nop
11472                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11473                <op>     op[0],0($tempreg)
11474              If there is a base register, we add it to $tempreg before
11475              the <op>.  If there is a constant, we stick it in the
11476              <op> instruction.  We don't handle constants larger than
11477              16 bits, because we have no way to load the upper 16 bits
11478              (actually, we could handle them for the subset of cases
11479              in which we are not using $at).  */
11480           gas_assert (offset_expr.X_op == O_symbol);
11481           expr1.X_add_number = offset_expr.X_add_number;
11482           offset_expr.X_add_number = 0;
11483           if (expr1.X_add_number < -0x8000
11484               || expr1.X_add_number >= 0x8000)
11485             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11486           gpdelay = reg_needs_delay (mips_gp_register);
11487           relax_start (offset_expr.X_add_symbol);
11488           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11489                        BFD_RELOC_MIPS_GOT_HI16);
11490           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11491                        mips_gp_register);
11492           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11493                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11494           relax_switch ();
11495           if (gpdelay)
11496             macro_build (NULL, "nop", "");
11497           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11498                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11499           load_delay_nop ();
11500           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11501                        tempreg, BFD_RELOC_LO16);
11502           relax_end ();
11503
11504           if (breg != 0)
11505             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11506                          tempreg, tempreg, breg);
11507           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11508         }
11509       else if (mips_big_got && HAVE_NEWABI)
11510         {
11511           /* If this is a reference to an external symbol, we want
11512                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11513                add      $tempreg,$tempreg,$gp
11514                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11515                <op>     op[0],<ofst>($tempreg)
11516              Otherwise, for local symbols, we want:
11517                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11518                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11519           gas_assert (offset_expr.X_op == O_symbol);
11520           expr1.X_add_number = offset_expr.X_add_number;
11521           offset_expr.X_add_number = 0;
11522           if (expr1.X_add_number < -0x8000
11523               || expr1.X_add_number >= 0x8000)
11524             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11525           relax_start (offset_expr.X_add_symbol);
11526           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11527                        BFD_RELOC_MIPS_GOT_HI16);
11528           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11529                        mips_gp_register);
11530           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11531                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11532           if (breg != 0)
11533             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11534                          tempreg, tempreg, breg);
11535           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11536
11537           relax_switch ();
11538           offset_expr.X_add_number = expr1.X_add_number;
11539           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11540                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11541           if (breg != 0)
11542             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11543                          tempreg, tempreg, breg);
11544           macro_build (&offset_expr, s, fmt, op[0],
11545                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11546           relax_end ();
11547         }
11548       else
11549         abort ();
11550
11551       break;
11552
11553     case M_JRADDIUSP:
11554       gas_assert (mips_opts.micromips);
11555       gas_assert (mips_opts.insn32);
11556       start_noreorder ();
11557       macro_build (NULL, "jr", "s", RA);
11558       expr1.X_add_number = op[0] << 2;
11559       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11560       end_noreorder ();
11561       break;
11562
11563     case M_JRC:
11564       gas_assert (mips_opts.micromips);
11565       gas_assert (mips_opts.insn32);
11566       macro_build (NULL, "jr", "s", op[0]);
11567       if (mips_opts.noreorder)
11568         macro_build (NULL, "nop", "");
11569       break;
11570
11571     case M_LI:
11572     case M_LI_S:
11573       load_register (op[0], &imm_expr, 0);
11574       break;
11575
11576     case M_DLI:
11577       load_register (op[0], &imm_expr, 1);
11578       break;
11579
11580     case M_LI_SS:
11581       if (imm_expr.X_op == O_constant)
11582         {
11583           used_at = 1;
11584           load_register (AT, &imm_expr, 0);
11585           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11586           break;
11587         }
11588       else
11589         {
11590           gas_assert (imm_expr.X_op == O_absent
11591                       && offset_expr.X_op == O_symbol
11592                       && strcmp (segment_name (S_GET_SEGMENT
11593                                                (offset_expr.X_add_symbol)),
11594                                  ".lit4") == 0
11595                       && offset_expr.X_add_number == 0);
11596           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11597                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11598           break;
11599         }
11600
11601     case M_LI_D:
11602       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11603          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11604          order 32 bits of the value and the low order 32 bits are either
11605          zero or in OFFSET_EXPR.  */
11606       if (imm_expr.X_op == O_constant)
11607         {
11608           if (GPR_SIZE == 64)
11609             load_register (op[0], &imm_expr, 1);
11610           else
11611             {
11612               int hreg, lreg;
11613
11614               if (target_big_endian)
11615                 {
11616                   hreg = op[0];
11617                   lreg = op[0] + 1;
11618                 }
11619               else
11620                 {
11621                   hreg = op[0] + 1;
11622                   lreg = op[0];
11623                 }
11624
11625               if (hreg <= 31)
11626                 load_register (hreg, &imm_expr, 0);
11627               if (lreg <= 31)
11628                 {
11629                   if (offset_expr.X_op == O_absent)
11630                     move_register (lreg, 0);
11631                   else
11632                     {
11633                       gas_assert (offset_expr.X_op == O_constant);
11634                       load_register (lreg, &offset_expr, 0);
11635                     }
11636                 }
11637             }
11638           break;
11639         }
11640       gas_assert (imm_expr.X_op == O_absent);
11641
11642       /* We know that sym is in the .rdata section.  First we get the
11643          upper 16 bits of the address.  */
11644       if (mips_pic == NO_PIC)
11645         {
11646           macro_build_lui (&offset_expr, AT);
11647           used_at = 1;
11648         }
11649       else
11650         {
11651           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11652                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11653           used_at = 1;
11654         }
11655
11656       /* Now we load the register(s).  */
11657       if (GPR_SIZE == 64)
11658         {
11659           used_at = 1;
11660           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11661                        BFD_RELOC_LO16, AT);
11662         }
11663       else
11664         {
11665           used_at = 1;
11666           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11667                        BFD_RELOC_LO16, AT);
11668           if (op[0] != RA)
11669             {
11670               /* FIXME: How in the world do we deal with the possible
11671                  overflow here?  */
11672               offset_expr.X_add_number += 4;
11673               macro_build (&offset_expr, "lw", "t,o(b)",
11674                            op[0] + 1, BFD_RELOC_LO16, AT);
11675             }
11676         }
11677       break;
11678
11679     case M_LI_DD:
11680       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11681          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11682          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11683          the value and the low order 32 bits are either zero or in
11684          OFFSET_EXPR.  */
11685       if (imm_expr.X_op == O_constant)
11686         {
11687           used_at = 1;
11688           load_register (AT, &imm_expr, FPR_SIZE == 64);
11689           if (FPR_SIZE == 64)
11690             {
11691               gas_assert (GPR_SIZE == 64);
11692               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11693             }
11694           else
11695             {
11696               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11697               if (offset_expr.X_op == O_absent)
11698                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11699               else
11700                 {
11701                   gas_assert (offset_expr.X_op == O_constant);
11702                   load_register (AT, &offset_expr, 0);
11703                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11704                 }
11705             }
11706           break;
11707         }
11708
11709       gas_assert (imm_expr.X_op == O_absent
11710                   && offset_expr.X_op == O_symbol
11711                   && offset_expr.X_add_number == 0);
11712       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11713       if (strcmp (s, ".lit8") == 0)
11714         {
11715           op[2] = mips_gp_register;
11716           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11717           offset_reloc[1] = BFD_RELOC_UNUSED;
11718           offset_reloc[2] = BFD_RELOC_UNUSED;
11719         }
11720       else
11721         {
11722           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11723           used_at = 1;
11724           if (mips_pic != NO_PIC)
11725             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11726                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11727           else
11728             {
11729               /* FIXME: This won't work for a 64 bit address.  */
11730               macro_build_lui (&offset_expr, AT);
11731             }
11732
11733           op[2] = AT;
11734           offset_reloc[0] = BFD_RELOC_LO16;
11735           offset_reloc[1] = BFD_RELOC_UNUSED;
11736           offset_reloc[2] = BFD_RELOC_UNUSED;
11737         }
11738       align = 8;
11739       /* Fall through */
11740
11741     case M_L_DAB:
11742       /*
11743        * The MIPS assembler seems to check for X_add_number not
11744        * being double aligned and generating:
11745        *        lui     at,%hi(foo+1)
11746        *        addu    at,at,v1
11747        *        addiu   at,at,%lo(foo+1)
11748        *        lwc1    f2,0(at)
11749        *        lwc1    f3,4(at)
11750        * But, the resulting address is the same after relocation so why
11751        * generate the extra instruction?
11752        */
11753       /* Itbl support may require additional care here.  */
11754       coproc = 1;
11755       fmt = "T,o(b)";
11756       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11757         {
11758           s = "ldc1";
11759           goto ld_st;
11760         }
11761       s = "lwc1";
11762       goto ldd_std;
11763
11764     case M_S_DAB:
11765       gas_assert (!mips_opts.micromips);
11766       /* Itbl support may require additional care here.  */
11767       coproc = 1;
11768       fmt = "T,o(b)";
11769       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11770         {
11771           s = "sdc1";
11772           goto ld_st;
11773         }
11774       s = "swc1";
11775       goto ldd_std;
11776
11777     case M_LQ_AB:
11778       fmt = "t,o(b)";
11779       s = "lq";
11780       goto ld;
11781
11782     case M_SQ_AB:
11783       fmt = "t,o(b)";
11784       s = "sq";
11785       goto ld_st;
11786
11787     case M_LD_AB:
11788       fmt = "t,o(b)";
11789       if (GPR_SIZE == 64)
11790         {
11791           s = "ld";
11792           goto ld;
11793         }
11794       s = "lw";
11795       goto ldd_std;
11796
11797     case M_SD_AB:
11798       fmt = "t,o(b)";
11799       if (GPR_SIZE == 64)
11800         {
11801           s = "sd";
11802           goto ld_st;
11803         }
11804       s = "sw";
11805
11806     ldd_std:
11807       /* Even on a big endian machine $fn comes before $fn+1.  We have
11808          to adjust when loading from memory.  We set coproc if we must
11809          load $fn+1 first.  */
11810       /* Itbl support may require additional care here.  */
11811       if (!target_big_endian)
11812         coproc = 0;
11813
11814       breg = op[2];
11815       if (small_offset_p (0, align, 16))
11816         {
11817           ep = &offset_expr;
11818           if (!small_offset_p (4, align, 16))
11819             {
11820               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11821                            -1, offset_reloc[0], offset_reloc[1],
11822                            offset_reloc[2]);
11823               expr1.X_add_number = 0;
11824               ep = &expr1;
11825               breg = AT;
11826               used_at = 1;
11827               offset_reloc[0] = BFD_RELOC_LO16;
11828               offset_reloc[1] = BFD_RELOC_UNUSED;
11829               offset_reloc[2] = BFD_RELOC_UNUSED;
11830             }
11831           if (strcmp (s, "lw") == 0 && op[0] == breg)
11832             {
11833               ep->X_add_number += 4;
11834               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11835                            offset_reloc[1], offset_reloc[2], breg);
11836               ep->X_add_number -= 4;
11837               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11838                            offset_reloc[1], offset_reloc[2], breg);
11839             }
11840           else
11841             {
11842               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11843                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11844                            breg);
11845               ep->X_add_number += 4;
11846               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11847                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11848                            breg);
11849             }
11850           break;
11851         }
11852
11853       if (offset_expr.X_op != O_symbol
11854           && offset_expr.X_op != O_constant)
11855         {
11856           as_bad (_("expression too complex"));
11857           offset_expr.X_op = O_constant;
11858         }
11859
11860       if (HAVE_32BIT_ADDRESSES
11861           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11862         {
11863           char value [32];
11864
11865           sprintf_vma (value, offset_expr.X_add_number);
11866           as_bad (_("number (0x%s) larger than 32 bits"), value);
11867         }
11868
11869       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11870         {
11871           /* If this is a reference to a GP relative symbol, we want
11872                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11873                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11874              If we have a base register, we use this
11875                addu     $at,$breg,$gp
11876                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11877                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11878              If this is not a GP relative symbol, we want
11879                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11880                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11881                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11882              If there is a base register, we add it to $at after the
11883              lui instruction.  If there is a constant, we always use
11884              the last case.  */
11885           if (offset_expr.X_op == O_symbol
11886               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11887               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11888             {
11889               relax_start (offset_expr.X_add_symbol);
11890               if (breg == 0)
11891                 {
11892                   tempreg = mips_gp_register;
11893                 }
11894               else
11895                 {
11896                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11897                                AT, breg, mips_gp_register);
11898                   tempreg = AT;
11899                   used_at = 1;
11900                 }
11901
11902               /* Itbl support may require additional care here.  */
11903               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11904                            BFD_RELOC_GPREL16, tempreg);
11905               offset_expr.X_add_number += 4;
11906
11907               /* Set mips_optimize to 2 to avoid inserting an
11908                  undesired nop.  */
11909               hold_mips_optimize = mips_optimize;
11910               mips_optimize = 2;
11911               /* Itbl support may require additional care here.  */
11912               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11913                            BFD_RELOC_GPREL16, tempreg);
11914               mips_optimize = hold_mips_optimize;
11915
11916               relax_switch ();
11917
11918               offset_expr.X_add_number -= 4;
11919             }
11920           used_at = 1;
11921           if (offset_high_part (offset_expr.X_add_number, 16)
11922               != offset_high_part (offset_expr.X_add_number + 4, 16))
11923             {
11924               load_address (AT, &offset_expr, &used_at);
11925               offset_expr.X_op = O_constant;
11926               offset_expr.X_add_number = 0;
11927             }
11928           else
11929             macro_build_lui (&offset_expr, AT);
11930           if (breg != 0)
11931             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11932           /* Itbl support may require additional care here.  */
11933           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11934                        BFD_RELOC_LO16, AT);
11935           /* FIXME: How do we handle overflow here?  */
11936           offset_expr.X_add_number += 4;
11937           /* Itbl support may require additional care here.  */
11938           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11939                        BFD_RELOC_LO16, AT);
11940           if (mips_relax.sequence)
11941             relax_end ();
11942         }
11943       else if (!mips_big_got)
11944         {
11945           /* If this is a reference to an external symbol, we want
11946                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11947                nop
11948                <op>     op[0],0($at)
11949                <op>     op[0]+1,4($at)
11950              Otherwise we want
11951                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11952                nop
11953                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11954                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11955              If there is a base register we add it to $at before the
11956              lwc1 instructions.  If there is a constant we include it
11957              in the lwc1 instructions.  */
11958           used_at = 1;
11959           expr1.X_add_number = offset_expr.X_add_number;
11960           if (expr1.X_add_number < -0x8000
11961               || expr1.X_add_number >= 0x8000 - 4)
11962             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11963           load_got_offset (AT, &offset_expr);
11964           load_delay_nop ();
11965           if (breg != 0)
11966             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11967
11968           /* Set mips_optimize to 2 to avoid inserting an undesired
11969              nop.  */
11970           hold_mips_optimize = mips_optimize;
11971           mips_optimize = 2;
11972
11973           /* Itbl support may require additional care here.  */
11974           relax_start (offset_expr.X_add_symbol);
11975           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11976                        BFD_RELOC_LO16, AT);
11977           expr1.X_add_number += 4;
11978           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11979                        BFD_RELOC_LO16, AT);
11980           relax_switch ();
11981           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11982                        BFD_RELOC_LO16, AT);
11983           offset_expr.X_add_number += 4;
11984           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11985                        BFD_RELOC_LO16, AT);
11986           relax_end ();
11987
11988           mips_optimize = hold_mips_optimize;
11989         }
11990       else if (mips_big_got)
11991         {
11992           int gpdelay;
11993
11994           /* If this is a reference to an external symbol, we want
11995                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11996                addu     $at,$at,$gp
11997                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11998                nop
11999                <op>     op[0],0($at)
12000                <op>     op[0]+1,4($at)
12001              Otherwise we want
12002                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12003                nop
12004                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12005                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12006              If there is a base register we add it to $at before the
12007              lwc1 instructions.  If there is a constant we include it
12008              in the lwc1 instructions.  */
12009           used_at = 1;
12010           expr1.X_add_number = offset_expr.X_add_number;
12011           offset_expr.X_add_number = 0;
12012           if (expr1.X_add_number < -0x8000
12013               || expr1.X_add_number >= 0x8000 - 4)
12014             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12015           gpdelay = reg_needs_delay (mips_gp_register);
12016           relax_start (offset_expr.X_add_symbol);
12017           macro_build (&offset_expr, "lui", LUI_FMT,
12018                        AT, BFD_RELOC_MIPS_GOT_HI16);
12019           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12020                        AT, AT, mips_gp_register);
12021           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12022                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12023           load_delay_nop ();
12024           if (breg != 0)
12025             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12026           /* Itbl support may require additional care here.  */
12027           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12028                        BFD_RELOC_LO16, AT);
12029           expr1.X_add_number += 4;
12030
12031           /* Set mips_optimize to 2 to avoid inserting an undesired
12032              nop.  */
12033           hold_mips_optimize = mips_optimize;
12034           mips_optimize = 2;
12035           /* Itbl support may require additional care here.  */
12036           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12037                        BFD_RELOC_LO16, AT);
12038           mips_optimize = hold_mips_optimize;
12039           expr1.X_add_number -= 4;
12040
12041           relax_switch ();
12042           offset_expr.X_add_number = expr1.X_add_number;
12043           if (gpdelay)
12044             macro_build (NULL, "nop", "");
12045           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12046                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12047           load_delay_nop ();
12048           if (breg != 0)
12049             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12050           /* Itbl support may require additional care here.  */
12051           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12052                        BFD_RELOC_LO16, AT);
12053           offset_expr.X_add_number += 4;
12054
12055           /* Set mips_optimize to 2 to avoid inserting an undesired
12056              nop.  */
12057           hold_mips_optimize = mips_optimize;
12058           mips_optimize = 2;
12059           /* Itbl support may require additional care here.  */
12060           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12061                        BFD_RELOC_LO16, AT);
12062           mips_optimize = hold_mips_optimize;
12063           relax_end ();
12064         }
12065       else
12066         abort ();
12067
12068       break;
12069         
12070     case M_SAA_AB:
12071       s = "saa";
12072       offbits = 0;
12073       fmt = "t,(b)";
12074       goto ld_st;
12075     case M_SAAD_AB:
12076       s = "saad";
12077       offbits = 0;
12078       fmt = "t,(b)";
12079       goto ld_st;
12080
12081    /* New code added to support COPZ instructions.
12082       This code builds table entries out of the macros in mip_opcodes.
12083       R4000 uses interlocks to handle coproc delays.
12084       Other chips (like the R3000) require nops to be inserted for delays.
12085
12086       FIXME: Currently, we require that the user handle delays.
12087       In order to fill delay slots for non-interlocked chips,
12088       we must have a way to specify delays based on the coprocessor.
12089       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12090       What are the side-effects of the cop instruction?
12091       What cache support might we have and what are its effects?
12092       Both coprocessor & memory require delays. how long???
12093       What registers are read/set/modified?
12094
12095       If an itbl is provided to interpret cop instructions,
12096       this knowledge can be encoded in the itbl spec.  */
12097
12098     case M_COP0:
12099       s = "c0";
12100       goto copz;
12101     case M_COP1:
12102       s = "c1";
12103       goto copz;
12104     case M_COP2:
12105       s = "c2";
12106       goto copz;
12107     case M_COP3:
12108       s = "c3";
12109     copz:
12110       gas_assert (!mips_opts.micromips);
12111       /* For now we just do C (same as Cz).  The parameter will be
12112          stored in insn_opcode by mips_ip.  */
12113       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12114       break;
12115
12116     case M_MOVE:
12117       move_register (op[0], op[1]);
12118       break;
12119
12120     case M_MOVEP:
12121       gas_assert (mips_opts.micromips);
12122       gas_assert (mips_opts.insn32);
12123       move_register (micromips_to_32_reg_h_map1[op[0]],
12124                      micromips_to_32_reg_m_map[op[1]]);
12125       move_register (micromips_to_32_reg_h_map2[op[0]],
12126                      micromips_to_32_reg_n_map[op[2]]);
12127       break;
12128
12129     case M_DMUL:
12130       dbl = 1;
12131     case M_MUL:
12132       if (mips_opts.arch == CPU_R5900)
12133         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12134                      op[2]);
12135       else
12136         {
12137           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12138           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12139         }
12140       break;
12141
12142     case M_DMUL_I:
12143       dbl = 1;
12144     case M_MUL_I:
12145       /* The MIPS assembler some times generates shifts and adds.  I'm
12146          not trying to be that fancy. GCC should do this for us
12147          anyway.  */
12148       used_at = 1;
12149       load_register (AT, &imm_expr, dbl);
12150       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12151       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12152       break;
12153
12154     case M_DMULO_I:
12155       dbl = 1;
12156     case M_MULO_I:
12157       imm = 1;
12158       goto do_mulo;
12159
12160     case M_DMULO:
12161       dbl = 1;
12162     case M_MULO:
12163     do_mulo:
12164       start_noreorder ();
12165       used_at = 1;
12166       if (imm)
12167         load_register (AT, &imm_expr, dbl);
12168       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12169                    op[1], imm ? AT : op[2]);
12170       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12171       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12172       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12173       if (mips_trap)
12174         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12175       else
12176         {
12177           if (mips_opts.micromips)
12178             micromips_label_expr (&label_expr);
12179           else
12180             label_expr.X_add_number = 8;
12181           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12182           macro_build (NULL, "nop", "");
12183           macro_build (NULL, "break", BRK_FMT, 6);
12184           if (mips_opts.micromips)
12185             micromips_add_label ();
12186         }
12187       end_noreorder ();
12188       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12189       break;
12190
12191     case M_DMULOU_I:
12192       dbl = 1;
12193     case M_MULOU_I:
12194       imm = 1;
12195       goto do_mulou;
12196
12197     case M_DMULOU:
12198       dbl = 1;
12199     case M_MULOU:
12200     do_mulou:
12201       start_noreorder ();
12202       used_at = 1;
12203       if (imm)
12204         load_register (AT, &imm_expr, dbl);
12205       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12206                    op[1], imm ? AT : op[2]);
12207       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12208       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12209       if (mips_trap)
12210         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12211       else
12212         {
12213           if (mips_opts.micromips)
12214             micromips_label_expr (&label_expr);
12215           else
12216             label_expr.X_add_number = 8;
12217           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12218           macro_build (NULL, "nop", "");
12219           macro_build (NULL, "break", BRK_FMT, 6);
12220           if (mips_opts.micromips)
12221             micromips_add_label ();
12222         }
12223       end_noreorder ();
12224       break;
12225
12226     case M_DROL:
12227       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12228         {
12229           if (op[0] == op[1])
12230             {
12231               tempreg = AT;
12232               used_at = 1;
12233             }
12234           else
12235             tempreg = op[0];
12236           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12237           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12238           break;
12239         }
12240       used_at = 1;
12241       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12242       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12243       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12244       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12245       break;
12246
12247     case M_ROL:
12248       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12249         {
12250           if (op[0] == op[1])
12251             {
12252               tempreg = AT;
12253               used_at = 1;
12254             }
12255           else
12256             tempreg = op[0];
12257           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12258           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12259           break;
12260         }
12261       used_at = 1;
12262       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12263       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12264       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12265       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12266       break;
12267
12268     case M_DROL_I:
12269       {
12270         unsigned int rot;
12271         char *l;
12272         char *rr;
12273
12274         rot = imm_expr.X_add_number & 0x3f;
12275         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12276           {
12277             rot = (64 - rot) & 0x3f;
12278             if (rot >= 32)
12279               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12280             else
12281               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12282             break;
12283           }
12284         if (rot == 0)
12285           {
12286             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12287             break;
12288           }
12289         l = (rot < 0x20) ? "dsll" : "dsll32";
12290         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12291         rot &= 0x1f;
12292         used_at = 1;
12293         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12294         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12295         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12296       }
12297       break;
12298
12299     case M_ROL_I:
12300       {
12301         unsigned int rot;
12302
12303         rot = imm_expr.X_add_number & 0x1f;
12304         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12305           {
12306             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12307                          (32 - rot) & 0x1f);
12308             break;
12309           }
12310         if (rot == 0)
12311           {
12312             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12313             break;
12314           }
12315         used_at = 1;
12316         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12317         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12318         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12319       }
12320       break;
12321
12322     case M_DROR:
12323       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12324         {
12325           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12326           break;
12327         }
12328       used_at = 1;
12329       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12330       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12331       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12332       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12333       break;
12334
12335     case M_ROR:
12336       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12337         {
12338           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12339           break;
12340         }
12341       used_at = 1;
12342       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12343       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12344       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12345       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12346       break;
12347
12348     case M_DROR_I:
12349       {
12350         unsigned int rot;
12351         char *l;
12352         char *rr;
12353
12354         rot = imm_expr.X_add_number & 0x3f;
12355         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12356           {
12357             if (rot >= 32)
12358               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12359             else
12360               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12361             break;
12362           }
12363         if (rot == 0)
12364           {
12365             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12366             break;
12367           }
12368         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12369         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12370         rot &= 0x1f;
12371         used_at = 1;
12372         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12373         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12374         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12375       }
12376       break;
12377
12378     case M_ROR_I:
12379       {
12380         unsigned int rot;
12381
12382         rot = imm_expr.X_add_number & 0x1f;
12383         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12384           {
12385             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12386             break;
12387           }
12388         if (rot == 0)
12389           {
12390             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12391             break;
12392           }
12393         used_at = 1;
12394         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12395         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12396         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12397       }
12398       break;
12399
12400     case M_SEQ:
12401       if (op[1] == 0)
12402         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12403       else if (op[2] == 0)
12404         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12405       else
12406         {
12407           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12408           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12409         }
12410       break;
12411
12412     case M_SEQ_I:
12413       if (imm_expr.X_add_number == 0)
12414         {
12415           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12416           break;
12417         }
12418       if (op[1] == 0)
12419         {
12420           as_warn (_("instruction %s: result is always false"),
12421                    ip->insn_mo->name);
12422           move_register (op[0], 0);
12423           break;
12424         }
12425       if (CPU_HAS_SEQ (mips_opts.arch)
12426           && -512 <= imm_expr.X_add_number
12427           && imm_expr.X_add_number < 512)
12428         {
12429           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12430                        (int) imm_expr.X_add_number);
12431           break;
12432         }
12433       if (imm_expr.X_add_number >= 0
12434           && imm_expr.X_add_number < 0x10000)
12435         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12436       else if (imm_expr.X_add_number > -0x8000
12437                && imm_expr.X_add_number < 0)
12438         {
12439           imm_expr.X_add_number = -imm_expr.X_add_number;
12440           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
12441                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12442         }
12443       else if (CPU_HAS_SEQ (mips_opts.arch))
12444         {
12445           used_at = 1;
12446           load_register (AT, &imm_expr, GPR_SIZE == 64);
12447           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12448           break;
12449         }
12450       else
12451         {
12452           load_register (AT, &imm_expr, GPR_SIZE == 64);
12453           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12454           used_at = 1;
12455         }
12456       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12457       break;
12458
12459     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12460       s = "slt";
12461       goto sge;
12462     case M_SGEU:
12463       s = "sltu";
12464     sge:
12465       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12466       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12467       break;
12468
12469     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12470     case M_SGEU_I:
12471       if (imm_expr.X_add_number >= -0x8000
12472           && imm_expr.X_add_number < 0x8000)
12473         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12474                      op[0], op[1], BFD_RELOC_LO16);
12475       else
12476         {
12477           load_register (AT, &imm_expr, GPR_SIZE == 64);
12478           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12479                        op[0], op[1], AT);
12480           used_at = 1;
12481         }
12482       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12483       break;
12484
12485     case M_SGT:         /* X > Y  <==>  Y < X */
12486       s = "slt";
12487       goto sgt;
12488     case M_SGTU:
12489       s = "sltu";
12490     sgt:
12491       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12492       break;
12493
12494     case M_SGT_I:       /* X > I  <==>  I < X */
12495       s = "slt";
12496       goto sgti;
12497     case M_SGTU_I:
12498       s = "sltu";
12499     sgti:
12500       used_at = 1;
12501       load_register (AT, &imm_expr, GPR_SIZE == 64);
12502       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12503       break;
12504
12505     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12506       s = "slt";
12507       goto sle;
12508     case M_SLEU:
12509       s = "sltu";
12510     sle:
12511       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12512       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12513       break;
12514
12515     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12516       s = "slt";
12517       goto slei;
12518     case M_SLEU_I:
12519       s = "sltu";
12520     slei:
12521       used_at = 1;
12522       load_register (AT, &imm_expr, GPR_SIZE == 64);
12523       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12524       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12525       break;
12526
12527     case M_SLT_I:
12528       if (imm_expr.X_add_number >= -0x8000
12529           && imm_expr.X_add_number < 0x8000)
12530         {
12531           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12532                        BFD_RELOC_LO16);
12533           break;
12534         }
12535       used_at = 1;
12536       load_register (AT, &imm_expr, GPR_SIZE == 64);
12537       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12538       break;
12539
12540     case M_SLTU_I:
12541       if (imm_expr.X_add_number >= -0x8000
12542           && imm_expr.X_add_number < 0x8000)
12543         {
12544           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12545                        BFD_RELOC_LO16);
12546           break;
12547         }
12548       used_at = 1;
12549       load_register (AT, &imm_expr, GPR_SIZE == 64);
12550       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12551       break;
12552
12553     case M_SNE:
12554       if (op[1] == 0)
12555         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12556       else if (op[2] == 0)
12557         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12558       else
12559         {
12560           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12561           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12562         }
12563       break;
12564
12565     case M_SNE_I:
12566       if (imm_expr.X_add_number == 0)
12567         {
12568           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12569           break;
12570         }
12571       if (op[1] == 0)
12572         {
12573           as_warn (_("instruction %s: result is always true"),
12574                    ip->insn_mo->name);
12575           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
12576                        op[0], 0, BFD_RELOC_LO16);
12577           break;
12578         }
12579       if (CPU_HAS_SEQ (mips_opts.arch)
12580           && -512 <= imm_expr.X_add_number
12581           && imm_expr.X_add_number < 512)
12582         {
12583           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12584                        (int) imm_expr.X_add_number);
12585           break;
12586         }
12587       if (imm_expr.X_add_number >= 0
12588           && imm_expr.X_add_number < 0x10000)
12589         {
12590           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12591                        BFD_RELOC_LO16);
12592         }
12593       else if (imm_expr.X_add_number > -0x8000
12594                && imm_expr.X_add_number < 0)
12595         {
12596           imm_expr.X_add_number = -imm_expr.X_add_number;
12597           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
12598                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12599         }
12600       else if (CPU_HAS_SEQ (mips_opts.arch))
12601         {
12602           used_at = 1;
12603           load_register (AT, &imm_expr, GPR_SIZE == 64);
12604           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12605           break;
12606         }
12607       else
12608         {
12609           load_register (AT, &imm_expr, GPR_SIZE == 64);
12610           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12611           used_at = 1;
12612         }
12613       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12614       break;
12615
12616     case M_SUB_I:
12617       s = "addi";
12618       s2 = "sub";
12619       goto do_subi;
12620     case M_SUBU_I:
12621       s = "addiu";
12622       s2 = "subu";
12623       goto do_subi;
12624     case M_DSUB_I:
12625       dbl = 1;
12626       s = "daddi";
12627       s2 = "dsub";
12628       if (!mips_opts.micromips)
12629         goto do_subi;
12630       if (imm_expr.X_add_number > -0x200
12631           && imm_expr.X_add_number <= 0x200)
12632         {
12633           macro_build (NULL, s, "t,r,.", op[0], op[1],
12634                        (int) -imm_expr.X_add_number);
12635           break;
12636         }
12637       goto do_subi_i;
12638     case M_DSUBU_I:
12639       dbl = 1;
12640       s = "daddiu";
12641       s2 = "dsubu";
12642     do_subi:
12643       if (imm_expr.X_add_number > -0x8000
12644           && imm_expr.X_add_number <= 0x8000)
12645         {
12646           imm_expr.X_add_number = -imm_expr.X_add_number;
12647           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12648           break;
12649         }
12650     do_subi_i:
12651       used_at = 1;
12652       load_register (AT, &imm_expr, dbl);
12653       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12654       break;
12655
12656     case M_TEQ_I:
12657       s = "teq";
12658       goto trap;
12659     case M_TGE_I:
12660       s = "tge";
12661       goto trap;
12662     case M_TGEU_I:
12663       s = "tgeu";
12664       goto trap;
12665     case M_TLT_I:
12666       s = "tlt";
12667       goto trap;
12668     case M_TLTU_I:
12669       s = "tltu";
12670       goto trap;
12671     case M_TNE_I:
12672       s = "tne";
12673     trap:
12674       used_at = 1;
12675       load_register (AT, &imm_expr, GPR_SIZE == 64);
12676       macro_build (NULL, s, "s,t", op[0], AT);
12677       break;
12678
12679     case M_TRUNCWS:
12680     case M_TRUNCWD:
12681       gas_assert (!mips_opts.micromips);
12682       gas_assert (mips_opts.isa == ISA_MIPS1);
12683       used_at = 1;
12684
12685       /*
12686        * Is the double cfc1 instruction a bug in the mips assembler;
12687        * or is there a reason for it?
12688        */
12689       start_noreorder ();
12690       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12691       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12692       macro_build (NULL, "nop", "");
12693       expr1.X_add_number = 3;
12694       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12695       expr1.X_add_number = 2;
12696       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12697       macro_build (NULL, "ctc1", "t,G", AT, RA);
12698       macro_build (NULL, "nop", "");
12699       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12700                    op[0], op[1]);
12701       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12702       macro_build (NULL, "nop", "");
12703       end_noreorder ();
12704       break;
12705
12706     case M_ULH_AB:
12707       s = "lb";
12708       s2 = "lbu";
12709       off = 1;
12710       goto uld_st;
12711     case M_ULHU_AB:
12712       s = "lbu";
12713       s2 = "lbu";
12714       off = 1;
12715       goto uld_st;
12716     case M_ULW_AB:
12717       s = "lwl";
12718       s2 = "lwr";
12719       offbits = (mips_opts.micromips ? 12 : 16);
12720       off = 3;
12721       goto uld_st;
12722     case M_ULD_AB:
12723       s = "ldl";
12724       s2 = "ldr";
12725       offbits = (mips_opts.micromips ? 12 : 16);
12726       off = 7;
12727       goto uld_st;
12728     case M_USH_AB:
12729       s = "sb";
12730       s2 = "sb";
12731       off = 1;
12732       ust = 1;
12733       goto uld_st;
12734     case M_USW_AB:
12735       s = "swl";
12736       s2 = "swr";
12737       offbits = (mips_opts.micromips ? 12 : 16);
12738       off = 3;
12739       ust = 1;
12740       goto uld_st;
12741     case M_USD_AB:
12742       s = "sdl";
12743       s2 = "sdr";
12744       offbits = (mips_opts.micromips ? 12 : 16);
12745       off = 7;
12746       ust = 1;
12747
12748     uld_st:
12749       breg = op[2];
12750       large_offset = !small_offset_p (off, align, offbits);
12751       ep = &offset_expr;
12752       expr1.X_add_number = 0;
12753       if (large_offset)
12754         {
12755           used_at = 1;
12756           tempreg = AT;
12757           if (small_offset_p (0, align, 16))
12758             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12759                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12760           else
12761             {
12762               load_address (tempreg, ep, &used_at);
12763               if (breg != 0)
12764                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12765                              tempreg, tempreg, breg);
12766             }
12767           offset_reloc[0] = BFD_RELOC_LO16;
12768           offset_reloc[1] = BFD_RELOC_UNUSED;
12769           offset_reloc[2] = BFD_RELOC_UNUSED;
12770           breg = tempreg;
12771           tempreg = op[0];
12772           ep = &expr1;
12773         }
12774       else if (!ust && op[0] == breg)
12775         {
12776           used_at = 1;
12777           tempreg = AT;
12778         }
12779       else
12780         tempreg = op[0];
12781
12782       if (off == 1)
12783         goto ulh_sh;
12784
12785       if (!target_big_endian)
12786         ep->X_add_number += off;
12787       if (offbits == 12)
12788         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12789       else
12790         macro_build (ep, s, "t,o(b)", tempreg, -1,
12791                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12792
12793       if (!target_big_endian)
12794         ep->X_add_number -= off;
12795       else
12796         ep->X_add_number += off;
12797       if (offbits == 12)
12798         macro_build (NULL, s2, "t,~(b)",
12799                      tempreg, (int) ep->X_add_number, breg);
12800       else
12801         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12802                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12803
12804       /* If necessary, move the result in tempreg to the final destination.  */
12805       if (!ust && op[0] != tempreg)
12806         {
12807           /* Protect second load's delay slot.  */
12808           load_delay_nop ();
12809           move_register (op[0], tempreg);
12810         }
12811       break;
12812
12813     ulh_sh:
12814       used_at = 1;
12815       if (target_big_endian == ust)
12816         ep->X_add_number += off;
12817       tempreg = ust || large_offset ? op[0] : AT;
12818       macro_build (ep, s, "t,o(b)", tempreg, -1,
12819                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12820
12821       /* For halfword transfers we need a temporary register to shuffle
12822          bytes.  Unfortunately for M_USH_A we have none available before
12823          the next store as AT holds the base address.  We deal with this
12824          case by clobbering TREG and then restoring it as with ULH.  */
12825       tempreg = ust == large_offset ? op[0] : AT;
12826       if (ust)
12827         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12828
12829       if (target_big_endian == ust)
12830         ep->X_add_number -= off;
12831       else
12832         ep->X_add_number += off;
12833       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12834                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12835
12836       /* For M_USH_A re-retrieve the LSB.  */
12837       if (ust && large_offset)
12838         {
12839           if (target_big_endian)
12840             ep->X_add_number += off;
12841           else
12842             ep->X_add_number -= off;
12843           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12844                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12845         }
12846       /* For ULH and M_USH_A OR the LSB in.  */
12847       if (!ust || large_offset)
12848         {
12849           tempreg = !large_offset ? AT : op[0];
12850           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12851           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12852         }
12853       break;
12854
12855     default:
12856       /* FIXME: Check if this is one of the itbl macros, since they
12857          are added dynamically.  */
12858       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12859       break;
12860     }
12861   if (!mips_opts.at && used_at)
12862     as_bad (_("macro used $at after \".set noat\""));
12863 }
12864
12865 /* Implement macros in mips16 mode.  */
12866
12867 static void
12868 mips16_macro (struct mips_cl_insn *ip)
12869 {
12870   const struct mips_operand_array *operands;
12871   int mask;
12872   int tmp;
12873   expressionS expr1;
12874   int dbl;
12875   const char *s, *s2, *s3;
12876   unsigned int op[MAX_OPERANDS];
12877   unsigned int i;
12878
12879   mask = ip->insn_mo->mask;
12880
12881   operands = insn_operands (ip);
12882   for (i = 0; i < MAX_OPERANDS; i++)
12883     if (operands->operand[i])
12884       op[i] = insn_extract_operand (ip, operands->operand[i]);
12885     else
12886       op[i] = -1;
12887
12888   expr1.X_op = O_constant;
12889   expr1.X_op_symbol = NULL;
12890   expr1.X_add_symbol = NULL;
12891   expr1.X_add_number = 1;
12892
12893   dbl = 0;
12894
12895   switch (mask)
12896     {
12897     default:
12898       abort ();
12899
12900     case M_DDIV_3:
12901       dbl = 1;
12902     case M_DIV_3:
12903       s = "mflo";
12904       goto do_div3;
12905     case M_DREM_3:
12906       dbl = 1;
12907     case M_REM_3:
12908       s = "mfhi";
12909     do_div3:
12910       start_noreorder ();
12911       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12912       expr1.X_add_number = 2;
12913       macro_build (&expr1, "bnez", "x,p", op[2]);
12914       macro_build (NULL, "break", "6", 7);
12915
12916       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12917          since that causes an overflow.  We should do that as well,
12918          but I don't see how to do the comparisons without a temporary
12919          register.  */
12920       end_noreorder ();
12921       macro_build (NULL, s, "x", op[0]);
12922       break;
12923
12924     case M_DIVU_3:
12925       s = "divu";
12926       s2 = "mflo";
12927       goto do_divu3;
12928     case M_REMU_3:
12929       s = "divu";
12930       s2 = "mfhi";
12931       goto do_divu3;
12932     case M_DDIVU_3:
12933       s = "ddivu";
12934       s2 = "mflo";
12935       goto do_divu3;
12936     case M_DREMU_3:
12937       s = "ddivu";
12938       s2 = "mfhi";
12939     do_divu3:
12940       start_noreorder ();
12941       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12942       expr1.X_add_number = 2;
12943       macro_build (&expr1, "bnez", "x,p", op[2]);
12944       macro_build (NULL, "break", "6", 7);
12945       end_noreorder ();
12946       macro_build (NULL, s2, "x", op[0]);
12947       break;
12948
12949     case M_DMUL:
12950       dbl = 1;
12951     case M_MUL:
12952       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12953       macro_build (NULL, "mflo", "x", op[0]);
12954       break;
12955
12956     case M_DSUBU_I:
12957       dbl = 1;
12958       goto do_subu;
12959     case M_SUBU_I:
12960     do_subu:
12961       imm_expr.X_add_number = -imm_expr.X_add_number;
12962       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12963       break;
12964
12965     case M_SUBU_I_2:
12966       imm_expr.X_add_number = -imm_expr.X_add_number;
12967       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12968       break;
12969
12970     case M_DSUBU_I_2:
12971       imm_expr.X_add_number = -imm_expr.X_add_number;
12972       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12973       break;
12974
12975     case M_BEQ:
12976       s = "cmp";
12977       s2 = "bteqz";
12978       goto do_branch;
12979     case M_BNE:
12980       s = "cmp";
12981       s2 = "btnez";
12982       goto do_branch;
12983     case M_BLT:
12984       s = "slt";
12985       s2 = "btnez";
12986       goto do_branch;
12987     case M_BLTU:
12988       s = "sltu";
12989       s2 = "btnez";
12990       goto do_branch;
12991     case M_BLE:
12992       s = "slt";
12993       s2 = "bteqz";
12994       goto do_reverse_branch;
12995     case M_BLEU:
12996       s = "sltu";
12997       s2 = "bteqz";
12998       goto do_reverse_branch;
12999     case M_BGE:
13000       s = "slt";
13001       s2 = "bteqz";
13002       goto do_branch;
13003     case M_BGEU:
13004       s = "sltu";
13005       s2 = "bteqz";
13006       goto do_branch;
13007     case M_BGT:
13008       s = "slt";
13009       s2 = "btnez";
13010       goto do_reverse_branch;
13011     case M_BGTU:
13012       s = "sltu";
13013       s2 = "btnez";
13014
13015     do_reverse_branch:
13016       tmp = op[1];
13017       op[1] = op[0];
13018       op[0] = tmp;
13019
13020     do_branch:
13021       macro_build (NULL, s, "x,y", op[0], op[1]);
13022       macro_build (&offset_expr, s2, "p");
13023       break;
13024
13025     case M_BEQ_I:
13026       s = "cmpi";
13027       s2 = "bteqz";
13028       s3 = "x,U";
13029       goto do_branch_i;
13030     case M_BNE_I:
13031       s = "cmpi";
13032       s2 = "btnez";
13033       s3 = "x,U";
13034       goto do_branch_i;
13035     case M_BLT_I:
13036       s = "slti";
13037       s2 = "btnez";
13038       s3 = "x,8";
13039       goto do_branch_i;
13040     case M_BLTU_I:
13041       s = "sltiu";
13042       s2 = "btnez";
13043       s3 = "x,8";
13044       goto do_branch_i;
13045     case M_BLE_I:
13046       s = "slti";
13047       s2 = "btnez";
13048       s3 = "x,8";
13049       goto do_addone_branch_i;
13050     case M_BLEU_I:
13051       s = "sltiu";
13052       s2 = "btnez";
13053       s3 = "x,8";
13054       goto do_addone_branch_i;
13055     case M_BGE_I:
13056       s = "slti";
13057       s2 = "bteqz";
13058       s3 = "x,8";
13059       goto do_branch_i;
13060     case M_BGEU_I:
13061       s = "sltiu";
13062       s2 = "bteqz";
13063       s3 = "x,8";
13064       goto do_branch_i;
13065     case M_BGT_I:
13066       s = "slti";
13067       s2 = "bteqz";
13068       s3 = "x,8";
13069       goto do_addone_branch_i;
13070     case M_BGTU_I:
13071       s = "sltiu";
13072       s2 = "bteqz";
13073       s3 = "x,8";
13074
13075     do_addone_branch_i:
13076       ++imm_expr.X_add_number;
13077
13078     do_branch_i:
13079       macro_build (&imm_expr, s, s3, op[0]);
13080       macro_build (&offset_expr, s2, "p");
13081       break;
13082
13083     case M_ABS:
13084       expr1.X_add_number = 0;
13085       macro_build (&expr1, "slti", "x,8", op[1]);
13086       if (op[0] != op[1])
13087         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13088       expr1.X_add_number = 2;
13089       macro_build (&expr1, "bteqz", "p");
13090       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13091       break;
13092     }
13093 }
13094
13095 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13096    opcode bits in *OPCODE_EXTRA.  */
13097
13098 static struct mips_opcode *
13099 mips_lookup_insn (struct hash_control *hash, const char *start,
13100                   ssize_t length, unsigned int *opcode_extra)
13101 {
13102   char *name, *dot, *p;
13103   unsigned int mask, suffix;
13104   ssize_t opend;
13105   struct mips_opcode *insn;
13106
13107   /* Make a copy of the instruction so that we can fiddle with it.  */
13108   name = alloca (length + 1);
13109   memcpy (name, start, length);
13110   name[length] = '\0';
13111
13112   /* Look up the instruction as-is.  */
13113   insn = (struct mips_opcode *) hash_find (hash, name);
13114   if (insn)
13115     return insn;
13116
13117   dot = strchr (name, '.');
13118   if (dot && dot[1])
13119     {
13120       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13121       p = mips_parse_vu0_channels (dot + 1, &mask);
13122       if (*p == 0 && mask != 0)
13123         {
13124           *dot = 0;
13125           insn = (struct mips_opcode *) hash_find (hash, name);
13126           *dot = '.';
13127           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13128             {
13129               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13130               return insn;
13131             }
13132         }
13133     }
13134
13135   if (mips_opts.micromips)
13136     {
13137       /* See if there's an instruction size override suffix,
13138          either `16' or `32', at the end of the mnemonic proper,
13139          that defines the operation, i.e. before the first `.'
13140          character if any.  Strip it and retry.  */
13141       opend = dot != NULL ? dot - name : length;
13142       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13143         suffix = 2;
13144       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13145         suffix = 4;
13146       else
13147         suffix = 0;
13148       if (suffix)
13149         {
13150           memcpy (name + opend - 2, name + opend, length - opend + 1);
13151           insn = (struct mips_opcode *) hash_find (hash, name);
13152           if (insn)
13153             {
13154               forced_insn_length = suffix;
13155               return insn;
13156             }
13157         }
13158     }
13159
13160   return NULL;
13161 }
13162
13163 /* Assemble an instruction into its binary format.  If the instruction
13164    is a macro, set imm_expr and offset_expr to the values associated
13165    with "I" and "A" operands respectively.  Otherwise store the value
13166    of the relocatable field (if any) in offset_expr.  In both cases
13167    set offset_reloc to the relocation operators applied to offset_expr.  */
13168
13169 static void
13170 mips_ip (char *str, struct mips_cl_insn *insn)
13171 {
13172   const struct mips_opcode *first, *past;
13173   struct hash_control *hash;
13174   char format;
13175   size_t end;
13176   struct mips_operand_token *tokens;
13177   unsigned int opcode_extra;
13178
13179   if (mips_opts.micromips)
13180     {
13181       hash = micromips_op_hash;
13182       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13183     }
13184   else
13185     {
13186       hash = op_hash;
13187       past = &mips_opcodes[NUMOPCODES];
13188     }
13189   forced_insn_length = 0;
13190   opcode_extra = 0;
13191
13192   /* We first try to match an instruction up to a space or to the end.  */
13193   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13194     continue;
13195
13196   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13197   if (first == NULL)
13198     {
13199       set_insn_error (0, _("unrecognized opcode"));
13200       return;
13201     }
13202
13203   if (strcmp (first->name, "li.s") == 0)
13204     format = 'f';
13205   else if (strcmp (first->name, "li.d") == 0)
13206     format = 'd';
13207   else
13208     format = 0;
13209   tokens = mips_parse_arguments (str + end, format);
13210   if (!tokens)
13211     return;
13212
13213   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13214       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13215     set_insn_error (0, _("invalid operands"));
13216
13217   obstack_free (&mips_operand_tokens, tokens);
13218 }
13219
13220 /* As for mips_ip, but used when assembling MIPS16 code.
13221    Also set forced_insn_length to the resulting instruction size in
13222    bytes if the user explicitly requested a small or extended instruction.  */
13223
13224 static void
13225 mips16_ip (char *str, struct mips_cl_insn *insn)
13226 {
13227   char *end, *s, c;
13228   struct mips_opcode *first;
13229   struct mips_operand_token *tokens;
13230
13231   forced_insn_length = 0;
13232
13233   for (s = str; ISLOWER (*s); ++s)
13234     ;
13235   end = s;
13236   c = *end;
13237   switch (c)
13238     {
13239     case '\0':
13240       break;
13241
13242     case ' ':
13243       s++;
13244       break;
13245
13246     case '.':
13247       if (s[1] == 't' && s[2] == ' ')
13248         {
13249           forced_insn_length = 2;
13250           s += 3;
13251           break;
13252         }
13253       else if (s[1] == 'e' && s[2] == ' ')
13254         {
13255           forced_insn_length = 4;
13256           s += 3;
13257           break;
13258         }
13259       /* Fall through.  */
13260     default:
13261       set_insn_error (0, _("unrecognized opcode"));
13262       return;
13263     }
13264
13265   if (mips_opts.noautoextend && !forced_insn_length)
13266     forced_insn_length = 2;
13267
13268   *end = 0;
13269   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13270   *end = c;
13271
13272   if (!first)
13273     {
13274       set_insn_error (0, _("unrecognized opcode"));
13275       return;
13276     }
13277
13278   tokens = mips_parse_arguments (s, 0);
13279   if (!tokens)
13280     return;
13281
13282   if (!match_mips16_insns (insn, first, tokens))
13283     set_insn_error (0, _("invalid operands"));
13284
13285   obstack_free (&mips_operand_tokens, tokens);
13286 }
13287
13288 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13289    NBITS is the number of significant bits in VAL.  */
13290
13291 static unsigned long
13292 mips16_immed_extend (offsetT val, unsigned int nbits)
13293 {
13294   int extval;
13295   if (nbits == 16)
13296     {
13297       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13298       val &= 0x1f;
13299     }
13300   else if (nbits == 15)
13301     {
13302       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13303       val &= 0xf;
13304     }
13305   else
13306     {
13307       extval = ((val & 0x1f) << 6) | (val & 0x20);
13308       val = 0;
13309     }
13310   return (extval << 16) | val;
13311 }
13312
13313 /* Like decode_mips16_operand, but require the operand to be defined and
13314    require it to be an integer.  */
13315
13316 static const struct mips_int_operand *
13317 mips16_immed_operand (int type, bfd_boolean extended_p)
13318 {
13319   const struct mips_operand *operand;
13320
13321   operand = decode_mips16_operand (type, extended_p);
13322   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13323     abort ();
13324   return (const struct mips_int_operand *) operand;
13325 }
13326
13327 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13328
13329 static bfd_boolean
13330 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13331                          bfd_reloc_code_real_type reloc, offsetT sval)
13332 {
13333   int min_val, max_val;
13334
13335   min_val = mips_int_operand_min (operand);
13336   max_val = mips_int_operand_max (operand);
13337   if (reloc != BFD_RELOC_UNUSED)
13338     {
13339       if (min_val < 0)
13340         sval = SEXT_16BIT (sval);
13341       else
13342         sval &= 0xffff;
13343     }
13344
13345   return (sval >= min_val
13346           && sval <= max_val
13347           && (sval & ((1 << operand->shift) - 1)) == 0);
13348 }
13349
13350 /* Install immediate value VAL into MIPS16 instruction *INSN,
13351    extending it if necessary.  The instruction in *INSN may
13352    already be extended.
13353
13354    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13355    if none.  In the former case, VAL is a 16-bit number with no
13356    defined signedness.
13357
13358    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13359    is the length that the user requested, or 0 if none.  */
13360
13361 static void
13362 mips16_immed (char *file, unsigned int line, int type,
13363               bfd_reloc_code_real_type reloc, offsetT val,
13364               unsigned int user_insn_length, unsigned long *insn)
13365 {
13366   const struct mips_int_operand *operand;
13367   unsigned int uval, length;
13368
13369   operand = mips16_immed_operand (type, FALSE);
13370   if (!mips16_immed_in_range_p (operand, reloc, val))
13371     {
13372       /* We need an extended instruction.  */
13373       if (user_insn_length == 2)
13374         as_bad_where (file, line, _("invalid unextended operand value"));
13375       else
13376         *insn |= MIPS16_EXTEND;
13377     }
13378   else if (user_insn_length == 4)
13379     {
13380       /* The operand doesn't force an unextended instruction to be extended.
13381          Warn if the user wanted an extended instruction anyway.  */
13382       *insn |= MIPS16_EXTEND;
13383       as_warn_where (file, line,
13384                      _("extended operand requested but not required"));
13385     }
13386
13387   length = mips16_opcode_length (*insn);
13388   if (length == 4)
13389     {
13390       operand = mips16_immed_operand (type, TRUE);
13391       if (!mips16_immed_in_range_p (operand, reloc, val))
13392         as_bad_where (file, line,
13393                       _("operand value out of range for instruction"));
13394     }
13395   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13396   if (length == 2)
13397     *insn = mips_insert_operand (&operand->root, *insn, uval);
13398   else
13399     *insn |= mips16_immed_extend (uval, operand->root.size);
13400 }
13401 \f
13402 struct percent_op_match
13403 {
13404   const char *str;
13405   bfd_reloc_code_real_type reloc;
13406 };
13407
13408 static const struct percent_op_match mips_percent_op[] =
13409 {
13410   {"%lo", BFD_RELOC_LO16},
13411   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13412   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13413   {"%call16", BFD_RELOC_MIPS_CALL16},
13414   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13415   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13416   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13417   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13418   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13419   {"%got", BFD_RELOC_MIPS_GOT16},
13420   {"%gp_rel", BFD_RELOC_GPREL16},
13421   {"%half", BFD_RELOC_16},
13422   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13423   {"%higher", BFD_RELOC_MIPS_HIGHER},
13424   {"%neg", BFD_RELOC_MIPS_SUB},
13425   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13426   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13427   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13428   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13429   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13430   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13431   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13432   {"%hi", BFD_RELOC_HI16_S}
13433 };
13434
13435 static const struct percent_op_match mips16_percent_op[] =
13436 {
13437   {"%lo", BFD_RELOC_MIPS16_LO16},
13438   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13439   {"%got", BFD_RELOC_MIPS16_GOT16},
13440   {"%call16", BFD_RELOC_MIPS16_CALL16},
13441   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13442   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13443   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13444   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13445   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13446   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13447   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13448   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13449 };
13450
13451
13452 /* Return true if *STR points to a relocation operator.  When returning true,
13453    move *STR over the operator and store its relocation code in *RELOC.
13454    Leave both *STR and *RELOC alone when returning false.  */
13455
13456 static bfd_boolean
13457 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13458 {
13459   const struct percent_op_match *percent_op;
13460   size_t limit, i;
13461
13462   if (mips_opts.mips16)
13463     {
13464       percent_op = mips16_percent_op;
13465       limit = ARRAY_SIZE (mips16_percent_op);
13466     }
13467   else
13468     {
13469       percent_op = mips_percent_op;
13470       limit = ARRAY_SIZE (mips_percent_op);
13471     }
13472
13473   for (i = 0; i < limit; i++)
13474     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13475       {
13476         int len = strlen (percent_op[i].str);
13477
13478         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13479           continue;
13480
13481         *str += strlen (percent_op[i].str);
13482         *reloc = percent_op[i].reloc;
13483
13484         /* Check whether the output BFD supports this relocation.
13485            If not, issue an error and fall back on something safe.  */
13486         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13487           {
13488             as_bad (_("relocation %s isn't supported by the current ABI"),
13489                     percent_op[i].str);
13490             *reloc = BFD_RELOC_UNUSED;
13491           }
13492         return TRUE;
13493       }
13494   return FALSE;
13495 }
13496
13497
13498 /* Parse string STR as a 16-bit relocatable operand.  Store the
13499    expression in *EP and the relocations in the array starting
13500    at RELOC.  Return the number of relocation operators used.
13501
13502    On exit, EXPR_END points to the first character after the expression.  */
13503
13504 static size_t
13505 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13506                        char *str)
13507 {
13508   bfd_reloc_code_real_type reversed_reloc[3];
13509   size_t reloc_index, i;
13510   int crux_depth, str_depth;
13511   char *crux;
13512
13513   /* Search for the start of the main expression, recoding relocations
13514      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13515      of the main expression and with CRUX_DEPTH containing the number
13516      of open brackets at that point.  */
13517   reloc_index = -1;
13518   str_depth = 0;
13519   do
13520     {
13521       reloc_index++;
13522       crux = str;
13523       crux_depth = str_depth;
13524
13525       /* Skip over whitespace and brackets, keeping count of the number
13526          of brackets.  */
13527       while (*str == ' ' || *str == '\t' || *str == '(')
13528         if (*str++ == '(')
13529           str_depth++;
13530     }
13531   while (*str == '%'
13532          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13533          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13534
13535   my_getExpression (ep, crux);
13536   str = expr_end;
13537
13538   /* Match every open bracket.  */
13539   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13540     if (*str++ == ')')
13541       crux_depth--;
13542
13543   if (crux_depth > 0)
13544     as_bad (_("unclosed '('"));
13545
13546   expr_end = str;
13547
13548   if (reloc_index != 0)
13549     {
13550       prev_reloc_op_frag = frag_now;
13551       for (i = 0; i < reloc_index; i++)
13552         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13553     }
13554
13555   return reloc_index;
13556 }
13557
13558 static void
13559 my_getExpression (expressionS *ep, char *str)
13560 {
13561   char *save_in;
13562
13563   save_in = input_line_pointer;
13564   input_line_pointer = str;
13565   expression (ep);
13566   expr_end = input_line_pointer;
13567   input_line_pointer = save_in;
13568 }
13569
13570 char *
13571 md_atof (int type, char *litP, int *sizeP)
13572 {
13573   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13574 }
13575
13576 void
13577 md_number_to_chars (char *buf, valueT val, int n)
13578 {
13579   if (target_big_endian)
13580     number_to_chars_bigendian (buf, val, n);
13581   else
13582     number_to_chars_littleendian (buf, val, n);
13583 }
13584 \f
13585 static int support_64bit_objects(void)
13586 {
13587   const char **list, **l;
13588   int yes;
13589
13590   list = bfd_target_list ();
13591   for (l = list; *l != NULL; l++)
13592     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13593         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13594       break;
13595   yes = (*l != NULL);
13596   free (list);
13597   return yes;
13598 }
13599
13600 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13601    NEW_VALUE.  Warn if another value was already specified.  Note:
13602    we have to defer parsing the -march and -mtune arguments in order
13603    to handle 'from-abi' correctly, since the ABI might be specified
13604    in a later argument.  */
13605
13606 static void
13607 mips_set_option_string (const char **string_ptr, const char *new_value)
13608 {
13609   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13610     as_warn (_("a different %s was already specified, is now %s"),
13611              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13612              new_value);
13613
13614   *string_ptr = new_value;
13615 }
13616
13617 int
13618 md_parse_option (int c, char *arg)
13619 {
13620   unsigned int i;
13621
13622   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13623     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13624       {
13625         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
13626                                            c == mips_ases[i].option_on);
13627         return 1;
13628       }
13629
13630   switch (c)
13631     {
13632     case OPTION_CONSTRUCT_FLOATS:
13633       mips_disable_float_construction = 0;
13634       break;
13635
13636     case OPTION_NO_CONSTRUCT_FLOATS:
13637       mips_disable_float_construction = 1;
13638       break;
13639
13640     case OPTION_TRAP:
13641       mips_trap = 1;
13642       break;
13643
13644     case OPTION_BREAK:
13645       mips_trap = 0;
13646       break;
13647
13648     case OPTION_EB:
13649       target_big_endian = 1;
13650       break;
13651
13652     case OPTION_EL:
13653       target_big_endian = 0;
13654       break;
13655
13656     case 'O':
13657       if (arg == NULL)
13658         mips_optimize = 1;
13659       else if (arg[0] == '0')
13660         mips_optimize = 0;
13661       else if (arg[0] == '1')
13662         mips_optimize = 1;
13663       else
13664         mips_optimize = 2;
13665       break;
13666
13667     case 'g':
13668       if (arg == NULL)
13669         mips_debug = 2;
13670       else
13671         mips_debug = atoi (arg);
13672       break;
13673
13674     case OPTION_MIPS1:
13675       file_mips_opts.isa = ISA_MIPS1;
13676       break;
13677
13678     case OPTION_MIPS2:
13679       file_mips_opts.isa = ISA_MIPS2;
13680       break;
13681
13682     case OPTION_MIPS3:
13683       file_mips_opts.isa = ISA_MIPS3;
13684       break;
13685
13686     case OPTION_MIPS4:
13687       file_mips_opts.isa = ISA_MIPS4;
13688       break;
13689
13690     case OPTION_MIPS5:
13691       file_mips_opts.isa = ISA_MIPS5;
13692       break;
13693
13694     case OPTION_MIPS32:
13695       file_mips_opts.isa = ISA_MIPS32;
13696       break;
13697
13698     case OPTION_MIPS32R2:
13699       file_mips_opts.isa = ISA_MIPS32R2;
13700       break;
13701
13702     case OPTION_MIPS32R3:
13703       file_mips_opts.isa = ISA_MIPS32R3;
13704       break;
13705
13706     case OPTION_MIPS32R5:
13707       file_mips_opts.isa = ISA_MIPS32R5;
13708       break;
13709
13710     case OPTION_MIPS64R2:
13711       file_mips_opts.isa = ISA_MIPS64R2;
13712       break;
13713
13714     case OPTION_MIPS64R3:
13715       file_mips_opts.isa = ISA_MIPS64R3;
13716       break;
13717
13718     case OPTION_MIPS64R5:
13719       file_mips_opts.isa = ISA_MIPS64R5;
13720       break;
13721
13722     case OPTION_MIPS64:
13723       file_mips_opts.isa = ISA_MIPS64;
13724       break;
13725
13726     case OPTION_MTUNE:
13727       mips_set_option_string (&mips_tune_string, arg);
13728       break;
13729
13730     case OPTION_MARCH:
13731       mips_set_option_string (&mips_arch_string, arg);
13732       break;
13733
13734     case OPTION_M4650:
13735       mips_set_option_string (&mips_arch_string, "4650");
13736       mips_set_option_string (&mips_tune_string, "4650");
13737       break;
13738
13739     case OPTION_NO_M4650:
13740       break;
13741
13742     case OPTION_M4010:
13743       mips_set_option_string (&mips_arch_string, "4010");
13744       mips_set_option_string (&mips_tune_string, "4010");
13745       break;
13746
13747     case OPTION_NO_M4010:
13748       break;
13749
13750     case OPTION_M4100:
13751       mips_set_option_string (&mips_arch_string, "4100");
13752       mips_set_option_string (&mips_tune_string, "4100");
13753       break;
13754
13755     case OPTION_NO_M4100:
13756       break;
13757
13758     case OPTION_M3900:
13759       mips_set_option_string (&mips_arch_string, "3900");
13760       mips_set_option_string (&mips_tune_string, "3900");
13761       break;
13762
13763     case OPTION_NO_M3900:
13764       break;
13765
13766     case OPTION_MICROMIPS:
13767       if (file_mips_opts.mips16 == 1)
13768         {
13769           as_bad (_("-mmicromips cannot be used with -mips16"));
13770           return 0;
13771         }
13772       file_mips_opts.micromips = 1;
13773       mips_no_prev_insn ();
13774       break;
13775
13776     case OPTION_NO_MICROMIPS:
13777       file_mips_opts.micromips = 0;
13778       mips_no_prev_insn ();
13779       break;
13780
13781     case OPTION_MIPS16:
13782       if (file_mips_opts.micromips == 1)
13783         {
13784           as_bad (_("-mips16 cannot be used with -micromips"));
13785           return 0;
13786         }
13787       file_mips_opts.mips16 = 1;
13788       mips_no_prev_insn ();
13789       break;
13790
13791     case OPTION_NO_MIPS16:
13792       file_mips_opts.mips16 = 0;
13793       mips_no_prev_insn ();
13794       break;
13795
13796     case OPTION_FIX_24K:
13797       mips_fix_24k = 1;
13798       break;
13799
13800     case OPTION_NO_FIX_24K:
13801       mips_fix_24k = 0;
13802       break;
13803
13804     case OPTION_FIX_RM7000:
13805       mips_fix_rm7000 = 1;
13806       break;
13807
13808     case OPTION_NO_FIX_RM7000:
13809       mips_fix_rm7000 = 0;
13810       break;
13811
13812     case OPTION_FIX_LOONGSON2F_JUMP:
13813       mips_fix_loongson2f_jump = TRUE;
13814       break;
13815
13816     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13817       mips_fix_loongson2f_jump = FALSE;
13818       break;
13819
13820     case OPTION_FIX_LOONGSON2F_NOP:
13821       mips_fix_loongson2f_nop = TRUE;
13822       break;
13823
13824     case OPTION_NO_FIX_LOONGSON2F_NOP:
13825       mips_fix_loongson2f_nop = FALSE;
13826       break;
13827
13828     case OPTION_FIX_VR4120:
13829       mips_fix_vr4120 = 1;
13830       break;
13831
13832     case OPTION_NO_FIX_VR4120:
13833       mips_fix_vr4120 = 0;
13834       break;
13835
13836     case OPTION_FIX_VR4130:
13837       mips_fix_vr4130 = 1;
13838       break;
13839
13840     case OPTION_NO_FIX_VR4130:
13841       mips_fix_vr4130 = 0;
13842       break;
13843
13844     case OPTION_FIX_CN63XXP1:
13845       mips_fix_cn63xxp1 = TRUE;
13846       break;
13847
13848     case OPTION_NO_FIX_CN63XXP1:
13849       mips_fix_cn63xxp1 = FALSE;
13850       break;
13851
13852     case OPTION_RELAX_BRANCH:
13853       mips_relax_branch = 1;
13854       break;
13855
13856     case OPTION_NO_RELAX_BRANCH:
13857       mips_relax_branch = 0;
13858       break;
13859
13860     case OPTION_INSN32:
13861       file_mips_opts.insn32 = TRUE;
13862       break;
13863
13864     case OPTION_NO_INSN32:
13865       file_mips_opts.insn32 = FALSE;
13866       break;
13867
13868     case OPTION_MSHARED:
13869       mips_in_shared = TRUE;
13870       break;
13871
13872     case OPTION_MNO_SHARED:
13873       mips_in_shared = FALSE;
13874       break;
13875
13876     case OPTION_MSYM32:
13877       file_mips_opts.sym32 = TRUE;
13878       break;
13879
13880     case OPTION_MNO_SYM32:
13881       file_mips_opts.sym32 = FALSE;
13882       break;
13883
13884       /* When generating ELF code, we permit -KPIC and -call_shared to
13885          select SVR4_PIC, and -non_shared to select no PIC.  This is
13886          intended to be compatible with Irix 5.  */
13887     case OPTION_CALL_SHARED:
13888       mips_pic = SVR4_PIC;
13889       mips_abicalls = TRUE;
13890       break;
13891
13892     case OPTION_CALL_NONPIC:
13893       mips_pic = NO_PIC;
13894       mips_abicalls = TRUE;
13895       break;
13896
13897     case OPTION_NON_SHARED:
13898       mips_pic = NO_PIC;
13899       mips_abicalls = FALSE;
13900       break;
13901
13902       /* The -xgot option tells the assembler to use 32 bit offsets
13903          when accessing the got in SVR4_PIC mode.  It is for Irix
13904          compatibility.  */
13905     case OPTION_XGOT:
13906       mips_big_got = 1;
13907       break;
13908
13909     case 'G':
13910       g_switch_value = atoi (arg);
13911       g_switch_seen = 1;
13912       break;
13913
13914       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13915          and -mabi=64.  */
13916     case OPTION_32:
13917       mips_abi = O32_ABI;
13918       break;
13919
13920     case OPTION_N32:
13921       mips_abi = N32_ABI;
13922       break;
13923
13924     case OPTION_64:
13925       mips_abi = N64_ABI;
13926       if (!support_64bit_objects())
13927         as_fatal (_("no compiled in support for 64 bit object file format"));
13928       break;
13929
13930     case OPTION_GP32:
13931       file_mips_opts.gp = 32;
13932       break;
13933
13934     case OPTION_GP64:
13935       file_mips_opts.gp = 64;
13936       break;
13937
13938     case OPTION_FP32:
13939       file_mips_opts.fp = 32;
13940       break;
13941
13942     case OPTION_FP64:
13943       file_mips_opts.fp = 64;
13944       break;
13945
13946     case OPTION_SINGLE_FLOAT:
13947       file_mips_opts.single_float = 1;
13948       break;
13949
13950     case OPTION_DOUBLE_FLOAT:
13951       file_mips_opts.single_float = 0;
13952       break;
13953
13954     case OPTION_SOFT_FLOAT:
13955       file_mips_opts.soft_float = 1;
13956       break;
13957
13958     case OPTION_HARD_FLOAT:
13959       file_mips_opts.soft_float = 0;
13960       break;
13961
13962     case OPTION_MABI:
13963       if (strcmp (arg, "32") == 0)
13964         mips_abi = O32_ABI;
13965       else if (strcmp (arg, "o64") == 0)
13966         mips_abi = O64_ABI;
13967       else if (strcmp (arg, "n32") == 0)
13968         mips_abi = N32_ABI;
13969       else if (strcmp (arg, "64") == 0)
13970         {
13971           mips_abi = N64_ABI;
13972           if (! support_64bit_objects())
13973             as_fatal (_("no compiled in support for 64 bit object file "
13974                         "format"));
13975         }
13976       else if (strcmp (arg, "eabi") == 0)
13977         mips_abi = EABI_ABI;
13978       else
13979         {
13980           as_fatal (_("invalid abi -mabi=%s"), arg);
13981           return 0;
13982         }
13983       break;
13984
13985     case OPTION_M7000_HILO_FIX:
13986       mips_7000_hilo_fix = TRUE;
13987       break;
13988
13989     case OPTION_MNO_7000_HILO_FIX:
13990       mips_7000_hilo_fix = FALSE;
13991       break;
13992
13993     case OPTION_MDEBUG:
13994       mips_flag_mdebug = TRUE;
13995       break;
13996
13997     case OPTION_NO_MDEBUG:
13998       mips_flag_mdebug = FALSE;
13999       break;
14000
14001     case OPTION_PDR:
14002       mips_flag_pdr = TRUE;
14003       break;
14004
14005     case OPTION_NO_PDR:
14006       mips_flag_pdr = FALSE;
14007       break;
14008
14009     case OPTION_MVXWORKS_PIC:
14010       mips_pic = VXWORKS_PIC;
14011       break;
14012
14013     case OPTION_NAN:
14014       if (strcmp (arg, "2008") == 0)
14015         mips_flag_nan2008 = TRUE;
14016       else if (strcmp (arg, "legacy") == 0)
14017         mips_flag_nan2008 = FALSE;
14018       else
14019         {
14020           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14021           return 0;
14022         }
14023       break;
14024
14025     default:
14026       return 0;
14027     }
14028
14029     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14030
14031   return 1;
14032 }
14033 \f
14034 /* Set up globals to tune for the ISA or processor described by INFO.  */
14035
14036 static void
14037 mips_set_tune (const struct mips_cpu_info *info)
14038 {
14039   if (info != 0)
14040     mips_tune = info->cpu;
14041 }
14042
14043
14044 void
14045 mips_after_parse_args (void)
14046 {
14047   const struct mips_cpu_info *arch_info = 0;
14048   const struct mips_cpu_info *tune_info = 0;
14049
14050   /* GP relative stuff not working for PE */
14051   if (strncmp (TARGET_OS, "pe", 2) == 0)
14052     {
14053       if (g_switch_seen && g_switch_value != 0)
14054         as_bad (_("-G not supported in this configuration"));
14055       g_switch_value = 0;
14056     }
14057
14058   if (mips_abi == NO_ABI)
14059     mips_abi = MIPS_DEFAULT_ABI;
14060
14061   /* The following code determines the architecture.
14062      Similar code was added to GCC 3.3 (see override_options() in
14063      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14064      as much as possible.  */
14065
14066   if (mips_arch_string != 0)
14067     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14068
14069   if (file_mips_opts.isa != ISA_UNKNOWN)
14070     {
14071       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14072          ISA level specified by -mipsN, while arch_info->isa contains
14073          the -march selection (if any).  */
14074       if (arch_info != 0)
14075         {
14076           /* -march takes precedence over -mipsN, since it is more descriptive.
14077              There's no harm in specifying both as long as the ISA levels
14078              are the same.  */
14079           if (file_mips_opts.isa != arch_info->isa)
14080             as_bad (_("-%s conflicts with the other architecture options,"
14081                       " which imply -%s"),
14082                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14083                     mips_cpu_info_from_isa (arch_info->isa)->name);
14084         }
14085       else
14086         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14087     }
14088
14089   if (arch_info == 0)
14090     {
14091       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14092       gas_assert (arch_info);
14093     }
14094
14095   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14096     as_bad (_("-march=%s is not compatible with the selected ABI"),
14097             arch_info->name);
14098
14099   file_mips_opts.arch = arch_info->cpu;
14100   file_mips_opts.isa = arch_info->isa;
14101
14102   /* Set up initial mips_opts state.  */
14103   mips_opts = file_mips_opts;
14104
14105   /* The register size inference code is now placed in
14106      file_mips_check_options.  */
14107
14108   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14109      processor.  */
14110   if (mips_tune_string != 0)
14111     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14112
14113   if (tune_info == 0)
14114     mips_set_tune (arch_info);
14115   else
14116     mips_set_tune (tune_info);
14117
14118   if (mips_flag_mdebug < 0)
14119     mips_flag_mdebug = 0;
14120 }
14121 \f
14122 void
14123 mips_init_after_args (void)
14124 {
14125   /* initialize opcodes */
14126   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14127   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14128 }
14129
14130 long
14131 md_pcrel_from (fixS *fixP)
14132 {
14133   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14134   switch (fixP->fx_r_type)
14135     {
14136     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14137     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14138       /* Return the address of the delay slot.  */
14139       return addr + 2;
14140
14141     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14142     case BFD_RELOC_MICROMIPS_JMP:
14143     case BFD_RELOC_16_PCREL_S2:
14144     case BFD_RELOC_MIPS_JMP:
14145       /* Return the address of the delay slot.  */
14146       return addr + 4;
14147
14148     default:
14149       return addr;
14150     }
14151 }
14152
14153 /* This is called before the symbol table is processed.  In order to
14154    work with gcc when using mips-tfile, we must keep all local labels.
14155    However, in other cases, we want to discard them.  If we were
14156    called with -g, but we didn't see any debugging information, it may
14157    mean that gcc is smuggling debugging information through to
14158    mips-tfile, in which case we must generate all local labels.  */
14159
14160 void
14161 mips_frob_file_before_adjust (void)
14162 {
14163 #ifndef NO_ECOFF_DEBUGGING
14164   if (ECOFF_DEBUGGING
14165       && mips_debug != 0
14166       && ! ecoff_debugging_seen)
14167     flag_keep_locals = 1;
14168 #endif
14169 }
14170
14171 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14172    the corresponding LO16 reloc.  This is called before md_apply_fix and
14173    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14174    relocation operators.
14175
14176    For our purposes, a %lo() expression matches a %got() or %hi()
14177    expression if:
14178
14179       (a) it refers to the same symbol; and
14180       (b) the offset applied in the %lo() expression is no lower than
14181           the offset applied in the %got() or %hi().
14182
14183    (b) allows us to cope with code like:
14184
14185         lui     $4,%hi(foo)
14186         lh      $4,%lo(foo+2)($4)
14187
14188    ...which is legal on RELA targets, and has a well-defined behaviour
14189    if the user knows that adding 2 to "foo" will not induce a carry to
14190    the high 16 bits.
14191
14192    When several %lo()s match a particular %got() or %hi(), we use the
14193    following rules to distinguish them:
14194
14195      (1) %lo()s with smaller offsets are a better match than %lo()s with
14196          higher offsets.
14197
14198      (2) %lo()s with no matching %got() or %hi() are better than those
14199          that already have a matching %got() or %hi().
14200
14201      (3) later %lo()s are better than earlier %lo()s.
14202
14203    These rules are applied in order.
14204
14205    (1) means, among other things, that %lo()s with identical offsets are
14206    chosen if they exist.
14207
14208    (2) means that we won't associate several high-part relocations with
14209    the same low-part relocation unless there's no alternative.  Having
14210    several high parts for the same low part is a GNU extension; this rule
14211    allows careful users to avoid it.
14212
14213    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14214    with the last high-part relocation being at the front of the list.
14215    It therefore makes sense to choose the last matching low-part
14216    relocation, all other things being equal.  It's also easier
14217    to code that way.  */
14218
14219 void
14220 mips_frob_file (void)
14221 {
14222   struct mips_hi_fixup *l;
14223   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14224
14225   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14226     {
14227       segment_info_type *seginfo;
14228       bfd_boolean matched_lo_p;
14229       fixS **hi_pos, **lo_pos, **pos;
14230
14231       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14232
14233       /* If a GOT16 relocation turns out to be against a global symbol,
14234          there isn't supposed to be a matching LO.  Ignore %gots against
14235          constants; we'll report an error for those later.  */
14236       if (got16_reloc_p (l->fixp->fx_r_type)
14237           && !(l->fixp->fx_addsy
14238                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14239         continue;
14240
14241       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14242       if (fixup_has_matching_lo_p (l->fixp))
14243         continue;
14244
14245       seginfo = seg_info (l->seg);
14246
14247       /* Set HI_POS to the position of this relocation in the chain.
14248          Set LO_POS to the position of the chosen low-part relocation.
14249          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14250          relocation that matches an immediately-preceding high-part
14251          relocation.  */
14252       hi_pos = NULL;
14253       lo_pos = NULL;
14254       matched_lo_p = FALSE;
14255       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14256
14257       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14258         {
14259           if (*pos == l->fixp)
14260             hi_pos = pos;
14261
14262           if ((*pos)->fx_r_type == looking_for_rtype
14263               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14264               && (*pos)->fx_offset >= l->fixp->fx_offset
14265               && (lo_pos == NULL
14266                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14267                   || (!matched_lo_p
14268                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14269             lo_pos = pos;
14270
14271           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14272                           && fixup_has_matching_lo_p (*pos));
14273         }
14274
14275       /* If we found a match, remove the high-part relocation from its
14276          current position and insert it before the low-part relocation.
14277          Make the offsets match so that fixup_has_matching_lo_p()
14278          will return true.
14279
14280          We don't warn about unmatched high-part relocations since some
14281          versions of gcc have been known to emit dead "lui ...%hi(...)"
14282          instructions.  */
14283       if (lo_pos != NULL)
14284         {
14285           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14286           if (l->fixp->fx_next != *lo_pos)
14287             {
14288               *hi_pos = l->fixp->fx_next;
14289               l->fixp->fx_next = *lo_pos;
14290               *lo_pos = l->fixp;
14291             }
14292         }
14293     }
14294 }
14295
14296 int
14297 mips_force_relocation (fixS *fixp)
14298 {
14299   if (generic_force_reloc (fixp))
14300     return 1;
14301
14302   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14303      so that the linker relaxation can update targets.  */
14304   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14305       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14306       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14307     return 1;
14308
14309   return 0;
14310 }
14311
14312 /* Read the instruction associated with RELOC from BUF.  */
14313
14314 static unsigned int
14315 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14316 {
14317   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14318     return read_compressed_insn (buf, 4);
14319   else
14320     return read_insn (buf);
14321 }
14322
14323 /* Write instruction INSN to BUF, given that it has been relocated
14324    by RELOC.  */
14325
14326 static void
14327 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14328                   unsigned long insn)
14329 {
14330   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14331     write_compressed_insn (buf, insn, 4);
14332   else
14333     write_insn (buf, insn);
14334 }
14335
14336 /* Apply a fixup to the object file.  */
14337
14338 void
14339 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14340 {
14341   char *buf;
14342   unsigned long insn;
14343   reloc_howto_type *howto;
14344
14345   if (fixP->fx_pcrel)
14346     switch (fixP->fx_r_type)
14347       {
14348       case BFD_RELOC_16_PCREL_S2:
14349       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14350       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14351       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14352       case BFD_RELOC_32_PCREL:
14353         break;
14354
14355       case BFD_RELOC_32:
14356         fixP->fx_r_type = BFD_RELOC_32_PCREL;
14357         break;
14358
14359       default:
14360         as_bad_where (fixP->fx_file, fixP->fx_line,
14361                       _("PC-relative reference to a different section"));
14362         break;
14363       }
14364
14365   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
14366      that have no MIPS ELF equivalent.  */
14367   if (fixP->fx_r_type != BFD_RELOC_8)
14368     {
14369       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14370       if (!howto)
14371         return;
14372     }
14373
14374   gas_assert (fixP->fx_size == 2
14375               || fixP->fx_size == 4
14376               || fixP->fx_r_type == BFD_RELOC_8
14377               || fixP->fx_r_type == BFD_RELOC_16
14378               || fixP->fx_r_type == BFD_RELOC_64
14379               || fixP->fx_r_type == BFD_RELOC_CTOR
14380               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14381               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14382               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14383               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14384               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14385
14386   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14387
14388   /* Don't treat parts of a composite relocation as done.  There are two
14389      reasons for this:
14390
14391      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14392          should nevertheless be emitted if the first part is.
14393
14394      (2) In normal usage, composite relocations are never assembly-time
14395          constants.  The easiest way of dealing with the pathological
14396          exceptions is to generate a relocation against STN_UNDEF and
14397          leave everything up to the linker.  */
14398   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14399     fixP->fx_done = 1;
14400
14401   switch (fixP->fx_r_type)
14402     {
14403     case BFD_RELOC_MIPS_TLS_GD:
14404     case BFD_RELOC_MIPS_TLS_LDM:
14405     case BFD_RELOC_MIPS_TLS_DTPREL32:
14406     case BFD_RELOC_MIPS_TLS_DTPREL64:
14407     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14408     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14409     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14410     case BFD_RELOC_MIPS_TLS_TPREL32:
14411     case BFD_RELOC_MIPS_TLS_TPREL64:
14412     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14413     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14414     case BFD_RELOC_MICROMIPS_TLS_GD:
14415     case BFD_RELOC_MICROMIPS_TLS_LDM:
14416     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14417     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14418     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14419     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14420     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14421     case BFD_RELOC_MIPS16_TLS_GD:
14422     case BFD_RELOC_MIPS16_TLS_LDM:
14423     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14424     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14425     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14426     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14427     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14428       if (!fixP->fx_addsy)
14429         {
14430           as_bad_where (fixP->fx_file, fixP->fx_line,
14431                         _("TLS relocation against a constant"));
14432           break;
14433         }
14434       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14435       /* fall through */
14436
14437     case BFD_RELOC_MIPS_JMP:
14438     case BFD_RELOC_MIPS_SHIFT5:
14439     case BFD_RELOC_MIPS_SHIFT6:
14440     case BFD_RELOC_MIPS_GOT_DISP:
14441     case BFD_RELOC_MIPS_GOT_PAGE:
14442     case BFD_RELOC_MIPS_GOT_OFST:
14443     case BFD_RELOC_MIPS_SUB:
14444     case BFD_RELOC_MIPS_INSERT_A:
14445     case BFD_RELOC_MIPS_INSERT_B:
14446     case BFD_RELOC_MIPS_DELETE:
14447     case BFD_RELOC_MIPS_HIGHEST:
14448     case BFD_RELOC_MIPS_HIGHER:
14449     case BFD_RELOC_MIPS_SCN_DISP:
14450     case BFD_RELOC_MIPS_REL16:
14451     case BFD_RELOC_MIPS_RELGOT:
14452     case BFD_RELOC_MIPS_JALR:
14453     case BFD_RELOC_HI16:
14454     case BFD_RELOC_HI16_S:
14455     case BFD_RELOC_LO16:
14456     case BFD_RELOC_GPREL16:
14457     case BFD_RELOC_MIPS_LITERAL:
14458     case BFD_RELOC_MIPS_CALL16:
14459     case BFD_RELOC_MIPS_GOT16:
14460     case BFD_RELOC_GPREL32:
14461     case BFD_RELOC_MIPS_GOT_HI16:
14462     case BFD_RELOC_MIPS_GOT_LO16:
14463     case BFD_RELOC_MIPS_CALL_HI16:
14464     case BFD_RELOC_MIPS_CALL_LO16:
14465     case BFD_RELOC_MIPS16_GPREL:
14466     case BFD_RELOC_MIPS16_GOT16:
14467     case BFD_RELOC_MIPS16_CALL16:
14468     case BFD_RELOC_MIPS16_HI16:
14469     case BFD_RELOC_MIPS16_HI16_S:
14470     case BFD_RELOC_MIPS16_LO16:
14471     case BFD_RELOC_MIPS16_JMP:
14472     case BFD_RELOC_MICROMIPS_JMP:
14473     case BFD_RELOC_MICROMIPS_GOT_DISP:
14474     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14475     case BFD_RELOC_MICROMIPS_GOT_OFST:
14476     case BFD_RELOC_MICROMIPS_SUB:
14477     case BFD_RELOC_MICROMIPS_HIGHEST:
14478     case BFD_RELOC_MICROMIPS_HIGHER:
14479     case BFD_RELOC_MICROMIPS_SCN_DISP:
14480     case BFD_RELOC_MICROMIPS_JALR:
14481     case BFD_RELOC_MICROMIPS_HI16:
14482     case BFD_RELOC_MICROMIPS_HI16_S:
14483     case BFD_RELOC_MICROMIPS_LO16:
14484     case BFD_RELOC_MICROMIPS_GPREL16:
14485     case BFD_RELOC_MICROMIPS_LITERAL:
14486     case BFD_RELOC_MICROMIPS_CALL16:
14487     case BFD_RELOC_MICROMIPS_GOT16:
14488     case BFD_RELOC_MICROMIPS_GOT_HI16:
14489     case BFD_RELOC_MICROMIPS_GOT_LO16:
14490     case BFD_RELOC_MICROMIPS_CALL_HI16:
14491     case BFD_RELOC_MICROMIPS_CALL_LO16:
14492     case BFD_RELOC_MIPS_EH:
14493       if (fixP->fx_done)
14494         {
14495           offsetT value;
14496
14497           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14498             {
14499               insn = read_reloc_insn (buf, fixP->fx_r_type);
14500               if (mips16_reloc_p (fixP->fx_r_type))
14501                 insn |= mips16_immed_extend (value, 16);
14502               else
14503                 insn |= (value & 0xffff);
14504               write_reloc_insn (buf, fixP->fx_r_type, insn);
14505             }
14506           else
14507             as_bad_where (fixP->fx_file, fixP->fx_line,
14508                           _("unsupported constant in relocation"));
14509         }
14510       break;
14511
14512     case BFD_RELOC_64:
14513       /* This is handled like BFD_RELOC_32, but we output a sign
14514          extended value if we are only 32 bits.  */
14515       if (fixP->fx_done)
14516         {
14517           if (8 <= sizeof (valueT))
14518             md_number_to_chars (buf, *valP, 8);
14519           else
14520             {
14521               valueT hiv;
14522
14523               if ((*valP & 0x80000000) != 0)
14524                 hiv = 0xffffffff;
14525               else
14526                 hiv = 0;
14527               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14528               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14529             }
14530         }
14531       break;
14532
14533     case BFD_RELOC_RVA:
14534     case BFD_RELOC_32:
14535     case BFD_RELOC_32_PCREL:
14536     case BFD_RELOC_16:
14537     case BFD_RELOC_8:
14538       /* If we are deleting this reloc entry, we must fill in the
14539          value now.  This can happen if we have a .word which is not
14540          resolved when it appears but is later defined.  */
14541       if (fixP->fx_done)
14542         md_number_to_chars (buf, *valP, fixP->fx_size);
14543       break;
14544
14545     case BFD_RELOC_16_PCREL_S2:
14546       if ((*valP & 0x3) != 0)
14547         as_bad_where (fixP->fx_file, fixP->fx_line,
14548                       _("branch to misaligned address (%lx)"), (long) *valP);
14549
14550       /* We need to save the bits in the instruction since fixup_segment()
14551          might be deleting the relocation entry (i.e., a branch within
14552          the current segment).  */
14553       if (! fixP->fx_done)
14554         break;
14555
14556       /* Update old instruction data.  */
14557       insn = read_insn (buf);
14558
14559       if (*valP + 0x20000 <= 0x3ffff)
14560         {
14561           insn |= (*valP >> 2) & 0xffff;
14562           write_insn (buf, insn);
14563         }
14564       else if (mips_pic == NO_PIC
14565                && fixP->fx_done
14566                && fixP->fx_frag->fr_address >= text_section->vma
14567                && (fixP->fx_frag->fr_address
14568                    < text_section->vma + bfd_get_section_size (text_section))
14569                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14570                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14571                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14572         {
14573           /* The branch offset is too large.  If this is an
14574              unconditional branch, and we are not generating PIC code,
14575              we can convert it to an absolute jump instruction.  */
14576           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14577             insn = 0x0c000000;  /* jal */
14578           else
14579             insn = 0x08000000;  /* j */
14580           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14581           fixP->fx_done = 0;
14582           fixP->fx_addsy = section_symbol (text_section);
14583           *valP += md_pcrel_from (fixP);
14584           write_insn (buf, insn);
14585         }
14586       else
14587         {
14588           /* If we got here, we have branch-relaxation disabled,
14589              and there's nothing we can do to fix this instruction
14590              without turning it into a longer sequence.  */
14591           as_bad_where (fixP->fx_file, fixP->fx_line,
14592                         _("branch out of range"));
14593         }
14594       break;
14595
14596     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14597     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14598     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14599       /* We adjust the offset back to even.  */
14600       if ((*valP & 0x1) != 0)
14601         --(*valP);
14602
14603       if (! fixP->fx_done)
14604         break;
14605
14606       /* Should never visit here, because we keep the relocation.  */
14607       abort ();
14608       break;
14609
14610     case BFD_RELOC_VTABLE_INHERIT:
14611       fixP->fx_done = 0;
14612       if (fixP->fx_addsy
14613           && !S_IS_DEFINED (fixP->fx_addsy)
14614           && !S_IS_WEAK (fixP->fx_addsy))
14615         S_SET_WEAK (fixP->fx_addsy);
14616       break;
14617
14618     case BFD_RELOC_VTABLE_ENTRY:
14619       fixP->fx_done = 0;
14620       break;
14621
14622     default:
14623       abort ();
14624     }
14625
14626   /* Remember value for tc_gen_reloc.  */
14627   fixP->fx_addnumber = *valP;
14628 }
14629
14630 static symbolS *
14631 get_symbol (void)
14632 {
14633   int c;
14634   char *name;
14635   symbolS *p;
14636
14637   name = input_line_pointer;
14638   c = get_symbol_end ();
14639   p = (symbolS *) symbol_find_or_make (name);
14640   *input_line_pointer = c;
14641   return p;
14642 }
14643
14644 /* Align the current frag to a given power of two.  If a particular
14645    fill byte should be used, FILL points to an integer that contains
14646    that byte, otherwise FILL is null.
14647
14648    This function used to have the comment:
14649
14650       The MIPS assembler also automatically adjusts any preceding label.
14651
14652    The implementation therefore applied the adjustment to a maximum of
14653    one label.  However, other label adjustments are applied to batches
14654    of labels, and adjusting just one caused problems when new labels
14655    were added for the sake of debugging or unwind information.
14656    We therefore adjust all preceding labels (given as LABELS) instead.  */
14657
14658 static void
14659 mips_align (int to, int *fill, struct insn_label_list *labels)
14660 {
14661   mips_emit_delays ();
14662   mips_record_compressed_mode ();
14663   if (fill == NULL && subseg_text_p (now_seg))
14664     frag_align_code (to, 0);
14665   else
14666     frag_align (to, fill ? *fill : 0, 0);
14667   record_alignment (now_seg, to);
14668   mips_move_labels (labels, FALSE);
14669 }
14670
14671 /* Align to a given power of two.  .align 0 turns off the automatic
14672    alignment used by the data creating pseudo-ops.  */
14673
14674 static void
14675 s_align (int x ATTRIBUTE_UNUSED)
14676 {
14677   int temp, fill_value, *fill_ptr;
14678   long max_alignment = 28;
14679
14680   /* o Note that the assembler pulls down any immediately preceding label
14681        to the aligned address.
14682      o It's not documented but auto alignment is reinstated by
14683        a .align pseudo instruction.
14684      o Note also that after auto alignment is turned off the mips assembler
14685        issues an error on attempt to assemble an improperly aligned data item.
14686        We don't.  */
14687
14688   temp = get_absolute_expression ();
14689   if (temp > max_alignment)
14690     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14691   else if (temp < 0)
14692     {
14693       as_warn (_("alignment negative, 0 assumed"));
14694       temp = 0;
14695     }
14696   if (*input_line_pointer == ',')
14697     {
14698       ++input_line_pointer;
14699       fill_value = get_absolute_expression ();
14700       fill_ptr = &fill_value;
14701     }
14702   else
14703     fill_ptr = 0;
14704   if (temp)
14705     {
14706       segment_info_type *si = seg_info (now_seg);
14707       struct insn_label_list *l = si->label_list;
14708       /* Auto alignment should be switched on by next section change.  */
14709       auto_align = 1;
14710       mips_align (temp, fill_ptr, l);
14711     }
14712   else
14713     {
14714       auto_align = 0;
14715     }
14716
14717   demand_empty_rest_of_line ();
14718 }
14719
14720 static void
14721 s_change_sec (int sec)
14722 {
14723   segT seg;
14724
14725   /* The ELF backend needs to know that we are changing sections, so
14726      that .previous works correctly.  We could do something like check
14727      for an obj_section_change_hook macro, but that might be confusing
14728      as it would not be appropriate to use it in the section changing
14729      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14730      This should be cleaner, somehow.  */
14731   obj_elf_section_change_hook ();
14732
14733   mips_emit_delays ();
14734
14735   switch (sec)
14736     {
14737     case 't':
14738       s_text (0);
14739       break;
14740     case 'd':
14741       s_data (0);
14742       break;
14743     case 'b':
14744       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14745       demand_empty_rest_of_line ();
14746       break;
14747
14748     case 'r':
14749       seg = subseg_new (RDATA_SECTION_NAME,
14750                         (subsegT) get_absolute_expression ());
14751       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14752                                               | SEC_READONLY | SEC_RELOC
14753                                               | SEC_DATA));
14754       if (strncmp (TARGET_OS, "elf", 3) != 0)
14755         record_alignment (seg, 4);
14756       demand_empty_rest_of_line ();
14757       break;
14758
14759     case 's':
14760       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14761       bfd_set_section_flags (stdoutput, seg,
14762                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14763       if (strncmp (TARGET_OS, "elf", 3) != 0)
14764         record_alignment (seg, 4);
14765       demand_empty_rest_of_line ();
14766       break;
14767
14768     case 'B':
14769       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14770       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14771       if (strncmp (TARGET_OS, "elf", 3) != 0)
14772         record_alignment (seg, 4);
14773       demand_empty_rest_of_line ();
14774       break;
14775     }
14776
14777   auto_align = 1;
14778 }
14779
14780 void
14781 s_change_section (int ignore ATTRIBUTE_UNUSED)
14782 {
14783   char *section_name;
14784   char c;
14785   char next_c = 0;
14786   int section_type;
14787   int section_flag;
14788   int section_entry_size;
14789   int section_alignment;
14790
14791   section_name = input_line_pointer;
14792   c = get_symbol_end ();
14793   if (c)
14794     next_c = *(input_line_pointer + 1);
14795
14796   /* Do we have .section Name<,"flags">?  */
14797   if (c != ',' || (c == ',' && next_c == '"'))
14798     {
14799       /* just after name is now '\0'.  */
14800       *input_line_pointer = c;
14801       input_line_pointer = section_name;
14802       obj_elf_section (ignore);
14803       return;
14804     }
14805   input_line_pointer++;
14806
14807   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14808   if (c == ',')
14809     section_type = get_absolute_expression ();
14810   else
14811     section_type = 0;
14812   if (*input_line_pointer++ == ',')
14813     section_flag = get_absolute_expression ();
14814   else
14815     section_flag = 0;
14816   if (*input_line_pointer++ == ',')
14817     section_entry_size = get_absolute_expression ();
14818   else
14819     section_entry_size = 0;
14820   if (*input_line_pointer++ == ',')
14821     section_alignment = get_absolute_expression ();
14822   else
14823     section_alignment = 0;
14824   /* FIXME: really ignore?  */
14825   (void) section_alignment;
14826
14827   section_name = xstrdup (section_name);
14828
14829   /* When using the generic form of .section (as implemented by obj-elf.c),
14830      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14831      traditionally had to fall back on the more common @progbits instead.
14832
14833      There's nothing really harmful in this, since bfd will correct
14834      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14835      means that, for backwards compatibility, the special_section entries
14836      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14837
14838      Even so, we shouldn't force users of the MIPS .section syntax to
14839      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14840      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14841      generic type-checking code.  */
14842   if (section_type == SHT_MIPS_DWARF)
14843     section_type = SHT_PROGBITS;
14844
14845   obj_elf_change_section (section_name, section_type, section_flag,
14846                           section_entry_size, 0, 0, 0);
14847
14848   if (now_seg->name != section_name)
14849     free (section_name);
14850 }
14851
14852 void
14853 mips_enable_auto_align (void)
14854 {
14855   auto_align = 1;
14856 }
14857
14858 static void
14859 s_cons (int log_size)
14860 {
14861   segment_info_type *si = seg_info (now_seg);
14862   struct insn_label_list *l = si->label_list;
14863
14864   mips_emit_delays ();
14865   if (log_size > 0 && auto_align)
14866     mips_align (log_size, 0, l);
14867   cons (1 << log_size);
14868   mips_clear_insn_labels ();
14869 }
14870
14871 static void
14872 s_float_cons (int type)
14873 {
14874   segment_info_type *si = seg_info (now_seg);
14875   struct insn_label_list *l = si->label_list;
14876
14877   mips_emit_delays ();
14878
14879   if (auto_align)
14880     {
14881       if (type == 'd')
14882         mips_align (3, 0, l);
14883       else
14884         mips_align (2, 0, l);
14885     }
14886
14887   float_cons (type);
14888   mips_clear_insn_labels ();
14889 }
14890
14891 /* Handle .globl.  We need to override it because on Irix 5 you are
14892    permitted to say
14893        .globl foo .text
14894    where foo is an undefined symbol, to mean that foo should be
14895    considered to be the address of a function.  */
14896
14897 static void
14898 s_mips_globl (int x ATTRIBUTE_UNUSED)
14899 {
14900   char *name;
14901   int c;
14902   symbolS *symbolP;
14903   flagword flag;
14904
14905   do
14906     {
14907       name = input_line_pointer;
14908       c = get_symbol_end ();
14909       symbolP = symbol_find_or_make (name);
14910       S_SET_EXTERNAL (symbolP);
14911
14912       *input_line_pointer = c;
14913       SKIP_WHITESPACE ();
14914
14915       /* On Irix 5, every global symbol that is not explicitly labelled as
14916          being a function is apparently labelled as being an object.  */
14917       flag = BSF_OBJECT;
14918
14919       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14920           && (*input_line_pointer != ','))
14921         {
14922           char *secname;
14923           asection *sec;
14924
14925           secname = input_line_pointer;
14926           c = get_symbol_end ();
14927           sec = bfd_get_section_by_name (stdoutput, secname);
14928           if (sec == NULL)
14929             as_bad (_("%s: no such section"), secname);
14930           *input_line_pointer = c;
14931
14932           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14933             flag = BSF_FUNCTION;
14934         }
14935
14936       symbol_get_bfdsym (symbolP)->flags |= flag;
14937
14938       c = *input_line_pointer;
14939       if (c == ',')
14940         {
14941           input_line_pointer++;
14942           SKIP_WHITESPACE ();
14943           if (is_end_of_line[(unsigned char) *input_line_pointer])
14944             c = '\n';
14945         }
14946     }
14947   while (c == ',');
14948
14949   demand_empty_rest_of_line ();
14950 }
14951
14952 static void
14953 s_option (int x ATTRIBUTE_UNUSED)
14954 {
14955   char *opt;
14956   char c;
14957
14958   opt = input_line_pointer;
14959   c = get_symbol_end ();
14960
14961   if (*opt == 'O')
14962     {
14963       /* FIXME: What does this mean?  */
14964     }
14965   else if (strncmp (opt, "pic", 3) == 0)
14966     {
14967       int i;
14968
14969       i = atoi (opt + 3);
14970       if (i == 0)
14971         mips_pic = NO_PIC;
14972       else if (i == 2)
14973         {
14974           mips_pic = SVR4_PIC;
14975           mips_abicalls = TRUE;
14976         }
14977       else
14978         as_bad (_(".option pic%d not supported"), i);
14979
14980       if (mips_pic == SVR4_PIC)
14981         {
14982           if (g_switch_seen && g_switch_value != 0)
14983             as_warn (_("-G may not be used with SVR4 PIC code"));
14984           g_switch_value = 0;
14985           bfd_set_gp_size (stdoutput, 0);
14986         }
14987     }
14988   else
14989     as_warn (_("unrecognized option \"%s\""), opt);
14990
14991   *input_line_pointer = c;
14992   demand_empty_rest_of_line ();
14993 }
14994
14995 /* This structure is used to hold a stack of .set values.  */
14996
14997 struct mips_option_stack
14998 {
14999   struct mips_option_stack *next;
15000   struct mips_set_options options;
15001 };
15002
15003 static struct mips_option_stack *mips_opts_stack;
15004
15005 static bfd_boolean
15006 parse_code_option (char * name)
15007 {
15008   const struct mips_ase *ase;
15009   if (strncmp (name, "at=", 3) == 0)
15010     {
15011       char *s = name + 3;
15012
15013       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15014         as_bad (_("unrecognized register name `%s'"), s);
15015     }
15016   else if (strcmp (name, "at") == 0)
15017     mips_opts.at = ATREG;
15018   else if (strcmp (name, "noat") == 0)
15019     mips_opts.at = ZERO;
15020   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15021     mips_opts.nomove = 0;
15022   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15023     mips_opts.nomove = 1;
15024   else if (strcmp (name, "bopt") == 0)
15025     mips_opts.nobopt = 0;
15026   else if (strcmp (name, "nobopt") == 0)
15027     mips_opts.nobopt = 1;
15028   else if (strcmp (name, "gp=32") == 0)
15029     mips_opts.gp = 32;
15030   else if (strcmp (name, "gp=64") == 0)
15031     mips_opts.gp = 64;
15032   else if (strcmp (name, "fp=32") == 0)
15033     mips_opts.fp = 32;
15034   else if (strcmp (name, "fp=64") == 0)
15035     mips_opts.fp = 64;
15036   else if (strcmp (name, "softfloat") == 0)
15037     mips_opts.soft_float = 1;
15038   else if (strcmp (name, "hardfloat") == 0)
15039     mips_opts.soft_float = 0;
15040   else if (strcmp (name, "singlefloat") == 0)
15041     mips_opts.single_float = 1;
15042   else if (strcmp (name, "doublefloat") == 0)
15043     mips_opts.single_float = 0;
15044   else if (strcmp (name, "mips16") == 0
15045            || strcmp (name, "MIPS-16") == 0)
15046     mips_opts.mips16 = 1;
15047   else if (strcmp (name, "nomips16") == 0
15048            || strcmp (name, "noMIPS-16") == 0)
15049     mips_opts.mips16 = 0;
15050   else if (strcmp (name, "micromips") == 0)
15051     mips_opts.micromips = 1;
15052   else if (strcmp (name, "nomicromips") == 0)
15053     mips_opts.micromips = 0;
15054   else if (name[0] == 'n'
15055            && name[1] == 'o'
15056            && (ase = mips_lookup_ase (name + 2)))
15057     mips_set_ase (ase, &mips_opts, FALSE);
15058   else if ((ase = mips_lookup_ase (name)))
15059     mips_set_ase (ase, &mips_opts, TRUE);
15060   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15061     {
15062       /* Permit the user to change the ISA and architecture on the fly.
15063          Needless to say, misuse can cause serious problems.  */
15064       if (strncmp (name, "arch=", 5) == 0)
15065         {
15066           const struct mips_cpu_info *p;
15067
15068           p = mips_parse_cpu ("internal use", name + 5);
15069           if (!p)
15070             as_bad (_("unknown architecture %s"), name + 5);
15071           else
15072             {
15073               mips_opts.arch = p->cpu;
15074               mips_opts.isa = p->isa;
15075             }
15076         }
15077       else if (strncmp (name, "mips", 4) == 0)
15078         {
15079           const struct mips_cpu_info *p;
15080
15081           p = mips_parse_cpu ("internal use", name);
15082           if (!p)
15083             as_bad (_("unknown ISA level %s"), name + 4);
15084           else
15085             {
15086               mips_opts.arch = p->cpu;
15087               mips_opts.isa = p->isa;
15088             }
15089         }
15090       else
15091         as_bad (_("unknown ISA or architecture %s"), name);
15092     }
15093   else if (strcmp (name, "autoextend") == 0)
15094     mips_opts.noautoextend = 0;
15095   else if (strcmp (name, "noautoextend") == 0)
15096     mips_opts.noautoextend = 1;
15097   else if (strcmp (name, "insn32") == 0)
15098     mips_opts.insn32 = TRUE;
15099   else if (strcmp (name, "noinsn32") == 0)
15100     mips_opts.insn32 = FALSE;
15101   else if (strcmp (name, "sym32") == 0)
15102     mips_opts.sym32 = TRUE;
15103   else if (strcmp (name, "nosym32") == 0)
15104     mips_opts.sym32 = FALSE;
15105   else
15106     return FALSE;
15107   return TRUE;
15108 }
15109
15110 /* Handle the .set pseudo-op.  */
15111
15112 static void
15113 s_mipsset (int x ATTRIBUTE_UNUSED)
15114 {
15115   char *name = input_line_pointer, ch;
15116   int prev_isa = mips_opts.isa;
15117
15118   file_mips_check_options ();
15119
15120   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15121     ++input_line_pointer;
15122   ch = *input_line_pointer;
15123   *input_line_pointer = '\0';
15124
15125   if (strchr (name, ','))
15126     {
15127       /* Generic ".set" directive; use the generic handler.  */
15128       *input_line_pointer = ch;
15129       input_line_pointer = name;
15130       s_set (0);
15131       return;
15132     }
15133
15134   if (strcmp (name, "reorder") == 0)
15135     {
15136       if (mips_opts.noreorder)
15137         end_noreorder ();
15138     }
15139   else if (strcmp (name, "noreorder") == 0)
15140     {
15141       if (!mips_opts.noreorder)
15142         start_noreorder ();
15143     }
15144   else if (strcmp (name, "macro") == 0)
15145     mips_opts.warn_about_macros = 0;
15146   else if (strcmp (name, "nomacro") == 0)
15147     {
15148       if (mips_opts.noreorder == 0)
15149         as_bad (_("`noreorder' must be set before `nomacro'"));
15150       mips_opts.warn_about_macros = 1;
15151     }
15152   else if (strcmp (name, "gp=default") == 0)
15153     mips_opts.gp = file_mips_opts.gp;
15154   else if (strcmp (name, "fp=default") == 0)
15155     mips_opts.fp = file_mips_opts.fp;
15156   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15157     {
15158       mips_opts.isa = file_mips_opts.isa;
15159       mips_opts.arch = file_mips_opts.arch;
15160       mips_opts.gp = file_mips_opts.gp;
15161       mips_opts.fp = file_mips_opts.fp;
15162     }
15163   else if (strcmp (name, "push") == 0)
15164     {
15165       struct mips_option_stack *s;
15166
15167       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15168       s->next = mips_opts_stack;
15169       s->options = mips_opts;
15170       mips_opts_stack = s;
15171     }
15172   else if (strcmp (name, "pop") == 0)
15173     {
15174       struct mips_option_stack *s;
15175
15176       s = mips_opts_stack;
15177       if (s == NULL)
15178         as_bad (_(".set pop with no .set push"));
15179       else
15180         {
15181           /* If we're changing the reorder mode we need to handle
15182              delay slots correctly.  */
15183           if (s->options.noreorder && ! mips_opts.noreorder)
15184             start_noreorder ();
15185           else if (! s->options.noreorder && mips_opts.noreorder)
15186             end_noreorder ();
15187
15188           mips_opts = s->options;
15189           mips_opts_stack = s->next;
15190           free (s);
15191         }
15192     }
15193   else if (!parse_code_option (name))
15194     as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15195
15196   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
15197      registers based on what is supported by the arch/cpu.  */
15198   if (mips_opts.isa != prev_isa)
15199     {
15200       switch (mips_opts.isa)
15201         {
15202         case 0:
15203           break;
15204         case ISA_MIPS1:
15205         case ISA_MIPS2:
15206         case ISA_MIPS32:
15207         case ISA_MIPS32R2:
15208         case ISA_MIPS32R3:
15209         case ISA_MIPS32R5:
15210           mips_opts.gp = 32;
15211           mips_opts.fp = 32;
15212           break;
15213         case ISA_MIPS3:
15214         case ISA_MIPS4:
15215         case ISA_MIPS5:
15216         case ISA_MIPS64:
15217         case ISA_MIPS64R2:
15218         case ISA_MIPS64R3:
15219         case ISA_MIPS64R5:
15220           mips_opts.gp = 64;
15221           if (mips_opts.arch == CPU_R5900)
15222             mips_opts.fp = 32;
15223           else
15224             mips_opts.fp = 64;
15225           break;
15226         default:
15227           as_bad (_("unknown ISA level %s"), name + 4);
15228           break;
15229         }
15230     }
15231
15232   mips_check_options (&mips_opts, FALSE);
15233
15234   mips_check_isa_supports_ases ();
15235   *input_line_pointer = ch;
15236   demand_empty_rest_of_line ();
15237 }
15238
15239 /* Handle the .module pseudo-op.  */
15240
15241 static void
15242 s_module (int ignore ATTRIBUTE_UNUSED)
15243 {
15244   char *name = input_line_pointer, ch;
15245
15246   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15247     ++input_line_pointer;
15248   ch = *input_line_pointer;
15249   *input_line_pointer = '\0';
15250
15251   if (!file_mips_opts_checked)
15252     {
15253       if (!parse_code_option (name))
15254         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
15255
15256       /* Update module level settings from mips_opts.  */
15257       file_mips_opts = mips_opts;
15258     }
15259   else
15260     as_bad (_(".module is not permitted after generating code"));
15261
15262   *input_line_pointer = ch;
15263   demand_empty_rest_of_line ();
15264 }
15265
15266 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15267    .option pic2.  It means to generate SVR4 PIC calls.  */
15268
15269 static void
15270 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15271 {
15272   mips_pic = SVR4_PIC;
15273   mips_abicalls = TRUE;
15274
15275   if (g_switch_seen && g_switch_value != 0)
15276     as_warn (_("-G may not be used with SVR4 PIC code"));
15277   g_switch_value = 0;
15278
15279   bfd_set_gp_size (stdoutput, 0);
15280   demand_empty_rest_of_line ();
15281 }
15282
15283 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15284    PIC code.  It sets the $gp register for the function based on the
15285    function address, which is in the register named in the argument.
15286    This uses a relocation against _gp_disp, which is handled specially
15287    by the linker.  The result is:
15288         lui     $gp,%hi(_gp_disp)
15289         addiu   $gp,$gp,%lo(_gp_disp)
15290         addu    $gp,$gp,.cpload argument
15291    The .cpload argument is normally $25 == $t9.
15292
15293    The -mno-shared option changes this to:
15294         lui     $gp,%hi(__gnu_local_gp)
15295         addiu   $gp,$gp,%lo(__gnu_local_gp)
15296    and the argument is ignored.  This saves an instruction, but the
15297    resulting code is not position independent; it uses an absolute
15298    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15299    can go into an ordinary executable, but not into a shared library.  */
15300
15301 static void
15302 s_cpload (int ignore ATTRIBUTE_UNUSED)
15303 {
15304   expressionS ex;
15305   int reg;
15306   int in_shared;
15307
15308   file_mips_check_options ();
15309
15310   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15311      .cpload is ignored.  */
15312   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15313     {
15314       s_ignore (0);
15315       return;
15316     }
15317
15318   if (mips_opts.mips16)
15319     {
15320       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15321       ignore_rest_of_line ();
15322       return;
15323     }
15324
15325   /* .cpload should be in a .set noreorder section.  */
15326   if (mips_opts.noreorder == 0)
15327     as_warn (_(".cpload not in noreorder section"));
15328
15329   reg = tc_get_register (0);
15330
15331   /* If we need to produce a 64-bit address, we are better off using
15332      the default instruction sequence.  */
15333   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15334
15335   ex.X_op = O_symbol;
15336   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15337                                          "__gnu_local_gp");
15338   ex.X_op_symbol = NULL;
15339   ex.X_add_number = 0;
15340
15341   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15342   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15343
15344   mips_mark_labels ();
15345   mips_assembling_insn = TRUE;
15346
15347   macro_start ();
15348   macro_build_lui (&ex, mips_gp_register);
15349   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15350                mips_gp_register, BFD_RELOC_LO16);
15351   if (in_shared)
15352     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15353                  mips_gp_register, reg);
15354   macro_end ();
15355
15356   mips_assembling_insn = FALSE;
15357   demand_empty_rest_of_line ();
15358 }
15359
15360 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15361      .cpsetup $reg1, offset|$reg2, label
15362
15363    If offset is given, this results in:
15364      sd         $gp, offset($sp)
15365      lui        $gp, %hi(%neg(%gp_rel(label)))
15366      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15367      daddu      $gp, $gp, $reg1
15368
15369    If $reg2 is given, this results in:
15370      daddu      $reg2, $gp, $0
15371      lui        $gp, %hi(%neg(%gp_rel(label)))
15372      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15373      daddu      $gp, $gp, $reg1
15374    $reg1 is normally $25 == $t9.
15375
15376    The -mno-shared option replaces the last three instructions with
15377         lui     $gp,%hi(_gp)
15378         addiu   $gp,$gp,%lo(_gp)  */
15379
15380 static void
15381 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15382 {
15383   expressionS ex_off;
15384   expressionS ex_sym;
15385   int reg1;
15386
15387   file_mips_check_options ();
15388
15389   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15390      We also need NewABI support.  */
15391   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15392     {
15393       s_ignore (0);
15394       return;
15395     }
15396
15397   if (mips_opts.mips16)
15398     {
15399       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15400       ignore_rest_of_line ();
15401       return;
15402     }
15403
15404   reg1 = tc_get_register (0);
15405   SKIP_WHITESPACE ();
15406   if (*input_line_pointer != ',')
15407     {
15408       as_bad (_("missing argument separator ',' for .cpsetup"));
15409       return;
15410     }
15411   else
15412     ++input_line_pointer;
15413   SKIP_WHITESPACE ();
15414   if (*input_line_pointer == '$')
15415     {
15416       mips_cpreturn_register = tc_get_register (0);
15417       mips_cpreturn_offset = -1;
15418     }
15419   else
15420     {
15421       mips_cpreturn_offset = get_absolute_expression ();
15422       mips_cpreturn_register = -1;
15423     }
15424   SKIP_WHITESPACE ();
15425   if (*input_line_pointer != ',')
15426     {
15427       as_bad (_("missing argument separator ',' for .cpsetup"));
15428       return;
15429     }
15430   else
15431     ++input_line_pointer;
15432   SKIP_WHITESPACE ();
15433   expression (&ex_sym);
15434
15435   mips_mark_labels ();
15436   mips_assembling_insn = TRUE;
15437
15438   macro_start ();
15439   if (mips_cpreturn_register == -1)
15440     {
15441       ex_off.X_op = O_constant;
15442       ex_off.X_add_symbol = NULL;
15443       ex_off.X_op_symbol = NULL;
15444       ex_off.X_add_number = mips_cpreturn_offset;
15445
15446       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15447                    BFD_RELOC_LO16, SP);
15448     }
15449   else
15450     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15451                  mips_gp_register, 0);
15452
15453   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15454     {
15455       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15456                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15457                    BFD_RELOC_HI16_S);
15458
15459       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15460                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15461                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15462
15463       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15464                    mips_gp_register, reg1);
15465     }
15466   else
15467     {
15468       expressionS ex;
15469
15470       ex.X_op = O_symbol;
15471       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15472       ex.X_op_symbol = NULL;
15473       ex.X_add_number = 0;
15474
15475       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15476       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15477
15478       macro_build_lui (&ex, mips_gp_register);
15479       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15480                    mips_gp_register, BFD_RELOC_LO16);
15481     }
15482
15483   macro_end ();
15484
15485   mips_assembling_insn = FALSE;
15486   demand_empty_rest_of_line ();
15487 }
15488
15489 static void
15490 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15491 {
15492   file_mips_check_options ();
15493
15494   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15495      .cplocal is ignored.  */
15496   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15497     {
15498       s_ignore (0);
15499       return;
15500     }
15501
15502   if (mips_opts.mips16)
15503     {
15504       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15505       ignore_rest_of_line ();
15506       return;
15507     }
15508
15509   mips_gp_register = tc_get_register (0);
15510   demand_empty_rest_of_line ();
15511 }
15512
15513 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15514    offset from $sp.  The offset is remembered, and after making a PIC
15515    call $gp is restored from that location.  */
15516
15517 static void
15518 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15519 {
15520   expressionS ex;
15521
15522   file_mips_check_options ();
15523
15524   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15525      .cprestore is ignored.  */
15526   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15527     {
15528       s_ignore (0);
15529       return;
15530     }
15531
15532   if (mips_opts.mips16)
15533     {
15534       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15535       ignore_rest_of_line ();
15536       return;
15537     }
15538
15539   mips_cprestore_offset = get_absolute_expression ();
15540   mips_cprestore_valid = 1;
15541
15542   ex.X_op = O_constant;
15543   ex.X_add_symbol = NULL;
15544   ex.X_op_symbol = NULL;
15545   ex.X_add_number = mips_cprestore_offset;
15546
15547   mips_mark_labels ();
15548   mips_assembling_insn = TRUE;
15549
15550   macro_start ();
15551   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15552                                 SP, HAVE_64BIT_ADDRESSES);
15553   macro_end ();
15554
15555   mips_assembling_insn = FALSE;
15556   demand_empty_rest_of_line ();
15557 }
15558
15559 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15560    was given in the preceding .cpsetup, it results in:
15561      ld         $gp, offset($sp)
15562
15563    If a register $reg2 was given there, it results in:
15564      daddu      $gp, $reg2, $0  */
15565
15566 static void
15567 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15568 {
15569   expressionS ex;
15570
15571   file_mips_check_options ();
15572
15573   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15574      We also need NewABI support.  */
15575   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15576     {
15577       s_ignore (0);
15578       return;
15579     }
15580
15581   if (mips_opts.mips16)
15582     {
15583       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15584       ignore_rest_of_line ();
15585       return;
15586     }
15587
15588   mips_mark_labels ();
15589   mips_assembling_insn = TRUE;
15590
15591   macro_start ();
15592   if (mips_cpreturn_register == -1)
15593     {
15594       ex.X_op = O_constant;
15595       ex.X_add_symbol = NULL;
15596       ex.X_op_symbol = NULL;
15597       ex.X_add_number = mips_cpreturn_offset;
15598
15599       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15600     }
15601   else
15602     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15603                  mips_cpreturn_register, 0);
15604   macro_end ();
15605
15606   mips_assembling_insn = FALSE;
15607   demand_empty_rest_of_line ();
15608 }
15609
15610 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15611    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15612    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15613    debug information or MIPS16 TLS.  */
15614
15615 static void
15616 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15617                      bfd_reloc_code_real_type rtype)
15618 {
15619   expressionS ex;
15620   char *p;
15621
15622   expression (&ex);
15623
15624   if (ex.X_op != O_symbol)
15625     {
15626       as_bad (_("unsupported use of %s"), dirstr);
15627       ignore_rest_of_line ();
15628     }
15629
15630   p = frag_more (bytes);
15631   md_number_to_chars (p, 0, bytes);
15632   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15633   demand_empty_rest_of_line ();
15634   mips_clear_insn_labels ();
15635 }
15636
15637 /* Handle .dtprelword.  */
15638
15639 static void
15640 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15641 {
15642   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15643 }
15644
15645 /* Handle .dtpreldword.  */
15646
15647 static void
15648 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15649 {
15650   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15651 }
15652
15653 /* Handle .tprelword.  */
15654
15655 static void
15656 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15657 {
15658   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15659 }
15660
15661 /* Handle .tpreldword.  */
15662
15663 static void
15664 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15665 {
15666   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15667 }
15668
15669 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15670    code.  It sets the offset to use in gp_rel relocations.  */
15671
15672 static void
15673 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15674 {
15675   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15676      We also need NewABI support.  */
15677   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15678     {
15679       s_ignore (0);
15680       return;
15681     }
15682
15683   mips_gprel_offset = get_absolute_expression ();
15684
15685   demand_empty_rest_of_line ();
15686 }
15687
15688 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15689    code.  It generates a 32 bit GP relative reloc.  */
15690
15691 static void
15692 s_gpword (int ignore ATTRIBUTE_UNUSED)
15693 {
15694   segment_info_type *si;
15695   struct insn_label_list *l;
15696   expressionS ex;
15697   char *p;
15698
15699   /* When not generating PIC code, this is treated as .word.  */
15700   if (mips_pic != SVR4_PIC)
15701     {
15702       s_cons (2);
15703       return;
15704     }
15705
15706   si = seg_info (now_seg);
15707   l = si->label_list;
15708   mips_emit_delays ();
15709   if (auto_align)
15710     mips_align (2, 0, l);
15711
15712   expression (&ex);
15713   mips_clear_insn_labels ();
15714
15715   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15716     {
15717       as_bad (_("unsupported use of .gpword"));
15718       ignore_rest_of_line ();
15719     }
15720
15721   p = frag_more (4);
15722   md_number_to_chars (p, 0, 4);
15723   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15724                BFD_RELOC_GPREL32);
15725
15726   demand_empty_rest_of_line ();
15727 }
15728
15729 static void
15730 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15731 {
15732   segment_info_type *si;
15733   struct insn_label_list *l;
15734   expressionS ex;
15735   char *p;
15736
15737   /* When not generating PIC code, this is treated as .dword.  */
15738   if (mips_pic != SVR4_PIC)
15739     {
15740       s_cons (3);
15741       return;
15742     }
15743
15744   si = seg_info (now_seg);
15745   l = si->label_list;
15746   mips_emit_delays ();
15747   if (auto_align)
15748     mips_align (3, 0, l);
15749
15750   expression (&ex);
15751   mips_clear_insn_labels ();
15752
15753   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15754     {
15755       as_bad (_("unsupported use of .gpdword"));
15756       ignore_rest_of_line ();
15757     }
15758
15759   p = frag_more (8);
15760   md_number_to_chars (p, 0, 8);
15761   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15762                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15763
15764   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15765   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15766            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15767
15768   demand_empty_rest_of_line ();
15769 }
15770
15771 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15772    tables.  It generates a R_MIPS_EH reloc.  */
15773
15774 static void
15775 s_ehword (int ignore ATTRIBUTE_UNUSED)
15776 {
15777   expressionS ex;
15778   char *p;
15779
15780   mips_emit_delays ();
15781
15782   expression (&ex);
15783   mips_clear_insn_labels ();
15784
15785   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15786     {
15787       as_bad (_("unsupported use of .ehword"));
15788       ignore_rest_of_line ();
15789     }
15790
15791   p = frag_more (4);
15792   md_number_to_chars (p, 0, 4);
15793   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15794                BFD_RELOC_MIPS_EH);
15795
15796   demand_empty_rest_of_line ();
15797 }
15798
15799 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15800    tables in SVR4 PIC code.  */
15801
15802 static void
15803 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15804 {
15805   int reg;
15806
15807   file_mips_check_options ();
15808
15809   /* This is ignored when not generating SVR4 PIC code.  */
15810   if (mips_pic != SVR4_PIC)
15811     {
15812       s_ignore (0);
15813       return;
15814     }
15815
15816   mips_mark_labels ();
15817   mips_assembling_insn = TRUE;
15818
15819   /* Add $gp to the register named as an argument.  */
15820   macro_start ();
15821   reg = tc_get_register (0);
15822   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15823   macro_end ();
15824
15825   mips_assembling_insn = FALSE;
15826   demand_empty_rest_of_line ();
15827 }
15828
15829 /* Handle the .insn pseudo-op.  This marks instruction labels in
15830    mips16/micromips mode.  This permits the linker to handle them specially,
15831    such as generating jalx instructions when needed.  We also make
15832    them odd for the duration of the assembly, in order to generate the
15833    right sort of code.  We will make them even in the adjust_symtab
15834    routine, while leaving them marked.  This is convenient for the
15835    debugger and the disassembler.  The linker knows to make them odd
15836    again.  */
15837
15838 static void
15839 s_insn (int ignore ATTRIBUTE_UNUSED)
15840 {
15841   mips_mark_labels ();
15842
15843   demand_empty_rest_of_line ();
15844 }
15845
15846 /* Handle the .nan pseudo-op.  */
15847
15848 static void
15849 s_nan (int ignore ATTRIBUTE_UNUSED)
15850 {
15851   static const char str_legacy[] = "legacy";
15852   static const char str_2008[] = "2008";
15853   size_t i;
15854
15855   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15856
15857   if (i == sizeof (str_2008) - 1
15858       && memcmp (input_line_pointer, str_2008, i) == 0)
15859     mips_flag_nan2008 = TRUE;
15860   else if (i == sizeof (str_legacy) - 1
15861            && memcmp (input_line_pointer, str_legacy, i) == 0)
15862     mips_flag_nan2008 = FALSE;
15863   else
15864     as_bad (_("bad .nan directive"));
15865
15866   input_line_pointer += i;
15867   demand_empty_rest_of_line ();
15868 }
15869
15870 /* Handle a .stab[snd] directive.  Ideally these directives would be
15871    implemented in a transparent way, so that removing them would not
15872    have any effect on the generated instructions.  However, s_stab
15873    internally changes the section, so in practice we need to decide
15874    now whether the preceding label marks compressed code.  We do not
15875    support changing the compression mode of a label after a .stab*
15876    directive, such as in:
15877
15878    foo:
15879         .stabs ...
15880         .set mips16
15881
15882    so the current mode wins.  */
15883
15884 static void
15885 s_mips_stab (int type)
15886 {
15887   mips_mark_labels ();
15888   s_stab (type);
15889 }
15890
15891 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15892
15893 static void
15894 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15895 {
15896   char *name;
15897   int c;
15898   symbolS *symbolP;
15899   expressionS exp;
15900
15901   name = input_line_pointer;
15902   c = get_symbol_end ();
15903   symbolP = symbol_find_or_make (name);
15904   S_SET_WEAK (symbolP);
15905   *input_line_pointer = c;
15906
15907   SKIP_WHITESPACE ();
15908
15909   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15910     {
15911       if (S_IS_DEFINED (symbolP))
15912         {
15913           as_bad (_("ignoring attempt to redefine symbol %s"),
15914                   S_GET_NAME (symbolP));
15915           ignore_rest_of_line ();
15916           return;
15917         }
15918
15919       if (*input_line_pointer == ',')
15920         {
15921           ++input_line_pointer;
15922           SKIP_WHITESPACE ();
15923         }
15924
15925       expression (&exp);
15926       if (exp.X_op != O_symbol)
15927         {
15928           as_bad (_("bad .weakext directive"));
15929           ignore_rest_of_line ();
15930           return;
15931         }
15932       symbol_set_value_expression (symbolP, &exp);
15933     }
15934
15935   demand_empty_rest_of_line ();
15936 }
15937
15938 /* Parse a register string into a number.  Called from the ECOFF code
15939    to parse .frame.  The argument is non-zero if this is the frame
15940    register, so that we can record it in mips_frame_reg.  */
15941
15942 int
15943 tc_get_register (int frame)
15944 {
15945   unsigned int reg;
15946
15947   SKIP_WHITESPACE ();
15948   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15949     reg = 0;
15950   if (frame)
15951     {
15952       mips_frame_reg = reg != 0 ? reg : SP;
15953       mips_frame_reg_valid = 1;
15954       mips_cprestore_valid = 0;
15955     }
15956   return reg;
15957 }
15958
15959 valueT
15960 md_section_align (asection *seg, valueT addr)
15961 {
15962   int align = bfd_get_section_alignment (stdoutput, seg);
15963
15964   /* We don't need to align ELF sections to the full alignment.
15965      However, Irix 5 may prefer that we align them at least to a 16
15966      byte boundary.  We don't bother to align the sections if we
15967      are targeted for an embedded system.  */
15968   if (strncmp (TARGET_OS, "elf", 3) == 0)
15969     return addr;
15970   if (align > 4)
15971     align = 4;
15972
15973   return ((addr + (1 << align) - 1) & (-1 << align));
15974 }
15975
15976 /* Utility routine, called from above as well.  If called while the
15977    input file is still being read, it's only an approximation.  (For
15978    example, a symbol may later become defined which appeared to be
15979    undefined earlier.)  */
15980
15981 static int
15982 nopic_need_relax (symbolS *sym, int before_relaxing)
15983 {
15984   if (sym == 0)
15985     return 0;
15986
15987   if (g_switch_value > 0)
15988     {
15989       const char *symname;
15990       int change;
15991
15992       /* Find out whether this symbol can be referenced off the $gp
15993          register.  It can be if it is smaller than the -G size or if
15994          it is in the .sdata or .sbss section.  Certain symbols can
15995          not be referenced off the $gp, although it appears as though
15996          they can.  */
15997       symname = S_GET_NAME (sym);
15998       if (symname != (const char *) NULL
15999           && (strcmp (symname, "eprol") == 0
16000               || strcmp (symname, "etext") == 0
16001               || strcmp (symname, "_gp") == 0
16002               || strcmp (symname, "edata") == 0
16003               || strcmp (symname, "_fbss") == 0
16004               || strcmp (symname, "_fdata") == 0
16005               || strcmp (symname, "_ftext") == 0
16006               || strcmp (symname, "end") == 0
16007               || strcmp (symname, "_gp_disp") == 0))
16008         change = 1;
16009       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16010                && (0
16011 #ifndef NO_ECOFF_DEBUGGING
16012                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16013                        && (symbol_get_obj (sym)->ecoff_extern_size
16014                            <= g_switch_value))
16015 #endif
16016                    /* We must defer this decision until after the whole
16017                       file has been read, since there might be a .extern
16018                       after the first use of this symbol.  */
16019                    || (before_relaxing
16020 #ifndef NO_ECOFF_DEBUGGING
16021                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16022 #endif
16023                        && S_GET_VALUE (sym) == 0)
16024                    || (S_GET_VALUE (sym) != 0
16025                        && S_GET_VALUE (sym) <= g_switch_value)))
16026         change = 0;
16027       else
16028         {
16029           const char *segname;
16030
16031           segname = segment_name (S_GET_SEGMENT (sym));
16032           gas_assert (strcmp (segname, ".lit8") != 0
16033                   && strcmp (segname, ".lit4") != 0);
16034           change = (strcmp (segname, ".sdata") != 0
16035                     && strcmp (segname, ".sbss") != 0
16036                     && strncmp (segname, ".sdata.", 7) != 0
16037                     && strncmp (segname, ".sbss.", 6) != 0
16038                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16039                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16040         }
16041       return change;
16042     }
16043   else
16044     /* We are not optimizing for the $gp register.  */
16045     return 1;
16046 }
16047
16048
16049 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16050
16051 static bfd_boolean
16052 pic_need_relax (symbolS *sym, asection *segtype)
16053 {
16054   asection *symsec;
16055
16056   /* Handle the case of a symbol equated to another symbol.  */
16057   while (symbol_equated_reloc_p (sym))
16058     {
16059       symbolS *n;
16060
16061       /* It's possible to get a loop here in a badly written program.  */
16062       n = symbol_get_value_expression (sym)->X_add_symbol;
16063       if (n == sym)
16064         break;
16065       sym = n;
16066     }
16067
16068   if (symbol_section_p (sym))
16069     return TRUE;
16070
16071   symsec = S_GET_SEGMENT (sym);
16072
16073   /* This must duplicate the test in adjust_reloc_syms.  */
16074   return (!bfd_is_und_section (symsec)
16075           && !bfd_is_abs_section (symsec)
16076           && !bfd_is_com_section (symsec)
16077           && !s_is_linkonce (sym, segtype)
16078           /* A global or weak symbol is treated as external.  */
16079           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16080 }
16081
16082
16083 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16084    extended opcode.  SEC is the section the frag is in.  */
16085
16086 static int
16087 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16088 {
16089   int type;
16090   const struct mips_int_operand *operand;
16091   offsetT val;
16092   segT symsec;
16093   fragS *sym_frag;
16094
16095   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16096     return 0;
16097   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16098     return 1;
16099
16100   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16101   operand = mips16_immed_operand (type, FALSE);
16102
16103   sym_frag = symbol_get_frag (fragp->fr_symbol);
16104   val = S_GET_VALUE (fragp->fr_symbol);
16105   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16106
16107   if (operand->root.type == OP_PCREL)
16108     {
16109       const struct mips_pcrel_operand *pcrel_op;
16110       addressT addr;
16111       offsetT maxtiny;
16112
16113       /* We won't have the section when we are called from
16114          mips_relax_frag.  However, we will always have been called
16115          from md_estimate_size_before_relax first.  If this is a
16116          branch to a different section, we mark it as such.  If SEC is
16117          NULL, and the frag is not marked, then it must be a branch to
16118          the same section.  */
16119       pcrel_op = (const struct mips_pcrel_operand *) operand;
16120       if (sec == NULL)
16121         {
16122           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16123             return 1;
16124         }
16125       else
16126         {
16127           /* Must have been called from md_estimate_size_before_relax.  */
16128           if (symsec != sec)
16129             {
16130               fragp->fr_subtype =
16131                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16132
16133               /* FIXME: We should support this, and let the linker
16134                  catch branches and loads that are out of range.  */
16135               as_bad_where (fragp->fr_file, fragp->fr_line,
16136                             _("unsupported PC relative reference to different section"));
16137
16138               return 1;
16139             }
16140           if (fragp != sym_frag && sym_frag->fr_address == 0)
16141             /* Assume non-extended on the first relaxation pass.
16142                The address we have calculated will be bogus if this is
16143                a forward branch to another frag, as the forward frag
16144                will have fr_address == 0.  */
16145             return 0;
16146         }
16147
16148       /* In this case, we know for sure that the symbol fragment is in
16149          the same section.  If the relax_marker of the symbol fragment
16150          differs from the relax_marker of this fragment, we have not
16151          yet adjusted the symbol fragment fr_address.  We want to add
16152          in STRETCH in order to get a better estimate of the address.
16153          This particularly matters because of the shift bits.  */
16154       if (stretch != 0
16155           && sym_frag->relax_marker != fragp->relax_marker)
16156         {
16157           fragS *f;
16158
16159           /* Adjust stretch for any alignment frag.  Note that if have
16160              been expanding the earlier code, the symbol may be
16161              defined in what appears to be an earlier frag.  FIXME:
16162              This doesn't handle the fr_subtype field, which specifies
16163              a maximum number of bytes to skip when doing an
16164              alignment.  */
16165           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16166             {
16167               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16168                 {
16169                   if (stretch < 0)
16170                     stretch = - ((- stretch)
16171                                  & ~ ((1 << (int) f->fr_offset) - 1));
16172                   else
16173                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16174                   if (stretch == 0)
16175                     break;
16176                 }
16177             }
16178           if (f != NULL)
16179             val += stretch;
16180         }
16181
16182       addr = fragp->fr_address + fragp->fr_fix;
16183
16184       /* The base address rules are complicated.  The base address of
16185          a branch is the following instruction.  The base address of a
16186          PC relative load or add is the instruction itself, but if it
16187          is in a delay slot (in which case it can not be extended) use
16188          the address of the instruction whose delay slot it is in.  */
16189       if (pcrel_op->include_isa_bit)
16190         {
16191           addr += 2;
16192
16193           /* If we are currently assuming that this frag should be
16194              extended, then, the current address is two bytes
16195              higher.  */
16196           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16197             addr += 2;
16198
16199           /* Ignore the low bit in the target, since it will be set
16200              for a text label.  */
16201           val &= -2;
16202         }
16203       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16204         addr -= 4;
16205       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16206         addr -= 2;
16207
16208       val -= addr & -(1 << pcrel_op->align_log2);
16209
16210       /* If any of the shifted bits are set, we must use an extended
16211          opcode.  If the address depends on the size of this
16212          instruction, this can lead to a loop, so we arrange to always
16213          use an extended opcode.  We only check this when we are in
16214          the main relaxation loop, when SEC is NULL.  */
16215       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16216         {
16217           fragp->fr_subtype =
16218             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16219           return 1;
16220         }
16221
16222       /* If we are about to mark a frag as extended because the value
16223          is precisely the next value above maxtiny, then there is a
16224          chance of an infinite loop as in the following code:
16225              la $4,foo
16226              .skip      1020
16227              .align     2
16228            foo:
16229          In this case when the la is extended, foo is 0x3fc bytes
16230          away, so the la can be shrunk, but then foo is 0x400 away, so
16231          the la must be extended.  To avoid this loop, we mark the
16232          frag as extended if it was small, and is about to become
16233          extended with the next value above maxtiny.  */
16234       maxtiny = mips_int_operand_max (operand);
16235       if (val == maxtiny + (1 << operand->shift)
16236           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16237           && sec == NULL)
16238         {
16239           fragp->fr_subtype =
16240             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16241           return 1;
16242         }
16243     }
16244   else if (symsec != absolute_section && sec != NULL)
16245     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16246
16247   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16248 }
16249
16250 /* Compute the length of a branch sequence, and adjust the
16251    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16252    worst-case length is computed, with UPDATE being used to indicate
16253    whether an unconditional (-1), branch-likely (+1) or regular (0)
16254    branch is to be computed.  */
16255 static int
16256 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16257 {
16258   bfd_boolean toofar;
16259   int length;
16260
16261   if (fragp
16262       && S_IS_DEFINED (fragp->fr_symbol)
16263       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16264     {
16265       addressT addr;
16266       offsetT val;
16267
16268       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16269
16270       addr = fragp->fr_address + fragp->fr_fix + 4;
16271
16272       val -= addr;
16273
16274       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16275     }
16276   else if (fragp)
16277     /* If the symbol is not defined or it's in a different segment,
16278        assume the user knows what's going on and emit a short
16279        branch.  */
16280     toofar = FALSE;
16281   else
16282     toofar = TRUE;
16283
16284   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16285     fragp->fr_subtype
16286       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16287                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16288                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16289                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16290                              toofar);
16291
16292   length = 4;
16293   if (toofar)
16294     {
16295       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16296         length += 8;
16297
16298       if (mips_pic != NO_PIC)
16299         {
16300           /* Additional space for PIC loading of target address.  */
16301           length += 8;
16302           if (mips_opts.isa == ISA_MIPS1)
16303             /* Additional space for $at-stabilizing nop.  */
16304             length += 4;
16305         }
16306
16307       /* If branch is conditional.  */
16308       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16309         length += 8;
16310     }
16311
16312   return length;
16313 }
16314
16315 /* Compute the length of a branch sequence, and adjust the
16316    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16317    worst-case length is computed, with UPDATE being used to indicate
16318    whether an unconditional (-1), or regular (0) branch is to be
16319    computed.  */
16320
16321 static int
16322 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16323 {
16324   bfd_boolean toofar;
16325   int length;
16326
16327   if (fragp
16328       && S_IS_DEFINED (fragp->fr_symbol)
16329       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16330     {
16331       addressT addr;
16332       offsetT val;
16333
16334       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16335       /* Ignore the low bit in the target, since it will be set
16336          for a text label.  */
16337       if ((val & 1) != 0)
16338         --val;
16339
16340       addr = fragp->fr_address + fragp->fr_fix + 4;
16341
16342       val -= addr;
16343
16344       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16345     }
16346   else if (fragp)
16347     /* If the symbol is not defined or it's in a different segment,
16348        assume the user knows what's going on and emit a short
16349        branch.  */
16350     toofar = FALSE;
16351   else
16352     toofar = TRUE;
16353
16354   if (fragp && update
16355       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16356     fragp->fr_subtype = (toofar
16357                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16358                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16359
16360   length = 4;
16361   if (toofar)
16362     {
16363       bfd_boolean compact_known = fragp != NULL;
16364       bfd_boolean compact = FALSE;
16365       bfd_boolean uncond;
16366
16367       if (compact_known)
16368         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16369       if (fragp)
16370         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16371       else
16372         uncond = update < 0;
16373
16374       /* If label is out of range, we turn branch <br>:
16375
16376                 <br>    label                   # 4 bytes
16377             0:
16378
16379          into:
16380
16381                 j       label                   # 4 bytes
16382                 nop                             # 2 bytes if compact && !PIC
16383             0:
16384        */
16385       if (mips_pic == NO_PIC && (!compact_known || compact))
16386         length += 2;
16387
16388       /* If assembling PIC code, we further turn:
16389
16390                         j       label                   # 4 bytes
16391
16392          into:
16393
16394                         lw/ld   at, %got(label)(gp)     # 4 bytes
16395                         d/addiu at, %lo(label)          # 4 bytes
16396                         jr/c    at                      # 2 bytes
16397        */
16398       if (mips_pic != NO_PIC)
16399         length += 6;
16400
16401       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16402
16403                         <brneg> 0f                      # 4 bytes
16404                         nop                             # 2 bytes if !compact
16405        */
16406       if (!uncond)
16407         length += (compact_known && compact) ? 4 : 6;
16408     }
16409
16410   return length;
16411 }
16412
16413 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16414    bit accordingly.  */
16415
16416 static int
16417 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16418 {
16419   bfd_boolean toofar;
16420
16421   if (fragp
16422       && S_IS_DEFINED (fragp->fr_symbol)
16423       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16424     {
16425       addressT addr;
16426       offsetT val;
16427       int type;
16428
16429       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16430       /* Ignore the low bit in the target, since it will be set
16431          for a text label.  */
16432       if ((val & 1) != 0)
16433         --val;
16434
16435       /* Assume this is a 2-byte branch.  */
16436       addr = fragp->fr_address + fragp->fr_fix + 2;
16437
16438       /* We try to avoid the infinite loop by not adding 2 more bytes for
16439          long branches.  */
16440
16441       val -= addr;
16442
16443       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16444       if (type == 'D')
16445         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16446       else if (type == 'E')
16447         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16448       else
16449         abort ();
16450     }
16451   else
16452     /* If the symbol is not defined or it's in a different segment,
16453        we emit a normal 32-bit branch.  */
16454     toofar = TRUE;
16455
16456   if (fragp && update
16457       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16458     fragp->fr_subtype
16459       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16460                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16461
16462   if (toofar)
16463     return 4;
16464
16465   return 2;
16466 }
16467
16468 /* Estimate the size of a frag before relaxing.  Unless this is the
16469    mips16, we are not really relaxing here, and the final size is
16470    encoded in the subtype information.  For the mips16, we have to
16471    decide whether we are using an extended opcode or not.  */
16472
16473 int
16474 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16475 {
16476   int change;
16477
16478   if (RELAX_BRANCH_P (fragp->fr_subtype))
16479     {
16480
16481       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16482
16483       return fragp->fr_var;
16484     }
16485
16486   if (RELAX_MIPS16_P (fragp->fr_subtype))
16487     /* We don't want to modify the EXTENDED bit here; it might get us
16488        into infinite loops.  We change it only in mips_relax_frag().  */
16489     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16490
16491   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16492     {
16493       int length = 4;
16494
16495       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16496         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16497       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16498         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16499       fragp->fr_var = length;
16500
16501       return length;
16502     }
16503
16504   if (mips_pic == NO_PIC)
16505     change = nopic_need_relax (fragp->fr_symbol, 0);
16506   else if (mips_pic == SVR4_PIC)
16507     change = pic_need_relax (fragp->fr_symbol, segtype);
16508   else if (mips_pic == VXWORKS_PIC)
16509     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16510     change = 0;
16511   else
16512     abort ();
16513
16514   if (change)
16515     {
16516       fragp->fr_subtype |= RELAX_USE_SECOND;
16517       return -RELAX_FIRST (fragp->fr_subtype);
16518     }
16519   else
16520     return -RELAX_SECOND (fragp->fr_subtype);
16521 }
16522
16523 /* This is called to see whether a reloc against a defined symbol
16524    should be converted into a reloc against a section.  */
16525
16526 int
16527 mips_fix_adjustable (fixS *fixp)
16528 {
16529   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16530       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16531     return 0;
16532
16533   if (fixp->fx_addsy == NULL)
16534     return 1;
16535
16536   /* If symbol SYM is in a mergeable section, relocations of the form
16537      SYM + 0 can usually be made section-relative.  The mergeable data
16538      is then identified by the section offset rather than by the symbol.
16539
16540      However, if we're generating REL LO16 relocations, the offset is split
16541      between the LO16 and parterning high part relocation.  The linker will
16542      need to recalculate the complete offset in order to correctly identify
16543      the merge data.
16544
16545      The linker has traditionally not looked for the parterning high part
16546      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16547      placed anywhere.  Rather than break backwards compatibility by changing
16548      this, it seems better not to force the issue, and instead keep the
16549      original symbol.  This will work with either linker behavior.  */
16550   if ((lo16_reloc_p (fixp->fx_r_type)
16551        || reloc_needs_lo_p (fixp->fx_r_type))
16552       && HAVE_IN_PLACE_ADDENDS
16553       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16554     return 0;
16555
16556   /* There is no place to store an in-place offset for JALR relocations.
16557      Likewise an in-range offset of limited PC-relative relocations may
16558      overflow the in-place relocatable field if recalculated against the
16559      start address of the symbol's containing section.  */
16560   if (HAVE_IN_PLACE_ADDENDS
16561       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16562           || jalr_reloc_p (fixp->fx_r_type)))
16563     return 0;
16564
16565   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16566      to a floating-point stub.  The same is true for non-R_MIPS16_26
16567      relocations against MIPS16 functions; in this case, the stub becomes
16568      the function's canonical address.
16569
16570      Floating-point stubs are stored in unique .mips16.call.* or
16571      .mips16.fn.* sections.  If a stub T for function F is in section S,
16572      the first relocation in section S must be against F; this is how the
16573      linker determines the target function.  All relocations that might
16574      resolve to T must also be against F.  We therefore have the following
16575      restrictions, which are given in an intentionally-redundant way:
16576
16577        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16578           symbols.
16579
16580        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16581           if that stub might be used.
16582
16583        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16584           symbols.
16585
16586        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16587           that stub might be used.
16588
16589      There is a further restriction:
16590
16591        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16592           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16593           targets with in-place addends; the relocation field cannot
16594           encode the low bit.
16595
16596      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16597      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16598      such relocations on REL targets.
16599
16600      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16601      relocation against some symbol R, no relocation against R may be
16602      reduced.  (Note that this deals with (2) as well as (1) because
16603      relocations against global symbols will never be reduced on ELF
16604      targets.)  This approach is a little simpler than trying to detect
16605      stub sections, and gives the "all or nothing" per-symbol consistency
16606      that we have for MIPS16 symbols.  */
16607   if (fixp->fx_subsy == NULL
16608       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16609           || *symbol_get_tc (fixp->fx_addsy)
16610           || (HAVE_IN_PLACE_ADDENDS
16611               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16612               && jmp_reloc_p (fixp->fx_r_type))))
16613     return 0;
16614
16615   return 1;
16616 }
16617
16618 /* Translate internal representation of relocation info to BFD target
16619    format.  */
16620
16621 arelent **
16622 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16623 {
16624   static arelent *retval[4];
16625   arelent *reloc;
16626   bfd_reloc_code_real_type code;
16627
16628   memset (retval, 0, sizeof(retval));
16629   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16630   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16631   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16632   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16633
16634   if (fixp->fx_pcrel)
16635     {
16636       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16637                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16638                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16639                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16640                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16641
16642       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16643          Relocations want only the symbol offset.  */
16644       reloc->addend = fixp->fx_addnumber + reloc->address;
16645     }
16646   else
16647     reloc->addend = fixp->fx_addnumber;
16648
16649   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16650      entry to be used in the relocation's section offset.  */
16651   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16652     {
16653       reloc->address = reloc->addend;
16654       reloc->addend = 0;
16655     }
16656
16657   code = fixp->fx_r_type;
16658
16659   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16660   if (reloc->howto == NULL)
16661     {
16662       as_bad_where (fixp->fx_file, fixp->fx_line,
16663                     _("cannot represent %s relocation in this object file"
16664                       " format"),
16665                     bfd_get_reloc_code_name (code));
16666       retval[0] = NULL;
16667     }
16668
16669   return retval;
16670 }
16671
16672 /* Relax a machine dependent frag.  This returns the amount by which
16673    the current size of the frag should change.  */
16674
16675 int
16676 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16677 {
16678   if (RELAX_BRANCH_P (fragp->fr_subtype))
16679     {
16680       offsetT old_var = fragp->fr_var;
16681
16682       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16683
16684       return fragp->fr_var - old_var;
16685     }
16686
16687   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16688     {
16689       offsetT old_var = fragp->fr_var;
16690       offsetT new_var = 4;
16691
16692       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16693         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16694       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16695         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16696       fragp->fr_var = new_var;
16697
16698       return new_var - old_var;
16699     }
16700
16701   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16702     return 0;
16703
16704   if (mips16_extended_frag (fragp, NULL, stretch))
16705     {
16706       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16707         return 0;
16708       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16709       return 2;
16710     }
16711   else
16712     {
16713       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16714         return 0;
16715       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16716       return -2;
16717     }
16718
16719   return 0;
16720 }
16721
16722 /* Convert a machine dependent frag.  */
16723
16724 void
16725 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16726 {
16727   if (RELAX_BRANCH_P (fragp->fr_subtype))
16728     {
16729       char *buf;
16730       unsigned long insn;
16731       expressionS exp;
16732       fixS *fixp;
16733
16734       buf = fragp->fr_literal + fragp->fr_fix;
16735       insn = read_insn (buf);
16736
16737       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16738         {
16739           /* We generate a fixup instead of applying it right now
16740              because, if there are linker relaxations, we're going to
16741              need the relocations.  */
16742           exp.X_op = O_symbol;
16743           exp.X_add_symbol = fragp->fr_symbol;
16744           exp.X_add_number = fragp->fr_offset;
16745
16746           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16747                               BFD_RELOC_16_PCREL_S2);
16748           fixp->fx_file = fragp->fr_file;
16749           fixp->fx_line = fragp->fr_line;
16750
16751           buf = write_insn (buf, insn);
16752         }
16753       else
16754         {
16755           int i;
16756
16757           as_warn_where (fragp->fr_file, fragp->fr_line,
16758                          _("relaxed out-of-range branch into a jump"));
16759
16760           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16761             goto uncond;
16762
16763           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16764             {
16765               /* Reverse the branch.  */
16766               switch ((insn >> 28) & 0xf)
16767                 {
16768                 case 4:
16769                   if ((insn & 0xff000000) == 0x47000000
16770                       || (insn & 0xff600000) == 0x45600000)
16771                     {
16772                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16773                          reversed by tweaking bit 23.  */
16774                       insn ^= 0x00800000;
16775                     }
16776                   else
16777                     {
16778                       /* bc[0-3][tf]l? instructions can have the condition
16779                          reversed by tweaking a single TF bit, and their
16780                          opcodes all have 0x4???????.  */
16781                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16782                       insn ^= 0x00010000;
16783                     }
16784                   break;
16785
16786                 case 0:
16787                   /* bltz       0x04000000      bgez    0x04010000
16788                      bltzal     0x04100000      bgezal  0x04110000  */
16789                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16790                   insn ^= 0x00010000;
16791                   break;
16792
16793                 case 1:
16794                   /* beq        0x10000000      bne     0x14000000
16795                      blez       0x18000000      bgtz    0x1c000000  */
16796                   insn ^= 0x04000000;
16797                   break;
16798
16799                 default:
16800                   abort ();
16801                 }
16802             }
16803
16804           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16805             {
16806               /* Clear the and-link bit.  */
16807               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16808
16809               /* bltzal         0x04100000      bgezal  0x04110000
16810                  bltzall        0x04120000      bgezall 0x04130000  */
16811               insn &= ~0x00100000;
16812             }
16813
16814           /* Branch over the branch (if the branch was likely) or the
16815              full jump (not likely case).  Compute the offset from the
16816              current instruction to branch to.  */
16817           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16818             i = 16;
16819           else
16820             {
16821               /* How many bytes in instructions we've already emitted?  */
16822               i = buf - fragp->fr_literal - fragp->fr_fix;
16823               /* How many bytes in instructions from here to the end?  */
16824               i = fragp->fr_var - i;
16825             }
16826           /* Convert to instruction count.  */
16827           i >>= 2;
16828           /* Branch counts from the next instruction.  */
16829           i--;
16830           insn |= i;
16831           /* Branch over the jump.  */
16832           buf = write_insn (buf, insn);
16833
16834           /* nop */
16835           buf = write_insn (buf, 0);
16836
16837           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16838             {
16839               /* beql $0, $0, 2f */
16840               insn = 0x50000000;
16841               /* Compute the PC offset from the current instruction to
16842                  the end of the variable frag.  */
16843               /* How many bytes in instructions we've already emitted?  */
16844               i = buf - fragp->fr_literal - fragp->fr_fix;
16845               /* How many bytes in instructions from here to the end?  */
16846               i = fragp->fr_var - i;
16847               /* Convert to instruction count.  */
16848               i >>= 2;
16849               /* Don't decrement i, because we want to branch over the
16850                  delay slot.  */
16851               insn |= i;
16852
16853               buf = write_insn (buf, insn);
16854               buf = write_insn (buf, 0);
16855             }
16856
16857         uncond:
16858           if (mips_pic == NO_PIC)
16859             {
16860               /* j or jal.  */
16861               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16862                       ? 0x0c000000 : 0x08000000);
16863               exp.X_op = O_symbol;
16864               exp.X_add_symbol = fragp->fr_symbol;
16865               exp.X_add_number = fragp->fr_offset;
16866
16867               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16868                                   FALSE, BFD_RELOC_MIPS_JMP);
16869               fixp->fx_file = fragp->fr_file;
16870               fixp->fx_line = fragp->fr_line;
16871
16872               buf = write_insn (buf, insn);
16873             }
16874           else
16875             {
16876               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16877
16878               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16879               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16880               insn |= at << OP_SH_RT;
16881               exp.X_op = O_symbol;
16882               exp.X_add_symbol = fragp->fr_symbol;
16883               exp.X_add_number = fragp->fr_offset;
16884
16885               if (fragp->fr_offset)
16886                 {
16887                   exp.X_add_symbol = make_expr_symbol (&exp);
16888                   exp.X_add_number = 0;
16889                 }
16890
16891               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16892                                   FALSE, BFD_RELOC_MIPS_GOT16);
16893               fixp->fx_file = fragp->fr_file;
16894               fixp->fx_line = fragp->fr_line;
16895
16896               buf = write_insn (buf, insn);
16897
16898               if (mips_opts.isa == ISA_MIPS1)
16899                 /* nop */
16900                 buf = write_insn (buf, 0);
16901
16902               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16903               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16904               insn |= at << OP_SH_RS | at << OP_SH_RT;
16905
16906               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16907                                   FALSE, BFD_RELOC_LO16);
16908               fixp->fx_file = fragp->fr_file;
16909               fixp->fx_line = fragp->fr_line;
16910
16911               buf = write_insn (buf, insn);
16912
16913               /* j(al)r $at.  */
16914               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16915                 insn = 0x0000f809;
16916               else
16917                 insn = 0x00000008;
16918               insn |= at << OP_SH_RS;
16919
16920               buf = write_insn (buf, insn);
16921             }
16922         }
16923
16924       fragp->fr_fix += fragp->fr_var;
16925       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16926       return;
16927     }
16928
16929   /* Relax microMIPS branches.  */
16930   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16931     {
16932       char *buf = fragp->fr_literal + fragp->fr_fix;
16933       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16934       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16935       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16936       bfd_boolean short_ds;
16937       unsigned long insn;
16938       expressionS exp;
16939       fixS *fixp;
16940
16941       exp.X_op = O_symbol;
16942       exp.X_add_symbol = fragp->fr_symbol;
16943       exp.X_add_number = fragp->fr_offset;
16944
16945       fragp->fr_fix += fragp->fr_var;
16946
16947       /* Handle 16-bit branches that fit or are forced to fit.  */
16948       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16949         {
16950           /* We generate a fixup instead of applying it right now,
16951              because if there is linker relaxation, we're going to
16952              need the relocations.  */
16953           if (type == 'D')
16954             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16955                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16956           else if (type == 'E')
16957             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16958                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16959           else
16960             abort ();
16961
16962           fixp->fx_file = fragp->fr_file;
16963           fixp->fx_line = fragp->fr_line;
16964
16965           /* These relocations can have an addend that won't fit in
16966              2 octets.  */
16967           fixp->fx_no_overflow = 1;
16968
16969           return;
16970         }
16971
16972       /* Handle 32-bit branches that fit or are forced to fit.  */
16973       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16974           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16975         {
16976           /* We generate a fixup instead of applying it right now,
16977              because if there is linker relaxation, we're going to
16978              need the relocations.  */
16979           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16980                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16981           fixp->fx_file = fragp->fr_file;
16982           fixp->fx_line = fragp->fr_line;
16983
16984           if (type == 0)
16985             return;
16986         }
16987
16988       /* Relax 16-bit branches to 32-bit branches.  */
16989       if (type != 0)
16990         {
16991           insn = read_compressed_insn (buf, 2);
16992
16993           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16994             insn = 0x94000000;                          /* beq  */
16995           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16996             {
16997               unsigned long regno;
16998
16999               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17000               regno = micromips_to_32_reg_d_map [regno];
17001               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17002               insn |= regno << MICROMIPSOP_SH_RS;
17003             }
17004           else
17005             abort ();
17006
17007           /* Nothing else to do, just write it out.  */
17008           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17009               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17010             {
17011               buf = write_compressed_insn (buf, insn, 4);
17012               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17013               return;
17014             }
17015         }
17016       else
17017         insn = read_compressed_insn (buf, 4);
17018
17019       /* Relax 32-bit branches to a sequence of instructions.  */
17020       as_warn_where (fragp->fr_file, fragp->fr_line,
17021                      _("relaxed out-of-range branch into a jump"));
17022
17023       /* Set the short-delay-slot bit.  */
17024       short_ds = al && (insn & 0x02000000) != 0;
17025
17026       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17027         {
17028           symbolS *l;
17029
17030           /* Reverse the branch.  */
17031           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17032               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17033             insn ^= 0x20000000;
17034           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17035                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17036                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17037                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17038                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17039                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17040                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17041                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17042                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17043                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17044             insn ^= 0x00400000;
17045           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17046                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17047                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17048                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17049             insn ^= 0x00200000;
17050           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
17051                                                                    BNZ.df  */
17052                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
17053                                                                    BNZ.V */
17054             insn ^= 0x00800000;
17055           else
17056             abort ();
17057
17058           if (al)
17059             {
17060               /* Clear the and-link and short-delay-slot bits.  */
17061               gas_assert ((insn & 0xfda00000) == 0x40200000);
17062
17063               /* bltzal  0x40200000     bgezal  0x40600000  */
17064               /* bltzals 0x42200000     bgezals 0x42600000  */
17065               insn &= ~0x02200000;
17066             }
17067
17068           /* Make a label at the end for use with the branch.  */
17069           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17070           micromips_label_inc ();
17071           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17072
17073           /* Refer to it.  */
17074           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17075                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17076           fixp->fx_file = fragp->fr_file;
17077           fixp->fx_line = fragp->fr_line;
17078
17079           /* Branch over the jump.  */
17080           buf = write_compressed_insn (buf, insn, 4);
17081           if (!compact)
17082             /* nop */
17083             buf = write_compressed_insn (buf, 0x0c00, 2);
17084         }
17085
17086       if (mips_pic == NO_PIC)
17087         {
17088           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17089
17090           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17091           insn = al ? jal : 0xd4000000;
17092
17093           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17094                               BFD_RELOC_MICROMIPS_JMP);
17095           fixp->fx_file = fragp->fr_file;
17096           fixp->fx_line = fragp->fr_line;
17097
17098           buf = write_compressed_insn (buf, insn, 4);
17099           if (compact)
17100             /* nop */
17101             buf = write_compressed_insn (buf, 0x0c00, 2);
17102         }
17103       else
17104         {
17105           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17106           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17107           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17108
17109           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17110           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17111           insn |= at << MICROMIPSOP_SH_RT;
17112
17113           if (exp.X_add_number)
17114             {
17115               exp.X_add_symbol = make_expr_symbol (&exp);
17116               exp.X_add_number = 0;
17117             }
17118
17119           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17120                               BFD_RELOC_MICROMIPS_GOT16);
17121           fixp->fx_file = fragp->fr_file;
17122           fixp->fx_line = fragp->fr_line;
17123
17124           buf = write_compressed_insn (buf, insn, 4);
17125
17126           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17127           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17128           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17129
17130           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17131                               BFD_RELOC_MICROMIPS_LO16);
17132           fixp->fx_file = fragp->fr_file;
17133           fixp->fx_line = fragp->fr_line;
17134
17135           buf = write_compressed_insn (buf, insn, 4);
17136
17137           /* jr/jrc/jalr/jalrs $at  */
17138           insn = al ? jalr : jr;
17139           insn |= at << MICROMIPSOP_SH_MJ;
17140
17141           buf = write_compressed_insn (buf, insn, 2);
17142         }
17143
17144       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17145       return;
17146     }
17147
17148   if (RELAX_MIPS16_P (fragp->fr_subtype))
17149     {
17150       int type;
17151       const struct mips_int_operand *operand;
17152       offsetT val;
17153       char *buf;
17154       unsigned int user_length, length;
17155       unsigned long insn;
17156       bfd_boolean ext;
17157
17158       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17159       operand = mips16_immed_operand (type, FALSE);
17160
17161       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17162       val = resolve_symbol_value (fragp->fr_symbol);
17163       if (operand->root.type == OP_PCREL)
17164         {
17165           const struct mips_pcrel_operand *pcrel_op;
17166           addressT addr;
17167
17168           pcrel_op = (const struct mips_pcrel_operand *) operand;
17169           addr = fragp->fr_address + fragp->fr_fix;
17170
17171           /* The rules for the base address of a PC relative reloc are
17172              complicated; see mips16_extended_frag.  */
17173           if (pcrel_op->include_isa_bit)
17174             {
17175               addr += 2;
17176               if (ext)
17177                 addr += 2;
17178               /* Ignore the low bit in the target, since it will be
17179                  set for a text label.  */
17180               val &= -2;
17181             }
17182           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17183             addr -= 4;
17184           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17185             addr -= 2;
17186
17187           addr &= -(1 << pcrel_op->align_log2);
17188           val -= addr;
17189
17190           /* Make sure the section winds up with the alignment we have
17191              assumed.  */
17192           if (operand->shift > 0)
17193             record_alignment (asec, operand->shift);
17194         }
17195
17196       if (ext
17197           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17198               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17199         as_warn_where (fragp->fr_file, fragp->fr_line,
17200                        _("extended instruction in delay slot"));
17201
17202       buf = fragp->fr_literal + fragp->fr_fix;
17203
17204       insn = read_compressed_insn (buf, 2);
17205       if (ext)
17206         insn |= MIPS16_EXTEND;
17207
17208       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17209         user_length = 4;
17210       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17211         user_length = 2;
17212       else
17213         user_length = 0;
17214
17215       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17216                     BFD_RELOC_UNUSED, val, user_length, &insn);
17217
17218       length = (ext ? 4 : 2);
17219       gas_assert (mips16_opcode_length (insn) == length);
17220       write_compressed_insn (buf, insn, length);
17221       fragp->fr_fix += length;
17222     }
17223   else
17224     {
17225       relax_substateT subtype = fragp->fr_subtype;
17226       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17227       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17228       int first, second;
17229       fixS *fixp;
17230
17231       first = RELAX_FIRST (subtype);
17232       second = RELAX_SECOND (subtype);
17233       fixp = (fixS *) fragp->fr_opcode;
17234
17235       /* If the delay slot chosen does not match the size of the instruction,
17236          then emit a warning.  */
17237       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17238            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17239         {
17240           relax_substateT s;
17241           const char *msg;
17242
17243           s = subtype & (RELAX_DELAY_SLOT_16BIT
17244                          | RELAX_DELAY_SLOT_SIZE_FIRST
17245                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17246           msg = macro_warning (s);
17247           if (msg != NULL)
17248             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17249           subtype &= ~s;
17250         }
17251
17252       /* Possibly emit a warning if we've chosen the longer option.  */
17253       if (use_second == second_longer)
17254         {
17255           relax_substateT s;
17256           const char *msg;
17257
17258           s = (subtype
17259                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17260           msg = macro_warning (s);
17261           if (msg != NULL)
17262             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17263           subtype &= ~s;
17264         }
17265
17266       /* Go through all the fixups for the first sequence.  Disable them
17267          (by marking them as done) if we're going to use the second
17268          sequence instead.  */
17269       while (fixp
17270              && fixp->fx_frag == fragp
17271              && fixp->fx_where < fragp->fr_fix - second)
17272         {
17273           if (subtype & RELAX_USE_SECOND)
17274             fixp->fx_done = 1;
17275           fixp = fixp->fx_next;
17276         }
17277
17278       /* Go through the fixups for the second sequence.  Disable them if
17279          we're going to use the first sequence, otherwise adjust their
17280          addresses to account for the relaxation.  */
17281       while (fixp && fixp->fx_frag == fragp)
17282         {
17283           if (subtype & RELAX_USE_SECOND)
17284             fixp->fx_where -= first;
17285           else
17286             fixp->fx_done = 1;
17287           fixp = fixp->fx_next;
17288         }
17289
17290       /* Now modify the frag contents.  */
17291       if (subtype & RELAX_USE_SECOND)
17292         {
17293           char *start;
17294
17295           start = fragp->fr_literal + fragp->fr_fix - first - second;
17296           memmove (start, start + first, second);
17297           fragp->fr_fix -= first;
17298         }
17299       else
17300         fragp->fr_fix -= second;
17301     }
17302 }
17303
17304 /* This function is called after the relocs have been generated.
17305    We've been storing mips16 text labels as odd.  Here we convert them
17306    back to even for the convenience of the debugger.  */
17307
17308 void
17309 mips_frob_file_after_relocs (void)
17310 {
17311   asymbol **syms;
17312   unsigned int count, i;
17313
17314   syms = bfd_get_outsymbols (stdoutput);
17315   count = bfd_get_symcount (stdoutput);
17316   for (i = 0; i < count; i++, syms++)
17317     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17318         && ((*syms)->value & 1) != 0)
17319       {
17320         (*syms)->value &= ~1;
17321         /* If the symbol has an odd size, it was probably computed
17322            incorrectly, so adjust that as well.  */
17323         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17324           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17325       }
17326 }
17327
17328 /* This function is called whenever a label is defined, including fake
17329    labels instantiated off the dot special symbol.  It is used when
17330    handling branch delays; if a branch has a label, we assume we cannot
17331    move it.  This also bumps the value of the symbol by 1 in compressed
17332    code.  */
17333
17334 static void
17335 mips_record_label (symbolS *sym)
17336 {
17337   segment_info_type *si = seg_info (now_seg);
17338   struct insn_label_list *l;
17339
17340   if (free_insn_labels == NULL)
17341     l = (struct insn_label_list *) xmalloc (sizeof *l);
17342   else
17343     {
17344       l = free_insn_labels;
17345       free_insn_labels = l->next;
17346     }
17347
17348   l->label = sym;
17349   l->next = si->label_list;
17350   si->label_list = l;
17351 }
17352
17353 /* This function is called as tc_frob_label() whenever a label is defined
17354    and adds a DWARF-2 record we only want for true labels.  */
17355
17356 void
17357 mips_define_label (symbolS *sym)
17358 {
17359   mips_record_label (sym);
17360   dwarf2_emit_label (sym);
17361 }
17362
17363 /* This function is called by tc_new_dot_label whenever a new dot symbol
17364    is defined.  */
17365
17366 void
17367 mips_add_dot_label (symbolS *sym)
17368 {
17369   mips_record_label (sym);
17370   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17371     mips_compressed_mark_label (sym);
17372 }
17373 \f
17374 /* Some special processing for a MIPS ELF file.  */
17375
17376 void
17377 mips_elf_final_processing (void)
17378 {
17379   /* Write out the register information.  */
17380   if (mips_abi != N64_ABI)
17381     {
17382       Elf32_RegInfo s;
17383
17384       s.ri_gprmask = mips_gprmask;
17385       s.ri_cprmask[0] = mips_cprmask[0];
17386       s.ri_cprmask[1] = mips_cprmask[1];
17387       s.ri_cprmask[2] = mips_cprmask[2];
17388       s.ri_cprmask[3] = mips_cprmask[3];
17389       /* The gp_value field is set by the MIPS ELF backend.  */
17390
17391       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17392                                        ((Elf32_External_RegInfo *)
17393                                         mips_regmask_frag));
17394     }
17395   else
17396     {
17397       Elf64_Internal_RegInfo s;
17398
17399       s.ri_gprmask = mips_gprmask;
17400       s.ri_pad = 0;
17401       s.ri_cprmask[0] = mips_cprmask[0];
17402       s.ri_cprmask[1] = mips_cprmask[1];
17403       s.ri_cprmask[2] = mips_cprmask[2];
17404       s.ri_cprmask[3] = mips_cprmask[3];
17405       /* The gp_value field is set by the MIPS ELF backend.  */
17406
17407       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17408                                        ((Elf64_External_RegInfo *)
17409                                         mips_regmask_frag));
17410     }
17411
17412   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17413      sort of BFD interface for this.  */
17414   if (mips_any_noreorder)
17415     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17416   if (mips_pic != NO_PIC)
17417     {
17418       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17419       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17420     }
17421   if (mips_abicalls)
17422     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17423
17424   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17425      defined at present; this might need to change in future.  */
17426   if (file_ase_mips16)
17427     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17428   if (file_ase_micromips)
17429     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17430   if (file_mips_opts.ase & ASE_MDMX)
17431     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17432
17433   /* Set the MIPS ELF ABI flags.  */
17434   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17435     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17436   else if (mips_abi == O64_ABI)
17437     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17438   else if (mips_abi == EABI_ABI)
17439     {
17440       if (file_mips_opts.gp == 64)
17441         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17442       else
17443         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17444     }
17445   else if (mips_abi == N32_ABI)
17446     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17447
17448   /* Nothing to do for N64_ABI.  */
17449
17450   if (mips_32bitmode)
17451     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17452
17453   if (mips_flag_nan2008)
17454     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17455
17456   /* 32 bit code with 64 bit FP registers.  */
17457   if (file_mips_opts.fp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
17458     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17459 }
17460 \f
17461 typedef struct proc {
17462   symbolS *func_sym;
17463   symbolS *func_end_sym;
17464   unsigned long reg_mask;
17465   unsigned long reg_offset;
17466   unsigned long fpreg_mask;
17467   unsigned long fpreg_offset;
17468   unsigned long frame_offset;
17469   unsigned long frame_reg;
17470   unsigned long pc_reg;
17471 } procS;
17472
17473 static procS cur_proc;
17474 static procS *cur_proc_ptr;
17475 static int numprocs;
17476
17477 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17478    as "2", and a normal nop as "0".  */
17479
17480 #define NOP_OPCODE_MIPS         0
17481 #define NOP_OPCODE_MIPS16       1
17482 #define NOP_OPCODE_MICROMIPS    2
17483
17484 char
17485 mips_nop_opcode (void)
17486 {
17487   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17488     return NOP_OPCODE_MICROMIPS;
17489   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17490     return NOP_OPCODE_MIPS16;
17491   else
17492     return NOP_OPCODE_MIPS;
17493 }
17494
17495 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17496    32-bit microMIPS NOPs here (if applicable).  */
17497
17498 void
17499 mips_handle_align (fragS *fragp)
17500 {
17501   char nop_opcode;
17502   char *p;
17503   int bytes, size, excess;
17504   valueT opcode;
17505
17506   if (fragp->fr_type != rs_align_code)
17507     return;
17508
17509   p = fragp->fr_literal + fragp->fr_fix;
17510   nop_opcode = *p;
17511   switch (nop_opcode)
17512     {
17513     case NOP_OPCODE_MICROMIPS:
17514       opcode = micromips_nop32_insn.insn_opcode;
17515       size = 4;
17516       break;
17517     case NOP_OPCODE_MIPS16:
17518       opcode = mips16_nop_insn.insn_opcode;
17519       size = 2;
17520       break;
17521     case NOP_OPCODE_MIPS:
17522     default:
17523       opcode = nop_insn.insn_opcode;
17524       size = 4;
17525       break;
17526     }
17527
17528   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17529   excess = bytes % size;
17530
17531   /* Handle the leading part if we're not inserting a whole number of
17532      instructions, and make it the end of the fixed part of the frag.
17533      Try to fit in a short microMIPS NOP if applicable and possible,
17534      and use zeroes otherwise.  */
17535   gas_assert (excess < 4);
17536   fragp->fr_fix += excess;
17537   switch (excess)
17538     {
17539     case 3:
17540       *p++ = '\0';
17541       /* Fall through.  */
17542     case 2:
17543       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17544         {
17545           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17546           break;
17547         }
17548       *p++ = '\0';
17549       /* Fall through.  */
17550     case 1:
17551       *p++ = '\0';
17552       /* Fall through.  */
17553     case 0:
17554       break;
17555     }
17556
17557   md_number_to_chars (p, opcode, size);
17558   fragp->fr_var = size;
17559 }
17560
17561 static long
17562 get_number (void)
17563 {
17564   int negative = 0;
17565   long val = 0;
17566
17567   if (*input_line_pointer == '-')
17568     {
17569       ++input_line_pointer;
17570       negative = 1;
17571     }
17572   if (!ISDIGIT (*input_line_pointer))
17573     as_bad (_("expected simple number"));
17574   if (input_line_pointer[0] == '0')
17575     {
17576       if (input_line_pointer[1] == 'x')
17577         {
17578           input_line_pointer += 2;
17579           while (ISXDIGIT (*input_line_pointer))
17580             {
17581               val <<= 4;
17582               val |= hex_value (*input_line_pointer++);
17583             }
17584           return negative ? -val : val;
17585         }
17586       else
17587         {
17588           ++input_line_pointer;
17589           while (ISDIGIT (*input_line_pointer))
17590             {
17591               val <<= 3;
17592               val |= *input_line_pointer++ - '0';
17593             }
17594           return negative ? -val : val;
17595         }
17596     }
17597   if (!ISDIGIT (*input_line_pointer))
17598     {
17599       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17600               *input_line_pointer, *input_line_pointer);
17601       as_warn (_("invalid number"));
17602       return -1;
17603     }
17604   while (ISDIGIT (*input_line_pointer))
17605     {
17606       val *= 10;
17607       val += *input_line_pointer++ - '0';
17608     }
17609   return negative ? -val : val;
17610 }
17611
17612 /* The .file directive; just like the usual .file directive, but there
17613    is an initial number which is the ECOFF file index.  In the non-ECOFF
17614    case .file implies DWARF-2.  */
17615
17616 static void
17617 s_mips_file (int x ATTRIBUTE_UNUSED)
17618 {
17619   static int first_file_directive = 0;
17620
17621   if (ECOFF_DEBUGGING)
17622     {
17623       get_number ();
17624       s_app_file (0);
17625     }
17626   else
17627     {
17628       char *filename;
17629
17630       filename = dwarf2_directive_file (0);
17631
17632       /* Versions of GCC up to 3.1 start files with a ".file"
17633          directive even for stabs output.  Make sure that this
17634          ".file" is handled.  Note that you need a version of GCC
17635          after 3.1 in order to support DWARF-2 on MIPS.  */
17636       if (filename != NULL && ! first_file_directive)
17637         {
17638           (void) new_logical_line (filename, -1);
17639           s_app_file_string (filename, 0);
17640         }
17641       first_file_directive = 1;
17642     }
17643 }
17644
17645 /* The .loc directive, implying DWARF-2.  */
17646
17647 static void
17648 s_mips_loc (int x ATTRIBUTE_UNUSED)
17649 {
17650   if (!ECOFF_DEBUGGING)
17651     dwarf2_directive_loc (0);
17652 }
17653
17654 /* The .end directive.  */
17655
17656 static void
17657 s_mips_end (int x ATTRIBUTE_UNUSED)
17658 {
17659   symbolS *p;
17660
17661   /* Following functions need their own .frame and .cprestore directives.  */
17662   mips_frame_reg_valid = 0;
17663   mips_cprestore_valid = 0;
17664
17665   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17666     {
17667       p = get_symbol ();
17668       demand_empty_rest_of_line ();
17669     }
17670   else
17671     p = NULL;
17672
17673   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17674     as_warn (_(".end not in text section"));
17675
17676   if (!cur_proc_ptr)
17677     {
17678       as_warn (_(".end directive without a preceding .ent directive"));
17679       demand_empty_rest_of_line ();
17680       return;
17681     }
17682
17683   if (p != NULL)
17684     {
17685       gas_assert (S_GET_NAME (p));
17686       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17687         as_warn (_(".end symbol does not match .ent symbol"));
17688
17689       if (debug_type == DEBUG_STABS)
17690         stabs_generate_asm_endfunc (S_GET_NAME (p),
17691                                     S_GET_NAME (p));
17692     }
17693   else
17694     as_warn (_(".end directive missing or unknown symbol"));
17695
17696   /* Create an expression to calculate the size of the function.  */
17697   if (p && cur_proc_ptr)
17698     {
17699       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17700       expressionS *exp = xmalloc (sizeof (expressionS));
17701
17702       obj->size = exp;
17703       exp->X_op = O_subtract;
17704       exp->X_add_symbol = symbol_temp_new_now ();
17705       exp->X_op_symbol = p;
17706       exp->X_add_number = 0;
17707
17708       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17709     }
17710
17711   /* Generate a .pdr section.  */
17712   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17713     {
17714       segT saved_seg = now_seg;
17715       subsegT saved_subseg = now_subseg;
17716       expressionS exp;
17717       char *fragp;
17718
17719 #ifdef md_flush_pending_output
17720       md_flush_pending_output ();
17721 #endif
17722
17723       gas_assert (pdr_seg);
17724       subseg_set (pdr_seg, 0);
17725
17726       /* Write the symbol.  */
17727       exp.X_op = O_symbol;
17728       exp.X_add_symbol = p;
17729       exp.X_add_number = 0;
17730       emit_expr (&exp, 4);
17731
17732       fragp = frag_more (7 * 4);
17733
17734       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17735       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17736       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17737       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17738       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17739       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17740       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17741
17742       subseg_set (saved_seg, saved_subseg);
17743     }
17744
17745   cur_proc_ptr = NULL;
17746 }
17747
17748 /* The .aent and .ent directives.  */
17749
17750 static void
17751 s_mips_ent (int aent)
17752 {
17753   symbolS *symbolP;
17754
17755   symbolP = get_symbol ();
17756   if (*input_line_pointer == ',')
17757     ++input_line_pointer;
17758   SKIP_WHITESPACE ();
17759   if (ISDIGIT (*input_line_pointer)
17760       || *input_line_pointer == '-')
17761     get_number ();
17762
17763   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17764     as_warn (_(".ent or .aent not in text section"));
17765
17766   if (!aent && cur_proc_ptr)
17767     as_warn (_("missing .end"));
17768
17769   if (!aent)
17770     {
17771       /* This function needs its own .frame and .cprestore directives.  */
17772       mips_frame_reg_valid = 0;
17773       mips_cprestore_valid = 0;
17774
17775       cur_proc_ptr = &cur_proc;
17776       memset (cur_proc_ptr, '\0', sizeof (procS));
17777
17778       cur_proc_ptr->func_sym = symbolP;
17779
17780       ++numprocs;
17781
17782       if (debug_type == DEBUG_STABS)
17783         stabs_generate_asm_func (S_GET_NAME (symbolP),
17784                                  S_GET_NAME (symbolP));
17785     }
17786
17787   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17788
17789   demand_empty_rest_of_line ();
17790 }
17791
17792 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17793    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17794    s_mips_frame is used so that we can set the PDR information correctly.
17795    We can't use the ecoff routines because they make reference to the ecoff
17796    symbol table (in the mdebug section).  */
17797
17798 static void
17799 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17800 {
17801   if (ECOFF_DEBUGGING)
17802     s_ignore (ignore);
17803   else
17804     {
17805       long val;
17806
17807       if (cur_proc_ptr == (procS *) NULL)
17808         {
17809           as_warn (_(".frame outside of .ent"));
17810           demand_empty_rest_of_line ();
17811           return;
17812         }
17813
17814       cur_proc_ptr->frame_reg = tc_get_register (1);
17815
17816       SKIP_WHITESPACE ();
17817       if (*input_line_pointer++ != ','
17818           || get_absolute_expression_and_terminator (&val) != ',')
17819         {
17820           as_warn (_("bad .frame directive"));
17821           --input_line_pointer;
17822           demand_empty_rest_of_line ();
17823           return;
17824         }
17825
17826       cur_proc_ptr->frame_offset = val;
17827       cur_proc_ptr->pc_reg = tc_get_register (0);
17828
17829       demand_empty_rest_of_line ();
17830     }
17831 }
17832
17833 /* The .fmask and .mask directives. If the mdebug section is present
17834    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17835    embedded targets, s_mips_mask is used so that we can set the PDR
17836    information correctly. We can't use the ecoff routines because they
17837    make reference to the ecoff symbol table (in the mdebug section).  */
17838
17839 static void
17840 s_mips_mask (int reg_type)
17841 {
17842   if (ECOFF_DEBUGGING)
17843     s_ignore (reg_type);
17844   else
17845     {
17846       long mask, off;
17847
17848       if (cur_proc_ptr == (procS *) NULL)
17849         {
17850           as_warn (_(".mask/.fmask outside of .ent"));
17851           demand_empty_rest_of_line ();
17852           return;
17853         }
17854
17855       if (get_absolute_expression_and_terminator (&mask) != ',')
17856         {
17857           as_warn (_("bad .mask/.fmask directive"));
17858           --input_line_pointer;
17859           demand_empty_rest_of_line ();
17860           return;
17861         }
17862
17863       off = get_absolute_expression ();
17864
17865       if (reg_type == 'F')
17866         {
17867           cur_proc_ptr->fpreg_mask = mask;
17868           cur_proc_ptr->fpreg_offset = off;
17869         }
17870       else
17871         {
17872           cur_proc_ptr->reg_mask = mask;
17873           cur_proc_ptr->reg_offset = off;
17874         }
17875
17876       demand_empty_rest_of_line ();
17877     }
17878 }
17879
17880 /* A table describing all the processors gas knows about.  Names are
17881    matched in the order listed.
17882
17883    To ease comparison, please keep this table in the same order as
17884    gcc's mips_cpu_info_table[].  */
17885 static const struct mips_cpu_info mips_cpu_info_table[] =
17886 {
17887   /* Entries for generic ISAs */
17888   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17889   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17890   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17891   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17892   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17893   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17894   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17895   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
17896   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
17897   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17898   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17899   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
17900   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
17901
17902   /* MIPS I */
17903   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17904   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17905   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17906
17907   /* MIPS II */
17908   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17909
17910   /* MIPS III */
17911   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17912   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17913   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17914   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17915   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17916   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17917   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17918   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17919   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17920   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17921   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17922   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17923   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17924   /* ST Microelectronics Loongson 2E and 2F cores */
17925   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17926   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17927
17928   /* MIPS IV */
17929   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17930   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17931   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17932   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17933   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17934   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17935   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17936   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17937   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17938   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17939   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17940   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17941   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17942   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17943   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17944
17945   /* MIPS 32 */
17946   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17947   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17948   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17949   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17950
17951   /* MIPS 32 Release 2 */
17952   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17953   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17954   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17955   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17956   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17957   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17958   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17959   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17960   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17961                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17962   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17963                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17964   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17965   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17966   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17967   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17968   /* Deprecated forms of the above.  */
17969   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17970   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17971   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17972   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17973   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17974   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17975   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17976   /* Deprecated forms of the above.  */
17977   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17978   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17979   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17980   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17981   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17982   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17983   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17984   /* Deprecated forms of the above.  */
17985   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17986   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17987   /* 34Kn is a 34kc without DSP.  */
17988   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17989   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17990   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17991   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17992   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17993   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17994   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17995   /* Deprecated forms of the above.  */
17996   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17997   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17998   /* 1004K cores are multiprocessor versions of the 34K.  */
17999   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18000   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18001   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18002   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
18003   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
18004   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
18005
18006   /* MIPS 64 */
18007   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18008   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
18009   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18010   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
18011
18012   /* Broadcom SB-1 CPU core */
18013   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18014   /* Broadcom SB-1A CPU core */
18015   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
18016   
18017   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
18018
18019   /* MIPS 64 Release 2 */
18020
18021   /* Cavium Networks Octeon CPU core */
18022   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
18023   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
18024   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
18025
18026   /* RMI Xlr */
18027   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
18028
18029   /* Broadcom XLP.
18030      XLP is mostly like XLR, with the prominent exception that it is
18031      MIPS64R2 rather than MIPS64.  */
18032   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
18033
18034   /* End marker */
18035   { NULL, 0, 0, 0, 0 }
18036 };
18037
18038
18039 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
18040    with a final "000" replaced by "k".  Ignore case.
18041
18042    Note: this function is shared between GCC and GAS.  */
18043
18044 static bfd_boolean
18045 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
18046 {
18047   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
18048     given++, canonical++;
18049
18050   return ((*given == 0 && *canonical == 0)
18051           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
18052 }
18053
18054
18055 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
18056    CPU name.  We've traditionally allowed a lot of variation here.
18057
18058    Note: this function is shared between GCC and GAS.  */
18059
18060 static bfd_boolean
18061 mips_matching_cpu_name_p (const char *canonical, const char *given)
18062 {
18063   /* First see if the name matches exactly, or with a final "000"
18064      turned into "k".  */
18065   if (mips_strict_matching_cpu_name_p (canonical, given))
18066     return TRUE;
18067
18068   /* If not, try comparing based on numerical designation alone.
18069      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
18070   if (TOLOWER (*given) == 'r')
18071     given++;
18072   if (!ISDIGIT (*given))
18073     return FALSE;
18074
18075   /* Skip over some well-known prefixes in the canonical name,
18076      hoping to find a number there too.  */
18077   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
18078     canonical += 2;
18079   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
18080     canonical += 2;
18081   else if (TOLOWER (canonical[0]) == 'r')
18082     canonical += 1;
18083
18084   return mips_strict_matching_cpu_name_p (canonical, given);
18085 }
18086
18087
18088 /* Parse an option that takes the name of a processor as its argument.
18089    OPTION is the name of the option and CPU_STRING is the argument.
18090    Return the corresponding processor enumeration if the CPU_STRING is
18091    recognized, otherwise report an error and return null.
18092
18093    A similar function exists in GCC.  */
18094
18095 static const struct mips_cpu_info *
18096 mips_parse_cpu (const char *option, const char *cpu_string)
18097 {
18098   const struct mips_cpu_info *p;
18099
18100   /* 'from-abi' selects the most compatible architecture for the given
18101      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18102      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18103      version.  Look first at the -mgp options, if given, otherwise base
18104      the choice on MIPS_DEFAULT_64BIT.
18105
18106      Treat NO_ABI like the EABIs.  One reason to do this is that the
18107      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18108      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18109      'mips64', just as we did in the days before 'from-abi'.  */
18110   if (strcasecmp (cpu_string, "from-abi") == 0)
18111     {
18112       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18113         return mips_cpu_info_from_isa (ISA_MIPS1);
18114
18115       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18116         return mips_cpu_info_from_isa (ISA_MIPS3);
18117
18118       if (file_mips_opts.gp >= 0)
18119         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
18120                                        ? ISA_MIPS1 : ISA_MIPS3);
18121
18122       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18123                                      ? ISA_MIPS3
18124                                      : ISA_MIPS1);
18125     }
18126
18127   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18128   if (strcasecmp (cpu_string, "default") == 0)
18129     return 0;
18130
18131   for (p = mips_cpu_info_table; p->name != 0; p++)
18132     if (mips_matching_cpu_name_p (p->name, cpu_string))
18133       return p;
18134
18135   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18136   return 0;
18137 }
18138
18139 /* Return the canonical processor information for ISA (a member of the
18140    ISA_MIPS* enumeration).  */
18141
18142 static const struct mips_cpu_info *
18143 mips_cpu_info_from_isa (int isa)
18144 {
18145   int i;
18146
18147   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18148     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18149         && isa == mips_cpu_info_table[i].isa)
18150       return (&mips_cpu_info_table[i]);
18151
18152   return NULL;
18153 }
18154
18155 static const struct mips_cpu_info *
18156 mips_cpu_info_from_arch (int arch)
18157 {
18158   int i;
18159
18160   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18161     if (arch == mips_cpu_info_table[i].cpu)
18162       return (&mips_cpu_info_table[i]);
18163
18164   return NULL;
18165 }
18166 \f
18167 static void
18168 show (FILE *stream, const char *string, int *col_p, int *first_p)
18169 {
18170   if (*first_p)
18171     {
18172       fprintf (stream, "%24s", "");
18173       *col_p = 24;
18174     }
18175   else
18176     {
18177       fprintf (stream, ", ");
18178       *col_p += 2;
18179     }
18180
18181   if (*col_p + strlen (string) > 72)
18182     {
18183       fprintf (stream, "\n%24s", "");
18184       *col_p = 24;
18185     }
18186
18187   fprintf (stream, "%s", string);
18188   *col_p += strlen (string);
18189
18190   *first_p = 0;
18191 }
18192
18193 void
18194 md_show_usage (FILE *stream)
18195 {
18196   int column, first;
18197   size_t i;
18198
18199   fprintf (stream, _("\
18200 MIPS options:\n\
18201 -EB                     generate big endian output\n\
18202 -EL                     generate little endian output\n\
18203 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18204 -G NUM                  allow referencing objects up to NUM bytes\n\
18205                         implicitly with the gp register [default 8]\n"));
18206   fprintf (stream, _("\
18207 -mips1                  generate MIPS ISA I instructions\n\
18208 -mips2                  generate MIPS ISA II instructions\n\
18209 -mips3                  generate MIPS ISA III instructions\n\
18210 -mips4                  generate MIPS ISA IV instructions\n\
18211 -mips5                  generate MIPS ISA V instructions\n\
18212 -mips32                 generate MIPS32 ISA instructions\n\
18213 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18214 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
18215 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
18216 -mips64                 generate MIPS64 ISA instructions\n\
18217 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18218 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
18219 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
18220 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18221
18222   first = 1;
18223
18224   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18225     show (stream, mips_cpu_info_table[i].name, &column, &first);
18226   show (stream, "from-abi", &column, &first);
18227   fputc ('\n', stream);
18228
18229   fprintf (stream, _("\
18230 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18231 -no-mCPU                don't generate code specific to CPU.\n\
18232                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18233
18234   first = 1;
18235
18236   show (stream, "3900", &column, &first);
18237   show (stream, "4010", &column, &first);
18238   show (stream, "4100", &column, &first);
18239   show (stream, "4650", &column, &first);
18240   fputc ('\n', stream);
18241
18242   fprintf (stream, _("\
18243 -mips16                 generate mips16 instructions\n\
18244 -no-mips16              do not generate mips16 instructions\n"));
18245   fprintf (stream, _("\
18246 -mmicromips             generate microMIPS instructions\n\
18247 -mno-micromips          do not generate microMIPS instructions\n"));
18248   fprintf (stream, _("\
18249 -msmartmips             generate smartmips instructions\n\
18250 -mno-smartmips          do not generate smartmips instructions\n"));  
18251   fprintf (stream, _("\
18252 -mdsp                   generate DSP instructions\n\
18253 -mno-dsp                do not generate DSP instructions\n"));
18254   fprintf (stream, _("\
18255 -mdspr2                 generate DSP R2 instructions\n\
18256 -mno-dspr2              do not generate DSP R2 instructions\n"));
18257   fprintf (stream, _("\
18258 -mmt                    generate MT instructions\n\
18259 -mno-mt                 do not generate MT instructions\n"));
18260   fprintf (stream, _("\
18261 -mmcu                   generate MCU instructions\n\
18262 -mno-mcu                do not generate MCU instructions\n"));
18263   fprintf (stream, _("\
18264 -mmsa                   generate MSA instructions\n\
18265 -mno-msa                do not generate MSA instructions\n"));
18266   fprintf (stream, _("\
18267 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
18268 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
18269   fprintf (stream, _("\
18270 -mvirt                  generate Virtualization instructions\n\
18271 -mno-virt               do not generate Virtualization instructions\n"));
18272   fprintf (stream, _("\
18273 -minsn32                only generate 32-bit microMIPS instructions\n\
18274 -mno-insn32             generate all microMIPS instructions\n"));
18275   fprintf (stream, _("\
18276 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18277 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18278 -mfix-vr4120            work around certain VR4120 errata\n\
18279 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18280 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18281 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18282 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18283 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18284 -msym32                 assume all symbols have 32-bit values\n\
18285 -O0                     remove unneeded NOPs, do not swap branches\n\
18286 -O                      remove unneeded NOPs and swap branches\n\
18287 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18288 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18289   fprintf (stream, _("\
18290 -mhard-float            allow floating-point instructions\n\
18291 -msoft-float            do not allow floating-point instructions\n\
18292 -msingle-float          only allow 32-bit floating-point operations\n\
18293 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18294 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18295 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18296 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18297
18298   first = 1;
18299
18300   show (stream, "legacy", &column, &first);
18301   show (stream, "2008", &column, &first);
18302
18303   fputc ('\n', stream);
18304
18305   fprintf (stream, _("\
18306 -KPIC, -call_shared     generate SVR4 position independent code\n\
18307 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18308 -mvxworks-pic           generate VxWorks position independent code\n\
18309 -non_shared             do not generate code that can operate with DSOs\n\
18310 -xgot                   assume a 32 bit GOT\n\
18311 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18312 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18313                         position dependent (non shared) code\n\
18314 -mabi=ABI               create ABI conformant object file for:\n"));
18315
18316   first = 1;
18317
18318   show (stream, "32", &column, &first);
18319   show (stream, "o64", &column, &first);
18320   show (stream, "n32", &column, &first);
18321   show (stream, "64", &column, &first);
18322   show (stream, "eabi", &column, &first);
18323
18324   fputc ('\n', stream);
18325
18326   fprintf (stream, _("\
18327 -32                     create o32 ABI object file (default)\n\
18328 -n32                    create n32 ABI object file\n\
18329 -64                     create 64 ABI object file\n"));
18330 }
18331
18332 #ifdef TE_IRIX
18333 enum dwarf2_format
18334 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18335 {
18336   if (HAVE_64BIT_SYMBOLS)
18337     return dwarf2_format_64bit_irix;
18338   else
18339     return dwarf2_format_32bit;
18340 }
18341 #endif
18342
18343 int
18344 mips_dwarf2_addr_size (void)
18345 {
18346   if (HAVE_64BIT_OBJECTS)
18347     return 8;
18348   else
18349     return 4;
18350 }
18351
18352 /* Standard calling conventions leave the CFA at SP on entry.  */
18353 void
18354 mips_cfi_frame_initial_instructions (void)
18355 {
18356   cfi_add_CFA_def_cfa_register (SP);
18357 }
18358
18359 int
18360 tc_mips_regname_to_dw2regnum (char *regname)
18361 {
18362   unsigned int regnum = -1;
18363   unsigned int reg;
18364
18365   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18366     regnum = reg;
18367
18368   return regnum;
18369 }
18370
18371 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
18372    Given a symbolic attribute NAME, return the proper integer value.
18373    Returns -1 if the attribute is not known.  */
18374
18375 int
18376 mips_convert_symbolic_attribute (const char *name)
18377 {
18378   static const struct
18379   {
18380     const char * name;
18381     const int    tag;
18382   }
18383   attribute_table[] =
18384     {
18385 #define T(tag) {#tag, tag}
18386       T (Tag_GNU_MIPS_ABI_FP),
18387       T (Tag_GNU_MIPS_ABI_MSA),
18388 #undef T
18389     };
18390   unsigned int i;
18391
18392   if (name == NULL)
18393     return -1;
18394
18395   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
18396     if (streq (name, attribute_table[i].name))
18397       return attribute_table[i].tag;
18398
18399   return -1;
18400 }
18401
18402 void
18403 md_mips_end (void)
18404 {
18405   mips_emit_delays ();
18406   if (cur_proc_ptr)
18407     as_warn (_("missing .end at end of assembly"));
18408
18409   /* Just in case no code was emitted, do the consistency check.  */
18410   file_mips_check_options ();
18411 }